Article

GPU-Architecture

#GPU#CUDA
On this page 17

GPU Architecture

0. Introduction

Deep learning drove a rapid advance in AI. Training and inference involve large numbers of vector operations, expressed as matrix operations that need substantial parallel compute. This gave GPUs, originally designed for graphics rendering, a new role.

NVIDIA’s CUDA is a mature and widely used platform for AI programming. I’ll use Hopper and Blackwell as examples.

0.1 thread

First, what is a thread?

A thread is a fundamental abstraction. Logically, it is a small unit of program execution. Physically, it is an independent execution context.

Thread Context={RegistersPC (Program Counter)Predicate / Execution State\text{Thread Context} = \begin{cases} \text{Registers}\\ \text{PC (Program Counter)}\\ \text{Predicate / Execution State} \end{cases}

A single CPU core uses its program counter to execute a thread and switches contexts as needed. On a multicore CPU, each core keeps track of its own program counter.

GPU execution resources are more specialized. Compute and control are handled by separate units, with thread and warp control state tracking the threads in flight. The implementation details are not public.

1. Hardware Architecture

NVIDIA GPUs are widely used for programming through the CUDA ecosystem.

Designs vary by generation. See this history of NVIDIA Tensor Core architecture for more detail.

This post focuses on Hopper and Blackwell.

Hardware Hierarchy

The diagram shows the hardware organization of Blackwell, introduced in 2024. Blackwell hardware organization

From largest to smallest, the hierarchy is:

GPU -> GPC (Graphics Processing Cluster) 
    -> TPC (Texture Processing Cluster)
    -> SM  (Streaming Multiprocessor)

The streaming multiprocessor (SM) is a central building block of a GPU. In the diagram, each SM has four subpartitions (SMSPs), each containing:

  • Control units
    • Warp scheduler: selects a warp based on priority and operand readiness.
    • Dispatch unit: sends instructions to the appropriate execution unit.
  • Execution units
    • CUDA cores: execute basic scalar operations.
    • Tensor Core: performs a small matrix multiply-accumulate (MMA) in one instruction.
    • SFU (Special Function Unit): evaluates certain nonlinear math functions.
    • LD/ST: moves data to and from memory or cache.
  • Cache resources
    • L0 Instruction cache
  • Storage resources
    • Register

Outside the SMSPs, the SM also has a TMA and L1 cache / shared memory.

The Tensor Memory Accelerator (TMA) transfers large blocks of data between global and shared memory.

Blackwell adds TMEM (Tensor Memory) to this picture.

SM Diagrams

Hopper

hopper-SM

Blackwell

Blackwell-Ultra-SM-architecture

The subpartitions in an SM share these resources:

  • Share Memory
  • L1 cache
  • L1 Instruction Cache
  • Texture Unit
  • (TMEM)

The memory section below covers the cache and storage in more detail.

The hardware follows SIMT, or single instruction, multiple threads.

A single instruction operates on multiple threads at once.


2. Programming Model

As AI workloads grew, GPUs added Tensor Cores to accelerate matrix operations. Here I’ll look at the model from the CUDA source code level. I may cover compilation separately.


CUDA language basics

This section introduces a few basics. Later sections add more detail.

CUDA C++ extends C++ with keywords that specify where a function executes and where it can be called from.

DeclarationRuns onCalled fromPurpose
__host__CPUCPUOrdinary CPU function
__device__GPUGPUGPU helper function
__global__GPUUsually launched from the CPUGPU kernel entry point
__host__ __device__CPU / GPUCPU / GPUCompiles a version for each target

These are called execution space specifiers.

For example, use __global__ to declare a kernel:

__global__
void my_kernel(const float* A, float* B, int N) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;

    if (i < N) {
        B[i] = transform(A[i]);
    }

The next section explains the indices.

The CPU launches the kernel like this:

int main(){
    // Assume d_A and d_B already point to allocated GPU memory.
    int N = 1024;

    my_kernel<<<4, 256>>>(d_A, d_B, N);

    cudaDeviceSynchronize();
}

CUDA is thread-centric. The kernel body describes what a single thread does, and the <<<grid, block>>> launch syntax sets the number of blocks and the number of threads per block.


Programming CUDA Cores

A CUDA core is a small execution unit that performs scalar operations.

A programming model lets many of these units work together on an operation such as matrix multiplication.

The programming model has this hierarchy:

Grid -> Block -> Warp -> Thread
  • Thread: the basic unit of execution. Threads run the same function on different data.
  • Warp:
    • 1 Warp = 32 Thread
    • A warp is the smallest scheduling unit.
    • Threads in a warp issue the same instruction together. Divergent branches can reduce efficiency.
  • Block:
    • A block contains multiple threads.
    • It can be one-, two-, or three-dimensional.
    • Threads in a block:
      • Share block-local shared memory and use the same SM’s L1 cache.
  • Grid:
    • A grid contains multiple blocks.
    • Different blocks in a conventional grid:
      • Cannot directly synchronize with each other.
      • Have separate shared memory.

image-20260929104242213

The figure shows a grid of 2×3=62\times3=6 blocks. Each block has blockDim.x = 16 and blockDim.y = 4.

The hardware schedules threads by their linear indices. Here, the thread at row 1, column 14 has index 1×16+14=301\times16+14=30. Each warp groups 32 consecutive linear indices.

Why give a block two dimensions if the hardware uses linear indices?

A two-dimensional block reads more naturally and maps directly to a matrix. With a one-dimensional block, code that writes image[row][col] = ...; may have to recover coordinates using expressions such as row = tid / N. Integer division and modulo can be relatively expensive.


This figure maps the programming model to the hardware. Mapping the CUDA programming model to hardware

The GPU executes a grid. Blocks are assigned to SMs, and a block’s warps are assigned to the SM’s subpartitions. CUDA cores execute the scalar instructions for individual threads.

The hardware maps blocks to SMs and warps to SMSPs.

CUDA programmers control grid size, block size, and resource use.

An SM can run multiple blocks to increase throughput. Each block receives resources such as registers and shared memory, as described in Memory Design. Each SMSP schedules multiple resident warps.

A warp may stall while waiting for data from global memory. The SMSP can issue work from another resident warp that is ready, hiding some of the memory latency.

In the SIMT model, each thread has its own registers, and active lanes in a warp execute the issued instruction together.


Matrix multiplication gives a simple example of parallel programming.

C=A×BC = A \times B

// Three nested loops on the CPU
for (int i = 0; i < M; i++)
  for (int j = 0; j < N; j++)
    for (int k = 0; k < K; k++)
      C[i][j] += A[i][k] * B[k][j];

A possible division of work is:

  • One thread computes one element of C.
  • One block computes one output tile.
  • The grid covers the entire output matrix.

Divide the M×NM\times N output matrix into tiles and compute those tiles in parallel.

Suppose a block has 16×1616\times16 threads, or eight warps, and is assigned an 8×88\times8 output tile for this example. Covering the output requires ⌈M/8⌉×⌈N/8⌉\lceil M/8\rceil \times \lceil N/8\rceil blocks in the grid.

To compute a thread’s coordinates in the output matrix, combine its block index in the grid with its thread index within the block.

row = blockIdx.y * blockDim.y + threadIdx.y
col = blockIdx.x * blockDim.x + threadIdx.x

The hardware assigns blocks to SMs. Each warp executes the same kernel code.

float sum = 0.0f;

for (int k = 0; k < K; k++) {
    sum += A[row * K + k] * B[k * N + col];
}

C[row * N + col] = sum;

This pattern is called SPMD, or single program, multiple data.

One program processes different pieces of data in parallel.

Here is the complete kernel:

// Kernel executed on the GPU
__global__ void matmul(
    const float* A,
    const float* B,
    float* C,
    int M, int N, int K
) {
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;

    if (row >= M || col >= N) return;

    float sum = 0.0f;

    for (int k = 0; k < K; k++) {
        sum += A[row*K+k] * B[k*N+col];
    }

    C[row*N+col] = sum;
}

The CPU launches the kernel:

dim3 block(16, 16);
dim3 grid(
    (N + 15) / 16,
    (M + 15) / 16
);

matmul<<<grid, block>>>(A, B, C, M, N, K);

The programmer specifies what one thread does. CUDA launches many thread instances, and the GPU executes them in warps.


Programming Tensor Cores

The WMMA interface operates at warp granularity.

In a cycle when a warp scheduler issues an instruction, it picks an eligible warp in its subpartition.

The programming interface lets the warp invoke the matrix operation as a group.

Start with a block of 256 threads, or 25632=8\frac{256}{32}=8 warps. In the simple CUDA core example, those threads cover 256 output elements.

With the same eight warps using Tensor Cores, each warp can work on a 16×1616\times16 output tile. Together they cover 8×16×16=20488\times16\times16=2048 elements, eight times as many output elements per block in this example.

The naive CUDA core kernel assigns one output element to each thread. The Tensor Core version assigns an output tile to each warp.

Since CUDA expresses the kernel per thread, each thread has to figure out which warp it belongs to.

tile-warp

// Warp arrangement within a block: 4 rows × 2 columns = 8 warps
#define WARPS_PER_BLOCK_M 4
#define WARPS_PER_BLOCK_N 2
#define WARPS_PER_BLOCK  (WARPS_PER_BLOCK_M * WARPS_PER_BLOCK_N)

// Output region covered by each block
#define BLOCK_TILE_M  (WARPS_PER_BLOCK_M * WMMA_M)  // 64
#define BLOCK_TILE_N  (WARPS_PER_BLOCK_N * WMMA_N)  // 32

// Threads per block: 8 warps × 32 threads = 256
#define THREADS_PER_BLOCK (WARPS_PER_BLOCK * 32)

// Eight warps per block
int warp_id = threadIdx.x / 32;

// Arrange the eight warps in four rows and two columns
int warp_m = warp_id / WARPS_PER_BLOCK_N;
int warp_n = warp_id % WARPS_PER_BLOCK_N;

// Top-left corner of the current warp's output tile
int row = blockIdx.y * BLOCK_TILE_M + warp_m * 16;
int col = blockIdx.x * BLOCK_TILE_N + warp_n * 16;

We now know the thread’s warp and the top-left coordinates of its output tile.

The actual Tensor Core computation appears in the next example.

Ordinary scalar arithmetic typically runs on CUDA cores.

The WMMA operations here use Tensor Cores.

Here is how the WMMA interface works.

WMMA
Full nameWarp Matrix Multiply-Accumulate
InterfaceHigh-level CUDA C++ API
HardwareTensor Core
ExecutionOne warp of 32 threads works together
Data layoutManaged by the compiler
Typical callwmma::mma_sync(...)

The WMMA API supports fixed MMA shapes. Examples for (M, N, K) are (16,16,16), (32,8,16), and (8,32,16).

WMMA represents a logical matrix as a fragment distributed across the threads of a warp. The interface works with fragments instead of plain C++ two-dimensional arrays.

wamma-pipe

Include <mma.h> to use the API in the nvcuda::wmma namespace.

APIPurpose
wmma::fragmentDeclare a distributed matrix fragment
wmma::fill_fragmentInitialize a fragment
wmma::load_matrix_syncLoad a matrix tile from memory into a fragment
wmma::mma_syncPerform matrix multiply-accumulate
wmma::store_matrix_syncWrite the fragment back to memory

Here is the complete kernel. It calculates the warp ID, finds the output tile, and then loads, computes, and stores the fragments.

#include <cuda_fp16.h>
#include <mma.h>

using namespace nvcuda;

__global__ void wmma_gemm(
    const half* A,
    const half* B,
    float* C
) {
    // 1. Identify the warp
    int warp_id = threadIdx.x / 32;
    int warps_per_block = blockDim.x / 32;

    int global_warp_id =
        blockIdx.x * warps_per_block + warp_id;

    // 2. Find the warp's output tile
    int warp_row = global_warp_id / 4;
    int warp_col = global_warp_id % 4;

    int row = warp_row * 16;
    int col = warp_col * 16;

    // 3. Declare the fragments
    wmma::fragment<
        wmma::matrix_a, 16, 16, 16,
        half, wmma::row_major
    > a_frag;

    wmma::fragment<
        wmma::matrix_b, 16, 16, 16,
        half, wmma::row_major
    > b_frag;

    wmma::fragment<
        wmma::accumulator, 16, 16, 16,
        float
    > c_frag;

    wmma::fill_fragment(c_frag, 0.0f);

    // 4. Load the current warp's A and B tiles
    // A: [64, 16], leading dimension = 16
    // B: [16, 64], leading dimension = 64
    wmma::load_matrix_sync(
        a_frag, A + row * 16, 16
    );

    wmma::load_matrix_sync(
        b_frag, B + col, 64
    );

    // 5. Perform matrix multiplication
    wmma::mma_sync(
        c_frag, a_frag, b_frag, c_frag
    );

    // 6. Store the output in C: [64, 64]
    wmma::store_matrix_sync(
        C + row * 64 + col,
        c_frag, 64, wmma::mem_row_major
    );
}

In the CUDA source, all 32 threads in a warp execute the kernel and each has its own fragment variable. The compiler organizes the WMMA operations into a warp-wide computation. All threads in the warp must call mma_sync together. Otherwise, behavior is undefined.


3. Memory Design

mem

This figure shows the GPU memory architecture.

Host (CPU DRAM)
        ↓ PCIe / NVLink
Global Memory (HBM / GDDR)
        ↓
L2 Cache (Chip-wide)
        ↓
Within an SM:
    ├─ L1 Cache
    ├─ Shared Memory
    ├─ Register File

Inside an SM

Register (SRAM)

Registers are private to a thread and offer the fastest access. Each register is 32 bits, or four bytes.

256KiB / 32bit = 65536

When a block is assigned to an SM, its threads reserve registers from the register file according to the kernel’s compiled resource requirements.

GPUs need large register files because they keep many threads resident. The hardware limit can be up to 2,048 threads on an SM, depending on the architecture. A kernel’s register usage affects how many threads can be resident at once.

Registers also make it cheap to switch between ready warps and hide data transfer latency. Keeping each resident warp’s state on chip lets the GPU switch issue slots without saving and restoring the warp’s state in memory.

eligible-warps

Each SMSP has its own warp scheduler. It can manage multiple resident warps and typically issues from one eligible warp per cycle.

If a warp stalls on a dependency on global memory, the scheduler can issue from a different ready warp. The register state for both warps is already resident.

The GPU trades on-chip resources such as registers for low-overhead scheduling and latency hiding, improving throughput.

Shared Memory (SRAM)

  • Shared by threads in the same block.
  • Managed explicitly by the programmer.
  • Can be accessed concurrently.

The physical address space is striped across 32 banks, each with a four-byte word width. A stripe spanning all banks holds 4×324\times32 bytes.

Because shared memory is explicitly allocated, it behaves much like an array.

L1 Cache (SRAM)

Local to an SM and automatically caches accesses to global memory.

Shares physical SRAM with shared memory.

Like a CPU cache, L1 organizes data into cache lines. A line is 128 bytes. Cache organization and replacement policies are outside the scope of this post.

The diagram shows how the hardware divides the available SRAM between the two.

SRAM

Shared memory has 32 banks, each with many four-byte words. The mapping is Bank ID=⌊Address4⌋ mod 32\text{Bank ID}=\left\lfloor\frac{\text{Address}}{4}\right\rfloor\bmod32.

L1 has many cache lines, each with four sectors: 1 Cache Line=128 B=4×32 B Sectors1\text{ Cache Line}=128\text{ B}=4\times32\text{ B Sectors}.

The partition is adjustable. More shared memory leaves less SRAM for L1.

The CUDA runtime and the GPU determine the split based on kernel requirements and configuration. Programmers can also specify preferences.

L2 Cache (SRAM)

L2 is shared across the chip and reduces accesses to off-chip memory.

Global Memory

Off-chip HBM or GDDR has relatively high latency.

TMEM

TMEM stands for Tensor Memory. It is dedicated on-chip storage for Blackwell’s fifth-generation Tensor Cores. The data-center SM100 architecture has it, while the consumer SM120 architecture does not.

It supports matrix operations, particularly by holding Tensor Core accumulators so large intermediate matrices do not tie up thread registers.

TMEM is organized as follows:

  • It is dynamically allocated in columns.

  • Each column has 128 32-bit cells.

  • tcgen05.alloc allocates TMEM and tcgen05.dealloc releases it.

  • Special load and store instructions access TMEM and impose specific warp and layout requirements.

TMEM

A GEMM on Blackwell can use the following data path:

Global Memory→TMAShared MemoryShared Memory→tcgen05.mmaTensor Core computationAccumulator⟶TMEMTMEM→tcgen05.ldRegisters⟶Output\begin{aligned} &\text{Global Memory} \xrightarrow{\text{TMA}} \text{Shared Memory}\\ &\text{Shared Memory} \xrightarrow{\text{tcgen05.mma}} \text{Tensor Core computation}\\ &\text{Accumulator}\longrightarrow\text{TMEM}\\ &\text{TMEM}\xrightarrow{\text{tcgen05.ld}} \text{Registers} \longrightarrow\text{Output} \end{aligned}


CUDA Language of Memory

Variable Storage

A variable’s declaration in the kernel determines its storage space, subject to compiler decisions about registers and local memory.

CodeStorageVisibility
float x;Usually a registerCurrent thread
float arr[100];Registers or local memory, depending on compilationCurrent thread
__shared__ float buf[256];Shared memoryCurrent block
__device__ float x; (outside a function)Global memoryGPU threads
__constant__ float c[256];Constant memoryGPU threads

For example, here is a kernel that adds data from a neighboring thread.

__global__ void neighbor_sum(
    const float* A,
    float* C,
    int N
) {
    __shared__ float tile[256];

    int tid = threadIdx.x; // Assume a one-dimensional block.
    int i = blockIdx.x * blockDim.x + tid;

    // Global Memory → Shared Memory
    tile[tid] = (i < N) ? A[i] : 0.0f;

    // Wait for all threads in the block to finish writing.
    __syncthreads();

    if (i < N) {
        float right = 0.0f;

        if (tid + 1 < blockDim.x && i + 1 < N) {
            right = tile[tid + 1];
        }

        C[i] = tile[tid] + right;
    }
}

Managing GPU Memory

A kernel can take scalars or pointers. A pointer generally has to reference memory that the GPU can access.

CUDA provides these APIs to manage device memory:

APIPurpose
cudaMallocAllocate device global memory
cudaMemcpyCopy data between memory spaces, such as host and device
cudaMemsetInitialize device memory byte values
cudaFreeFree device memory
cudaMallocManagedAllocate managed memory accessible by both the CPU and GPU

Example

Suppose we want to add two vectors, C[i]=A[i]+B[i]C[i]=A[i]+B[i].

First, define the kernel:

__global__ void vector_add(
    const float* A,
    const float* B,
    float* C,
    int N
) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;

    if (i < N) {
        C[i] = A[i] + B[i];
    }
}

Then prepare the data on the host and launch the kernel:

#include <cuda_runtime.h>
#include <iostream>
#include <vector>

// Assume vector_add was defined above.

int main() {
    int N = 1024;
    size_t bytes = N * sizeof(float);

    // 1. Host memory
    std::vector<float> A(N, 1.0f);
    std::vector<float> B(N, 2.0f);
    std::vector<float> C(N);

    // 2. Allocate GPU memory
    float *d_A, *d_B, *d_C;

    cudaMalloc(&d_A, bytes);
    cudaMalloc(&d_B, bytes);
    cudaMalloc(&d_C, bytes);

    // 3. Host → Device
    cudaMemcpy(d_A, A.data(), bytes,
               cudaMemcpyHostToDevice);
    cudaMemcpy(d_B, B.data(), bytes,
               cudaMemcpyHostToDevice);

    // 4. Launch Kernel
    int threads = 256;
    int blocks = (N + threads - 1) / threads;

    vector_add<<<blocks, threads>>>(
        d_A, d_B, d_C, N
    );

    // 5. Wait for computation to finish
    cudaDeviceSynchronize();

    // 6. Device → Host
    cudaMemcpy(C.data(), d_C, bytes,
               cudaMemcpyDeviceToHost);

    std::cout << C[0] << std::endl;  // 3.0

    // 7. Free memory
    cudaFree(d_A);
    cudaFree(d_B);
    cudaFree(d_C);
}

TMA usage

Before TMA, a conventional copy from HBM to shared memory had threads compute addresses and issue load and store instructions for their parts of the data.

Warp scheduling can hide some of that latency. The instructions still consume scheduling, register, and memory resources.

TMA lets a small number of threads initiate large transfers. Dedicated hardware performs the transfer asynchronously, reducing the instructions and registers used for copying.

Modes

TMA supports two common modes:

ModeDescriptionRequires a tensor descriptor
1D Bulk CopyCopies a contiguous regionNo
Multi-dimensional Tensor CopyCopies a multidimensional tile using its tensor layoutYes
Required Components

The code uses a tensor descriptor for multidimensional copies, a copy instruction, and an MBarrier.

An MBarrier is a hardware-backed synchronization object. It tracks thread arrivals and asynchronous work.

Pending Arrivals\text{Pending Arrivals} counts the participants that have yet to arrive in the current phase. Pending Transactions\text{Pending Transactions} tracks outstanding asynchronous transfer work.

api

CUDA exposes the following interfaces:

InterfaceHow TMA is selected
Ordinary A[i] / tile[i] accessDoes not automatically use TMA
cuda::memcpy_asyncThe compiler can choose TMA or another implementation when the conditions allow
cuda::device::memcpy_async_txExplicitly uses the TMA path
cuda::ptx::cp_async_bulk_tensorExplicitly issues a tensor-map TMA operation
Example

This example uses TMA in a kernel that doubles values:

#include <cuda_runtime.h>
#include <cuda/barrier>
#include <cuda/std/utility>

using barrier_t =
    cuda::barrier<cuda::thread_scope_block>;

__global__ void tma_double(
    const int* A,
    int* C
) {
    constexpr int TILE_SIZE = 1024;
    constexpr size_t BYTES =
        TILE_SIZE * sizeof(int);

    int tid = threadIdx.x;
    int offset = blockIdx.x * TILE_SIZE;

    // Shared Memory:4096 Byte
    __shared__ alignas(16) int tile[TILE_SIZE];

    // MBarrier: all threads in the block participate.
    #pragma nv_diag_suppress static_var_with_dynamic_init
    __shared__ barrier_t bar;

    // 1. Initialize the barrier.
    if (tid == 0) {
        init(&bar, blockDim.x);
    }
    __syncthreads();

    // 2. One thread explicitly starts the TMA transfer.
    if (tid == 0) {
        cuda::device::memcpy_async_tx(
            tile,
            A + offset,
            cuda::aligned_size_t<16>(BYTES),
            bar
        );

        // Record the number of bytes expected in this phase.
        cuda::device::barrier_expect_tx(
            cuda::device::barrier_native_handle(bar),
            BYTES
        );
    }

    // 3. All threads arrive and wait for TMA to complete.
    auto token = bar.arrive();
    bar.wait(cuda::std::move(token));

    // 4. Read the data now available in shared memory.
    for (int i = tid; i < TILE_SIZE; i += blockDim.x) {
        C[offset + i] = tile[i] * 2;
    }
}

This example uses a one-dimensional transfer over a contiguous memory region.

A multidimensional TMA transfer uses a tensor descriptor, as in this example:

Tensor Descriptor

Global Address:    d_A
Element Type:      FP16
Tensor Shape:      [1024, 1024]
Row Stride:        2048 Bytes
Tile Shape:        [64, 64]
Swizzle:           None

Reference