GPU and Optimizations
1. GPU terminology
- SM — Streaming Multiprocessor: an independent GPU compute block that schedules warps and contains arithmetic units, registers, and on-chip memory.
- SRAM — Static Random-Access Memory: very small, very fast on-chip storage (for example shared memory/L1) used to reuse data close to the SM.
- Shared-memory/L1 SRAM per SM: A100 192 KiB, H100 256 KiB, and GB300’s Blackwell Ultra GPU 256 KiB (NVIDIA).
- HBM — High-Bandwidth Memory: large off-chip GPU memory that stores weights, activations, and KV cache; it has far more capacity than SRAM but much higher access cost.
- HBM per GPU: A100 40/80 GB, H100 SXM 80 GB, and GB300’s Blackwell Ultra GPU 288 GB.
- Arithmetic intensity: useful computation divided by memory traffic, measured in FLOPs/byte. Example:
200 FLOPs ÷ 100 bytes = 2 FLOPs/byte; raising reuse raises the intensity. - Memory-bound: runtime is limited by moving bytes rather than available arithmetic. Example: single-token decode repeatedly streams model weights and KV cache from HBM for relatively little computation.
- Compute-bound: runtime is limited by arithmetic throughput after data reuse is high enough. Example: prefill uses large matrix multiplications whose tiles are reused many times on the SMs.
2. Collective communication
- Broadcast
- Definition: one → everyone.
- Example: rank 0 sends a seed or configuration tensor; every rank receives an identical copy.
- Training use: Initialize replicated state or distribute metadata from the coordinator.
- Scatter
- Definition: one shards → everyone.
- Example: rank 0 splits [a,b,c,d], sending one shard to each of four ranks.
- Training use: Distribute batch or tensor shards when one process initially owns the full input.
- Gather
- Definition: everyone → one.
- Example: ranks holding [1], [2], [3], [4] send them to rank 0, which receives [1,2,3,4].
- Training use: Collect evaluation predictions, checkpoints, or diagnostics on one destination.
- Reduce
- Definition: combine → one.
- Example: local losses 1,2,3,4 are summed to 10 only on rank 0.
- Training use: Aggregate a metric or scalar loss on the logging rank without replicating it everywhere.
- All-reduce
- Definition: combine → everyone.
- Example: all ranks sum local gradient values and every rank receives the same total.
- Training use: Distributed Data Parallel synchronizes replicated-model gradients before each optimizer step.
- All-gather
- Definition: all shards → everyone.
- Example: four parameter shards become one full [1,2,3,4] tensor on every rank.
- Training use: FSDP/ZeRO-3 reconstructs the next layer parameters just in time for forward or backward.
- Reduce-scatter
- Definition: combine → one shard each.
- Example: elementwise-sum four gradient vectors, then give rank i only reduced shard i.
- Training use: FSDP/ZeRO keeps reduced gradients sharded instead of materializing a full gradient on every rank.
- All-to-all
- Definition: each rank → a different shard to every rank.
- Example: each rank sends a different token slice to each destination, transposing ownership.
- Training use: Expert Parallelism dispatches routed tokens to MoE experts and returns their outputs.
Reduce-scatter sums each vector position, then distributes the reduced shards; all-gather copies shards without adding them. Reduce-scatter + all-gather = all-reduce.
3. Parallelism
| Parallelism | What is split? | One-line intuition |
|---|---|---|
| DP — Data Parallelism | Batch | Every GPU has the same model and trains on different data. |
| TP — Tensor Parallelism | Weight matrix / hidden dimension | Split a large layer across GPUs so they compute it together. |
| PP — Pipeline Parallelism | Transformer layers | Each GPU owns different layers, forming a pipeline. |
| CP — Context Parallelism | Sequence length | Split one long sequence’s token positions across GPUs. |
| EP — Expert Parallelism | MoE experts | Different GPUs host different experts; route tokens to them as needed. |
- Data parallelism
- Split examples within a \(B\)-sized batch across \(M\) devices and exchange gradients.
- Steps:
- Run the forward pass on the local micro-batch.
- Compute gradients for all parameters.
- All-reduce gradients across GPUs so each GPU has the averaged \(G\).
- Each GPU independently updates all parameters.
- Each GPU does identical work in this step.
- When the model and its training state fit on one device, DP is the usual starting point for throughput scaling.
- Gradient synchronization happens during backward, apart from initialization and optional buffer synchronization.
- Add devices to increase the global batch size, subject to useful batch-size limits.
FSDP / ZeRO · model-state sharding
FSDP / ZeRO further shards parameters, gradients, or optimizer states to reduce the model-state memory of DP replicas; it is model-state sharding in the Data Parallel family, rather than Tensor Parallelism.
- ZeRO stage 1: shard optimizer states
- each device holds \(1/M\) of the Adam vectors, and only updates the parameters that it has optimizers for
- steps
- run forward pass on local micro-batch
- compute grads for all params
- reduce-scatter gradients: each GPU has reduced gradients for its subset of parameters
- each GPU updates their subset of params using its subset of optimizer states
- all-gather the updated parameters
- reduce-scatter plus all-gather has comparable communication volume to all-reduce; actual runtime depends on the implementation and overlap
- ZeRO stage 2: shard optimizer states + gradients
- also shard gradients so each device only holds \(1/M\) of the gradients
- steps
- run forward pass on local micro-batch
- as each layer’s gradients are computed, they’re immediately reduce-scattered. each GPU keeps only its subset of gradients and frees the rest.
- each GPU updates their subset of params using its subset of optimizer states
- all-gather the updated parameters
- ZeRO stage 3: shard optimizer states + gradients + parameters (FSDP)
- also shards parameters so each device only holds \(1/M\) of the parameters
- all-gather parameters for each layer just in time, use them, then discard
- can train models that don’t fit on one GPU
- ZeRO-3 additionally all-gathers parameters for computation and typically communicates more than ZeRO-1/2; traffic depends on the resharding policy
- Tensor parallelism
Tensor-parallel MLP · four GPUs - For an MLP (two linear layers with an activation in between), use column parallelism for \(W^{\text{up}}\) → local activation → row parallelism for \(W^{\text{down}}\).
- Split the first weight matrix column-wise: \(W^{\text{up}}_i\in\mathbb{R}^{D\times(F/4)}\) on four GPUs.
- Each GPU computes its shard and applies the activation locally: \(h_i=\sigma(XW^{\text{up}}_i)\).
- Split the second weight matrix row-wise: \(W^{\text{down}}_i\in\mathbb{R}^{(F/4)\times D}\).
- Each GPU computes a partial output \(y_i=h_iW^{\text{down}}_i\), then all-reduce sums the partial outputs: \(y=\sum_{i=0}^{3}y_i\).
- The key identity is \(y=[h_0,h_1,h_2,h_3]\begin{bmatrix}W^{\text{down}}_0\\W^{\text{down}}_1\\W^{\text{down}}_2\\W^{\text{down}}_3\end{bmatrix}=\sum_i h_iW^{\text{down}}_i\).
- For an MLP (two linear layers with an activation in between), use column parallelism for \(W^{\text{up}}\) → local activation → row parallelism for \(W^{\text{down}}\).
4. FlashAttention
standard attention
- the memory problem is that
attn_weightsis(batch, num_heads, seq_len, seq_len)- with
seq_len= 8192 and 32 heads in FP16, that's 8192² × 32 × 2 bytes ≈ 4 GiB for batch size 1
- with
import torch import torch.nn.functional as F import math def standard_attention(q, k, v): # q, k, v are all (batch, num_heads, seq_len, head_dim) scale = math.sqrt(q.size(-1)) # Materialize full N×N attention matrix attn_weights = torch.matmul(q, k.transpose(-2, -1)) / scale # (batch, num_heads, seq_len, seq_len) attn_weights = F.softmax(attn_weights, dim=-1) output = torch.matmul(attn_weights, v) # (batch, num_heads, seq_len, head_dim) return output- why standard attention is memory bound: the \(N\times N\) attention matrix is written to HBM, read back (to compute softmax), written again, read again (to actually use)
- the memory problem is that
flash attention computes attention in blocks using online softmax trick, keeping intermediate results in fast SRAM rather than writing the full attention matrix to GPU main memory
- reduces activation memory for attention from \(O(n^2)\) to \(O(n)\)
- faster because memory bandwidth isn’t the bottleneck
- enable at inference time with
model.to_bettertransformer()orattn_implementation="flash_attention_2"infrom_pretrained()
def flash_attention(q, k, v): # Same input shapes: (batch, num_heads, seq_len, head_dim) # PyTorch picks the best backend automatically (Flash Attention, memory-efficient, or math) output = F.scaled_dot_product_attention(q, k, v, is_causal=True) return outputFlashAttention never materializes the full \(N\times N\) matrix, and instead computes attention in tiles small enough to fit in SRAM
conceptually
- load a block of \(Q\) (say, 64 rows)
- load a block of K and V (say, 64 columns)
- compute that tile of attention scores, apply softmax, multiply by V — all in SRAM
- repeat for all tiles
- normalize the completed output, then write it to HBM
detailed process
Online softmax example: keep only \(m\), \(\ell\), and \(o_{\mathrm{num}}\) as running state; discard each temporary score tile after consuming it. Displayed decimals are rounded.
- Load a query block. Keep the query rows on chip while iterating over K/V tiles.
- Example: follow one query whose four keys are all visible; its already-scaled score row is \([1,0,1,2]\). Ordinary attention sees all four scores together; FlashAttention processes two tiles.
- Load one K/V tile. Bring only the current keys and values into SRAM.
- Example: tile 1 has scores \([1,0]\) and values \(V_1=[1,0],\ V_2=[0,2]\); tile 2 has scores \([1,2]\) and values \(V_3=[3,1],\ V_4=[2,2]\).
- Compute the first tile and initialize the running state. Track a maximum, an exponential sum, and an unnormalized weighted-value numerator.
- Example: \(m^{(1)}=\max(1,0)=1\), \(\ell^{(1)}=e^{1-1}+e^{0-1}=1+e^{-1}\approx1.368\), and weights \([1,e^{-1}]\approx[1,0.368]\) give \(o_{\mathrm{num}}^{(1)}=1[1,0]+e^{-1}[0,2]=[1,2e^{-1}]\approx[1,0.736]\). The running state is \((m,\ell,o_{\mathrm{num}})\approx(1,1.368,[1,0.736])\).
- Repeat over K/V tiles, rescaling and merging. If a later tile raises the running maximum, rescale both the old sum and numerator before adding the new tile.
- Example, tile 2 denominator: \(m_{\mathrm{tile}}=\max(1,2)=2\), \(m'=\max(1,2)=2\), and \(\alpha=e^{m-m'}=e^{-1}\approx0.368\). Rescale the old sum: \(\ell_{\mathrm{old,rescaled}}=(1+e^{-1})e^{-1}\approx1.368\times0.368\approx0.503\); the new tile contributes \(\ell_{\mathrm{tile}}=e^{1-2}+e^{2-2}=e^{-1}+1\approx1.368\), so \(\ell'=1+2e^{-1}+e^{-2}\approx0.503+1.368=1.871\).
- Example, tile 2 numerator: its weighted values are \(e^{-1}[3,1]+1[2,2]\approx[3.104,2.368]\). Rescale the old numerator: \(e^{-1}[1,2e^{-1}]\approx[0.368,0.271]\), then merge: \(o'_{\mathrm{num}}=[2+4e^{-1},\ 2+e^{-1}+2e^{-2}]\approx[0.368,0.271]+[3.104,2.368]=[3.472,2.639]\).
- Normalize and write the final output to HBM. Only write the completed output after all K/V tiles have contributed.
- Example: \(o=\frac{o'_{\mathrm{num}}}{\ell'}\approx[1.855,1.410]\) for this query, using unrounded intermediate values. This matches computing softmax over \([1,0,1,2]\) at once and multiplying by the four value vectors; only the execution order changes.
Why subtract the row maximum? Before exponentiating, subtract the largest score seen so far to avoid numerical overflow from very large \(e^x\).
- Example: start with scores \([1,0]\); find the max, \(m=\max(1,0)=1\); shift the scores, \([1,0]-1=[0,-1]\); exponentiate, \([e^0,e^{-1}]\approx[1,0.368]\). The local exp-sum is \(\boxed{\ell=e^0+e^{-1}\approx1.368}\); the \(-1\) comes from \(0-1=-1\).
- Softmax is unchanged: \(\operatorname{softmax}(x_i)=\frac{e^{x_i}}{\sum_j e^{x_j}}\) and \(\frac{e^{x_i-m}}{\sum_j e^{x_j-m}}=\frac{e^{x_i}/e^m}{\sum_j e^{x_j}/e^m}=\frac{e^{x_i}}{\sum_j e^{x_j}}\). The common \(e^m\) factor cancels between numerator and denominator.
since every (batch, head) combination is completely independent, you have
batch × num_headsparallel workers working on eachm × head_dimtile of Q, K, V wheremis the tile sizeFlash Attention is an exact, not approximate, method
how to use Flash Attention
is_causal=Trueflag is fused into the kernel efficiently rather than materializing a mask matrix
def flash_attention(q, k, v): # Same input shapes: (batch, num_heads, seq_len, head_dim) # PyTorch picks the best backend automatically (Flash Attention, memory-efficient, or math) output = F.scaled_dot_product_attention(q, k, v, is_causal=True) return output