OpenCL (Open Computing Language) is a new framework for writing programs that execute in parallel on different computing devices (such as CPUs and GPUs) from different vendors (AMD, Intel, ATI, Nvidia etc.). The framework defines a language to write “kernels” in. These kernels are the functions which are to run on the different computing devices. In this post, I explain how to get started with OpenCL and how to make a small OpenCL program that will compute the sum of two lists in parallel. After that, I will show you how to write a GPU Cryptocurrency miner with the help of OpenCL based on the knowledge we just learned.
The kernel
The kernel is written in the OpenCL language which is a subset of C and has a lot of math and vector functions included. The kernel to perform the vector addition operation is defined below.
1 2 3 4 5 6 7 8 |
|
The host program
The host program controls the execution of kernels on the computing devices. The host program is written in C, but bindings for other languages like C++ and Python exists. The OpenCL API is defined in the cl.h (or opencl.h for apple) header file. Below is the code for the host program that executes the kernel above on computing device. I will not go into details on each step as this is supposed to be an introductory article.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
|
You can also refer to https://www.eriksmistad.no/getting-started-with-opencl-and-gpu-computing/ to get a more detailed getting started guide, and the above code is from that article.
Compiling an OpenCL program
The easiest way is to create a Makefile and in this way, we don’t need to remember those compile library and compilation parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
GPU Miner
To write a GPU Miner with OpenCL is very easy now as all need to do is to implement an algorithm. As an exapmle, a GPU Miner for blake2b (from https://github.com/NebulousLabs/Sia-GPU-Miner/blob/master/sia-gpu-miner.cl):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
|
Please note after BitMain released A3 ASIC for blake2b algorithm (https://www.bitsonline.com/review-antminer-a3-blake-2b-asic-miner/), it’s not profitable anymore to mining blake2b coins with GPU.
Here, this code is only for learning GPU Miner.
References
Blake2: https://blake2.net/blake2.pdf