O núcleo ingênuo de multiplicação de matrizes
Uma referência indexada em duas dimensões e suas limitações.
O núcleo ingênuo de multiplicação de matrizes é uma aula grátis de CUDA Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de CUDA Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de CUDA Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Matrix Multiply, GPU Style
Matrix multiplication is the heart of graphics and AI. Today you build a naive GPU version first, then learn why it leaves speed on the table.
The Math in One Line
Each output cell C[row][col] is a dot product: multiply a full row of A by a full column of B and sum the results. 🧮
C[row][col] = sum over k of A[row][k] * B[k][col]One Thread per Output
The simplest plan gives each thread one output element of C. Thousands of cells get computed at the same time across the GPU.
A 2D Grid of Threads
Since C is a 2D grid, you launch threads in two dimensions. The x index maps to a column and the y index maps to a row.
dim3 threads(16, 16);
dim3 blocks((N+15)/16, (N+15)/16);Finding This Thread's Cell
Inside the kernel, each thread computes its own row and col from its block and thread indices, just like 1D indexing but on both axes.
int row = blockIdx.y*blockDim.y + threadIdx.y;
int col = blockIdx.x*blockDim.x + threadIdx.x;The Bounds Check
Grids round up, so some threads fall outside the matrix. Guard with if (row < N && col < N) before you touch memory.
if (row < N && col < N) {
// safe to compute
}The Inner Loop
Each thread runs a loop over k, accumulating products into a local sum. That local variable lives in a fast register.
float sum = 0.0f;
for (int k = 0; k < N; ++k)
sum += A[row*N+k] * B[k*N+col];Writing the Result
After the loop finishes, the thread stores its accumulated sum into C exactly once. One thread, one clean write.
C[row*N + col] = sum;Row-Major Flattening
The matrix is a flat 1D array, so you index it as row*N + col. Getting this layout right is half the battle in matmul.
Why It Works, But Slowly
This kernel is correct and easy to read, but every thread reads its row and column straight from global memory, the slowest space.
The Hidden Cost
Neighboring threads re-read the same A rows and B columns over and over. That wasted memory traffic is exactly what tiling will fix next.
Quick Check
Think about how the naive kernel maps work to threads.
Recap
You mapped one thread to one output cell, looped over k from global memory, and saw the redundant reads. Next you cut that traffic with tiling. 🚀
Perguntas Frequentes
A aula “O núcleo ingênuo de multiplicação de matrizes” é grátis?
Sim — o texto completo de “O núcleo ingênuo de multiplicação de matrizes” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de CUDA Academy, atualize para CoddyKit PRO. O curso de CUDA Academy inclui 4 aulas no total.
O que vou aprender em “O núcleo ingênuo de multiplicação de matrizes”?
Uma referência indexada em duas dimensões e suas limitações. Você pratica CUDA Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar CUDA Academy?
Nenhuma experiência prévia é necessária. CUDA Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “O núcleo ingênuo de multiplicação de matrizes”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de CUDA Academy?
Sim. Cada aula de CUDA Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- O núcleo ingênuo de multiplicação de matrizes
- Divida o produto interno em blocos
- Percorra as fases dos blocos
- Meça o ganho de velocidade