Prefer Your Language

Search This Blog

Optimization in histogram CUDA code: When number of Bins not equal to max threads in a block


Continuing from Part3

       Part4
Optimization in  histogram CUDA code


When number of Bins not equal to max threads in a block


As I already mentioned at last section of Part3 that when the number of bins not equal to the maximum number of thread in a block, than problem become more complicated to solve. In this part of the article we’ll concentrate how to solve this problem efficiently.
In order to solve this problem, it is very necessary to understand how we wrote our kernel where number of bins is equal to no. of threads in a block. So let examine them.
Our previous kernel is look like this;


__global__ void histo_kernel_optimized5( unsigned char *buffer, long size,
                               unsigned int *histo )
{
Line 1:     __shared__ unsigned int temp[256];
Line 2:     temp[threadIdx.x] = 0;
Line 3:     __syncthreads();

Line 4:     int i = threadIdx.x + blockIdx.x * blockDim.x;
Line 5:     int offset = blockDim.x * gridDim.x;
Line 6:     while (i < size)
            {
Line 7:              atomicAdd( &temp[buffer[i]], 1);
Line 8:              i += offset;
           }
Line 9:     __syncthreads();


Line 10:    atomicAdd( &(histo[threadIdx.x]), temp[threadIdx.x] );
}


And kernel invocation was like this;

histo_kernel_optimized <<<blocks*2,256>>>( dev_buffer, SIZE, dev_histo );


So in kernel; at Line 1: we are allocating memory in shared memory refere as temp; the memory size is equal to number of bins (256).
At Line 2: We fill the temp array with zero, so effectively we are filling 256 elements as 0 in shared memory.
At Line 3: all threads wait for Line 2 task.
Line 4 and 5: These lines are trivial we are calculating absolute id and offset according to 256 threads (which is equal to number of bins).
Line 6: In line 6 we loop over all the element of buffer till our absolute id touch Size value.
Line 7: We are extracting the value located in buffer and increment the count in shared memory array temp.
Line 8: Incrementing absolute id by offset
Line 9: threads wait for all other thread In a block.
Line 10: finally we update our final result.

Now In order to change the above code for Bincount = 1024 (say), we need to care that each element will touch once. Since, at the kernel invocation we are lunching 256 threads in a block and our number of bins is 1024 then shared memory size should be equal to number bins, so it should be 1024, it implies that line 1 will change as below.


Line 1:     __shared__ unsigned int temp[1024];


                                                What about the Line 2; if threads = 256 then only 256 element will affect but our bins count was 1024 then all should be initialize by 0. Then how we achieve this?
Since our memory pattern was look like this;
Thread_Id            update at location
0                                              0
1                                              1
2                                              2
.
.
255                                         255

The entire element followed by 255 means from 256 to 1023 was not affect at all. One method is to allow only last thread to update from 255 to 1023 but by doing this we are forcing last threads to does more work than other threads. So we can take advantage of other threads. One way to do this, let say last thread fill 1023 location then second last thread should update 1022 location and so on then pattern will look like this;
Thread_Id                     update at location
0                                              0,256,512,768
1                                              1,257,513,769
2                                              2,258,514,770
.
.
255                                         255,511,767,1023


So, Line 2 will change and look like this.

temp[threadIdx.x + 0] = 0;
temp[threadIdx.x + 256] = 0;
temp[threadIdx.x + 512] = 0;
temp[threadIdx.x + 768] = 0;


Now what about the line from 3 to 9, does anything will change? No, Since loop is working fine and it will update accordingly. For example let say at absolute id = 10, if the buffer value is 678 then corresponding value will update.  
And the line 10 has to be change accordingly as line 2 changed;

atomicAdd( &(histo[threadIdx.x + 0]), temp[threadIdx.x + 0] );
atomicAdd( &(histo[threadIdx.x + 256]), temp[threadIdx.x + 256] );
atomicAdd( &(histo[threadIdx.x + 512]), temp[threadIdx.x + 512] );
atomicAdd( &(histo[threadIdx.x + 768]), temp[threadIdx.x + 768] );


Hence our final kernel will look like this;


__global__ void histo_kernel_optimized5( unsigned char *buffer, long size,
                               unsigned int *histo )
{   
    __shared__ unsigned int temp[1024];
  
     temp[threadIdx.x + 0] = 0;
     temp[threadIdx.x + 256] = 0;
     temp[threadIdx.x + 512] = 0;
     temp[threadIdx.x + 768] = 0;
     __syncthreads();

     int i = threadIdx.x + blockIdx.x * blockDim.x;
     int offset = blockDim.x * gridDim.x;
     while (i < size)
     {
              atomicAdd( &temp[buffer[i]], 1);
              i += offset;
     }
     __syncthreads();


  
    atomicAdd( &(histo[threadIdx.x + 0]), temp[threadIdx.x + 0] );
    atomicAdd( &(histo[threadIdx.x + 256]), temp[threadIdx.x + 256] );
    atomicAdd( &(histo[threadIdx.x + 512]), temp[threadIdx.x + 512] );
    atomicAdd( &(histo[threadIdx.x + 768]), temp[threadIdx.x + 768] );

}


All the updated lines are colored red in above code and we are done, our kernel invocation does not change.
Now time for quiz, if you’ll run your CUDA code in GPU GTX 280 with CC = 1.3 having 30 multiprocessor. Then how many element per thread in above code you are operating? You can answer in comment box.

Hint: Blocks = 2*30 = 60 and threads= 256 in a block so total threads = blocks*threads;
I hope you must like this article and have learned histogram computation with GPU using CUDA.
Got Questions?
Feel free to ask me any question by commenting below because I'd be happy to walk you through step by step! 
Want to Contact us? Click here

Further Optimization in histogram CUDA code | Fast implementation of histogram in CUDA


Continuing from Part2

                                                          Part3

Further Optimization in  histogram CUDA code | Fast implementation of histogram in CUDA

Optimization step 4

HISTOGRAM KERNEL USING SHARED AND GLOBAL MEMORY ATOMICS

Up to this step, our performance on GPU was really bad as compare to CPU version. The one of the possible optimization I though start using shared memory. If reader is not familiar with shared memory concept feel free to follow this link, I explained shared memory with wide details.
So, I’m damn sure all the reader must thought how this optimization comes in my mind?
Well answer is trivial, since when we using global memory, the memory traffic is terrible and even you can use Visual profiler to profile your code to get to know about the performance, or you can build a performance matrix for that, follow
this link for that.   
Apart from the shared memory there is another way to optimize it, which we have discussed in “Optimization step 3” lunching two dimension blocks and threads. Well, I’m interested to optimize my code first with shared memory than I’ll configure my blocks and grids dimension.

Motivation for Shared memory

Ironically, despite that the atomic operations cause this performance degradation, alleviating the slowdown actually involves using more atomics, not fewer. The core problem was not the use of atomics so much as the fact that thousands of threads were competing for access to a relatively small number of memory addresses.
To address this issue, we will split our histogram computation into two phases.

Phase 1

Computing histogram in shared memory

In phase one, each parallel block will compute a separate histogram of the data that its constituent threads examine. Since each block does this independently, we can compute these histograms in shared memory, saving us the time of sending each write-off chip to DRAM. Doing this does not free us from needing atomic operations, though, since multiple threads within the block can still examine data elements with the same value. However, the fact that only 256 threads will now be competing for 256 addresses will reduce contention from the global version where thousands of threads were competing.

The first phase then involves allocating and zeroing a shared memory buffer to hold each block’s intermediate histogram. Recall from shared memory article, that since the subsequent step will involve reading and modifying this buffer, we need a __syncthreads() call to ensure that every thread’s write has completed before progressing.


__global__ void histo_kernel_optimized5 ( unsigned char *buffer, long size,
                               unsigned int *histo )
{
     __shared__ unsigned int temp[256];
     temp[threadIdx.x] = 0;
     __syncthreads();


After zeroing the histogram, the next step is remarkably similar to our original GPU histogram. The sole differences here are that we use the shared memory buffer temp[] instead of the global memory buffer histo[] and that we need a subsequent call to __syncthreads() to ensure the last of our writes have been committed.


int i = threadIdx.x + blockIdx.x * blockDim.x;
int offset = blockDim.x * gridDim.x;
while (i < size)
{
   atomicAdd( &temp[buffer[i]], 1);
   i += offset;
}
__syncthreads();


Phase 2

Merging histograms

The last step in our modified histogram example requires that we merge each block’s temporary histogram into the global buffer histo[].
Suppose we split the input in half and two threads look at different halves and compute separate histograms. If thread A sees byte 0xFC 20 times in the input and thread B sees byte 0xFC 5 times, the byte 0xFC must have appeared 25 times in the input. Likewise, each bin of the final histogram is just the sum of the corresponding bin in thread A’s histogram and thread B’s histogram. This logic extends to any number of threads, so merging every block’s histogram into a single final histogram involves adding each entry in the block’s histogram to the corresponding entry in the final histogram. For all the reasons we’ve seen already, this needs to be done atomically:

    atomicAdd( &(histo[threadIdx.x]), temp[threadIdx.x] );
}


Important note
Since we have decided to use 256 threads and have 256 histogram bins, each thread atomically adds a single bin to the final histogram’s total. If these numbers didn’t match, this phase would be more complicated. Note that we have no guarantees about what order the blocks add their values to the final histogram, but since integer addition is commutative, we will always get the same answer provided that the additions occur atomically.

And with this, our two phase histogram computation kernel is complete. Here it is from start to finish:


__global__ void histo_kernel_optimized5( unsigned char *buffer, long size,
                               unsigned int *histo )
{
     __shared__ unsigned int temp[256];
     temp[threadIdx.x] = 0;
     __syncthreads();

     int i = threadIdx.x + blockIdx.x * blockDim.x;
     int offset = blockDim.x * gridDim.x;
     while (i < size)
     {
              atomicAdd( &temp[buffer[i]], 1);
              i += offset;
     }
     __syncthreads();


    atomicAdd( &(histo[threadIdx.x]), temp[threadIdx.x] );
}



This version of our histogram example improves dramatically over the previous GPU version. Adding the shared memory component drops our running time on a GeForce GTX 285 to 0.057 seconds. Not only is this significantly better than the version that used global memory atomics only, but this beats our original CPU implementation by an order of magnitude (from 0.416 seconds to 0.057 seconds). This improvement represents greater than a sevenfold boost in speed over the CPU version. So despite the early setback in adapting the histogram to a GPU implementation, our version that uses both shared and global atomics should be considered a success.


Can we do more faster
Yes we can do, after profiling above code, I found it has bank conflict. So if we are able to remove bank conflict then time can reduce by factor 2 or 4 or 8 or even more.
I left this task now for reader, 
I’ll present bank conflict free histogram computation in subsequent article.

Now what about competition,

In that online competition, number of bins was 1024 and Size = 1000*1024 = 1024000 elements.

my naïve implementation (optimization 3) was performed well and time was 16.xx ms, with optimization step 4 implementation, time was 8.xx ms ( 2x faster ) and with the optimization step 5 implementation, time was 1.xx ms, it means 8 time faster than global memory version and 16 time faster than naïve implementation.

My kernel invocation was look like this;


// with naïve implementation
naive_kernel <<<blocks*8,1024>>>( d_vals, d_histo, numElems );

//with optimized implementaion    
  
OptimizedStep5 <<<blocks*8,1024, 1024*sizeof(int)>>>( d_vals, d_histo,
                                                      numElems );


You may noticed, I lunched 1024 threads with dynamic shared memory allocation (look third argument of kernel invocation) since number of bins was 1024.

Further Problem statement
If these numbers of bins and threads in a block does not match than this problem will be more complicate, like as above, number of bins was 1024 and let say I can lunch only 512 threads in a block then how to solve this problem?
 I've cover this approach in Part4 of this article.



Optimizing histogram CUDA code | Optimization in histogram in CUDA


Continuing from Part1 
                                                          Part2

Optimizing histogram CUDA code | Optimization in histogram in CUDA

We would like to adapt the histogram computation example to run on the GPU. If our input array is large enough, it might save a considerable amount of time to have different threads examining different parts of the buffer. Having different threads read different parts of the input should be easy enough. After all, it’s very similar to things we have seen in many previous posts. The problem with computing a histogram from the input data arises from the fact that multiple threads may want to increment the same bin of the output histogram at the same time. In this situation, we will need to use atomic increments to avoid this situation.
I’ll assume you know about atomicAdd () function, so I’ll not describe this in this post.

Our main() routine looks very similar to the CPU version, although we will need to add some of the CUDA C plumbing in order to get input to the GPU and results from the GPU. However, we start exactly as we did on the CPU:


#define SIZE (100*1024*1024) // 100 MB
int main( void ) {
unsigned char *buffer = (unsigned char*)big_random_block( SIZE );


We will be interested in measuring how our code performs, so we initialize events for timing exactly like we always have.


cudaEvent_t start, stop;
checkCudaErrors( cudaEventCreate( &start ) );
checkCudaErrors ( cudaEventCreate( &stop ) );
checkCudaErrors ( cudaEventRecord( start, 0 ) );


After setting up our input data and events, we look to GPU memory. We will need to allocate space for our random input data and our output histogram. After allocating the input buffer, we copy the array we generated with big_random_block() to the GPU. Likewise, after allocating the histogram, we initialize it to zero just like we did in the CPU version.


// allocate memory on the GPU for the file's data
unsigned char *dev_buffer;
unsigned int *dev_histo;
checkCudaErrors( cudaMalloc( (void**)&dev_buffer, SIZE ) );
checkCudaErrors( cudaMemcpy( dev_buffer, buffer, SIZE,
cudaMemcpyHostToDevice ) );
checkCudaErrors( cudaMalloc( (void**)&dev_histo,256 * sizeof( long ) ) );
checkCudaErrors( cudaMemset( dev_histo, 0,256 * sizeof( int ) ) );


You may notice that we slipped in a new CUDA runtime function, cudaMemset(). This function has a similar signature to the standard C function memset(), and the two functions behave nearly identically. The difference in signature is between these functions is that cudaMemset() returns an error code while the C library function memset() does not. This error code will inform the caller whether anything bad happened while attempting to set GPU memory. Aside from the error code return, the only difference is that cudaMemset() operates on GPU
memory while memset() operates on host memory.

After initializing the input and output buffers, we are ready to compute our histogram. You will see how we prepare and launch the histogram kernel momentarily. For the time being, assume that we have computed the histogram on the GPU. After finishing, we need to copy the histogram back to the CPU, so we allocate a 256-entry array and perform a copy from device to host.


unsigned int histo[256];
checkCudaErrors ( cudaMemcpy( histo, dev_histo,256 * sizeof( int ),
cudaMemcpyDeviceToHost ) );


At this point, we are done with the histogram computation so we can stop our timers and display the elapsed time. Just like the previous event code, this is identical to the timing code we’ve used for several previous articles.


// get stop time, and display the timing results
checkCudaErrors ( cudaEventRecord( stop, 0 ) );
checkCudaErrors ( cudaEventSynchronize( stop ) );
float elapsedTime;
checkCudaErrors ( cudaEventElapsedTime( &elapsedTime,start, stop ) );
printf( "Time to generate: %3.1f ms\n", elapsedTime );



At this point, we could pass the histogram as input to another stage in the algorithm, but since we are not using the histogram for anything else, we will simply verify that the computed GPU histogram matches what we get on the CPU. First, we verify that the histogram sum matches what we expect. This is identical to the CPU code shown here:


long histoCount = 0;
for (int i=0; i<256; i++) {
        histoCount += histo[i];
}
printf( "Histogram Sum: %ld\n", histoCount );


To fully verify the GPU histogram, though, we will use the CPU to compute the
To fully verify the GPU histogram, though, we will use the CPU to compute the same histogram. The obvious way to do this would be to allocate a new histogram array, compute a histogram from the input using the code from Part1 : CPU Histogram Computation, and, finally, ensure that each bin in the GPU and CPU version match. But rather than allocate a new histogram array, we’ll opt to start with the GPU histogram and compute the CPU histogram “in reverse.” By computing the histogram “in reverse,” we mean that rather than starting at zero and incrementing bin values when we see data elements, we will start with the GPU histogram and decrement the bin’s value when the CPU sees data elements. Therefore, the CPU has computed the same histogram as the GPU if and only if every bin has the value zero when we are finished. In some sense, we are computing the difference between these two histograms. The code will look remarkably like the CPU histogram computation but with a decrement operator instead of an increment operator.



long histoCount = 0;
for (int i=0; i<256; i++) {
           histoCount += histo[i];
}
printf( "Histogram Sum: %ld\n", histoCount );


As usual, the finale involves cleaning up our allocated CUDA events, GPU memory, and host memory.


checkCudaErrors ( cudaEventDestroy( start ) );
checkCudaErrors ( cudaEventDestroy( stop ) );
checkCudaErrors ( cudaFree( dev_histo ) ) ;
checkCudaErrors ( cudaFree( dev_buffer ) ) ;
free( buffer );
return 0;
}


Now, be concentrate while reading further;

Before, we assumed that we had launched a kernel that computed our histogram and then pressed on to discuss the aftermath. Our kernel launch is slightly more complicated than usual because of performance concerns. Because the histogram contains 256 bins, using 256 threads per block proves convenient as well as results in high performance. But we have a lot of flexibility in terms of the number of blocks we launch. For example, with 100MB of data, we have 104,857,600 bytes of data. We could launch a single block and have each thread examine 409,600 data elements. Likewise, we could launch 409,600 blocks and have each thread examine a single data element.
As you might have guessed, the optimal solution is at a point between these two extremes. By running some performance experiments, optimal performance is achieved when the number of blocks we launch is exactly twice the number of multiprocessors our GPU contains. For example, a GeForce GTX 280 has 30 multiprocessors, so our histogram kernel happens to run fastest on a GeForce GTX 280 when launched with 60 parallel blocks.

In Querying Device Properties, we discussed a method for querying various properties of the hardware on which our program is running. We will need to use one of these device properties if we intend to dynamically size our launch based on our current hardware platform. To accomplish this, we will use the following code segment. Although you haven’t yet seen the kernel implementation, you should still be able to follow what is going on.





cudaDeviceProp prop;
checkCudaErrors( cudaGetDeviceProperties( &prop, 0 ) );
int blocks = prop.multiProcessorCount;
histo_kernel_optimized <<<blocks*2,256>>>( dev_buffer, SIZE, dev_histo );


Since our walk-through of main() has been somewhat fragmented, here is the entire routine from start to finish:

Histogram.cu


#define SIZE (100*1024*1024) // 100 MB

// Write kernel code here



int main( void ) {
unsigned char *buffer = (unsigned char*)big_random_block( SIZE );

cudaEvent_t start, stop;
checkCudaErrors( cudaEventCreate( &start ) );
checkCudaErrors ( cudaEventCreate( &stop ) );
checkCudaErrors ( cudaEventRecord( start, 0 ) );


// allocate memory on the GPU for the file's data
unsigned char *dev_buffer;
unsigned int *dev_histo;
checkCudaErrors( cudaMalloc( (void**)&dev_buffer, SIZE ) );
checkCudaErrors( cudaMemcpy( dev_buffer, buffer, SIZE,
cudaMemcpyHostToDevice ) );
checkCudaErrors( cudaMalloc( (void**)&dev_histo,256 * sizeof( long ) ) );
checkCudaErrors( cudaMemset( dev_histo, 0,256 * sizeof( int ) ) );

cudaDeviceProp prop;
checkCudaErrors( cudaGetDeviceProperties( &prop, 0 ) );
int blocks = prop.multiProcessorCount;
histo_kernel_optimized <<<blocks*2,256>>>( dev_buffer, SIZE, dev_histo );

unsigned int histo[256];
checkCudaErrors ( cudaMemcpy( histo, dev_histo,256 * sizeof( int ),
cudaMemcpyDeviceToHost ) );

// get stop time, and display the timing results
checkCudaErrors ( cudaEventRecord( stop, 0 ) );
checkCudaErrors ( cudaEventSynchronize( stop ) );
float elapsedTime;
checkCudaErrors ( cudaEventElapsedTime( &elapsedTime,start, stop ) );
printf( "Time to generate: %3.1f ms\n", elapsedTime );

// verify that we have the same counts via CPU

long histoCount = 0;
for (int i=0; i<256; i++) {
           histoCount += histo[i];
}
printf( "Histogram Sum: %ld\n", histoCount );

// verify that we have the same counts via CPU
for (int i=0; i<SIZE; i++)
histo[buffer[i]]--;
for (int i=0; i<256; i++) {
if (histo[i] != 0)
printf( "Failure at %d!\n", i );
}


checkCudaErrors ( cudaEventDestroy( start ) );
checkCudaErrors ( cudaEventDestroy( stop ) );
checkCudaErrors ( cudaFree( dev_histo ) ) ;
checkCudaErrors ( cudaFree( dev_buffer ) ) ;
free( buffer );
return 0;
}



Optimization step 3
HISTOGRAM KERNEL USING GLOBAL MEMORY ATOMICS

And now for the fun part: the GPU code that computes the histogram! The kernel that computes the histogram itself needs to be given a pointer to the input data array, the length of the input array, and a pointer to the output histogram. The first thing our kernel needs to compute is a linearized offset into the input data array. Each thread will start with an offset between 0 and the number of threads minus 1. It will then stride by the total number of threads that have been launched. We hope you remember this technique; we used the same logic to add vectors of arbitrary length.




__global__ void
histo_kernel_optimized4( unsigned char *buffer,
long size,
unsigned int *histo ) {
int i = threadIdx.x + blockIdx.x * blockDim.x;
int stride = blockDim.x * gridDim.x;


Once each thread knows its starting offset i and the stride it should use, the code walks through the input array incrementing the corresponding histogram bin.


while (i < size)
{
          atomicAdd( &(histo[buffer[i]]), 1 );
              i += stride;
}

}

The highlighted line represents the way we use atomic operations in CUDA C. The call atomicAdd( addr, y ); generates an atomic sequence of operations that read the value at address addr, adds y to that value, and stores the result back to the memory address addr. The hardware guarantees us that no other thread can read or write the value at address addr while we perform these operations, thus ensuring predictable results. In our example, the address in
question is the location of the histogram bin that corresponds to the current byte. If the current byte is buffer[i], just like we saw in the CPU version, the corresponding histogram bin is histo[buffer[i]]. The atomic operation needs the address of this bin, so the first argument is therefore &(histo[buffer[i]]). Since we simply want to increment the value in that bin by one, the second argument is 1.

So after that entire hullabaloo, our GPU histogram computation is fairly similar to the corresponding CPU version.



__global__ void
histo_kernel_optimized4( unsigned char *buffer,
long size,
unsigned int *histo ) {
int i = threadIdx.x + blockIdx.x * blockDim.x;
int stride = blockDim.x * gridDim.x;
  while (i < size)
  {
          atomicAdd( &(histo[buffer[i]]), 1 );
              i += stride;
  }

}


However, we need to save the celebrations for later. After running this example, we discover that a GeForce GTX 285 can construct a histogram from 100MB of input data in 1.752 seconds. If you read the section on CPU-based histograms (Part1), you will realize that this performance is terrible. In fact, this is more than four times slower than the CPU version! But this is why we always measure our baseline performance. It would be a shame to settle for such a low-performance implementation simply because it runs on the GPU.

Since we do very little work in the kernel, it is quite likely that the atomic operation on global memory is causing the problem. Essentially, when thousands of threads are trying to access a handful of memory locations, a great deal of contention for our 256 histogram bins can occur. To ensure atomicity of the increment operations, the hardware needs to serialize operations to the same memory location. This can result in a long queue of pending operations, and any performance gain we might have had will vanish. We will need to improve the algorithm itself in order to recover this performance.

Happy to read Further Part3
Become a contributor to this blog. Click on contact us tab
Blogger Template by Clairvo