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.
  • 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.
    BroadcastFour ranks, before and after broadcast: one → everyone. Reduction uses elementwise sum.BroadcastBeforeAfter0abcd1230abcd1abcd2abcd3abcdcolumns = ranks · colored cells = owned data
  • 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.
    ScatterFour ranks, before and after scatter: one shards → everyone. Reduction uses elementwise sum.ScatterBeforeAfter0abcd1230a1b2c3dcolumns = ranks · colored cells = owned data
  • 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.
    GatherFour ranks, before and after gather: everyone → one. Reduction uses elementwise sum.GatherBeforeAfter0a1b2c3d0abcd123columns = ranks · colored cells = owned data
  • 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.
    ReduceFour ranks, before and after reduce: combine → one. Reduction uses elementwise sum.ReduceBeforeAfter01122334010123columns = ranks · colored cells = owned data
  • 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-reduceFour ranks, before and after all-reduce: combine → everyone. Reduction uses elementwise sum.All-reduceBeforeAfter01122334010110210310columns = ranks · colored cells = owned data
  • 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.
    All-gatherFour ranks, before and after all-gather: all shards → everyone. Reduction uses elementwise sum.All-gatherBeforeAfter0a1b2c3d0abcd1abcd2abcd3abcdcolumns = ranks · colored cells = owned data
  • 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.
    Reduce-scatterFour ranks, before and after reduce-scatter: combine → one shard each. Reduction uses elementwise sum.Reduce-scatterBeforeAfter0123411020304021002003004003100020003000400001111122222333334444columns = ranks · colored cells = owned data
  • 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.
    All-to-allFour ranks, before and after all-to-all: each rank → a different shard to every rank. Reduction uses elementwise sum.All-to-allBeforeAfter0a0a1a2a31b0b1b2b32c0c1c2c33d0d1d2d30a0b0c0d01a1b1c1d12a2b2c2d23a3b3c3d3columns = ranks · colored cells = owned data

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

ParallelismWhat is split?One-line intuition
DP — Data ParallelismBatchEvery GPU has the same model and trains on different data.
TP — Tensor ParallelismWeight matrix / hidden dimensionSplit a large layer across GPUs so they compute it together.
PP — Pipeline ParallelismTransformer layersEach GPU owns different layers, forming a pipeline.
CP — Context ParallelismSequence lengthSplit one long sequence’s token positions across GPUs.
EP — Expert ParallelismMoE expertsDifferent 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:
      1. Run the forward pass on the local micro-batch.
      2. Compute gradients for all parameters.
      3. All-reduce gradients across GPUs so each GPU has the averaged \(G\).
      4. 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
        1. run forward pass on local micro-batch
        2. compute grads for all params
        3. reduce-scatter gradients: each GPU has reduced gradients for its subset of parameters
        4. each GPU updates their subset of params using its subset of optimizer states
        5. 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
        1. run forward pass on local micro-batch
        2. as each layer’s gradients are computed, they’re immediately reduce-scattered. each GPU keeps only its subset of gradients and frees the rest.
        3. each GPU updates their subset of params using its subset of optimizer states
        4. 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
    Tensor-parallel MLP on four GPUsSplit W up of shape D by F into four column shards D by F over four. Compute h i equals activation of x times W up i locally. Split W down of shape F by D into four row shards F over four by D. Each local y i has shape one by D; all-reduce sums all four partial outputs.1 · Column-parallel up-projectionW_upD × F0123W_up⁽ⁱ⁾D × (F/4)Same x on every GPU → local matmul → local activationGPU 0h0 = σ(x W_up⁽0⁾)1 × (F/4)GPU 1h1 = σ(x W_up⁽1⁾)1 × (F/4)GPU 2h2 = σ(x W_up⁽2⁾)1 × (F/4)GPU 3h3 = σ(x W_up⁽3⁾)1 × (F/4)2 · Row-parallel down-projectionW_downF × DW_down⁽0⁾W_down⁽1⁾W_down⁽2⁾W_down⁽3⁾W_down⁽ⁱ⁾: (F/4) × Dyᵢ = hᵢ W_down⁽ⁱ⁾yᵢ: 1 × D (a partial sum)No all-gather between the two layers.3 · All-reduce the partial outputsGPU 0: y01 × DGPU 1: y11 × DGPU 2: y21 × DGPU 3: y31 × DSUM: y = y₀ + y₁ + y₂ + y₃Every GPU receives the same complete y: 1 × D.
    • 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\).

4. FlashAttention

  • standard attention

    • the memory problem is that attn_weights is (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
    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)
  • 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() or attn_implementation="flash_attention_2" in from_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 output
  • FlashAttention never materializes the full \(N\times N\) matrix, and instead computes attention in tiles small enough to fit in SRAM

  • conceptually

    1. load a block of \(Q\) (say, 64 rows)
    2. load a block of K and V (say, 64 columns)
    3. compute that tile of attention scores, apply softmax, multiply by V — all in SRAM
    4. repeat for all tiles
    5. 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.

    1. 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.
    2. 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]\).
    3. 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])\).
    4. 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]\).
    5. 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_heads parallel workers working on each m × head_dim tile of Q, K, V where m is the tile size

  • Flash Attention is an exact, not approximate, method

  • how to use Flash Attention

    • is_causal=True flag 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