Using multiple GPUs OpenCL - 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.

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.

OpenCL: Object not getting initialized with value

If I do the following:
this->bufferParams = cl::Buffer(context, CL_MEM_READ_ONLY, sizeof(Params), &params, NULL);
My buffer doesnt seem to get populated with my params object. However if I do this
this->queue.enqueueWriteBuffer(this->bufferParams, CL_TRUE, 0, sizeof(Params), &params, NULL);
Then it seems to work. Is there any way in the cl::Buffer syntax to initialize the params object directly rather than doing the enqueue command
Just do this:
this->bufferParams = cl::Buffer(context, CL_MEM_READ_ONLY|
CL_MEM_COPY_HOST_PTR, sizeof(Params), &params, NULL);
If you don use the flag to copy from the host pointer it is not going to copy.
That pointer may be used for other things (like acquire memory) so you need to set the flag accordingly.
EXTRA: Also, for very small structure objects, like your Params probably is, use it directly on clSetKernelArgs(). No need to create a buffer if you are just setting some constant values that are never written. It also goes trough a more optimized memory path.

parallel invocation of kernel in OpenCl?

Does the following code, invokes all the 4 kernel in parallel and all the 4 events will wait for them to complete?
event1 = event2 = event3 = event4 = 0;
printf("sending enqueue task..\n");
clEnqueueTask(command_queue, calculate1, 0, NULL, &event1);
clEnqueueTask(command_queue, calculate2, 0, NULL, &event2);
clEnqueueTask(command_queue, calculate3, 0, NULL, &event3);
clEnqueueTask(command_queue, calculate4, 0, NULL, &event4);
printf("waiting after enquing task..\n");
clWaitForEvents(1, &event1);
clWaitForEvents(1, &event2);
clWaitForEvents(1, &event3);
clWaitForEvents(1, &event4);
Or, is it the right way to perform the task for invoking all the kernels parallel? Is it even possible? What device info i need to see for confirming the same?
These tasks might execute in parallel, if you are using an out-of-order command queue and the device has support for executing multiple kernels in parallel. Unfortunately, there isn't any device info query that you can perform to verify whether the device has this capability, so you'll have to check the start/end times of the resulting events if you want to check whether this actually happened. An alternative method of achieving parallel kernel execution is by using multiple command queues (as discussed in the comments). Note that this kind of coarse-grained task parallelism won't execute particularly efficiently on massively parallel architectures such as GPU.
Rather than waiting for each event individually, you could just call clFinish(command_queue) to wait for all commands to complete. You might also want to experiment with calling clFlush(command_queue) immediately after enqueuing all the tasks to ensure that they are all submitted to the device.

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.

Executing different kernels on different GPUs simultaneously

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.

Resources