Grids, threads… THE ULTIMATE GUIDE


So most users struggle a lot with this topic, on CUDA is important to make a good use of how many grids and threads we need to use so let’s start:

What are grids blocks and thread blocks?

In CUDA we have to define how our grid is going to be and how many threads are going to be inside a grid.

The kernels are executed in grids just like the following image:

N-1 grids each grid has 256 threads



Identify the dimension of the problem

There are multiple ways to do this, but let’s try to make it simple.

On CUDA or GPU programming in general we have from 1 to 3 dimensions, values different than those will give runtime errors.

So for example, if we have an array, our problem is a one-dimensional problem, a matrix is a two-dimensional problem and a cube/parallelepiped is a three-dimensional problem.

One dimensional problems

These are the easiest ones, we only need to work on the X axis, and basically our problem is reduced to the length of the array.

Let’s say we have an Array with length 1Million:

we have to decide how many grids blocks we want and how many threads per block we want.

First we have to remember, on most devices the maximum threads per block available is 512 or 1024, something bigger than this will give an error.

After deciding the threads per blocks (I’m going to use 1024) the grid is ceil(1M/1024).

Our declaration and call to the kernel will look something like this

dim3 gridBlocks(ceil(1000000/1024),1,1);

dim3 threadsPerBlock(1024,1,1);

kernel<<<gridBlocks, threadsPerBlock>>> (arg1, arg2...);

this seems pretty straight forward, the Y and Z axis is 1 since we are only working on the X axis.


Two dimensional problems

These might be the most common, we need to work on the X and Y axis.

Let us divide this into two examples,

A square and a rectangle, the first being an exclusive case of the second one, when both sides of the rectangle are the same length, is a square (Duh!?).


Let us assume we have a square image with A x A pixels, se we need to create a grid that minimizes the number of threads in order to use them the most efficient way

First we need to set the size of our grid, this is a problem specific matter but we can set some various examples.

For very small values of A (A >8 and A <64):

We can divide the square into 4 sub-squares, for example if A = 16 we have the following layout

16 x 16
2 x 2 grid with 8 x 8 threads per block

So our grid will be 2 x 2 and each grid block will have 8 x 8 threads

We can code that as follow:

dim3 gridBlocks(2,2,1);
dim3 threadsPerBlock(8,8,1);
kernel<<<gridBlocks, threadsPerBlock>>>(arg1, arg2...);


For medium sizes (A>64 and A < 512):

We can divide the square into 16-sub squares

32 x32
4 x 4 grid with 8 x 8 threads per block


This is 32 x 32 I’m using a small grid just for illustration purposes

We can code this as follow

dim3 gridBlocks(4,4,1); // 4 x 4 grid
dim3 threadsPerBlock(8,8,1);// each grid will have 8 x 8 threads
kernel<<<gridBlocks, threadsPerBlock>>>(arg1, arg2...);

This examples are just illustrations, is not by any means a rule, remember the number of grids and threads is a specific matter of the problem itself.


So let us assume we have an image that is shaped like a rectangle with A x B pixels and A != B

Assuming A and B big enough for illustration purposes, I will set two cases, A > B and B > A

A < B:

We get the following layout

4 x 2 grid, each block has 8 x 8 threads

This can be coded as follow

dim3 gridBlocks(4,2,1); // 4 x 2 grid
dim3 threadsPerBlock(8,8,1);// each grid will have 8 x 8 threads
kernel<<<gridBlocks, threadsPerBlock>>>(arg1, arg2...);


A > B:

We get the following layout

2 x 4 grid, each block has 8 x 8 threads

This can be coded as follow

dim3 gridBlocks(2,4,1); // 4 x 2 grid
dim3 threadsPerBlock(8,8,1);// each grid will have 8 x 8 threads
kernel<<<gridBlocks, threadsPerBlock>>>(arg1, arg2...);






My First CUDA Program

So for this post I wanted to show you guys the “Hello World” in CUDA, and no, we are not going to printf(“Hello World “) , we are going to add vectors!, yeah feeling the hype!?

so let’s start:

First, if you are a complete newbie I recommend my previous post First steps on CUDA, get a handle on how I work and then come back.

Since we are all good software developers, let’s define our problem and propose a simple solution in the programming language C.

Our problem in C

We want to do something like C = A+B where A,B,C are vectors, obviously these 3 have the same lenght.


Allocate memory for A, B and C (for simplicity, the lenght of the array is an input parameter, and the type will be float)

        int length;
        float *vA,*vB,*vC;

        if (argc!=2){
	        printf("./exec n \n");
        length = atoi(argv[1]);
        //Allocating memory
        vA = (float*)malloc(sizeof(float)*length);
        vB = (float*)malloc(sizeof(float)*length);
        vC = (float*)malloc(sizeof(float)*length);

Initialize A, B

/* Initialize A and B, A[i] will have it's own index by 2 and B[i] it's own index by 3*/
	for (int i=0;i < length; i++ ){

Make the computation C = A + B

        for (int i=0;i < length ; i++ )
	        vC[i] = vA[i]+ vB[i];

Show result on console

         for (int i=0;i < length; i++ )
	        printf ("C[%i] = %f \n",i,vC[i]);

Free memory


Seems pretty straight forward right? it’s easy to see that the computation of C[i] and C[i+1]  are completely independent, making it perfect to our GPU to make.


Our problem in CUDA

Now the fun part, is pretty similar to the solution in but now we have to add the GPU things ( DUH!).

To make the code more easy to understand, all the host variables will have the prefix h_

and our device variables will have the prefix d_

We need to:

Allocate memory for h_A, h_B and h_C on our Host. These Variables are our vectors

        int length;
        float *h_A,*h_B,*h_C,*d_A,*d_B,*d_C;

        if (argc!=2){
	        printf("./exec n \n");
        n = atoi(argv[1]);

        //Allocating memory
        h_A = (float*)malloc(sizeof(float)*length);
        h_B = (float*)malloc(sizeof(float)*length);
        h_C = (float*)malloc(sizeof(float)*length);

Allocate memory for d_A,d_B and d_C on our Device. These variables are our Vector in the device

        cudaMalloc((void **)&d_A,sizeof(float)*length);
        cudaMalloc((void **)&d_B,sizeof(float)*length);
        cudaMalloc((void **)&d_C,sizeof(float)*length);

Initialize the host vectors h_A and h_B.

         for (int i=0;i < length;i++){

Transfer the memory from  (h_A, h_B) to (d_A,d_B).

      /* CPU to GPU */
        cudaMemcpy(d_A, h_A, sizeof(float)*length, cudaMemcpyHostToDevice);
        cudaMemcpy(d_B, h_B, sizeof(float)*length, cudaMemcpyHostToDevice);	

Initialize grids and threads. Since is a 1D problem we will only work on the X axis making Y =Z=1.

//Each block will have 512 threads and as many blocks as needed
       dim3 dimGrid( ceil(length/512) +1, 1, 1); //	length/512 blocks
       dim3 dimBlock(512, 1, 1);	//512 threads for each block

Implement and call the kernel.

__global__ void addVector(float *d_A, float *d_B, float *d_C,int length )
        int index = blockIdx.x * blockDim.x + threadIdx.x;
        if (index < length)//we need to make sure our threads are within bounds
                d_C[index]= d_A[index]+d_B[index];

//call to the kernel in the main
addVector <<< dimGrid , dimBlock >>> (d_A, d_B,d_C,length);
cudaThreadSynchronize();/*let's make sure all the threads finish here to avoid race conditions.*/

Transfer memory from d_C to h_C.

         cudaMemcpy(h_C, d_C, sizeof(float)*length, cudaMemcpyDeviceToHost);

Show Result on Console.

         for (int i=0; i<length;i++)
                 printf ("C[%i] = %f \n",i,h_C[i]);

Free host and device memories.


also pretty straight forward.

Now… this code shows the result on console, but for extreme large vector  is not helpful at all .

Let’s workThatGPU! by measuring the time with very big vectors. And comparing our CUDA solution to the C solution.

First  vectors with size 4096

CPU Execution time 0.000072 ms.
GPU Execution time 0.000270 ms.

The CPU time is way smaller than the GPU, why? because the cudaMemcpy , actually transferring the memory back and forth takes more time than the actual computation

Vectors size 20000

CPU Execution time 0.000347 ms.
GPU Execution time 0.000471 ms.

very similar times but still the CPU is ahead.

Vectors size 1000000

CPU Execution time 0.015172 ms.
GPU Execution time 0.009702 ms.

Wow, nice! our GPU is 1.66 times faster than our CPU!

Vectors size 700000000!!

CPU Execution time 13.240476 ms.
GPU Execution time 0.035979 ms.

So for this size of vector, our GPU is 378,2 times faster than our CPU!! it makes sense that our GPU works better with very large amount of information but when it’s little, just don’t even bother.