Executing different kernels on different GPUs simultaneously - opencl

Basically I have two GPUs and I want to execute some kernels on each of them. I don't want the GPUs to be working on the same kernel with each doing some part of it(I don know if this is possible), just in case I don even want to see that behavior.
I just want to make sure that both the devices are being exercised. I have created context and the command queues for both of them. But I see only one kernel gets executed which means only one device is being used. This is how I have done it. . .
cl_device_id *device;
cl_kernel *kernels;
...
// creating context.
context = clCreateContext(0, num_devices, device, NULL, NULL, &error);
...
// creating command queues for all kernels
for(int i = 0; i<num_kenrels; i++)
cmdQ[i] = clCreateCommandQueue(context, *device, 0, &error);
...
// enqueue kernels
error = clEnqueueNDRangeKernel(*cmdQ, *kernels, 2, 0, glbsize, 0, 0, NULL, NULL);
Am I going the correct way?

It depends on how you actually filled your device array. In case you initialized it correctly, creating the context spanning the devices is correct.
Unfortunately, you have a wrong idea about kernels and command queues. A kernel is created from a program for a particular context. A queue on the other hand is used to communicate with a certain device. What you want to do is create one queue per device not kernel:
for (int i = 0; i < num_devices; i++)
cmdQ[i] = clCreateCommandQueue(context, device[i], 0, &error);
Now you can enqueue the different (or same) kernels on different devices via the corresponding command queues:
clEnqueueNDRangeKernel(cmdQ[0], kernels[0], /* ... */);
clEnqueueNDRangeKernel(cmdQ[1], kernels[1], /* ... */);
To sum up the terms:
A cl_context is created for a particular cl_platform_id and is like a container for a subset of devices,
a cl_program is created and built for a cl_context and its associated devices
a cl_kernel is extracted from a cl_program but can only be used on devices associated with the program's context,
a cl_command_queue is created for a specific device belonging to a certain context,
memory operations and kernel calls are enqueued in a command queue and executed on the corresponding device.

Related

Which devices does clBuildProgram build for, if we pass NULL to device_list parameter?

clBuildProgram allows one to give a list of devices to build the program for. That's the reason of the num_devices and device_list parameters in the declaration:
cl_int clBuildProgram(cl_program program, cl_uint num_devices, const cl_device_id *device_list, const char *options, void (CL_CALLBACK *pfn_notify)(cl_program program, void *user_data), void *user_data)
Now what happens, if we use it like this?
cl_int clBuildProgram(program, 0, NULL, ...
Does it build for all devices in the PC?
Does it build for only those devices I have created the context for? (I mean the context I used when I created program with clCreateProgramWithSource.)
The documentation says:
device_list: A pointer to a list of devices associated with program. If device_list is NULL value, the program executable is built for all devices associated with program for which a source or binary has been loaded. If device_list is a non-NULL value, the program executable is built for devices specified in this list for which a source or binary has been loaded.
I think the phrasing is a bit complicated here, but from that, I guess number 2. Is that right?
I am asking because in case of number 1, I would need to pass a device list to this function in order to avoid superfluous compilation for all devices.
2) is correct. Compilation is constrained to only the devices associated with the program's context. This cannot be every single device in the system unless the context was created using every single device.

How to collect binary kernels to distribute proprietary code

I have a code that contains know-how I would not like to distribute in source code. One of solutions is to provide a bunch of pre-compiled kernels and choose the correct binary depending on the user's hardware.
How to cover most of the users (AMD and Intel, as Nvidia can use CUDA code) with minimum of the binaries and minimum of the machines where I have to run my offline compiler? Are there families of GPUs that can use the same binaries? CUDA compiler can compile for different architectures, what about OpenCL? Binary compatibility data doesn't seem well documented but maybe someone collected these data for himself.
I know there's SPIR but older hardware doesn't support it.
Here are details of my implementation if someone found this question and did less than I do. I made a tool that compiles the kernel to the file and then I collected all these binaries into a C array to be included into the main application:
const char* binaries[] = {
//kernels/HD Graphics 4000
"\x62\x70\x6c\x69\x73\x74\x30\x30\xd4\x01\x02\x03"
"\x04\x05\x06\x07\x08\x5f\x10\x0f\x63\x6c\x42\x69"
"\x6e\x61\x72\x79\x56\x65\x72\x73\x69\x6f\x6e\x5c"
...
"\x00\x00\x00\x00\x00\x00\x00\x09\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x47\xe0"
,
//here more kernels
};
size_t binaries_sizes[] = {
204998,
205907,
...
};
And then I use the following code which iterates all the kernels (I didn't invent anything more clever than trial-and-error, choosing the first kernel that builds successfully, probably there's better solution):
int e3 = -1;
int i = 0;
while (e3 != CL_SUCCESS) {
if (i == lenof(binaries)) {
throw Error();
}
program = clCreateProgramWithBinary(context, 1, &deviceIds[devIdx], &binaries_sizes[i],
(const unsigned char**)&binaries[i],
nullptr, &e3);
if (e3 != CL_SUCCESS) {
++i;
continue;
}
int e4 = clBuildProgram(program, 1, &deviceIds[devIdx],
"", nullptr, nullptr);
e3 = e4;
++i;
}
Unfortunately, there is no standard solution for your problem. OpenCL is platform-independent, and there is no standard way (apart from SPIR) to deal with this problem. Each vendor decide a different compiler toolchain internally, and even this can change across multiple versions of the same driver, or for different devices.
You could add some meta-data to the kernel to identify which platform have you compiled it for, which will save you of the trial and error part (i.e, instead of just storing binaries and binaries_size, you can also store binary_platform and binary_device and then iterate through those arrays to see which binary you should load).
The best solution for you would be SPIR (or the new SPIRV), which are intermediate representations that can be then "re-compiled" by the OpenCL driver to the actual architecture instruction set.
If you store your binaries in SPIRV, and have access to/knowledge of some compiler magic, you can use a translator tool to get back the LLVM-IR and then compile down to other platforms, such as AMD or PTX, using the LLVM infrastructure (see https://github.com/KhronosGroup/SPIRV-LLVM)

Using multiple GPUs OpenCL

I have a loop within which I am launching multiple kernels onto a GPU. Below is the snippet:
for (int idx = start; idx <= end ;idx ++) {
ret = clEnqueueNDRangeKernel(command_queue, memset_kernel, 1, NULL,
&global_item_size_memset, &local_item_size, 0, NULL, NULL);
ASSERT_CL(ret, "Error after launching 1st memset_kernel !");
ret = clEnqueueNDRangeKernel(command_queue, cholesky_kernel, 1, NULL,
&global_item_size_cholesky, &local_item_size, 0, NULL, NULL);
ASSERT_CL(ret, "Error after launching 1st cholesky_kernel !");
ret = clEnqueueNDRangeKernel(command_queue, ckf_kernel1, 1, NULL,
&global_item_size_kernel1, &local_item_size, 0, NULL, NULL);
ASSERT_CL(ret, "Error after launching ckf_kernel1[i] !");
clFinish(command_queue);
ret = clEnqueueNDRangeKernel(command_queue, memset_kernel, 1, NULL,
&global_item_size_memset, &local_item_size, 0, NULL, NULL);
ASSERT_CL(ret, "Error after launching 2nd memset_kernel !");
ret = clEnqueueNDRangeKernel(command_queue, cholesky_kernel, 1, NULL,
&global_item_size_cholesky, &local_item_size, 0, NULL, NULL);
ASSERT_CL(ret, "Error after launching 2nd cholesky_kernel !");
ret = clSetKernelArg(ckf_kernel2, 4, sizeof(idx), (void *)&idx);
ret = clEnqueueNDRangeKernel(command_queue, ckf_kernel2, 1, NULL,
&global_item_size_kernel2, &local_item_size, 0, NULL, NULL);
ASSERT_CL(ret, "Error after launching ckf_kernel2 !");
Now, I am wanting to use this code for a system which has multiple GPUs. So I have completed the following steps:
created a single context for all the GPUs.
created one command queue per device.
created separate kernels for each device (code snippet below assuming two gpus)
allocated separate device buffers for each device
cl_kernel ckf_kernel1[2];
cl_kernel ckf_kernel2[2];
cl_kernel cholesky_kernel[2];
cl_kernel memset_kernel[2];
// read get kernel.
ckf_kernel1[0] = clCreateKernel(program, "ckf_kernel1", &ret);
ASSERT_CL(ret, "Cannot load ckf_kernel1[i]!");
ckf_kernel2[0] = clCreateKernel(program, "ckf_kernel2", &ret);
ASSERT_CL(ret, "Cannot load ckf_kernel2!");
memset_kernel[0] = clCreateKernel(program, "memset_zero", &ret);
ASSERT_CL(ret, "Cannot load memset_kernel!");
cholesky_kernel[0] = clCreateKernel(program, "cholesky_kernel", &ret);
ASSERT_CL(ret, "Cannot load cholesky_kernel!");
ckf_kernel1[1] = clCreateKernel(program, "ckf_kernel1", &ret);
ASSERT_CL(ret, "Cannot load ckf_kernel1[i]!");
ckf_kernel2[1] = clCreateKernel(program, "ckf_kernel2", &ret);
ASSERT_CL(ret, "Cannot load ckf_kernel2!");
memset_kernel[1] = clCreateKernel(program, "memset_zero", &ret);
ASSERT_CL(ret, "Cannot load memset_kernel!");
cholesky_kernel[1] = clCreateKernel(program, "cholesky_kernel", &ret);
ASSERT_CL(ret, "Cannot load cholesky_kernel!");
Now, I am not sure how to launch the kernels onto the different devices within the loop. How to get them to execute in parallel? Please note that there is a clFinish command within the loop above.
Another question: is it standard practice to use multiple threads/processes on the host where each thread/process is responsible for launching kernels on a single GPU?
You need not create separate contexts for all the devices. You only need to that if they are from different platforms.
You need not create separate kernels either. You can compile your kernels for multiple devices at the same time (clBuildProgram supports multi-device compilation), and if you launch a kernel on a device, the runtime will know that the kernel entity holds device binary valid for the given device or not.
Easiest thing is: create a context, fetch all devices that you need, place then in an array, and use that array for building your kernels, and create one command_queue for every device in them.
clEnqueueNDRange kernel is non-blocking. The only reason why your for loop doesn't dash through is because of the clFinish() statemen, and most likely because you are using in order queue, which means that the single device case would work fine without clFinish too.
The general idea for best usage of multi-GPU in OpenCL, is create context-kernels-queues the way I mentioned, and make the queues out-of-order. That way commands are allowed to execute in parallel, if they don't have unmet dependencies, for eg. the input of command2 is not the output of command1, then it is free to start executing in parallel to command1. If you are using this method however, you HAVE to use the final few parameters to clEnqueueNDRangeKernels, because you have to build this chain of dependencies using cl_events. Every clEnqueueWhatever can wait on an array of events, which originate from other commands. Execution of a command in the queue will only start once all it's dependencies are met.
There is one issue that you have not touched upon, and that is the idea of buffers. If you want to get multi-GPU running, you need to explicitly create buffers for your devices separately, and partition your data. It is not valid to have the same buffer set as argument on 2 devices, while both of them are trying to write it. At best, the runtime will serialize your work, and the 2 devices will not work in parallel. This is because buffers are handles to memory, and the runtime is responsible for moving the contents of the buffer to the devices that need it. (This can happen implicitly (lazy memory movement), or explicitly if you call clEnqueueMigrateBuffer.) The runtime is forbidden to give the same buffer with CL_MEM_READ_WRITE or CL_MEM_WRITE_ONLY flags to 2 devices simultaneously. Even though you know as the programmer, that the 2 devices might not be writing the same part of the buffer, the runtime does not. You have to tell it. Elegant way is to create 2 sub-buffers, that are part of the larger/original buffer; less elegant way is to simply create 2 buffers. The first approach is better, because it is easier to collect data from multiple devices back to host, because you need to fetch only the large buffer, and the runtime will know which sub-buffers have been modified on which devices, and it will take care of collecting the data.
If I saw your clSetKernelArgument calls, and the buffers you are using, I could see what the dependencies are to your kernels and write out what you need to do, but I think this is a fairly good start for you in getting multi-device running. Ultimately, it's all about the data. (And start using out-of-order queues, because it has the potential to be faster, and it forces you to start using events, which make it explicit to you and anyone reading the code, which kernels are allowed to run in parallel.

How to invoke single workgroup with multiple workitems which run parallel?

I am in a startup of OpenCl and still learning.
Kernel Code:
__kernel void gpu_kernel(__global float* data)
{
printf("workitem %d invoked\n", get_global_id(0));
int x = 0;
if (get_global_id(0) == 1) {
while (x < 1) {
x = 0;
}
}
printf("workitem %d completed\n", get_global_id(0));
}
C code for invoking kernel
size_t global_item_size = 4; // number of workitems total
size_t local_item_size = 1; // number of workitems per group
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL);
Ouput:
workitem 3 invoked
workitem 3 completed
workitem 0 invoked
workitem 0 completed
workitem 1 invoked
workitem 2 invoked
workitem 2 completed
## Here code is waiting on terminal for Workitem #1 to finish, which will never end
this clearly states, all workitems are parallel (but in different workgroup).
Another C code for invoking kernel (for 1 workgroup with 4 workitems)
size_t global_item_size = 4; // number of workitems total
size_t local_item_size = 4; // number of workitems per group
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL);
Ouput:
workitem 0 invoked
workitem 0 completed
workitem 1 invoked
## Here code is waiting on terminal for Workitem #1 to finish, which will never end
This clearly states that, this running in sequence (that's why it completed 1st Workitem and then got stuck on second and rest are never executed)
My Question:
I need to invoke 1 workgroup with 4 workitems which run parallel. So that i can use barrier in my code (which i guess is only possible within single workgroup)?
any help/suggestion/pointer will be appreciated.
Your second host code snippet correctly launches a single work-group that contains 4 work-items. You have no guarantees that these work-items will run in parallel, since the hardware might not have the resources to do so. However, they will run concurrently, which is exactly what you need in order to be able to use work-group synchronisation constructs such as barriers. See this Stack Overflow question for a concise description of the difference between parallelism and concurrency. Essentially, the work-items in a work-group will make forward progress independently of each other, even if they aren't actually executing in parallel.
OpenCL 1.2 Specification (Section 3.2: Execution Model)
The work-items in a given work-group execute concurrently on the processing elements of a single compute unit.
Based on your previous question on a similar topic, I assume you are using AMD's OpenCL implementation targeting the CPU. The way most OpenCL CPU implementations work is by serialising all work-items from a work-group into a single thread. This thread then executes each work-item in turn (ignoring vectorisation for the sake of argument), switching between them when they either finish or hit a barrier. This is how they achieve concurrent execution, and gives you all the guarantees you need in order to safely use barriers within your kernel. Parallel execution is achieved by having multiple work-groups (as in your first example), which will result in multiple threads executing on multiple cores (if available).
If you replaced your infinite loop with a barrier, you would clearly see that this does actually work.

How do I know if the kernels are executing concurrently?

I have a GPU with CC 3.0, so it should support 16 concurrent kernels. I am starting 10 kernels by looping through clEnqueueNDRangeKernel for 10 times. How do I get to know that the kernels are executing concurrently?
One way which I have thought is to get the time before and after the NDRangeKernel statement. I might have to use events so as to ensure the execution of the kernel has completed. But I still feel that the loop will start the kernels sequentially. Can someone help me out..
To determine if your kernel executions overlap, you have to profile them. This requires several steps:
1. Creating the command-queues
Profiling data is only collected if the command-queue is created with the property CL_QUEUE_PROFILING_ENABLE:
cl_command_queue queues[10];
for (int i = 0; i < 10; ++i) {
queues[i] = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE,
&errcode);
}
2. Making sure all kernels start at the same time
You are right in your assumption that the CPU queues the kernels sequentially. However, you can create a single user event and add it to the wait list for all kernels. This causes the kernels not to start running before the user event is completed:
// Create the user event
cl_event user_event = clCreateUserEvent(context, &errcode);
// Reserve space for kernel events
cl_event kernel_events[10];
// Enqueue kernels
for (int i = 0; i < 10; ++i) {
clEnqueueNDRangeKernel(queues[i], kernel, work_dim, global_work_offset,
global_work_size, 1, &user_event, &kernel_events[i]);
}
// Start all kernels by completing the user event
clSetUserEventStatus(user_event, CL_COMPLETE);
3. Obtain profiling times
Finally, we can collect the timing information for the kernel events:
// Block until all kernels have run to completion
clWaitForEvents(10, kernel_events);
for (int i = 0; i < 10; ++i) {
cl_ulong start;
clGetEventProfilingInfo(kernel_event[i], CL_PROFILING_COMMAND_START,
sizeof(start), &start, NULL);
cl_ulong end;
clGetEventProfilingInfo(kernel_event[i], CL_PROFILING_COMMAND_END,
sizeof(end), &end, NULL);
printf("Event %d: start=%llu, end=%llu", i, start, end);
}
4. Analyzing the output
Now that you have the start and end times of all kernel runs, you can check for overlaps (either by hand or programmatically). The output units are nanoseconds. Note however that the device timer is only accurate to a certain resolution. You can query the resolution using:
size_t resolution;
clGetDeviceInfo(device, CL_DEVICE_PROFILING_TIMER_RESOLUTION,
sizeof(resolution), &resolution, NULL);
FWIW, I tried this on a NVIDIA device with CC 2.0 (which should support concurrent kernels) and observed that the kernels were run sequentially.
You can avoid all the boilerplate code suggested in the other answers (which are correct by the way) by using C Framework for OpenCL, which simplifies this task a lot, and gives you detailed information about OpenCL events (kernel execution, data transfers, etc), including a table and a plot dedicated to overlapped execution of said events.
I developed this library in order to, among other things, simplify the process described in the other answers. You can see a basic usage example here.
Yes, as you suggest, try to use the events, and analyze all the QUEUED, SUBMIT, START, END values. These should be absolute values in "device time", and you may be able to see if processing (START to END) overlaps for the different kernels.

Resources