Understanding the basics of CUDA Thread Hierarchies

In this post, I would like to explain a basic but confusing concept of CUDA programming: Thread Hierarchies. It will not be an exhaustive reference. We will not cover all aspects, but it could be a nice first step.

If you are starting with CUDA and want to know how to setup your environment, using VS2017, I recommend you to read this post.

From CPU to GPU

To get started, let’s write something straightforward to run on the CPU.

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <cstdio>

void printHelloCPU()
{
	printf("Hello World from the CPU");
}

int main()
{
	printHelloCPU();
	getchar();
	return 0;
}

Now, let’s change this code to run on the GPU.

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <cstdio>

__global__ void printHelloGPU()
{
	printf("Hello World from the GPU\n");
}

int main()
{
	printHelloGPU<<<1, 1>>>();
	cudaDeviceSynchronize();
	
	getchar();
	return 0;
}

The cudaDeviceSyncronize function determines that all the processing on the GPU must be done before continuing.

Let’s remember some concepts we learned in a previous post:

  • The __global__ keyword indicates that the following function will run on the GPU.
  • The code executed on the CPU is referred to as host code, and code executed on the GPU is referred to as device code.
  • It is required that functions defined with the __global__ keyword return type void.
  • When calling a function to run on the GPU, we call this function a kernel (In the example, printHelloGPU is the kernel).
  • When launching a kernel, we must provide an execution configuration, which is done by using the <<< ... >>> syntax.

The Execution Configuration

At a high level, the execution configuration allows programmers to specify the thread hierarchy for a kernel launch, which defines the number of thread blocks, as well as
how many threads to execute in each block.

Notice, in the previous example, the kernel is launching with 1 block of threads (the first execution configuration argument) which contains 1 thread (the second configuration argument).

The execution configuration allows programmers to specify details about launching the kernel to run in parallel on multiple GPU threads. The syntax for this is:

<<< NUMBER_OF_BLOCKS, NUMBER_OF_THREADS_PER_BLOCK>>>

A kernel is executed once for every thread in every thread block configured when the kernel is launched.

Thus, under the assumption that a kernel called printHelloGPU has been defined, the following are true:

  • printHelloGPU<<<1, 1>>>() is configured to run in a single thread block which has a single thread and will, therefore, run only once.
  • printHelloGPU<<<1, 5>>>() is configured to run in a single thread block which has 5 threads and will, therefore, run 5 times.
  • printHelloGPU<<<5, 1>>>() is configured to run in 5 thread blocks which each have a single thread and will, therefore, run five times.
  • printHelloGPU<<<5, 5>>>() is configured to run in 5 thread blocks which each have five threads and will, therefore, run 25 times.

Let me try to explain this graphically:

In the drawing, each blue rectangle represents a thread. Each gray rectangle represents a block.The green rectangle represents the grid.

Thread Hierarchy Variables

In the kernel’s code, we can access variables provided by CUDA. These variables describe the thread, thread block, and grid.

gridDim.x is the number of the blocks in the grids.

blockIdx.x is the index of the current block within the grid.

blockDim.x is the number of threads in the block. All blocks in a grid contain the same number of threads.

threadIdx.x is index of the thread within a block (starting at 0).

X… Y, and Z

As you noted, we have been using the suffix .x for all variables. But, we could use, .y and .z as well.

The CUDA threads hierarchy can be 3-dimensional.

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <cstdio>


__global__ void printHelloGPU()
{
	printf("Hello x: #%d  y: #%d\n", threadIdx.x, threadIdx.y);
}

int main()
{
	dim3 threads(3, 3);
	printHelloGPU<<<1, threads>>>();
	cudaDeviceSynchronize();
	
	getchar();
	return 0;
}

We can use the dim3 structure to specify dimensions for blocks and threads. In the example, we specified we are creating a 2-dimensional structure (3x3x1).

Deciding what execution configuration to use

Consider:

  • printHelloGPU<<<1, 25>>>() is configured to run in a single thread block which has 25 threads and will, therefore, run 25 times.
  • printHelloGPU<<<1, dim3(5, 5)>>>() is configured to run in a single thread block which has 25 threads and will, therefore, run 25 times.
  • printHelloGPU<<<5, 5>>>() is configured to run in 5 thread blocks which each has 5 threads and will therefore run 25 times.

So, what configuration is right? Answer: All choices are valid. What should you use? It depends.

As you know, each thread will run the kernel once. If you are working on some data in memory, you should use the configuration that makes easier to address the data, using the thread hierarchy variables. Also, your graphics card has limitations that you need to consider.

Conclusions

If you are like me, you will need some time to understand Thread Hierarchies. In future posts, I will start to share some practical examples that can make it simpler.

For a while, feel free to comment this post.

Cover: Ilze Lucero

Compartilhe este insight:

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

“Microsserviços” é um trending topic. Grandes empresas estão tentando associar suas tecnologias com este conceito. Entretanto, é importante que se...
O banco onde sou correntista está demorando mais para processar recebimentos do que o usual. Ao conversar com meu gerente,...
Recebi um bocado de feedback positivo para minhas palestras no Devxperience deste ano. Muita gente mandou e-mails solicitando, principalmente, os...
For years, I have known developers who designed beautiful architectures. A lot of them are questioning the need for a...
Nesses últimos tempos, com a pandemia, inaugurei novos hábitos e aposentei outros. Estou trabalhando muito mais, mas também, agora que...
Há, muito, muito tempo atrás Em 2002, conheci o projeto SharpDevelop – uma ousada tentativa de criar, do zero, em...

Curso Reputação e Marketing Pessoal

Masterclasses

01

Introdução do curso

02

Por que sua “reputação” é importante?

03

Como você se apresenta?

04

Como você apresenta suas ideias?

05

Como usar Storytelling?

06

Você tem uma dor? Eu tenho o alívio!

07

Escrita efetiva para não escritores

08

Como aumentar (e manter) sua audiência?

09

Gatilhos! Gatilhos!

10

Triple Threat: Domine Produto, Embalagem e Distribuição

11

Estratégias Vencedoras: Desbloqueie o Poder da Teoria dos Jogos

12

Análise SWOT de sua marca pessoal

13

Soterrado por informações? Aprenda a fazer gestão do conhecimento pessoal, do jeito certo

14

Vendo além do óbvio com a Pentad de Burkle

15

Construindo Reputação através de Métricas: A Arte de Alinhar Expectativas com Lag e Lead Measures

16

A Tríade da Liderança: Navegando entre Líder, Liderado e Contexto no Mundo do Marketing Pessoal

17

Análise PESTEL para Marketing Pessoal

18

Canvas de Proposta de Valor para Marca Pessoal

19

Método OKR para Objetivos Pessoais

20

Análise de Competências de Gallup

21

Feedback 360 Graus para Autoavaliação

22

Modelo de Cinco Forças de Porter

23

Estratégia Blue Ocean para Diferenciação Pessoal

24

Análise de Tendências para Previsão de Mercado

25

Design Thinking para Inovação Pessoal

26

Metodologia Agile para Desenvolvimento Pessoal

27

Análise de Redes Sociais para Ampliar Conexões

Lições complementares

28

Apresentando-se do Jeito Certo

29

O mercado remunera raridade? Como evidenciar a sua?

30

O que pode estar te impedindo de ter sucesso

Recomendações de Leituras

31

Aprendendo a qualificar sua reputação do jeito certo

32

Quem é você?

33

Qual a sua “IDEIA”?

34

StoryTelling

35

Você tem uma dor? Eu tenho o alívio!

36

Escrita efetiva para não escritores

37

Gatilhos!

38

Triple Threat: Domine Produto, Embalagem e Distribuição

39

Estratégias Vencedoras: Desbloqueie o Poder da Teoria do Jogos

40

Análise SWOT de sua marca pessoal

Inscrição realizada com sucesso!

No dia da masterclass você receberá um e-mail com um link para acompanhar a aula ao vivo. Até lá!

A sua subscrição foi enviada com sucesso!

Aguarde, em breve entraremos em contato com você para lhe fornecer mais informações sobre como participar da mentoria.

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano anual do Clube de Estudos:

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano mensal do Clube de Estudos:

× Precisa de ajuda?