Mental model
Training optimizes parameters through forward passes, gradient accumulation, and optimizer state updates, demanding bytes of static state plus activations in compute-bound batches; inference freezes , replacing optimizer and gradient memory with dynamic KV-cache blocks while splitting between compute-bound prefill and HBM-bandwidth-bound decode.
Learning outcomes
- Compute roofline arithmetic intensity () against hardware ridge points to distinguish compute-bound from HBM-bandwidth-bound execution.
- Break down mixed-precision AdamW training memory ( static bytes plus activations) versus inference weight and KV-cache capacity.
- Explain why training and prompt prefill saturate Tensor Cores while low-batch autoregressive decode stalls on HBM memory reads.
- Decide cleanly when a product gap calls for prompting, RAG, or schema constraints at inference versus fine-tuning weights during training.
Theory
Every GPU kernel executes inside the hardware roofline model, bounded by either peak arithmetic throughput (FLOP/s) or off-chip HBM memory bandwidth (Bytes/s). A workload's arithmetic intensity measures computational reuse per byte moved across HBM:
When , kernels are compute-bound; when , Tensor Cores wait idle on HBM memory transfers (memory-bandwidth-bound).
Mixed-precision AdamW training sits firmly in the high-, memory-capacity-intensive regime. Across forward, backward, and activation-recomputation passes on dense transformers, total training work scales near FLOPs over tokens (versus FLOPs for an inference forward pass). Because BF16 gradients require FP32 optimizer accumulation to prevent underflow, static memory for parameters totals bytes:
On top of , training retains intermediate activations for backpropagation—scaling with micro-batch size, sequence length, and layer count unless activation checkpointing recomputes blocks during backward passes and FlashAttention-2 (dao-flashattention2-2023) eliminates attention-score matrices via SRAM work partitioning.
Autoregressive inference drops gradients, master weights, and AdamW states entirely (0 optimizer bytes), leaving only quantized or BF16 weights ( in BF16, in INT4), minimal runner CUDA-graph buffers (gpu_model_runner.py), and dynamic PagedAttention KV blocks. Crucially, inference splits into two opposite roofline phases:
- Prefill: Processes tokens simultaneously via matrix-matrix (
GEMM) multiplies, achieving and saturating compute cleanly. - Decode: Generates one token per sequence per step (
GEMVat batch ), streaming all weight bytes plus KV blocks from HBM to perform roughly FLOPs—yielding until continuous batching lifts effective token batch size toward .
Worked quantitative example
Consider serving and training a 7-billion-parameter model (, GQA-8 128 KiB/token KV footprint) on a single 80 GB NVIDIA H100 (989 TFLOP/s BF16 dense, 3.35 TB/s HBM3 bandwidth). The hardware roofline ridge point is:
- Mixed-Precision Training Static State: —exceeding a single
80 GBH100 before storing even one batch of activations! Full-parameter training therefore requires multi-GPU ZeRO sharding, tensor/pipeline parallelism, or parameter-efficient LoRA adapters (under2%trainable parameters). - BF16 Inference Memory: Frozen BF16 weights occupy . Reserving
6 GBfor CUDA runtime, activation scratchpad, and CUDA graphs leaves60 GBfor vLLM KV blocks—storing roughly491,520concurrent context tokens (120concurrent4k-token sessions). - Roofline Decode vs Prefill: Decoding at reads
14 GBweights to run14 GFLOPs(), hitting a hard HBM read floor of14 GB / 3.35 TB/s = 4.18 ms/tokenat0.34%Tensor Core utilization. BatchingB = 128decode steps together pushes compute to1,792 GFLOPsacross roughly14.5 GBHBM reads (), boosting throughput nearly100xwith barely higher step latency.
Training vs prefill vs decode workload comparison
| Execution Regime | Weights & Optimizer VRAM | Dominant Bottleneck | Approximate Roofline | Primary Engineering Lever |
|---|---|---|---|---|
| Full BF16 AdamW Training | + backward activations | HBM capacity & Tensor Core FLOPs | 250+ (high batch GEMM) | ZeRO-3 sharding, activation checkpointing, FlashAttention-2 |
| Inference Prefill | Weights + prompt KV blocks | Compute-bound (GEMM) | 100–500 (scales with prompt tokens) | Chunked prefill, FP8 Tensor Cores, prefix KV caching |
Inference Decode (B = 1) | Weights + active KV blocks | HBM memory bandwidth (GEMV) | ~1 FLOP/byte | Continuous batching, GQA, INT4/FP8 weight quantization |
Trade-offs
Updating weights via full fine-tuning or LoRA bakes specialized formatting, domain vocabulary, and latency-saving shorter prompts permanently into parameters, eliminating long few-shot prompt tokens at inference time. However, every weight update triggers an expensive training pipeline, catastrophic forgetting risks on general capabilities, evaluation regressions, and frozen knowledge cutoffs—meaning dynamic facts belong in inference-time RAG rather than training gradients.
During serving, aggressively quantizing weights (BF16 to INT4/AWQ) shrinks weight reads from 14 GB down to 3.5 GB, cutting decode step latency and freeing 10.5 GB for additional KV blocks. Yet weight quantization narrows accuracy margins on reasoning tasks and still leaves multi-tenant long-context decode limited by KV-cache HBM reads unless paired with GQA or FP8 KV quantization.
Failure modes and misconceptions
- Fine-tuning weights to fix knowledge freshness or JSON interface bugs. RAG injects live ground-truth records during inference without weight drift, and grammar-guided constrained decoding guarantees valid JSON syntax deterministically at zero training cost.
- Estimating training GPU fit using
2 * Phiweight size alone. Neglecting14 * Phioptimizer/gradient states plus forward activations causes immediate OOM crashes when transitioning from inference evaluation to fine-tuning. - Benchmarking inference latency solely at batch size 1. Single-stream
ms/tokenreflects raw HBM bandwidth, hiding how continuous batching shifts the GPU up the roofline curve toward compute saturation and dramatically alters cost per million tokens. - Ignoring FlashAttention-2 or activation checkpointing on long-context training. Training on
16ksequences without FlashAttention-2 and checkpointing explodes per-layer attention activations quadratically (O(N^2)), forcing micro-batch collapse.
Decision scenario
A product team wants to reduce \$0.12-per-query inference costs on a 70B model that reads 3,500-token formatting instructions and policy tables on every request, while complaining that single-GPU 16 GB training prototypes crash on a 7B baseline.
First, diagnose the two distinct regimes: the 7B AdamW crash occurs because plus activations exceeds 16 GB; resolve training capacity using QLoRA (4-bit quantized frozen base weights + BF16 LoRA adapters + FlashAttention-2 + activation checkpointing) rather than full-parameter AdamW. Second, on the 70B serving side, separate stable instructions (solved via radix prefix KV caching or distilled smaller LoRA adapters once formatting rules stabilize) from volatile policy facts (kept in RAG retrieval). Measure P95 accuracy, prefill TTFT, and decode throughput under realistic concurrent batch distributions before committing to training.
Implementation example
This runnable Python calculator computes exact static training memory (), inference weight plus KV-cache capacity on a target GPU, and roofline arithmetic intensity for prefill versus batched decode against the hardware ridge point.
pythonfrom dataclasses import dataclass@dataclass(frozen=True)class HardwareSpec:vram_gb: floatbf16_tflops: floathbm_tb_s: float@propertydef ridge_point(self) -> float:return (self.bf16_tflops * 1e12) / (self.hbm_tb_s * 1e12)def analyze_model_regimes(params_b: float, kv_bytes_per_tok: int, gpu: HardwareSpec, batch: int, seq_len: int) -> dict[str, float]:phi = params_b * 1e9train_static_gb, infer_weights_gb = (16.0 * phi) / 1e9, (2.0 * phi) / 1e9usable_kv_gb = max(0.0, gpu.vram_gb - infer_weights_gb - 6.0)decode_ai = (2.0 * phi * batch) / ((2.0 * phi) + (batch * seq_len * kv_bytes_per_tok))prefill_ai = (2.0 * phi * seq_len) / ((2.0 * phi) + (seq_len * kv_bytes_per_tok))return {"ridge_ai": round(gpu.ridge_point, 1),"train_static_gb": round(train_static_gb, 1),"max_kv_tokens": round((usable_kv_gb * 1e9) / kv_bytes_per_tok),"decode_ai": round(decode_ai, 2),"prefill_ai": round(prefill_ai, 1),}h100 = HardwareSpec(vram_gb=80.0, bf16_tflops=989.0, hbm_tb_s=3.35)stats = analyze_model_regimes(7.0, 131_072, h100, batch=1, seq_len=2048)assert stats["train_static_gb"] == 112.0 and stats["decode_ai"] < 1.5 and stats["prefill_ai"] > stats["ridge_ai"]
Why does a 7B model require over 112 GB of static state for mixed-precision AdamW training yet serve hundreds of concurrent sequences on a single 80 GB GPU?