GPU I: architecture and the CUDA programming model
A GPU is not a CPU with many cores: it is a throughput machine hiding latency with thousands of threads. Study SMs, warps and SIMT, CUDA's thread, block and grid hierarchy, the memory hierarchy, coalescing, occupancy, divergence, and CPU–GPU transfers, all measured on the local RTX 4060 Laptop (Ada Lovelace, compute capability 8.9, 8 GB).
After this lesson you can
- Explain SIMT and how a GPU hides memory latency through massive parallelism.
- Write CUDA kernels with Numba CUDA or CuPy assigning threads to data in 1D and 2D.
- Design coalesced accesses and choose between AoS and SoA layouts.
- Reason about occupancy from registers, shared memory and block size.
- Measure memory bandwidth, PCIe transfers, launch overhead and FP32 versus FP64 performance on the RTX 4060.
Before you start
- 09Memory hierarchyRoofline modelArithmetic intensitySIMD vectorizationShared-memory parallelism with OpenMPRace conditions and false sharingMemory microbenchmarks: pointer chasing and STREAMIEEE 754 and deep learning formats
- 00GPU software stackDevice placement and CPU-GPU transfersCUDA asynchronous execution
- 08Parallel reductionParallel prefix scan
Motivation: thousands of threads to hide half a microsecond
Training your own GPT, simulating ten million trajectories of a stochastic process or running AlphaZero self-play are fundamentally the same operation repeated billions of times on different data. On the course CPU (i9-14900HX), the roofline lesson measured about 64 GB/s memory bandwidth and around 160 GFLOP/s in float64 with all cores. The same laptop’s RTX 4060 Laptop GPU has theoretical bandwidth of 256 GB/s, four times more, and achieves several TFLOP/s in float32, tens of times the CPU in float64. But that advantage is not automatic. In this lesson’s lab you will see a vector-summing kernel using 1% of the card’s bandwidth, and in the final exercise write another exceeding 80%; the difference is how threads divide work, not arithmetic.
A GPU is not a CPU with many cores. It follows a different design philosophy: rather than doing one thing very quickly and minimizing memory waits, it does many things at once and hides waiting behind other work. Programming it well requires understanding four mechanisms, each with its own section and interactive:
- The SIMT model: groups of 32 threads (warps) executing the same instruction, and a scheduler switching between warps so arithmetic does not wait for memory.
- The CUDA thread hierarchy (grid, blocks, threads) and memory hierarchy (registers, shared memory, L2, global memory), the contract between your code and hardware.
- Coalescing: memory is served in 32-byte sectors, and a warp requesting 32 scattered numbers pays for 32 sectors.
- Occupancy, divergence and CPU–GPU transfers, which determine whether the thousands of threads actually exist, work at once and get data in time.
Everything is measured on the course GPU. You build on what you know about the CPU’s memory hierarchy, arithmetic intensity, SIMD vectorization and shared-memory parallelism, and tools: the GPU software stack, device placement and CUDA’s asynchronous execution.
CPU versus GPU: latency versus throughput
A CPU core is optimized for single-thread latency: it executes out of order, predicts branches, prefetches loads and devotes much area to caches and control logic so each instruction finishes quickly. A GPU is optimized for aggregate throughput: it devotes almost all silicon to simple arithmetic units, gives up much else and accepts that each individual operation takes a long time provided many are in flight.
The connecting piece is Little’s law, already used for CPU memory hierarchy: at steady state, mean requests in flight equal throughput times the time each spends in the system,
Applied to GPU global memory: if a load takes about 300 ns to return (the lab estimates this with lightly loaded memory from bandwidth achieved by one warp per SM) and you want to sustain GB/s, you need in flight
If each thread has one 4-byte float load in flight, that is 19 200 threads waiting at once, more in practice because requests queue and latency rises as memory nears its limit (in the lab from about 300 ns to over 900). A CPU core keeps on the order of one or two dozen cache misses in flight; the GPU needs thousands of times more. Volkov made the same calculation in 2010 for a GTX 480 (177 GB/s and under 800 cycles latency): about 100 KB had to be in flight, around 25 000 threads with 4-byte loads (Volkov, Better Performance at Lower Occupancy, GTC 2010). The GPU solves this with hardware keeping tens of thousands of threads resident and switching between them at no cost.
| CPU (i9-14900HX, un P-core) | GPU (RTX 4060 Laptop, un SM) | |
|---|---|---|
| Threads held simultaneously | 2 (hyperthreading) | 1536 (48 warps of 32) |
| Registers | 16 vector 256-bit per thread | 65 536 32-bit per SM (256 KiB) |
| Thread switch | OS-managed, microseconds | every cycle, no cost |
| Latency strategy | avoid: caches, prefetch, out of order | hide: another warp works meanwhile |
Notice the registers: an SM has 256 KiB of registers, twice its L1. All resident threads’ state stays on chip, so switching threads is free: nothing needs saving or restoring.
Architecture: SMs, cores, Tensor Cores and schedulers
An NVIDIA GPU chip is a collection of streaming multiprocessors (SMs), connected to a common L2 and global memory through memory controllers. According to the Ada architecture whitepaper, each SM in AD10x chips has 128 CUDA cores, four fourth-generation Tensor Cores, one RT Core, a 256 KB register file and 128 KB of L1 and shared memory. The SM is divided into four partitions (processing blocks), each with:
- a 64 KB register file (16 384 32-bit registers),
- one warp scheduler and a dispatch unit,
- 16 cores performing only FP32 operations and 16 performing FP32 or INT32 (up to 32 FP32 operations per cycle across both groups),
- one Tensor Core, four load/store units and one special-function unit (exponentials, sines, inverse roots).
Additionally, according to a whitepaper note, each SM has only two FP64 units versus 128 FP32 cores: the CUDA programming guide throughput table gives an FP32-to-FP64 ratio of 64 for capability 8.9. NVIDIA did not design these GPUs for double-precision computation; we return to this at the end.
NVIDIA introduced the term with the 2006 Tesla architecture (Lindholm, Nickolls, Oberman and Montrym, 2008). The difference from CPU SIMD is the programming model, not hardware: with SIMD you write an instruction operating on an 8- or 16-lane vector and handle masks and tails yourself; with SIMT you write code for one scalar thread, and hardware groups 32 threads and handles masks when they follow different paths. Underneath, each warp instruction occupies 32 lanes like a vector instruction.
This course’s RTX 4060 Laptop
The lab’s first cell prints your GPU figures with torch.cuda.get_device_properties. On this laptop:
| Property | RTX 4060 Laptop | Source |
|---|---|---|
| Compute capability | 8.9 (Ada Lovelace) | device properties |
| SMs | 24 | device properties |
| CUDA cores | Ada whitepaper; matches NVIDIA specifications | |
| Tensor Cores | Ada whitepaper | |
| Resident threads per SM | 1536 (48 warps) | properties and CUDA guide |
| Registers per SM | 65 536 | device properties |
| Shared memory per SM | up to 100 KiB (99 KiB per block) | properties and CUDA guide |
| L2 | 32 MiB | device properties |
| Global memory | 8 GiB GDDR6, 128-bit bus at 8001 MHz | device properties |
| Theoretical bandwidth | GB/s | calculated |
| SM boost clock | 1470 to 2370 MHz depending on laptop | NVIDIA specifications |
| CPU link | PCIe 4.0 x8 | nvidia-smi |
FP32 peak is cores times two flops per FMA (fused multiply-add, in one instruction) times frequency: , about 9 TFLOP/s at 1.5 GHz and 14.6 at 2.37 GHz. Actual frequency depends on laptop GPU power allowance (specifications give 35 to 115 W depending on manufacturer) and temperature, changing between measurements. This is the first warning that no performance figure on this laptop is constant.
The interactive is a deliberately simple partition model, but captures the essential calculation. A warp repeating “load, wait , instructions using the data” needs at least cycles per round, of which only are useful arithmetic. With interleaved warps, arithmetic-unit utilization under any policy is at most
and the first term is imposed by the load itself, which occupies one issue cycle. Saturation requires warps: with and , nine. This is Little’s law again, counted in warps. Actual latencies are higher (hundreds of cycles for global memory), and memory-bound kernels have small , so a partition would need dozens of warps but supports only 12 (48 per SM). That shortage forces real kernels also to use instruction-level parallelism: several independent loads in flight per thread, as seen in the occupancy section.
Whether the bound is reached depends on which warp the scheduler chooses. The greedy policy (greedy-then-oldest, GTO) keeps issuing from the same warp while it has a ready instruction and, when it stalls on a load, switches to the one longest without issuing: each warp performs its instructions consecutively and warps become staggered, each at a different cycle phase. Round-robin gives all an equal turn, so they progress together, reach loads nearly simultaneously and wait together. In the limit where they move as a group, a round lasts cycles and utilization is , approaching only when . This is the flaw identified by Narasiman, Lee, Shebanow, Miftakhutdinov, Mutlu and Patt (Improving GPU Performance via Large Warps and Two-Level Warp Scheduling, MICRO 2011): round-robin brings warps to long-latency operations nearly together, leaving nobody to hide them; their remedy, splitting warps into alternating groups, seeks the same staggering as greedy. NVIDIA does not document its scheduler policy; the model explains why issue order matters, not Ada’s actual policy.
The next cell is the same Python simulator with both policies. Greedy reaches the bound exactly: utilization grows linearly with up to nine warps and stays at . With round-robin, nine warps give under 50%, and even sixteen do not reach the bound.
def simula(W, L, c, ciclos, calentamiento=0, politica="codiciosa"):
"""Una partición de SM: W warps que repiten 'carga, espera L ciclos, c instrucciones aritméticas'.
Cada ciclo se emite una instrucción de un warp listo: con la política codiciosa, del mismo warp
que en el ciclo anterior si sigue listo; si no (o con la rotatoria), del que lleva más tiempo sin emitir."""
pendientes = [0] * W # aritméticas que le quedan a cada warp
listo_en = [0] * W # ciclo en que llega su carga
ultima = [-1] * W # último ciclo en que emitió
alu, anterior = 0, -1
for t in range(ciclos + calentamiento):
listos = [w for w in range(W) if listo_en[w] <= t]
if not listos:
continue
if politica == "codiciosa" and anterior in listos:
w = anterior
else:
w = min(listos, key=lambda k: ultima[k])
ultima[w], anterior = t, w
if pendientes[w] > 0:
pendientes[w] -= 1
alu += t >= calentamiento
else:
listo_en[w] = t + 1 + L # emite la carga: el dato llega L ciclos después
pendientes[w] = c
return alu / ciclos
L, c = 40, 4
print(f"L = {L} ciclos, c = {c} aritméticas por carga; warps necesarios = {-(-(c + 1 + L) // (c + 1))}")
print(" W codiciosa cota min(c/(c+1), W c/(c+1+L)) rotatoria en bloque W c/(W(c+1)+L)")
for W in (1, 2, 4, 6, 8, 9, 10, 12, 16):
u = simula(W, L, c, 4000, 1000)
r = simula(W, L, c, 4000, 1000, "rotatoria")
print(f"{W:2d} {u:8.1%} {min(c / (c + 1), W * c / (c + 1 + L)):10.1%}{'':22s}{r:8.1%} {W * c / (W * (c + 1) + L):10.1%}")Execution model: kernels, grids, blocks and threads
CUDA does not let you program warps directly: it provides a more convenient thread hierarchy and lets hardware distribute it.
At compute capability 8.9, a block has at most 1024 threads (with and ), and the grid up to blocks in . Within a block, threads are numbered linearly with as the fastest index,
and block warp comprises threads with . If block size is not a multiple of 32, the last warp is incomplete and remaining lanes are wasted.
The basic pattern assigns one thread per datum using a global index. In one dimension, ; since the grid uses whole blocks, threads are launched and each checks that its exists. Here is SAXPY, , in CUDA C:
extern "C" __global__ void saxpy(float a, const float* x, float* y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x; // índice global de este hilo
if (i < n) // la rejilla puede tener hilos de sobra
y[i] = a * x[i] + y[i];
}
// en el host: saxpy<<<(n + 255) / 256, 256>>>(2.0f, x, y, n);
There is no loop: the grid is the loop. In two dimensions, for a row-major image with rows and columns, the convention is for to traverse columns and rows:
with a grid of blocks. This convention is not cosmetic: consecutive warp lanes have consecutive threadIdx.x, so they read consecutive columns of one row, contiguous addresses. The lab measures what happens if you reverse it.
Three lessons from the mapping. Extra threads are the cost of whole blocks: with pixels and blocks, threads are launched for 273 pixels; in a large image this waste is a strip at two edges and does not matter. A warp in an block is four rows of 8 pixels, so accesses are four contiguous 32-byte spans instead of one 128-byte span: the coalescing section shows that is still efficient because memory is served in 32-byte sectors. Block size determines how many blocks fit in an SM, occupancy, discussed later.
Another useful pattern is the grid-stride loop: instead of launching one thread per datum, launch a fixed-size grid (for example, a few blocks per SM) and each thread traverses data with stride equal to total thread count:
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x)
y[i] = x[i];
The kernel works for any with any grid, each thread amortizes startup over many elements, and each iteration’s accesses remain contiguous across warp lanes. You will use it in the reduction.
The GPU memory hierarchy
The GPU has its own memory hierarchy, with an important difference from the CPU: you manage several levels explicitly.
On the RTX 4060 Laptop:
| Level | Size | Visible to | Lifetime |
|---|---|---|---|
| Registers | 64 Ki 32-bit registers per SM, up to 255 per thread | one thread | the thread |
| Shared memory and L1 | 128 KiB per SM, up to 100 KiB shared | one block (shared memory) | the block |
| L2 | 32 MiB | whole chip | hardware-managed |
| Global memory (GDDR6) | 8 GiB, theoretical 256 GB/s | all threads and host | until freed |
The L1/shared split (carveout) is selected among 0, 8, 16, 32, 64 and 100 KiB of shared memory per SM; the driver adjusts it to kernel requests. Ada’s L2 is huge compared with previous generations (the large AD102 chip has 96 MB versus its predecessor’s 6 MB, per the whitepaper): on the RTX 4060, a working set of a few megabytes reused across kernels may never touch DRAM.
Visibility and synchronization
Threads in a block communicate through shared memory, requiring ordering. The primitive is __syncthreads(): a barrier no block thread crosses until all have reached it, which also ensures all shared and global memory writes by block threads before the barrier are visible to all afterward. The typical pattern is write, synchronize and read what others wrote:
__shared__ float buf[256];
buf[threadIdx.x] = x[i]; // cada hilo escribe su casilla
__syncthreads(); // todos han escrito antes de que nadie lea
float vecino = buf[(threadIdx.x + 1) % 256];
Without the barrier, a thread could read its neighbor’s slot before the neighbor writes: the CPU’s race condition, except here the warp scheduler makes it very likely. Two rules must not be broken:
- All block threads must reach the same barrier. An
__syncthreads()inside anifwhose condition differs across the block is an error: behavior is undefined and in practice the kernel hangs or produces wrong results. - There is no barrier between blocks. If a result depends on all blocks (a vector’s total sum, for example), combine with global-memory atomics or launch a second kernel: kernel completion is a global barrier.
Shared memory is divided into 32 4-byte banks: the 32-bit word at address is in bank . If a warp’s 32 threads access words in different banks, access is served at once; if several access different words in the same bank, a bank conflict occurs and they are served serially (all reading the same word is not a conflict: it is broadcast). This is shared memory’s counterpart to coalescing, covered with shared-memory tiling in the next lesson.
Coalescing: 32-byte sectors
When a warp executes a load instruction, its 32 threads request 32 addresses, and hardware does not serve them one by one. Since compute capability 6.0, global memory is served in aligned 32-byte sectors (L1 and L2 lines are 128 bytes, four sectors), and the load unit calculates the distinct sectors covering the warp’s addresses and requests only those (CUDA C++ Best Practices Guide, section on coalesced global memory access).
Proof
Lane reads bytes through in sector (they do not cross a boundary because is a multiple of 4 and sectors of 32). If , distinct lanes satisfy and fall in distinct sectors: 32 sectors. If , indices advance in steps , so no sector is skipped between the first, 0, and last, . Since and , the last is , giving sectors. Useful bytes are , so for and for .
∎ with an offset not divisible by 8 elements is no longer aligned: 128 bytes fall into 5 sectors and efficiency drops to 80%. With 8- or 16-byte elements (double, float4), a contiguous warp requests 256 or 512 bytes in 8 or 16 sectors, all useful.
The next cell is the model drawn by the interactive: it counts sectors for any pattern and reproduces the theorem.
def sectores(direcciones, tam):
"""Sectores de 32 B distintos que cubren los accesos [a, a + tam) de un warp."""
s = set()
for a in direcciones:
for b in range(a, a + tam):
s.add(b // 32)
return len(s)
def eficiencia(stride, desplazamiento=0, tam=4):
dirs = [(desplazamiento + t * stride) * tam for t in range(32)]
n = sectores(dirs, tam)
return n, 32 * tam / (32 * n)
print("float32, alineado: stride sectores eficiencia teorema max(1/s, 1/8)")
for s in (1, 2, 3, 4, 5, 8, 16, 32):
n, e = eficiencia(s)
print(f"{'':21s}{s:4d} {n:8d} {e:9.1%} {max(1 / s, 1 / 8):9.1%}")
print("\nstride 1 con desplazamiento 1 (desalineado):", eficiencia(1, 1))
print("double contiguo:", eficiencia(1, 0, 8), " float4 contiguo:", eficiencia(1, 0, 16))
# AoS: partículas de 8 floats (32 B); el kernel lee solo x y vx (campos 0 y 3)
aos = sectores([(8 * t + f) * 4 for t in range(32) for f in (0, 3)], 4)
soa = sectores([4 * t for t in range(32)], 4) + sectores([4096 + 4 * t for t in range(32)], 4)
print(f"\nleer x y vx de 32 partículas: AoS {aos} sectores ({aos * 32} B), SoA {soa} sectores ({soa * 32} B) para 256 B útiles")Array of structures versus structure of arrays
The most common practical consequence of coalescing is data layout. An array of structures (AoS) stores each particle together, struct Particula { float x, y, z, vx, vy, vz, masa, carga; }, natural in object-oriented code. A structure of arrays (SoA) stores one array per field: all x together, all vx together. If a kernel updates only , with AoS each lane reads a different particle, 32 bytes from the previous: each load instruction touches 32 sectors and uses 4 bytes of each. Both loads, x and vx, touch the same 32 sectors (each particle occupies exactly one), so cache reuses them between instructions, but only 8 of each fetched 32-byte sector are used. With SoA both loads are contiguous: 8 sectors, all useful. The cell counts 32 sectors (1024 B) with AoS versus 8 (256 B) with SoA: a factor of 4 for reading. Writing x is worse: AoS touches 32 sectors to write 128 bytes, SoA 4. Total per warp is traffic bytes versus , a factor of 5.3. In lab runs the AoS kernel took 5.0 to 5.1 times longer than SoA.
If the kernel uses every field of each particle, AoS ceases to be a traffic problem because every fetched sector is ultimately useful (the interactive shows this reading all 8 fields with cache). The rule: lay out data according to the access pattern of the most time-consuming kernels, not code design.
Occupancy and latency hiding
The scheduler simulator left a question: how many warps can an SM actually hold? It depends on your kernel.
The four limits, with an -thread block, registers per thread and bytes of shared memory, at CC 8.9:
where rounds up to a multiple of . Registers are allocated per warp in units of 256, and each warp lives in one of four partitions with its 16 384-register file, so counting is per partition. Shared memory is allocated in 128-byte units, with 1 KiB reserved by the system per block. In the lab this calculator matches the driver’s (cuOccupancyMaxActiveBlocksPerMultiprocessor) in every tested configuration; without per-partition counting it failed in 43 of 1152, all above 100 registers per thread.
With 64 registers per thread, one warp occupies registers, one partition supports 8 warps and the SM 32: 67% occupancy even with a small block. With 32 registers per thread occupancy reaches 100%. The curve’s teeth are rounding: with 640-thread blocks (20 warps) only 2 fit per SM, 40 of 48 warps, while 512-thread blocks fit 3, or 48 warps. The compiler chooses register count; inspect it (in the lab with cuFuncGetAttribute) and limit it with __launch_bounds__ or -maxrregcount, at the cost of compiler spills to local memory.
What the lab measures
How much occupancy is needed? The lab launches a copy kernel with a grid-stride loop and controls warps per SM using grid size. Across four lab runs, one warp per SM achieved 21 to 22 GB/s; bandwidth grew nearly proportionally to warps up to 4 per SM (74 to 80 GB/s, 3.4 to 3.6 times more), then increasingly slowly: 130 to 139 at 8, 188 to 197 at 16, and 207 to 220 from 24, where it saturates. This is Little’s law: each warp has one 128-byte load in flight, and while memory has headroom latency is constant and bandwidth proportional to bytes in flight. With one warp per SM, bytes in flight give about 10.5 GB/s reading (half of 21, which counts reads and writes), corresponding to latency ns; the cell prints 278 to 294 ns depending on run. That is the motivating figure. Near the ceiling the same calculation gives increasing latency (over 900 ns at 32 warps): extra requests do not increase throughput, only lengthen the queue.
The sweep’s other lesson is bandwidth saturation before maximum occupancy: 24 of 48 warps already reach the ceiling, and increasing to 48 gains nothing. Volkov took this to the extreme in 2010: on a GTX 480, a copy moving 14 float4 per thread reached 84% of peak at 4% occupancy because each thread had many independent loads in flight. Occupancy is not the goal; enough operations in flight are, whether through many warps or more independent work per warp. More registers per thread reduce occupancy but may allow more instruction parallelism and data reuse in registers, exactly what cuBLAS matrix-multiplication kernels do. Conversely, pursuing 100% by forcing few registers can cause local-memory spills and worsen the kernel.
Warp divergence
SIMT lets you write if as in any language, but a warp has one instruction stream. If the condition differs among its 32 threads, the warp executes both branches one after another with nonparticipating lanes disabled.
Since Volta (capability 7.0), each thread has its own program counter and hardware can interleave branches of a divergent warp (independent thread scheduling): threads in one warp can wait for each other without deadlock, but cost does not change because each cycle the warp still issues one instruction for lanes of one path. It also means the 32 warp threads cannot be assumed synchronized: if an algorithm needs this, use __syncwarp() or *_sync primitives receiving the lane mask.
The interactive shows what matters: divergence is a per-warp matter. if (i < 80) splits the block’s 256 threads into two groups, but only the warp containing the boundary pays for both branches. if (i % 2 == 1) splits every warp in half and doubles all their time. if ((i / 32) % 2 == 0) distributes work like the previous one (half of threads per branch) but without divergence: threads taking each branch are grouped into full warps. Across four lab runs, a kernel with two branches of 2000 FMA each took 1.70 to 1.87 times longer with the odd i condition than with all threads on one branch, and virtually the same (0.96 to 0.99 times) with the per-warp condition. Branches dominate kernel time but are not everything (it also reads, writes and distributes blocks), so the factor stays below 2.
Avoid it by reorganizing data so the condition is uniform per warp (sort or group elements by their branch), replacing short branches with arithmetic (v = c ? a : b often compiles without jumps, using predication), or, if divergence is inevitable, keeping branches short. An apparent exception: the grid-end if (i < n) check splits only the final warp.
CPU and GPU: transfers, pinned memory and streams
Recall from the tools’ asynchronous execution lesson that the CPU enqueues work in a stream and continues, operations in one stream execute in order while different streams may overlap, and GPU time is measured with CUDA events or by synchronizing before stopping the clock. The other protagonist here is the PCIe bus carrying data between CPU and GPU memory.
The RTX 4060 Laptop link is PCIe 4.0 with 8 lanes: transfers per second per lane, 128b/130b encoding and 8 lanes yield GB/s each way. This is sixteen times less than the GPU’s own memory bandwidth. Any datum crossing the bus costs as much as reading it 16 times on the GPU, so the first rule is to keep data on the GPU and cross as little as possible.
Pageable and pinned memory
The GPU’s DMA engine copies directly from physical CPU memory without CPU intervention, requiring source pages not to move or be paged to disk during copying. Ordinary process memory is pageable: the OS can move it. When copying from it, the driver first copies each chunk to an internal pinned (page-locked) buffer and performs DMA from there, so copying takes two passes and cannot be asynchronous with respect to the CPU. If you allocate pinned memory yourself (torch.empty(..., pin_memory=True), tensor.pin_memory() or cudaMallocHost), DMA reads it directly.
Across four lab runs, copying 256 MiB CPU to GPU achieved 10.4 to 11.5 GB/s from pageable memory and 12.2 to 12.7 from pinned memory, 77 to 81% of link theory (GPU to CPU, 11.4 to 12.7 versus 13.1 or 13.2). Pinned memory improved upload by 9 to 21% in each run: on this laptop the driver’s intermediate copy costs little compared with the bus. The decisive reason for pinned memory is not that machine-dependent difference, but that without it copying is not asynchronous, and without asynchronous copies there is no compute overlap. Pinned memory is not free: the OS cannot reuse its physical pages, so allocate it once for transfer buffers, not everything.
Overlapping copy and compute
If a data batch must go to the GPU, be processed and return, serial time is . Splitting it into chunks across several streams lets chunk upload while is processed and downloads: a pipeline.
Proof
Lower bound. Number stages with times , , , and let be slowest, . Its engine processes chunks sequentially, so is busy . It cannot start the first chunk before earlier stages up to , and the last chunk after must still pass through later stages. Summing gives .
Achievability. Let be the time chunk finishes stage , and let and . In greedy scheduling, stage of chunk starts after its preceding stage and the previous chunk on that engine finish: , with and . By induction on and , . Substituting the hypothesis,
If , then and the second term, , is larger. If , then and the first, , is larger because . Both cases give . The last chunk finishes at .
One copy engine. That engine must perform uploads and downloads serially, giving .
∎If the whole batch takes to upload, to process and to download, the bound is , approaching with many chunks: the busiest resource’s time, the best possible result. If the kernel is faster than copying, overlap can at most hide the kernel: the bus dominates, and the only real improvement is moving less data.
One hardware detail theory misses is issue order. Each engine serves operations in arrival order. If the loop issues upload, kernel and download for each chunk and the GPU has one copy engine, its queue is “upload 0, download 0, upload 1, download 1…”: download 0 waits for kernel 0, and upload 1 waits behind it despite having no dependency. This is a false dependency, resulting in serial execution. Issuing by phases (all uploads, then all kernels, then all downloads) avoids it. Mark Harris measured this in 2012 on a Tesla C1060 with one copy engine: issuing chunk by chunk, streams took 13.6 ms versus 12.9 serially; issuing by phases took 8.8 ms (How to Overlap Data Transfers in CUDA C/C++). With two copy engines, one per direction, chunk-by-chunk order works.
The next cell is the same model with rounded times on the scale measured by the lab for 128 MiB (11 ms upload, 10 download and a 5 ms kernel), comparing both issue orders with one and two copy engines.
def canalizacion(trozos, streams, t_sube, t_kernel, t_baja, motores_copia=1, orden="trozo"):
"""Cada operación empieza cuando terminan la anterior de su stream y la anterior de su motor."""
motor = {"sube": 0, "kernel": 1, "baja": 0 if motores_copia == 1 else 2}
dur = {"sube": t_sube / trozos, "kernel": t_kernel / trozos, "baja": t_baja / trozos}
if orden == "trozo":
ops = [(c, f) for c in range(trozos) for f in ("sube", "kernel", "baja")]
else:
ops = [(c, f) for f in ("sube", "kernel", "baja") for c in range(trozos)]
fin_stream, fin_motor = [0.0] * streams, [0.0, 0.0, 0.0]
for c, f in ops:
s, m = c % streams, motor[f]
fin = max(fin_stream[s], fin_motor[m]) + dur[f]
fin_stream[s] = fin_motor[m] = fin
return max(fin_stream)
h, k, d = 11.0, 5.0, 10.0 # ms para 128 MiB, del orden de lo que mide el laboratorio
print(f"en serie: {h + k + d:.1f} ms; cota con un motor de copia: {h + d:.1f} ms; con dos: {max(h, k, d):.1f} ms")
for motores in (1, 2):
for orden in ("trozo", "fase"):
fila = [canalizacion(8, s, h, k, d, motores, orden) for s in (1, 2, 4, 8)]
print(f"{motores} motor(es), orden {orden:5s}, 8 trozos, 1/2/4/8 streams: " + ", ".join(f"{t:5.1f}" for t in fila) + " ms")
# la cota del teorema con dos motores (trozos iguales): h + k + d + (n - 1) max
for n in (1, 2, 4, 8, 16):
sim = canalizacion(n, n, h, k, d, 2, "trozo")
print(f"dos motores, {n:2d} trozos: simulado {sim:5.2f} ms, teorema {(h + k + d) / n + (n - 1) * max(h, k, d) / n:5.2f} ms")For the RTX 4060 with one copy engine, the model predicts chunk-by-chunk issue gains nothing (26 ms at any stream count), while phased issue does: 24.8 ms with 2 streams, 22.2 with 4 and 21 with 8, the time of both copies. The kernel is hidden and the bus (more precisely its one copy engine) dominates. With fewer streams than chunks, phased issue makes each stream enqueue a later upload before its first kernel, delaying kernels; reaching the bound therefore needs as many streams as chunks. With two copy engines, chunk-by-chunk works and 4 streams reach 12.9 ms, the theorem with . The lab tests the one-engine case.
FP64 on a consumer GPU
In floating point you studied why float64 is the default scientific-computing precision. On this GPU it is second-class. The CUDA guide gives an FP32-to-FP64 throughput ratio of 64 for capability 8.9, and the whitepaper says each Ada SM has 2 FP64 units versus 128 FP32 cores. In the lab, a kernel with 8 independent FMA chains per thread, measured in alternating precisions, gives a ratio around 60 (55 to 67 depending on round), close to the theoretical peaks’ 64.
The consequences for scientific computing on this machine are design choices, not fine tuning:
- Work that genuinely needs
float64and is compute-bound (a large double-precision matmul, for example) is no faster on the GPU than the CPU: the lab’s roughly 130 GFLOP/s indoubleis below the course CPU’s 164 infloat64with all cores, and the GPU also incurs data upload and download. - Memory-bound work (most vector and stencil kernels) suffers less: in
float64each element is twice as large and useful bandwidth in elements per second halves, rather than falling to one sixtieth. - The usual solution is mixed precision: perform most work in
float32(or less) and only necessary steps infloat64, as in mixed-precision iterative refinement in the topic’s last lesson. Data-center GPUs (A100, H100) have ratios of 2, so this problem does not arise there.
Lab 1: get to know your GPU
This lab runs locally (runtime=local), with PyTorch. To write CUDA C kernels without installing the full toolkit it uses torch.cuda._compile_kernel, compiling source with NVRTC (PyTorch’s bundled runtime CUDA compiler) and returning a launcher accepting grid, block and arguments. This is what cupy.RawKernel does. Two caveats: this is a private PyTorch API (the underscore indicates it) and may change between versions, and Python float arguments reach the kernel as double, so kernels below declare scalar parameters double.
The first cell queries device properties and defines four utilities used by the rest: compile a kernel, ask the driver its register count, ask how many blocks fit per SM, and measure GPU time with events (median of repetitions after warm-up, as in microbenchmark methodology).
import ctypes, os, statistics, subprocess, time
import torch
import torch.utils.cpp_extension as cpp_ext
assert torch.cuda.is_available(), "este laboratorio necesita una GPU con CUDA"
dev = torch.device("cuda")
p = torch.cuda.get_device_properties(0)
print(f"{p.name} capacidad de cómputo {p.major}.{p.minor}")
print(f"SM: {p.multi_processor_count} warp: {p.warp_size} hilos hilos residentes por SM: {p.max_threads_per_multi_processor}")
print(f"registros por SM: {p.regs_per_multiprocessor} memoria compartida por SM: {p.shared_memory_per_multiprocessor // 1024} KiB"
f" por bloque (opt-in): {p.shared_memory_per_block_optin // 1024} KiB")
print(f"L2: {p.L2_cache_size / 2**20:.0f} MiB memoria global: {p.total_memory / 2**30:.2f} GiB")
print(f"reloj de memoria: {p.memory_clock_rate / 1e3:.0f} MHz bus: {p.memory_bus_width} bits reloj de los SM que informa el driver: {p.clock_rate / 1e3:.0f} MHz")
B_teor = 2 * p.memory_clock_rate * 1e3 * p.memory_bus_width / 8 # GDDR: dos transferencias por ciclo
print(f"ancho de banda teórico de la memoria: {B_teor / 1e9:.0f} GB/s")
libcuda = torch.cuda._utils._get_gpu_runtime_library() # la API del driver de CUDA
def atributo(attr):
v = ctypes.c_int()
libcuda.cuDeviceGetAttribute(ctypes.byref(v), attr, 0)
return v.value
print(f"motores de copia asíncrona: {atributo(40)} bloques residentes por SM: {atributo(106)}")
try:
pcie = subprocess.run(["nvidia-smi", "--query-gpu=pcie.link.gen.max,pcie.link.width.max", "--format=csv,noheader"],
capture_output=True, text=True, timeout=10).stdout.strip()
print(f"enlace PCIe (generación, carriles): {pcie}")
except (OSError, subprocess.SubprocessError):
print("nvidia-smi no está disponible")
if cpp_ext.CUDA_HOME is None:
# NVRTC solo necesita una carpeta de cabeceras de CUDA; nuestros kernels no incluyen ninguna,
# así que basta con las que trae Triton si no tienes el toolkit instalado
import triton
cpp_ext.CUDA_HOME = os.path.join(os.path.dirname(triton.__file__), "backends", "nvidia")
def kernel(fuente, nombre, opciones=None):
"""Compila CUDA C con NVRTC y devuelve un lanzador: k(grid=(gx,gy,gz), block=(bx,by,bz), args=[...])."""
return torch.cuda._compile_kernel(fuente, nombre, nvcc_options=opciones)
def registros(k):
v = ctypes.c_int()
libcuda.cuFuncGetAttribute(ctypes.byref(v), 4, k.func) # CU_FUNC_ATTRIBUTE_NUM_REGS
return v.value
def bloques_residentes(k, hilos, smem=0):
v = ctypes.c_int()
libcuda.cuOccupancyMaxActiveBlocksPerMultiprocessor(ctypes.byref(v), k.func, hilos, smem)
return v.value
def t_gpu(f, rep=20):
"""Mediana del tiempo de GPU de f() medido con eventos CUDA, tras una ejecución de calentamiento."""
f(); torch.cuda.synchronize()
ts = []
for _ in range(rep):
e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
e0.record(); f(); e1.record(); e1.synchronize()
ts.append(e0.elapsed_time(e1) / 1e3)
return statistics.median(ts)npm run lab and open the connection link.On this laptop the cell gave the architecture table’s figures: 24 SMs, 1536 threads and 65 536 registers per SM, 100 KiB shared memory per SM, 32 MiB L2, a 128-bit bus at 8001 MHz (theoretical 256 GB/s), and PCIe 4.0 x8. Two figures deserve comment. The driver’s reported SM clock (1890 MHz) is not necessarily the GPU clock during measurement, which depends on power and temperature. And there is one asynchronous copy engine: copies in both directions share a queue, relevant to pipelining.
Transfers and launch overhead
N = 256 * 2**20 # 256 MiB
d = torch.empty(N, dtype=torch.uint8, device=dev)
for nombre, h in [("paginable", torch.empty(N, dtype=torch.uint8)),
("fijada (pinned)", torch.empty(N, dtype=torch.uint8).pin_memory())]:
h2d = t_gpu(lambda: d.copy_(h), rep=10)
d2h = t_gpu(lambda: h.copy_(d), rep=10)
print(f"{nombre:16s} CPU -> GPU {N / h2d / 1e9:5.1f} GB/s GPU -> CPU {N / d2h / 1e9:5.1f} GB/s")
print(f"teórico de PCIe 4.0 x8 por sentido: {16e9 * 8 * 128 / 130 / 8 / 1e9:.2f} GB/s")
del d, h
torch.cuda.empty_cache()npm run lab and open the connection link.Launching a kernel has fixed CPU cost (prepare arguments, enqueue command) and GPU cost (distribute blocks). The cell launches 2000 empty kernels with our Python launcher, 2000 one-element PyTorch additions and the same PyTorch kernels recorded in a CUDA Graph, sent once by the CPU and replayed by the GPU without further CPU intervention.
vacio = kernel('extern "C" __global__ void vacio() {}', "vacio")
L = 2000
for _ in range(100): vacio(grid=(1, 1, 1), block=(32, 1, 1))
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(L): vacio(grid=(1, 1, 1), block=(32, 1, 1))
t1 = time.perf_counter(); torch.cuda.synchronize(); t2 = time.perf_counter()
print(f"kernel vacío con el lanzador de Python: {(t1 - t0) / L * 1e6:6.1f} µs de CPU por lanzamiento, {(t2 - t0) / L * 1e6:6.1f} µs por kernel en total")
x = torch.zeros(1, device=dev)
for _ in range(100): x.add_(1)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(L): x.add_(1)
t1 = time.perf_counter(); torch.cuda.synchronize(); t2 = time.perf_counter()
print(f"x.add_(1) de PyTorch: {(t1 - t0) / L * 1e6:6.1f} µs de CPU por llamada, {(t2 - t0) / L * 1e6:6.1f} µs por kernel en total")
g = torch.cuda.CUDAGraph()
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s): # calentamiento en un stream aparte, como pide PyTorch
for _ in range(3): x.add_(1)
torch.cuda.current_stream().wait_stream(s)
with torch.cuda.graph(g):
for _ in range(100): x.add_(1)
g.replay(); torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(L // 100): g.replay()
torch.cuda.synchronize(); t2 = time.perf_counter()
print(f"x.add_(1) dentro de un CUDA Graph: {(t2 - t0) / L * 1e6:6.2f} µs por kernel en total")npm run lab and open the connection link.Across four runs, the Python launcher cost 27 to 45 µs per kernel (each call converts arguments with ctypes and reopens the driver library), a PyTorch operation 10 to 14 µs, and inside a CUDA Graph per-kernel cost fell to 1 to 1.7 µs. That last number is the actual cost of starting a tiny GPU kernel; earlier figures are CPU cost, the bottleneck in a loop of small kernels. A kernel processing a few thousand elements takes under a microsecond on the GPU, so launching tiny kernels wastes time: fuse them, batch work or record a graph.
Global-memory bandwidth and latency hiding
copia = kernel(r'''
extern "C" __global__ void copia(const float* __restrict__ x, float* __restrict__ y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = x[i];
}''', "copia")
n = 2**26 # 256 MiB por array
a = torch.rand(n, device=dev); b = torch.empty_like(a)
tc = t_gpu(lambda: copia(grid=((n + 255) // 256, 1, 1), block=(256, 1, 1), args=[a, b, n]))
assert torch.equal(a, b)
bw_copia = 8 * n / tc # lee 4n bytes y escribe 4n
print(f"copia de {4 * n / 2**20:.0f} MiB: {bw_copia / 1e9:.0f} GB/s ({bw_copia / B_teor:.0%} del teórico)")
copia_rejilla = kernel(r'''
extern "C" __global__ void copia_rejilla(const float* __restrict__ x, float* __restrict__ y, int n) {
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) y[i] = x[i];
}''', "copia_rejilla")
print("\nwarps por SM GB/s latencia estimada (ley de Little)")
for wps in (1, 2, 4, 8, 16, 24, 32, 48):
hilos = 32 * min(wps, 8)
bloques = p.multi_processor_count * wps * 32 // hilos
t = t_gpu(lambda: copia_rejilla(grid=(bloques, 1, 1), block=(hilos, 1, 1), args=[a, b, n]), rep=10)
bw = 8 * n / t
en_vuelo = p.multi_processor_count * wps * 128 # una carga de 128 B por warp en vuelo
print(f"{wps:8d} {bw / 1e9:6.1f} {en_vuelo / (bw / 2) * 1e9:6.0f} ns")npm run lab and open the connection link.The copy kernel reached 207 to 213 GB/s over four runs, 81 to 83% of theory: the actual memory ceiling used by the final roofline. The warps-per-SM sweep is that of the occupancy section: bandwidth grows nearly proportionally to warps up to about 4 per SM and saturates around 24. The latency column applies Little’s law: with few warps it is 280 to 330 ns; with many, estimated latency grows because bandwidth cannot grow and requests queue.
FP32 versus FP64
fma_src = r'''
extern "C" __global__ void fma_T(T* out, int iters) {
T a0 = threadIdx.x * (T)1e-3, a1 = a0 + 1, a2 = a0 + 2, a3 = a0 + 3, a4 = a0 + 4, a5 = a0 + 5, a6 = a0 + 6, a7 = a0 + 7;
const T b = (T)0.999, c = (T)1e-3;
for (int k = 0; k < iters; ++k) { // 8 cadenas independientes de FMA: paralelismo de instrucciones
a0 = a0 * b + c; a1 = a1 * b + c; a2 = a2 * b + c; a3 = a3 * b + c;
a4 = a4 * b + c; a5 = a5 * b + c; a6 = a6 * b + c; a7 = a7 * b + c;
}
out[blockIdx.x * blockDim.x + threadIdx.x] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7;
}'''
bloques, hilos = 64 * p.multi_processor_count, 256
fmas = {}
for T, iters in (("float", 16384), ("double", 512)): # unos 10 ms por lanzamiento cada uno
k = kernel(f"typedef {T} T;\n" + fma_src.replace("fma_T", f"fma_{T}"), f"fma_{T}")
out = torch.empty(bloques * hilos, device=dev, dtype=torch.float32 if T == "float" else torch.float64)
fmas[T] = (k, out, iters)
# la frecuencia de la GPU cambia de una medida a otra: alternar los dos kernels hace que el cociente
# compare medidas tomadas en las mismas condiciones
medidas = {"float": [], "double": []}
for ronda in range(5):
for T, (k, out, iters) in fmas.items():
t = t_gpu(lambda: k(grid=(bloques, 1, 1), block=(hilos, 1, 1), args=[out, iters]), rep=3)
medidas[T].append(2 * 8 * iters * bloques * hilos / t)
picos = {T: statistics.median(v) for T, v in medidas.items()}
cocientes = [f / d for f, d in zip(medidas["float"], medidas["double"])]
for T, (k, _, _) in fmas.items():
print(f"FMA en {T:6s}: {picos[T] / 1e9:8.0f} GFLOP/s (de {min(medidas[T]) / 1e9:.0f} a {max(medidas[T]) / 1e9:.0f} en 5 rondas; {registros(k)} registros por hilo)")
print(f"cociente FP32 / FP64 por ronda: de {min(cocientes):.0f} a {max(cocientes):.0f}, mediana {statistics.median(cocientes):.0f} (teórico en CC 8.9: 64)")
for f_ghz in (1.47, 2.37):
print(f"pico FP32 teórico a {f_ghz} GHz: {p.multi_processor_count * 128 * 2 * f_ghz / 1e3:.1f} TFLOP/s")npm run lab and open the connection link.Each thread performs 8 independent FMA chains so each FMA’s latency (a few cycles) is hidden by the other seven, and the grid has 64 blocks per SM for ample warps. The cell alternates measurements of both kernels for five rounds because GPU frequency changes between measurements: an initial version measuring each kernel once gave ratios 66 in two runs and 95 in a third. Alternating, the reference run gave 8.0 TFLOP/s in float (7.7 to 8.9 by round) and 129 GFLOP/s in double, with per-round ratio 55 to 67 and median 62, near theoretical 64. With peak , 8.0 TFLOP/s corresponds to at least GHz: sustained kernels around 10 ms can make the laptop drop its clock below the specification’s minimum boost range, and there is no way to fix it here.
The stream pipeline
The lab’s last cell tests the pipeline model with 128 MiB, 8 chunks, a kernel doing 800 FMA per element and both issue orders. Because wall time varies greatly between repetitions on this laptop, it reports the best of seven, the same statistic as STREAM: an estimate of what the machine can do without interference.
trabajo = kernel(r'''
extern "C" __global__ void trabajo(float* x, int n, int reps) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) { float v = x[i]; for (int r = 0; r < reps; ++r) v = v * 0.999f + 0.001f; x[i] = v; }
}''', "trabajo")
N = 2**25 # 128 MiB de float32
h_in = torch.rand(N).pin_memory(); h_out = torch.empty(N).pin_memory()
d = torch.empty(N, device=dev)
def canal(ns, trozos, reps, orden):
streams = [torch.cuda.Stream() for _ in range(ns)]
for s in streams: s.wait_stream(torch.cuda.current_stream())
m = N // trozos
sl = [slice(c * m, (c + 1) * m) for c in range(trozos)]
def sube(c):
with torch.cuda.stream(streams[c % ns]): d[sl[c]].copy_(h_in[sl[c]], non_blocking=True)
def calcula(c):
trabajo(grid=((m + 255) // 256, 1, 1), block=(256, 1, 1), args=[d[sl[c]], m, reps], stream=streams[c % ns])
def baja(c):
with torch.cuda.stream(streams[c % ns]): h_out[sl[c]].copy_(d[sl[c]], non_blocking=True)
if orden == "trozo":
for c in range(trozos): sube(c); calcula(c); baja(c)
else:
for c in range(trozos): sube(c)
for c in range(trozos): calcula(c)
for c in range(trozos): baja(c)
for s in streams: torch.cuda.current_stream().wait_stream(s)
def mejor_pared(f, rep=7):
f(); torch.cuda.synchronize(); ts = []
for _ in range(rep):
t0 = time.perf_counter(); f(); torch.cuda.synchronize(); ts.append(time.perf_counter() - t0)
return min(ts), statistics.median(ts)
reps = 800
t_h = mejor_pared(lambda: d.copy_(h_in, non_blocking=True))[0]
t_d = mejor_pared(lambda: h_out.copy_(d, non_blocking=True))[0]
t_k = mejor_pared(lambda: trabajo(grid=((N + 255) // 256, 1, 1), block=(256, 1, 1), args=[d, N, reps]))[0]
print(f"subida {t_h*1e3:.1f} ms, kernel {t_k*1e3:.1f} ms, bajada {t_d*1e3:.1f} ms: en serie {(t_h + t_k + t_d)*1e3:.1f} ms, "
f"cota con un motor de copia {(t_h + t_d)*1e3:.1f} ms")
for orden in ("trozo", "fase"):
for ns in (1, 2, 4):
mejor, mediana = mejor_pared(lambda: canal(ns, 8, reps, orden))
print(f"orden {orden:5s}, {ns} stream(s): mejor {mejor*1e3:5.1f} ms mediana {mediana*1e3:5.1f} ms")
del h_in, h_out, d
torch.cuda.empty_cache()npm run lab and open the connection link.Across four runs upload took 10.6 to 11.1 ms, kernel 4.4 to 5.3 and download 10.2 or 10.3: 25.2 to 26.2 ms serially and a 20.8 to 21.3 ms bound with one copy engine. Issuing chunk by chunk, no stream count went below 26.3 ms, never better than serial: the false dependency in the copy queue serializes everything as predicted. Issuing by phases, best time fell to 23.1–24.2 ms with 2 streams and 20.9–21.3 ms with 4: with 4 streams the kernel is hidden and time is virtually that of both copies, the bound. Using each run’s times, the preceding model predicts 24.1–25.0 ms with 2 streams and 21.9–22.5 with 4: measurement follows the same direction and gets another millisecond closer to the bound than the model, which is too pessimistic with few streams. With 1 stream no overlap is possible in either order.
Medians were within 4% of the minimum in these runs, but do not assume that. On Windows, consumer GPU drivers use WDDM mode, where the OS schedules the GPU and the driver batches work submissions, and a laptop GPU is also shared with other processes (desktop, browser); the resulting time sharing is outside CUDA’s control. That is why the experiment reports minimum and median, and why the takeaway is structural (issue order decides overlap with one copy engine), not the exact number.
Lab 2: first kernels
SAXPY and a two-dimensional image
saxpy = kernel(r'''
extern "C" __global__ void saxpy(double alfa, const float* __restrict__ x, float* __restrict__ y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = (float)alfa * x[i] + y[i];
}''', "saxpy")
y = torch.rand(n, device=dev); y0 = y.clone()
saxpy(grid=((n + 255) // 256, 1, 1), block=(256, 1, 1), args=[2.0, a, y, n]); torch.cuda.synchronize()
assert torch.allclose(y, 2 * a + y0)
ts = t_gpu(lambda: saxpy(grid=((n + 255) // 256, 1, 1), block=(256, 1, 1), args=[2.0, a, y, n]))
print(f"saxpy con n = 2^26: {12 * n / ts / 1e9:.0f} GB/s ({12 * n / ts / bw_copia:.0%} de la copia), "
f"{2 * n / ts / 1e9:.0f} GFLOP/s, intensidad {2 / 12:.3f} flops/B")npm run lab and open the connection link.SAXPY reads two float and writes one per two flops: flops per byte, well below the GPU’s balance point. In four runs it moved 199 to 208 GB/s (96 to 99% of copy) and computed 33 to 35 GFLOP/s, under 0.5% of FP32 peak: it is memory-bound, so what matters is how many bytes it moves and how well.
The image transformation applies gamma correction, , to an 8K image () in float32, using two kernels identical except for which index threadIdx.x traverses: in gamma_bien columns (contiguous addresses in a warp); in gamma_mal rows (addresses bytes apart).
src2d = r'''
extern "C" __global__ void gamma_bien(const float* x, float* y, int H, int W, double g) {
int col = blockIdx.x * blockDim.x + threadIdx.x; // threadIdx.x recorre columnas: contiguo
int fila = blockIdx.y * blockDim.y + threadIdx.y;
if (fila < H && col < W) y[fila * W + col] = powf(x[fila * W + col], (float)g);
}
extern "C" __global__ void gamma_mal(const float* x, float* y, int H, int W, double g) {
int fila = blockIdx.x * blockDim.x + threadIdx.x; // threadIdx.x recorre filas: saltos de W elementos
int col = blockIdx.y * blockDim.y + threadIdx.y;
if (fila < H && col < W) y[fila * W + col] = powf(x[fila * W + col], (float)g);
}'''
gb, gm = kernel(src2d, "gamma_bien"), kernel(src2d, "gamma_mal")
H, W = 4320, 7680
img = torch.rand(H, W, device=dev); out = torch.empty_like(img)
gb(grid=((W + 15) // 16, (H + 15) // 16, 1), block=(16, 16, 1), args=[img, out, H, W, 2.2]); torch.cuda.synchronize()
assert torch.allclose(out, img ** 2.2, rtol=1e-5, atol=1e-6)
print(f"bloques de 16 x 16 para 7680 x 4320: rejilla de {(W + 15) // 16} x {(H + 15) // 16} = {((W + 15) // 16) * ((H + 15) // 16)} bloques")
print("bloque x -> columnas x -> filas (GB/s)")
for bx, by in ((16, 16), (32, 8), (8, 32), (32, 32)):
t_b = t_gpu(lambda: gb(grid=((W + bx - 1) // bx, (H + by - 1) // by, 1), block=(bx, by, 1), args=[img, out, H, W, 2.2]))
t_m = t_gpu(lambda: gm(grid=((H + bx - 1) // bx, (W + by - 1) // by, 1), block=(bx, by, 1), args=[img, out, H, W, 2.2]))
print(f"{bx:2d} x {by:2d} {8 * H * W / t_b / 1e9:10.0f} {8 * H * W / t_m / 1e9:10.0f}")
print(f"registros por hilo: {registros(gb)}; bloques residentes por SM con 256 y con 1024 hilos: "
f"{bloques_residentes(gb, 256)}, {bloques_residentes(gb, 1024)}")
del img, outnpm run lab and open the connection link.Across four runs, with blocks the well-oriented kernel moved 215–229 GB/s and the reversed one 128–144; with , 201–227 versus 62–79, about three times less. The reversed version worsens as the block gets wider in because more warp lanes fall in different rows: with all 32 lanes read 32 rows, one sector per lane, yielding the theorem’s large-stride efficiency. With , by contrast, a reversed-kernel warp covers 8 rows by 4 consecutive columns: 8 spans of 16 bytes, half of 8 sectors, with less damage (163–189 GB/s). The lesson is the execution-model convention: threadIdx.x traverses the memory-contiguous index.
The block (1024 threads) performed worse even well oriented (144–176 GB/s). The driver says 6 blocks of 256 threads fit per SM (48 warps), but only 1 of 1024 (32 warps): huge blocks lower occupancy, and an SM must wait for the block’s last warp before receiving another. Blocks of 128 to 256 threads are a good starting point.
Measuring coalescing: stride and AoS versus SoA
salto = kernel(r'''
extern "C" __global__ void lee_con_salto(const float* __restrict__ x, float* __restrict__ y, int m, int s) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < m) y[i] = x[(long long)i * s];
}''', "lee_con_salto")
def t_frio(f, rep=10):
"""Como t_gpu, pero vacía la L2 antes de cada repetición: con stride 1 este kernel toca 32 MiB,
lo mismo que la L2, y entre repeticiones se serviría de la caché en lugar de la DRAM."""
f(); ts = []
for _ in range(rep):
b.zero_() # escribir 256 MiB expulsa de la L2 lo anterior
e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
e0.record(); f(); e1.record(); e1.synchronize()
ts.append(e0.elapsed_time(e1) / 1e3)
return statistics.median(ts)
m = 2**22
xs = torch.rand(m * 32, device=dev); ys = torch.empty(m, device=dev)
print("stride GB/s útiles modelo de sectores (fracción útil del tráfico)")
for s in (1, 2, 4, 8, 16, 32):
t = t_frio(lambda: salto(grid=((m + 255) // 256, 1, 1), block=(256, 1, 1), args=[xs, ys, m, s]))
util = 8 / (4 * min(s, 8) + 4) # 4 B útiles leídos de 4·min(s, 8) traídos, más 4 B escritos
print(f"{s:6d} {8 * m / t / 1e9:10.1f} {util:10.0%}")
t = t_gpu(lambda: salto(grid=((m + 255) // 256, 1, 1), block=(256, 1, 1), args=[xs, ys, m, 1]))
print(f"stride 1 sin vaciar la L2 entre repeticiones: {8 * m / t / 1e9:.1f} GB/s (el techo teórico de la DRAM es {B_teor / 1e9:.0f})")
del xs, ys
aos_src = r'''
struct Particula { float x, y, z, vx, vy, vz, masa, carga; }; // 32 bytes
extern "C" __global__ void mueve_aos(Particula* p, int n, double dt) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) p[i].x += (float)dt * p[i].vx;
}
extern "C" __global__ void mueve_soa(float* x, const float* vx, int n, double dt) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] += (float)dt * vx[i];
}'''
ka, ks = kernel(aos_src, "mueve_aos"), kernel(aos_src, "mueve_soa")
npart = 2**23
P = torch.rand(npart, 8, device=dev) # AoS: una fila de 8 floats por partícula
X, VX = P[:, 0].contiguous(), P[:, 3].contiguous() # SoA: un array por campo
g = ((npart + 255) // 256, 1, 1)
ka(grid=g, block=(256, 1, 1), args=[P, npart, 0.01]); ks(grid=g, block=(256, 1, 1), args=[X, VX, npart, 0.01])
torch.cuda.synchronize()
assert torch.allclose(P[:, 0], X)
t_a = t_frio(lambda: ka(grid=g, block=(256, 1, 1), args=[P, npart, 0.01]))
t_s = t_frio(lambda: ks(grid=g, block=(256, 1, 1), args=[X, VX, npart, 0.01]))
print(f"\nx += dt·vx con {npart} partículas: AoS {t_a*1e3:.2f} ms, SoA {t_s*1e3:.2f} ms, cociente {t_a / t_s:.1f}")
del P, X, VXnpm run lab and open the connection link.The cell measures with empty L2 (t_frio), which matters: at stride 1 the kernel touches only 32 MiB, fitting L2, and measuring with t_gpu, as the sweep’s last line prints, yields over 300 GB/s “useful,” above theoretical DRAM’s 256. When a measurement exceeds the specification ceiling, you are measuring a cache. With cold L2, stride behaves as predicted: across three runs, 207–211 useful GB/s at stride 1, 135–142 at 2, 80–82 at 4 and about 45 from 8 onward. Relative to stride 1 these are 64–67%, 38 or 39%, and 21–22%; the sector model (also counting 4 bytes written by each thread) predicts 67, 40 and 22%. At stride 8 or above, seven of every eight DRAM bytes read are discarded and useful bandwidth no longer worsens: each lane pays one whole sector and cannot pay more. Particle updating took 5.0 to 5.1 times longer with AoS than SoA versus the traffic-count factor 5.3 from the coalescing section.
Shared-memory reduction
Summing a vector is the parallel reduction analyzed using work and span: additions at depth when arranged in a tree. On the GPU, the tree has three natural levels: within a warp, within a block (shared memory), and between blocks (atomics or a second kernel). The cell compares two versions:
- Naive atomic: every thread adds its element to one accumulator with
atomicAdd. Correct for integer exactness, but atomics on one address serialize in L2. - Shared-memory tree: each 256-thread block loads 256 elements into shared memory, reduces them in steps separated by barriers and performs one atomic operation.
red_src = r'''
extern "C" __global__ void suma_atomica(const float* x, float* s, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) atomicAdd(s, x[i]);
}
extern "C" __global__ void suma_compartida(const float* x, float* s, int n) {
__shared__ float buf[256];
int t = threadIdx.x, i = blockIdx.x * blockDim.x + t;
buf[t] = (i < n) ? x[i] : 0.0f;
__syncthreads();
for (int k = blockDim.x / 2; k > 0; k >>= 1) { // en cada paso, la mitad de los hilos suma un par
if (t < k) buf[t] += buf[t + k];
__syncthreads();
}
if (t == 0) atomicAdd(s, buf[0]); // una atómica por bloque
}'''
acum = torch.zeros(1, device=dev)
ref = a.double().sum().item()
for nombre in ("suma_atomica", "suma_compartida"):
k = kernel(red_src, nombre)
def f(): acum.zero_(); k(grid=((n + 255) // 256, 1, 1), block=(256, 1, 1), args=[a, acum, n])
t = t_gpu(f, rep=10)
print(f"{nombre:16s}: {4 * n / t / 1e9:6.1f} GB/s ({4 * n / t / bw_copia:4.0%} de la copia) "
f"error relativo {abs(acum.item() - ref) / ref:.1e} {registros(k)} registros")
tt = t_gpu(lambda: a.sum())
print(f"{'torch.sum':16s}: {4 * n / tt / 1e9:6.1f} GB/s ({4 * n / tt / bw_copia:4.0%} de la copia) "
f"error relativo {abs(a.sum().item() - ref) / ref:.1e}")npm run lab and open the connection link.Across four runs the atomic version moved 2.7 or 2.8 GB/s, 1% of copy, and also produced 50% error. This is not an atomic failure: it is recursive summation of 67 million numbers between 0 and 1 in float32. When the accumulator reaches , consecutive float are spaced 2 apart, and adding a number below 1 leaves it unchanged after rounding: the accumulator stalls at half the exact value, about . The shared-memory tree sums pairwise within each block, has relative error to and reaches 55 to 59% of copy. torch.sum reaches 112 to 118%: a reduction only reads, and reading without writing outperforms copy alternating reads and writes.
Two ideas missing from the tree bring it closer to bandwidth; they are the final coding exercise. First, one thread per element requires 262 144 blocks, each with 8 barriers and one atomic to sum only 256 numbers; with a grid-stride loop each thread first sums many elements in a register. Second are warp primitives: __shfl_down_sync(mascara, v, k) returns each lane the v value from the lane positions above, directly between registers without shared memory or barriers. Five steps sum 32 warp values into lane 0. A block reduction then takes two rounds of five shuffles and one shared-memory write per warp.
Measuring divergence and occupancy
div = kernel(r'''
extern "C" __global__ void rama(float* x, int modo, int iters) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
float v = x[i];
bool c = (modo == 0) ? true : (modo == 1) ? ((i & 1) == 1) : (((i >> 5) & 1) == 1);
if (c) { for (int k = 0; k < iters; ++k) v = v * 0.999f + 0.001f; }
else { for (int k = 0; k < iters; ++k) v = v * 1.001f - 0.001f; }
x[i] = v;
}''', "rama")
nd = 24 * 1536 * 16
xd = torch.rand(nd, device=dev)
t0 = None
for modo, nombre in ((0, "todos por la misma rama"), (1, "i impar: divergen todos los warps"), (2, "(i / 32) impar: por warp")):
t = t_gpu(lambda: div(grid=(nd // 256, 1, 1), block=(256, 1, 1), args=[xd, modo, 2000]), rep=10)
t0 = t0 or t
print(f"{nombre:36s}: {t * 1e3:6.2f} ms ({t / t0:.2f} veces)")npm run lab and open the connection link.The last cell checks the interactive occupancy calculator against the driver. It compiles a kernel with increasing live values so the compiler uses more registers, and for each block size and several dynamic shared-memory amounts compares formula blocks per SM with cuOccupancyMaxActiveBlocksPerMultiprocessor. It also tests the naive variant counting SM registers as one bank.
import math
def ocupacion(hilos, regs, smem, por_particion=True):
"""Bloques residentes por SM en CC 8.9: el mínimo de los cuatro límites."""
wpb = math.ceil(hilos / 32)
regs_warp = math.ceil(regs * 32 / 256) * 256
warps_por_regs = 4 * (16384 // regs_warp) if por_particion else 65536 // regs_warp
smem_bloque = math.ceil((smem + 1024) / 128) * 128
return min(48 // wpb, 24, warps_por_regs // wpb, (100 * 1024) // smem_bloque)
goloso = r'''
extern "C" __global__ void goloso(float* out, int iters) {
extern __shared__ float sm[];
float a[NV];
#pragma unroll
for (int j = 0; j < NV; ++j) a[j] = threadIdx.x + j;
for (int k = 0; k < iters; ++k) {
#pragma unroll
for (int j = 0; j < NV; ++j) a[j] = a[j] * a[(j + 1) % NV] + 1.0f;
}
float s = 0;
#pragma unroll
for (int j = 0; j < NV; ++j) s += a[j];
if (blockDim.x > 4096) sm[threadIdx.x] = s; // nunca se ejecuta: solo declara memoria compartida dinámica
out[blockIdx.x * blockDim.x + threadIdx.x] = s;
}'''
total, bien, bien_ingenua = 0, 0, 0
for nv in (4, 16, 40, 60, 100, 200):
k = kernel(f"#define NV {nv}\n" + goloso, "goloso")
R = registros(k)
for hilos in range(32, 1025, 32):
for smem in (0, 1024, 8 * 1024, 20 * 1024, 40 * 1024, 47 * 1024):
d_ = bloques_residentes(k, hilos, smem)
total += 1
bien += d_ == ocupacion(hilos, R, smem)
bien_ingenua += d_ == ocupacion(hilos, R, smem, por_particion=False)
print(f"{nv:3d} valores vivos: {R:3d} registros por hilo")
print(f"la calculadora coincide con el driver en {bien} de {total} configuraciones "
f"(contando los registros como un solo banco: {bien_ingenua})")npm run lab and open the connection link.Kernels on the roofline
import numpy as np
import matplotlib.pyplot as plt
B = bw_copia # techo de memoria: la copia medida
P32, P64 = picos["float"], picos["double"] # techos de cómputo: las FMA medidas
puntos = { # (intensidad en flops/B, GFLOP/s medidos)
"saxpy": (2 / 12, 2 * n / ts / 1e9),
"suma en árbol": (1 / 4, None),
"FMA float": (2 * 8 * fmas["float"][2] / 4, P32 / 1e9),
"FMA double": (2 * 8 * fmas["double"][2] / 8, P64 / 1e9),
}
k = kernel(red_src, "suma_compartida")
def f(): acum.zero_(); k(grid=((n + 255) // 256, 1, 1), block=(256, 1, 1), args=[a, acum, n])
puntos["suma en árbol"] = (1 / 4, n / t_gpu(f, rep=10) / 1e9)
puntos["torch.sum"] = (1 / 4, n / t_gpu(lambda: a.sum()) / 1e9)
I = np.logspace(-2, 5, 200)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.loglog(I, np.minimum(P32, I * B) / 1e9, "k-", lw=2, label="techo float32")
ax.loglog(I, np.minimum(P64, I * B) / 1e9, "k--", lw=1.5, label="techo float64")
for nombre, (x_, y_) in puntos.items():
ax.loglog(x_, y_, "o", ms=8, label=nombre)
print(f"{nombre:14s} I = {x_:8.3f} flops/B {y_:8.1f} GFLOP/s {y_ / min(P32 if 'double' not in nombre else P64, x_ * B) * 1e9:5.0%} de su techo")
print(f"punto de equilibrio: {P32 / B:.0f} flops/B en float32 y {P64 / B:.2f} en float64")
ax.set_xlabel("intensidad aritmética (flops por byte de memoria global)")
ax.set_ylabel("GFLOP/s")
ax.legend(fontsize=8)
plt.show()npm run lab and open the connection link.The GPU roofline shows at a glance what the lab measured. SAXPY and reductions sit on the memory ramp at intensities below 1 flop per byte, and the only way to approach their ceiling is to move bytes better (coalescing, grid-stride loops, fewer kernels). FMA kernels are on the plateau: their ceiling is compute. The GPU balance point in float32 is tens of flops per byte, versus under one flop per byte in float64: in double precision on this GPU almost any kernel with arithmetic is compute-bound.
In the tools
In the lab you wrote kernels in CUDA C and compiled them with NVRTC. The Python tools you will encounter for the same purpose are:
- Numba CUDA writes the kernel in Python. NVIDIA’s maintained version is the
numba-cudapackage (pip install numba-cuda[cu12], bundling its own NVVM compiler; in this course’s environment Numba is installed without NVVM, so the lab does not use it). SAXPY and the reduction tree look like:
from numba import cuda, float32
@cuda.jit
def saxpy(a, x, y):
i = cuda.grid(1) # blockIdx.x * blockDim.x + threadIdx.x
if i < x.size:
y[i] = a * x[i] + y[i]
@cuda.jit
def suma_bloques(x, parciales):
buf = cuda.shared.array(256, float32)
t = cuda.threadIdx.x
i = cuda.grid(1)
buf[t] = x[i] if i < x.size else 0.0
cuda.syncthreads()
k = cuda.blockDim.x // 2
while k > 0:
if t < k:
buf[t] += buf[t + k]
cuda.syncthreads()
k //= 2
if t == 0:
parciales[cuda.blockIdx.x] = buf[0]
x = cuda.to_device(x_host) # copia explícita a la GPU
saxpy[(n + 255) // 256, 256](2.0, x, y) # rejilla y bloque entre corchetes
- CuPy imitates NumPy’s API on GPU and permits CUDA C kernels with
cp.RawKernel(fuente, "saxpy"), launched withk((rejilla,), (bloque,), (args...)); scalar arguments must use the exact type (cp.float32(2.0),cp.int32(n)). - torch.cuda is what you use daily:
get_device_propertiesfor hardware,torch.cuda.Event(enable_timing=True)andsynchronizeto measure,torch.cuda.Streamandnon_blocking=Truefor overlap,pin_memoryfor transfers,torch.cuda.CUDAGraphfor tiny kernels. For everyday custom PyTorch kernels use Triton, which works by blocks rather than threads and handles coalescing and shared memory; covered in training at scale. - Actual measurement:
nvidia-smigives instantaneous clocks, power and occupancy, and Nsight Systems (kernel, copy and stream timelines) and Nsight Compute (per-kernel metrics: sectors per request, achieved occupancy, divergence) measure rather than infer them. You will use them in the next lesson’s kernel-level profiling.
Common mistakes
Exercises
x[threadIdx.x * 32] from an aligned float32 array. Is a warp's access coalesced, and how many 32-byte sectors does it request?i processes a vector of elements. Which conditions cause divergence in most warps?More than one answer may be correct.
t0 = time.perf_counter(); k(grid=g, block=b, args=[x, y, n]); t1 = time.perf_counter(). It reports 15 µs for a kernel moving 1 GB, over 60 TB/s. What happened?suma in FUENTE that sums a GPU float32 tensor and reaches at least 80% of the lab copy kernel's bandwidth (counting bytes read for sum and for copy); the lab's shared-memory tree reaches just over half. The result must match the exact sum (in float64) with relative error below also for , and each block must perform one atomicAdd on s[0]. Also adjust the grid in suma_gpu. Starter code is the lab's atomic version: correct for small vectors, slow and with huge error for large ones.import os
import torch
import torch.utils.cpp_extension as cpp_ext
if cpp_ext.CUDA_HOME is None:
import triton
cpp_ext.CUDA_HOME = os.path.join(os.path.dirname(triton.__file__), "backends", "nvidia")
FUENTE = r'''
extern "C" __global__ void suma(const float* __restrict__ x, float* s, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) atomicAdd(s, x[i]);
}'''
_suma = torch.cuda._compile_kernel(FUENTE, "suma")
def suma_gpu(x):
"""Suma de un tensor float32 contiguo de la GPU; devuelve un tensor de un elemento."""
s = torch.zeros(1, device=x.device)
n = x.numel()
_suma(grid=((n + 255) // 256, 1, 1), block=(256, 1, 1), args=[x, s, n])
return sSummary
- SIMT: a 32-thread warp executes one instruction at a time for all; each Ada SM has four partitions with one scheduler each and up to 48 resident warps with on-chip state. Little’s law gives operations needed in flight: on RTX 4060, around 80 KB (about 20 000 threads with a 4-byte load) for idle latency alone, more under load.
- Execution model: kernel, grid of blocks, blocks up to 1024 threads; global index
blockIdx·blockDim + threadIdx, bounds check, grid-stride loops;threadIdx.xtraverses the memory-contiguous index. - Memory: registers (per thread), shared memory (per block, with
__syncthreads), 32 MiB L2 and 256 GB/s global memory. There are no barriers between blocks inside a kernel. - Coalescing: a warp pays in 32-byte sectors; with stride , efficiency is . Lay out data (SoA versus AoS) according to expensive kernels’ accesses.
- Occupancy: minimum of warp, block, register and shared-memory limits. Sufficient parallelism in flight matters, not maximum occupancy.
- Divergence: a warp serially executes every branch taken by any thread; what matters is whether the condition is uniform per warp.
- CPU and GPU: PCIe is 16 times slower than GPU memory; pinned memory, asynchronous copies, multiple streams and correct issue order overlap copy and compute up to the busiest resource’s bound.
- FP64 has 64 times less throughput than FP32 on this GPU: a scientific-computing design constraint.
In the next lesson, efficient kernels, you will use shared memory for matrix-product tiling, write complete reductions and scans (the parallel scan analyzed with work and span), meet Tensor Cores and measure kernels with Nsight. Later, Triton kernels and inter-GPU communication in training at scale build on this same model, and network training on your GPU depends on it for choosing batch sizes and data types.