Unit 12 · GPU Architecture and CUDA Programming¶
1. Setting the scene¶
Scenario: One million values, one operation each
The SensorGrid data science team trains a model that predicts pollution peaks. Before training, every reading must be standardised:
Every output depends on one input only. There are hundreds of millions of values, and training then repeats matrix multiplications billions of times. Sixteen CPU cores help, but the team's GPU has thousands of arithmetic lanes.
Guiding questions
- Why were GPUs invented, and why do they fit data science so well?
- How is a GPU organised, and how is that different from a CPU?
- How do we write a program that runs one small function per data element?
- When does a GPU not help?
2. Intended learning outcomes¶
| # | Outcome | Bloom | CLO |
|---|---|---|---|
| ILO 12.1 | Explain the graphics origins of GPUs and the idea of data parallelism. | UNDERSTAND | 1 |
| ILO 12.2 | Compare CPU and GPU architectures (latency versus throughput, SMs, SIMT, bandwidth). | ANALYSE | 5 |
| ILO 12.3 | Compute global thread indices, launch configurations and data transfer costs. | APPLY | 5 |
| ILO 12.4 | Implement vector addition, matrix addition and a shared memory convolution in CUDA. | APPLY | 5 |
| ILO 12.5 | Explain warps, divergence, latency hiding, occupancy and block scheduling. | UNDERSTAND | 5 |
| ILO 12.6 | Decide whether a data science workload is a good GPU candidate. | EVALUATE | 1 |
3. Motivation: why GPUs matter¶
Modern data science and AI mean doing the same numerical operation many times.
flowchart LR
D["Large data<br/>images, text, tables"] --> M["Repeated math<br/>multiply, add, compare"] --> R["Useful result<br/>model, prediction, image"]
GPU computing is not magic; it is a response to too much repeated numerical work.
Data parallelism¶
flowchart LR
F["same function f"]
d0["x₀"] --> F0["f"] --> o0["y₀"]
d1["x₁"] --> F1["f"] --> o1["y₁"]
d2["x₂"] --> F2["f"] --> o2["y₂"]
d3["x₃"] --> F3["f"] --> o3["y₃"]
Data parallelism = many data elements, the same (or a similar) operation, mostly independent results.
Throughput versus latency¶
| CPU | GPU | |
|---|---|---|
| Design goal | low latency: finish one complex task quickly | high throughput: finish many simple tasks together |
| Cores | few powerful cores | many simpler lanes |
| Best for | control, branching, OS, irregular tasks | arrays, matrices, pixels, tensors |
| Memory focus | large cache hierarchy | high bandwidth |
| Role in DS/AI | orchestration, loading data | matrix and tensor math |
A GPU may not make one operation faster. It makes a huge number of operations finish sooner.
Neural networks contain huge matrices and training repeats similar math millions or billions of times. A dense layer with batch size \(B\), \(n\) inputs and \(m\) outputs costs
For \(B = 256\), \(n = m = 4096\): \(2 \times 256 \times 4096^2 \approx 8.6 \times 10^{9}\) operations for a single layer, forward pass only. This is why GPUs became central to deep learning.
4. Where GPUs came from: graphics¶
GPUs were designed to accelerate graphics, especially 3D games. Rendering converts a 3D scene (objects, lights, materials, camera) into a 2D grid of pixels. A high resolution image has millions of pixels, and each can be computed largely independently.
flowchart LR
S["3D scene<br/>triangle meshes, lights,<br/>materials, camera"] --> G["GPU<br/>many pixel calculations"] --> I["2D image<br/>pixel grid"]
The graphics workload in two steps¶
flowchart TB
subgraph R1["Geometry"]
direction LR
V["Vertices"] --> VP["Vertex processing<br/>where is the triangle<br/>on screen?"] --> R["Rasterisation<br/>which pixels does it<br/>cover? (fragments)"]
end
subgraph R2["Shading"]
direction LR
FS["Fragment shader<br/>what colour is<br/>each pixel?"] --> P["Pixels"]
end
R1 --> R2
| Term | Simple meaning |
|---|---|
| Scene | everything we want to draw: geometry, materials, lights, camera |
| Vertex / primitive | a point in 3D space / a triangle, line or point built from vertices |
| Rasterisation | converting a triangle into the pixels it covers |
| Fragment | a candidate pixel contribution produced by a triangle: work that computes a pixel colour |
| Texture | an image used to colour or decorate a surface |
| Normal | a direction pointing away from the surface |
| Shader | a small function that computes how a surface looks at a point |
| RGBA | red, green, blue and alpha (transparency) |
A shader is a function, run millions of times¶
// simplified idea, not exact graphics code
Color shade(Texture tex, Vector normal, Vector light) {
Color base = tex.read();
float brightness = dot(normal, light);
return base * max(brightness, 0.0f);
}
The dot product measures how aligned the surface normal \(\mathbf{n}\) is with the light direction \(\mathbf{l}\):
Same direction (\(\theta = 0\)): bright. Perpendicular or facing away: dark. A frame may need the same shader millions of times, one per pixel. GPU cores became high throughput because graphics needed many shader executions per frame.
From graphics to data science¶
Around 2001 to 2003 the insight was simple: if a shader can run once per pixel, a numerical function can run once per array element.
flowchart LR
A["Graphics<br/>shader per pixel"] --> B["Same pattern<br/>function per data item"] --> C["Data science<br/>operation per element"]
GPGPU (general purpose computing on GPUs) started as a clever hack: draw a screen sized square of two triangles; a \(512 \times 512\) "image" is really an array; one pixel = one array element; the shader result = the output value. Brook treated the GPU as a stream processor (b = amount * a over 1000 values). In 2007, NVIDIA's Tesla architecture and CUDA removed the need to pretend that data was a picture: programs could launch compute kernels directly.
timeline
title From pixels to compute
1999 : GPUs accelerate graphics
2001 to 2003 : GPGPU with shaders
2004 : Brook streams
timeline
title From compute to AI
2007 : Tesla and CUDA
2012 : Deep networks on GPUs
2017 : Tensor cores
5. CPU refresher¶
A CPU core runs one instruction stream very well: fetch and decode, ALU, and an execution context (program counter, registers, state) that records where the program stopped and what values it had. A multicore CPU has several such strong cores sharing main memory and caches: excellent for irregular work (branches, small tasks, OS, I/O, databases), but if every data item needs the same operation, a few cores become a bottleneck while many tasks wait.
6. GPU architecture: the big picture¶
A GPU is a chip with many parallel compute units connected to high bandwidth memory.
flowchart TB
subgraph CHIP["GPU chip"]
direction LR
S1["SM"] ~~~ S2["SM"] ~~~ S3["SM"] ~~~ S4["SM"] ~~~ S5["SM"] ~~~ S6["SM"]
end
CHIP <-->|"wide memory bus"| DRAM[("GPU memory (DRAM)<br/>high bandwidth, shared by all SMs")]
Modern NVIDIA GPUs are organised around Streaming Multiprocessors (SMs), the main programmable compute units.
flowchart TB
subgraph SM["Streaming Multiprocessor"]
WS["Warp schedulers"] --> EL["Many execution lanes"]
RF["Register file"] --- EL
SH["Shared memory"] --- EL
end
SM <--> GM[("Global memory")]
| Part | Simple meaning |
|---|---|
| Warp scheduler | chooses which group of threads runs next |
| Execution lanes | perform arithmetic operations |
| Register file | very fast private storage for threads |
| Shared memory | fast memory shared by the threads of one block |
| Global memory path | connects the SM to the large GPU memory |
Why bandwidth matters¶
Many workers need data at the same time; compute units are useless if they cannot be fed. Distinguish memory size (how much can be stored) from memory bandwidth (how fast data moves). The roofline model captures the balance. With peak compute \(P_{\text{peak}}\), bandwidth \(\beta\) and arithmetic intensity \(I\) (operations per byte moved):
Worked example: vector addition is memory bound
C[i] = A[i] + B[i] with floats: 1 addition per 12 bytes (read 8, write 4), so \(I = 1/12\) FLOP/byte. With \(\beta = 900\) GB/s: \(P \le 900/12 = 75\) GFLOP/s, far below a peak of about 15 TFLOP/s. Matrix multiplication reuses data and reaches much higher intensity.
xychart-beta
title "Roofline (peak 15 TFLOP/s, 900 GB/s)"
x-axis "Arithmetic intensity (FLOP/byte)" [0.1, 0.5, 1, 2, 4, 8, 16, 32, 64]
y-axis "Attainable TFLOP/s" 0 --> 16
line [0.09, 0.45, 0.9, 1.8, 3.6, 7.2, 14.4, 15, 15]
SIMD and SIMT¶
- SIMD (single instruction, multiple data): one instruction applied to several data lanes at once, vector style.
- SIMT (single instruction, multiple threads): the GPU version. Programmers see threads, each with its own data and registers; the hardware executes groups of threads together with the same instruction.
Hiding latency with many threads¶
An SM keeps many groups of threads ready. When one group waits for memory, the scheduler switches to another, with no cost for saving context because every thread keeps its registers on chip.
gantt
title Latency hiding on one SM
dateFormat X
axisFormat %s
section Warp A
compute :0, 2
wait for memory :crit, 2, 8
compute :8, 10
section Warp B
compute :2, 4
wait :crit, 4, 10
section Warp C
compute :4, 6
section Warp D
compute :6, 8
Many workers + same instruction groups + high bandwidth memory = high throughput.
7. CUDA: compute mode¶
CUDA is a C/C++ language extension for NVIDIA GPUs, low level enough that its abstractions closely match the hardware. Keep asking three questions:
flowchart LR
Q1["How is work<br/>divided?"] ~~~ Q2["Where does<br/>data live?"] ~~~ Q3["How does hardware<br/>execute it?"]
A CUDA thread is not a CPU thread
| CPU pthread | CUDA thread |
|---|---|
| heavyweight software thread | very lightweight logical GPU thread |
| a few to hundreds | thousands to millions launched |
| scheduled by the operating system | scheduled by GPU hardware |
| good for general tasks | good for small data parallel tasks |
Mental model: write a small function for one element; CUDA runs many copies of it.
8. The CUDA thread hierarchy¶
classDiagram
class Grid {
gridDim.x, gridDim.y, gridDim.z
one per kernel launch
}
class Block {
blockIdx.x, blockIdx.y
blockDim.x, blockDim.y
shared memory
__syncthreads()
}
class Thread {
threadIdx.x, threadIdx.y
private registers
}
Grid "1" *-- "many" Block : contains
Block "1" *-- "many" Thread : contains
- A grid contains blocks; blocks contain threads; threads do the work.
- Threads in the same block form a team: they can cooperate through shared memory and synchronise.
- Blocks must be independent: CUDA may run them in any order, on any SM. Never write code that requires block 0 to run before block 1.
Launch syntax¶
dim3 threadsPerBlock(4, 3); // 12 threads per block
dim3 numBlocks(3, 2); // 6 blocks
matrixAdd<<<numBlocks, threadsPerBlock>>>(A, B, C);
The global index¶
For a 1D array each thread computes
flowchart LR
subgraph B0["Block 0"]
a0["t0 → 0"] ~~~ a1["t1 → 1"] ~~~ a2["t2 → 2"] ~~~ a3["t3 → 3"]
end
subgraph B1["Block 1"]
b0["t0 → 4"] ~~~ b1["t1 → 5"] ~~~ b2["t2 → 6"] ~~~ b3["t3 → 7"]
end
Worked example
blockIdx.x = 1, blockDim.x = 4, threadIdx.x = 2: \(i = 1 \times 4 + 2 = 6\). This thread works on element 6.
For matrices and images, use 2D indices and convert to a linear address in row major memory:
Boundary checks¶
The number of blocks is rounded up:
so some threads fall beyond the data. For \(n = 1000\) and 256 threads per block: 4 blocks, 1024 threads, 24 threads must do nothing. Every kernel needs if (i < n).
9. Host, device and memory¶
flowchart LR
H["<b>Host</b> = CPU<br/>runs once:<br/>allocation, data loading,<br/>launch configuration"] -->|"commands +<br/>data copies"| D["<b>Device</b> = GPU<br/>runs many times:<br/>numerical work<br/>per thread"]
// Host code: runs on CPU
matrixAdd<<<numBlocks, threadsPerBlock>>>(A, B, C);
// Device code: runs on GPU
__global__ void matrixAdd(float* A, float* B, float* C) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
C[i] = A[i] + B[i];
}
Separate memories: copying has a cost¶
CPU and GPU have different memories, connected by cudaMemcpy over the PCIe bus.
Worked example: when the copy dominates
Add two arrays of \(10^{8}\) floats (400 MB each). PCIe at 16 GB/s: copying \(A\) and \(B\) in and \(C\) out moves 1.2 GB, about 75 ms. The kernel itself, at 900 GB/s device bandwidth, needs about 1.3 ms. The GPU computes 50 times faster than it is fed. For small or one off problems, transfer overhead dominates; keep data on the GPU across many kernels.
gantt
title Vector addition: where the time goes (ms)
dateFormat X
axisFormat %s
section PCIe
copy A and B in :crit, 0, 50
copy C out :crit, 52, 77
section GPU
kernel :50, 52
Memory spaces on the device¶
flowchart LR
R["Registers<br/>private to a thread<br/>fastest, tiny"] --> S["Shared memory<br/>per block<br/>fast, small"] --> G["Global memory<br/>all blocks and kernels<br/>large, slower"] --> HR["Host RAM<br/>across PCIe<br/>slowest"]
- Local / register variables: each thread has its own copy (same variable name, separate storage per thread).
- Shared memory: visible to the threads of one block; use it when threads reuse nearby data.
- Global memory: visible to all threads, large but slower.
Memory access patterns and coalescing¶
A warp reads memory together. If neighbouring threads read neighbouring addresses (A[0], A[1], …, A[31]), the hardware coalesces the requests into a few wide transactions. Scattered accesses need many separate transactions.
versus up to 32 transactions for fully scattered access. Coalescing is one reason arrays and matrices are ideal GPU data structures.
Beginner performance model: four questions. Enough parallel work? Good memory access? Little divergence? Low transfer overhead?
10. First CUDA programs¶
Vector addition¶
void vectorAddCPU(float* A, float* B, float* C, int n) {
for (int i = 0; i < n; ++i)
C[i] = A[i] + B[i]; // every iteration is independent
}
__global__ void vectorAdd(float* A, float* B, float* C, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
C[i] = A[i] + B[i];
}
}
| CPU loop | CUDA kernel |
|---|---|
| one thread loops over all elements | many threads each handle one element |
index comes from the for loop |
index comes from thread and block IDs |
| no launch configuration | the launch tells the GPU how many threads to run |
The complete workflow¶
sequenceDiagram
participant H as Host (CPU)
participant D as Device (GPU)
H->>H: prepare h_A, h_B
H->>D: cudaMalloc d_A, d_B, d_C
H->>D: cudaMemcpy host → device (A, B)
H->>D: vectorAdd<<<blocks, 256>>>
Note over D: thousands of threads run in parallel
H->>D: cudaMemcpy device → host (C)
D-->>H: result h_C
H->>D: cudaFree
float *d_A, *d_B, *d_C;
size_t bytes = n * sizeof(float);
cudaMalloc(&d_A, bytes);
cudaMalloc(&d_B, bytes);
cudaMalloc(&d_C, bytes);
cudaMemcpy(d_A, h_A, bytes, cudaMemcpyHostToDevice);
cudaMemcpy(d_B, h_B, bytes, cudaMemcpyHostToDevice);
int threads = 256;
int blocks = (n + threads - 1) / threads;
vectorAdd<<<blocks, threads>>>(d_A, d_B, d_C, n);
cudaMemcpy(h_C, d_C, bytes, cudaMemcpyDeviceToHost); // also waits for the kernel
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
Matrix addition with 2D threads¶
__global__ void matrixAdd(float* A, float* B, float* C, int width, int height) {
int col = blockIdx.x * blockDim.x + threadIdx.x;
int row = blockIdx.y * blockDim.y + threadIdx.y;
if (col < width && row < height) {
int index = row * width + col;
C[index] = A[index] + B[index];
}
}
Back to the scenario: standardising readings¶
__global__ void standardise(const float* x, float* y, float mu, float sigma, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = (x[i] - mu) / sigma; // one thread, one reading
}
Many preprocessing steps (normalise, encode, scale) are exactly this pattern: one row or one value per thread.
Launch details¶
- A launch has two parts:
kernel<<<blocks, threadsPerBlock>>>(...). - Start with 128 or 256 threads per block for 1D arrays, then measure. Block sizes should be multiples of 32 (the warp size).
- Kernel launches are asynchronous: the CPU continues immediately.
cudaDeviceSynchronize()makes the CPU wait until the GPU is done (needed, for example, before timing).
11. Shared memory: convolution¶
A 1D convolution with a window of 3 reuses neighbouring values:
__global__ void convolve_v1(int N, float* input, float* output) {
int index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < N) {
float result = 0.0f;
for (int i = 0; i < 3; ++i)
result += input[index + i];
output[index] = result;
}
}
Neighbouring threads read overlapping values: every input element is read up to 3 times from global memory.
#define THREADS_PER_BLK 128
__global__ void convolve_v2(int N, float* input, float* output) {
__shared__ float support[THREADS_PER_BLK + 2];
int index = blockIdx.x * blockDim.x + threadIdx.x;
support[threadIdx.x] = input[index]; // each thread loads one value
if (threadIdx.x < 2) // two threads load the halo
support[THREADS_PER_BLK + threadIdx.x] = input[index + THREADS_PER_BLK];
__syncthreads(); // wait until the tile is complete
float result = 0.0f;
for (int i = 0; i < 3; ++i)
result += support[threadIdx.x + i];
output[index] = result;
}
(For clarity, this lecture version assumes the input has N + 2 elements and N is a multiple of the block size.)
flowchart TB
G[("Global memory: input array")] -->|"load once: 130 values"| T["Shared memory tile<br/>(128 + 2 halo)"]
T -->|"reuse 3 times each"| C["128 threads compute 128 outputs"]
Global reads per block drop from \(3 \times 128 = 384\) to \(128 + 2 = 130\), almost 3× less traffic.
Why __syncthreads()?¶
sequenceDiagram
participant T0 as Thread 0
participant T5 as Thread 5
participant S as Shared tile
T0->>S: store support[0]
Note over T5: still loading...
T0->>T0: __syncthreads() waits
T5->>S: store support[5]
T5->>T5: __syncthreads()
Note over T0,T5: barrier released: every value is in place
T0->>S: read support[0..2]
A barrier means nobody continues until everybody in the block reaches it. __syncthreads() synchronises threads of the same block only; there is no simple global barrier inside a kernel.
12. CUDA semantics¶
- Work hierarchy: grid, block, thread. Memory hierarchy: local, shared, global. Synchronisation: inside a block. Host and device are separate.
- Is CUDA data parallel? Partly: many blocks and threads process many elements (data parallel), but threads in a block cooperate and synchronise, which is SPMD (single program, multiple data) style.
- Address spaces: a shared address space inside a block; a distributed address space between CPU and GPU that requires explicit copies. CUDA is not purely shared memory programming.
- Compilation:
nvccsplits a.cufile into host code (a CPU binary) and device code (a GPU kernel binary). - Who assigns work? The programmer chooses grid and block sizes; the GPU scheduler decides where blocks run.
13. Warps, SMs and scheduling¶
The hardware groups CUDA threads into warps, commonly of 32 threads. The warp scheduler picks a ready warp and issues its next instruction; all active threads of the warp execute that instruction, each on its own data.
Branch divergence¶
gantt
title One warp with a divergent branch
dateFormat X
axisFormat %s
section Even lanes
doA :0, 4
idle :crit, 4, 8
section Odd lanes
idle :crit, 0, 4
doB :4, 8
If the warp's threads take different branches, the paths execute one after the other, with the other lanes masked off. Correctness is not the issue; performance is: with \(k\) distinct paths, efficiency can drop to about \(1/k\).
Occupancy¶
Occupancy is the ratio of active warps on an SM to the maximum it supports:
More ready warps help hide waiting. Each block consumes registers, shared memory and thread slots, so resources limit how many blocks fit on an SM at once. When a block starts, the SM allocates resources for all its threads; they stay until the block completes.
Worked example
An SM supports 64 warps and 64 KB of shared memory. Blocks of 256 threads (8 warps) each use 16 KB of shared memory. Shared memory allows \(64/16 = 4\) blocks, i.e. 32 warps: occupancy \(= 32/64 = 50\,\%\). Reducing shared memory to 8 KB per block allows 8 blocks = 64 warps = 100 %.
Scheduling blocks: a two core GPU¶
The original lecture explains scheduling on a fictitious GPU with two cores.
sequenceDiagram
participant Q as Block queue
participant C0 as Core 0
participant C1 as Core 1
Note over Q: B0 B1 B2 B3 B4 B5 B6 B7 waiting
Q->>C0: assign B0
Q->>C1: assign B1
C0-->>Q: B0 done, resources free
Q->>C0: assign B2
C1-->>Q: B1 done
Q->>C1: assign B3
Note over Q,C1: ... until the queue is empty
The GPU may schedule blocks in any order that is legal for the CUDA model: block 3 first or block 0 first are both allowed. And because threads of a block may synchronise, all threads of a block must exist together; partial block execution would break __syncthreads().
The NVIDIA V100 used in the original lecture has 80 SMs, each with its own warp schedulers and execution units; there is no need to memorise the numbers, only to appreciate the scale.
14. Advanced patterns and pitfalls¶
Histogram with atomics¶
__global__ void histogram(int* A, int* counts, int N) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < N)
atomicAdd(&counts[A[i]], 1); // safe concurrent update
}
An atomic operation updates shared data safely when many threads may update it: no lost updates (Unit 11). But many threads updating the same bin wait for each other (contention). A common optimisation: each block builds a private histogram in shared memory, then adds it to the global one.
Dangerous inter block waiting¶
flowchart LR
B0["Block 0<br/>sets a flag"] -.->|"never scheduled"| F(("flag"))
B1["Block 1<br/>spins until flag is set"] -->|"occupies the only SM"| F
If block 1 runs first on a GPU where only one block fits, block 0 may never run: a deadlock. Blocks must never wait for each other.
Persistent threads (advanced)¶
| Normal CUDA | Persistent threads |
|---|---|
| launch many blocks | launch just enough blocks to fill the GPU |
| hardware assigns blocks | the program pulls chunks from a global work counter |
| portable mental model | hardware specific |
| good for beginners | advanced optimisation style |
15. GPUs in data science and AI¶
mindmap
root((GPU in<br/>DS and AI))
Images
filter every pixel
Vision
CNN convolutions
Deep learning
matrix multiply
batches
Retrieval
embedding search
Tensor cores
small matrix units
- Batches give the GPU more parallel work at once: one example is too little, a batch fills the device.
- Vector search: comparing a query embedding with millions of document vectors is one dot product per document, a perfect data parallel task (compare IR Unit 9).
- Tensor cores are specialised units for very fast small matrix multiplications, the engine of deep learning speedups.
When GPUs do not help¶
quadrantChart
title Is this a GPU workload?
x-axis Few independent operations --> Many independent operations
y-axis Branchy or transfer heavy --> Regular and data resident
quadrant-1 Great GPU fit
quadrant-2 Restructure first
quadrant-3 Stay on CPU
quadrant-4 Maybe, measure
Add 100M element arrays: [0.9, 0.85]
Filter every pixel of a 4K image: [0.85, 0.8]
Train a neural network: [0.95, 0.9]
Read a small config file: [0.05, 0.1]
Complex decision tree for one item: [0.1, 0.25]
flowchart LR
A{"Many independent<br/>operations?"} -->|"yes"| B{"Enough data?"}
B -->|"yes"| C{"Low transfer<br/>overhead?"}
C -->|"yes"| G["Use the GPU"]
A -->|"no"| X["Use the CPU"]
B -->|"no"| X
C -->|"no"| X
End to end, CPU and GPU cooperate: the CPU loads data, a batch is copied to the GPU, the GPU trains, CPU and GPU evaluate. CPU organises; GPU calculates in parallel; an AI system uses both.
Finally, the same hardware serves two interfaces: the graphics pipeline (draw triangles) and CUDA compute (launch kernels). In CUDA we focus on the programmable SMs; the graphics specific units are mostly idle.
16. Classwork¶
Check your understanding 1: good GPU candidate?
- Add two arrays with 100 million elements.
- Read a small configuration file.
- Apply a filter to every pixel of a 4K image.
- Execute a complex decision tree with many branches for one item.
- Multiply large matrices during neural network training.
Answers
1 yes, 2 no, 3 yes, 4 no, 5 yes.
Check your understanding 2: thread, block, grid, warp
Explain each term. Which are programming concepts and which are mostly hardware execution concepts?
Answer
Thread, block and grid are programming concepts the programmer controls in the launch. A warp (32 threads executed together) is a hardware execution concept, although it affects performance through divergence and coalescing.
Mini exercise: write the index
Answer
blockIdx.x * blockDim.x + threadIdx.x
Mini exercise: identify memory spaces
In the workflow CPU array → GPU array → block tile, label host memory, device global memory and shared memory.
Answer
CPU array: host memory. GPU array: device global memory. Block tile: shared memory.
Launch arithmetic
\(n = 10^{6}\), 256 threads per block. How many blocks, threads, warps per block, and idle threads?
Answer
Blocks \(= \lceil 10^6 / 256 \rceil = 3907\); threads \(= 3907 \times 256 = 1{,}000{,}192\); 8 warps per block; 192 threads fail the boundary check.
Common mistakes¶
mindmap
root((Common<br/>mistakes))
Forgetting the boundary check
Copying too often
Unsafe block dependencies
Confusing thread and warp
Ignoring the memory access pattern
17. Key takeaways¶
- GPUs began as graphics processors computing many pixel colours.
- The same idea became general data parallel computation (GPGPU, then CUDA in 2007).
- A GPU has many SMs, many execution lanes and high bandwidth memory.
- CUDA divides work into grids, blocks and threads; \(i = \texttt{blockIdx.x}\cdot\texttt{blockDim.x} + \texttt{threadIdx.x}\).
- Threads in a block cooperate through shared memory and
__syncthreads(). - Hardware executes threads in warps (SIMT); divergence and scattered access cost performance.
- DS and AI fit GPUs: large arrays, matrices and tensors. But transfers, branches and small inputs can erase the benefit.
Best mental model: the CPU is the coordinator; the GPU is the high throughput numerical engine.
18. Link to assessment¶
Portfolio option: implement the SensorGrid standardisation and a distance or dot product kernel in CUDA (or CuPy / Numba if no CUDA toolkit is available), measure \(T_{\text{copy}}\) and \(T_{\text{kernel}}\) separately, and explain the result with the roofline model.
Further reading¶
- K. Fatahalian, K. Olukotun, CS149 Parallel Computing, Stanford, lectures on GPU architecture and CUDA.
- D. B. Kirk, W. W. Hwu, Programming Massively Parallel Processors, 4th ed.
- NVIDIA, CUDA C++ Programming Guide.
- S. Williams, A. Waterman, D. Patterson (2009), Roofline: an insightful visual performance model, CACM 52(4).