LLM Masterclass / Module 4 of 10 Phase 2: Pre-Training, SFT & Parameter-Efficient Fine-Tuning (LoRA/QLoRA)

Pre-Training Pipelines, Distributed Parallelism (ZeRO/FSDP/3D) & Autoregressive Decoding Samplers

28 min study + 2 Live Wasm Labs
⚑ Answer-First Executive Summary (TL;DR) Module 4 Key Takeaways
  • βœ“ In mixed-precision (BF16/FP32) pre-training with AdamW, every 1 billion parameters requires 16 GB of static VRAM just for model state: 2 GB BF16 weights + 2 GB BF16 gradients + 12 GB FP32 AdamW states (master weights + momentum m + variance v).
  • βœ“ ZeRO-3 / PyTorch FSDP eliminates redundant replication across N GPUs by sharding optimizer states (ZeRO-1), gradients (ZeRO-2), and model weights (ZeRO-3), reducing per-GPU static memory from 16Ξ¨ bytes to 16Ξ¨ / N bytes.
  • βœ“ Autoregressive decoding transforms raw logits z ∈ ℝ^V into token probabilities: Temperature T scales logits (z / T), Top-K keeps the K highest-logit tokens, Top-P (Nucleus) keeps the smallest prefix of tokens whose cumulative probability β‰₯ p, and Min-P filters tokens below p_min Γ— p_max.
  • βœ“ Speculative Decoding accelerates generation by 2–3x with zero quality change: a tiny Draft model proposes Ξ³ tokens serially, and the large Target model verifies all Ξ³+1 tokens in a single parallel forward pass.

01. The 16Ξ¨ Mixed-Precision Memory Rule & 4D Distributed Parallelism

Table 4.1 β€” Distributed LLM Training Strategies: Sharding & Interconnect Requirements
Parallelism Strategy What Is Sharded? Per-GPU Static VRAM (Ξ¨ params, N GPUs) Hardware Interconnect Scope
Standard DDP Input mini-batches only 2Ξ¨ + 2Ξ¨ + 12Ξ¨ = 16Ξ¨ (1120 GB for 70B!) Only fits models ≀ 3B per 80GB GPU.
ZeRO-1 FP32 Optimizer States (12Ξ¨) 4Ξ¨ + 12Ξ¨ / N Inter-node InfiniBand / RoCE (minimal comm overhead).
ZeRO-2 Optimizer States + Gradients (14Ξ¨) 2Ξ¨ + 14Ξ¨ / N Inter-node InfiniBand / RoCE.
ZeRO-3 / PyTorch FSDP Weights + Gradients + Optimizer (16Ξ¨) 16Ξ¨ / N (17.5 GB/GPU for 70B on 64 GPUs!) All-gather weights per layer before forward/backward.
Tensor Parallelism (TP) Intra-layer WQ, WK, WV, WFFN matrices Divides both weights & activations by TP Intra-Node NVLink ONLY (TP ∈ {2, 4, 8}).

02. The Autoregressive Logit Sampling Pipeline (Temperature β†’ Top-K β†’ Top-P β†’ Min-P)

Raw Unembedding Logits: z = h_last @ W_vocab^T   (z ∈ ℝ^V)
  β”‚
  β”œβ”€β–Ά 1. Repetition / Frequency Penalty: Penalize token IDs already present in prompt/output
  β”œβ”€β–Ά 2. Temperature Scaling: z_i <- z_i / T   (T -> 0 approaches argmax greedy; T > 1 flattens distribution)
  β”œβ”€β–Ά 3. Top-K Truncation: Mask all logits outside the K highest values to -∞
  β”œβ”€β–Ά 4. Softmax Normalization: p_i = exp(z_i) / Ξ£_j exp(z_j)
  β”œβ”€β–Ά 5. Top-P (Nucleus) & Min-P Filtering:
  β”‚      β€’ Top-P: Sort p descending; keep minimal prefix where cumulative sum >= P (e.g. P=0.90)
  β”‚      β€’ Min-P: Keep tokens where p_i >= min_p * p_max (adapts dynamically to model confidence!)
  └─▢ 6. Multinomial Sample from Renormalized Survivors

πŸ’» Hands-On WebAssembly LLM Engineering Labs (Module 4)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.

β–Ά Interactive Wasm Lab

Lab 4.1: Implementing Temperature, Top-K, Top-P (Nucleus) & Min-P Logit Samplers from Scratch

Run this live Python lab to inspect how Temperature, Top-K, Top-P Nucleus, and Min-P transform a vocabulary logit vector into a calibrated next-token probability distribution.

import math

raw_logits = {
    "SELECT":  4.20,
    "WITH":    3.60,
    "EXPLAIN": 2.50,
    "UPDATE":  1.10,
    "DROP":   -0.80,
    "banana": -3.50,
}

def sample_distribution(
    logits: dict[str, float],
    *,
    temperature: float = 1.0,
    top_k: int | None = None,
    top_p: float | None = None,
    min_p: float | None = None,
) -> dict[str, float]:
    # 1. Temperature scaling
    scaled = {tok: val / max(temperature, 1e-5) for tok, val in logits.items()}
    ranked = sorted(scaled.items(), key=lambda kv: kv[1], reverse=True)

    # 2. Top-K filter
    if top_k is not None:
        ranked = ranked[:top_k]

    # 3. Softmax
    max_l = ranked[0][1]
    exps = [(tok, math.exp(val - max_l)) for tok, val in ranked]
    total = sum(v for _, v in exps)
    probs = [(tok, v / total) for tok, v in exps]

    # 4. Min-P filter (relative to top token probability p_max)
    if min_p is not None and probs:
        threshold = probs[0][1] * min_p
        probs = [(tok, p) for tok, p in probs if p >= threshold]

    # 5. Top-P (Nucleus) cumulative probability cutoff
    if top_p is not None and probs:
        kept, cum = [], 0.0
        for tok, p in probs:
            kept.append((tok, p))
            cum += p
            if cum >= top_p:
                break
        probs = kept

    # 6. Renormalize survivors
    norm = sum(p for _, p in probs)
    return {tok: round(p / norm, 4) for tok, p in probs}

print("[1] Baseline Softmax (T=1.0):", sample_distribution(raw_logits, temperature=1.0))
print("[2] Low Temp Coding (T=0.2): ", sample_distribution(raw_logits, temperature=0.2))
print("[3] Top-K=3 + Top-P=0.90:    ", sample_distribution(raw_logits, temperature=0.8, top_k=3, top_p=0.90))
print("[4] Dynamic Min-P=0.15:      ", sample_distribution(raw_logits, temperature=0.8, min_p=0.15))
β–Ά Interactive Wasm Lab

Lab 4.2: Distributed Training VRAM Planner (Standard DDP vs. ZeRO-1 vs. ZeRO-2 vs. ZeRO-3 / FSDP)

Calculate exact per-GPU static memory consumption for training a 70B LLM across 64 GPUs under DDP, ZeRO-1, ZeRO-2, and ZeRO-3/FSDP.

def plan_training_vram(params_b: float, num_gpus: int):
    psi = params_b * 1e9
    gb = 1024 ** 3

    w_bytes = 2.0 * psi      # BF16 Weights (2B/param)
    g_bytes = 2.0 * psi      # BF16 Gradients (2B/param)
    opt_bytes = 12.0 * psi   # FP32 Master Weights (4B) + Adam m (4B) + Adam v (4B)

    configs = [
        ("Standard DDP (No Sharding)", w_bytes + g_bytes + opt_bytes),
        ("ZeRO-1 (Shard Optimizer)",   w_bytes + g_bytes + (opt_bytes / num_gpus)),
        ("ZeRO-2 (+ Shard Gradients)", w_bytes + ((g_bytes + opt_bytes) / num_gpus)),
        ("ZeRO-3 / FSDP (Full Shard)", (w_bytes + g_bytes + opt_bytes) / num_gpus),
    ]

    print(f"Static Model State VRAM Breakdown for {params_b}B Model across {num_gpus} GPUs:")
    print("-" * 74)
    for label, bytes_per_gpu in configs:
        vram_gb = bytes_per_gpu / gb
        fits = "βœ“ Fits 80GB H100" if vram_gb < 65 else "βœ— OOM on 80GB H100"
        print(f"  {label:<28} -> {vram_gb:>7.2f} GiB / GPU  [{fits}]")

plan_training_vram(params_b=70.0, num_gpus=64)

Frequently Asked Staff LLM Interview Questions (Module 4)

Why does mixed-precision AdamW training require 16 bytes per parameter before activations? β–Έ

Even when forward and backward passes run in 2-byte BF16 (2B weights + 2B gradients = 4B), small weight updates would underflow in BF16’s 7-bit mantissa. Therefore, AdamW maintains a 4-byte FP32 Master Copy of the weights (4B), a 4-byte FP32 first moment m (4B), and a 4-byte FP32 second moment v (4B)β€”totaling 2 + 2 + 4 + 4 + 4 = 16 bytes per parameter.

When should you use Tensor Parallelism (TP) vs. Pipeline Parallelism (PP) vs. FSDP (ZeRO-3)? β–Έ

Tensor Parallelism (TP) splits individual matrix multiplications across GPUs and requires an all-reduce after every attention and FFN blockβ€”so restrict TP (usually TP=8) to GPUs within a single node connected via 900 GB/s NVLink. Use Pipeline Parallelism (PP) and FSDP/ZeRO data parallelism across multi-node InfiniBand/RoCE links where communication can be overlapped with layer computation.

Why is Speculative Decoding mathematically lossless (exact same distribution as the Target model)? β–Έ

When the draft model q(x) proposes a token x and the target model evaluates p(x), speculative decoding accepts x with probability min(1, p(x) / q(x)). If rejected, it resamples from the residual distribution norm(max(0, p - q)), which provably recovers the exact target distribution p(x) while accepting 3–5 tokens per target forward pass.