I've been going through a few examples, reducing an array of elements to one element, without success. Someone posted this on an NVIDIA forum. I have changed from floating point variables to integers.
__kernel void sum(__global const short *A,__global unsigned long *C,uint size, __local unsigned long *L) {
unsigned long sum=0;
for(int i=get_local_id(0);i<size;i+=get_local_size(0))
sum+=A[i];
L[get_local_id(0)]=sum;
for(uint c=get_local_size(0)/2;c>0;c/=2)
{
barrier(CLK_LOCAL_MEM_FENCE);
if(c>get_local_id(0))
L[get_local_id(0)]+=L[get_local_id(0)+c];
}
if(get_local_id(0)==0)
C[0]=L[0];
barrier(CLK_LOCAL_MEM_FENCE);
}
Does this look right? The third argument "size", is that supposed to be the local work size, or global work size?
I set up my arguments like this,
clSetKernelArg(ocReduce, 0, sizeof(cl_mem), (void*) &DevA);
clSetKernelArg(ocReduce, 1, sizeof(cl_mem), (void*) &DevC);
clSetKernelArg(ocReduce, 2, sizeof(uint), (void*) &size);
clSetKernelArg(ocReduce, 3, LocalWorkSize * sizeof(unsigned long), NULL);
The first argument which is the input, I am trying to retain from the output of the kernel launched before it.
clRetainMemObject(DevA);
clEnqueueNDRangeKernel(hCmdQueue[Plat-1][Dev-1], ocKernel, 1, NULL, &GlobalWorkSize, &LocalWorkSize, 0, NULL, NULL);
//the device memory object DevA now has the data to be reduced
clEnqueueNDRangeKernel(hCmdQueue[Plat-1][Dev-1], ocReduce, 1, NULL, &GlobalWorkSize, &LocalWorkSize, 0, NULL, NULL);
clEnqueueReadBuffer(hCmdQueue[Plat-1][Dev-1],DevRE, CL_TRUE, 0, sizeof(unsigned long)*512,(void*) RE , 0, NULL, NULL);
Today I plan to try and convert the following cuda reduction example into openCL.
__global__ voidreduce1(int*g_idata, int*g_odata){
extern __shared__ intsdata[];
unsigned int tid = threadIdx.x;
unsigned int i = blockIdx.x*(blockDim.x*2) + threadIdx.x;
sdata[tid] = g_idata[i] + g_idata[i+blockDim.x];
__syncthreads();
for(unsigned int s=blockDim.x/2; s>0; s>>=1) {
if (tid < s) {
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
// write result for this block to global mem
if(tid == 0) g_odata[blockIdx.x] = sdata[0];
}
There is a more optimized, (completely unrolled+multiple elements per thread).
http://developer.download.nvidia.com/compute/cuda/1_1/Website/projects/reduction/doc/reduction.pdf
Is this possible using openCL?
Grizzly gave me this advice the other day,
"...use a reduction kernel which operates on n element and reduces them to something like n / 16 (or any other number). Then you iteratively call that kernel until you are down to one element, which is your result"
I want to try this as well, but I don't exactly know where to start, and I want to first just get something to work.