FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Training versus Inference

How parameter learning differs from runtime generation and serving operations.

Freshness: current•15 min read•Foundation Models and Multimodal AI

Key Learning Outcomes

  • ✓Separate learning from generation
  • ✓Identify inference-only controls
  • ✓Explain parameter updates
Full Technical Reference Document

Mental model

Training optimizes parameters Φ\Phi through forward passes, gradient accumulation, and optimizer state updates, demanding 16Φ16\Phi bytes of static state plus activations in compute-bound batches; inference freezes Φ\Phi, replacing optimizer and gradient memory with dynamic KV-cache blocks while splitting between compute-bound prefill and HBM-bandwidth-bound decode.

Training 16-Phi AdamW state
Forward and FlashAttention-2 pass
Frozen weight artifact
Compute-bound prefill phase
Bandwidth-bound KV decode loop
Conceptual teaching model synthesized from:How Transformers Solve TasksEfficient Memory Management for Large Language Model Serving with PagedAttentionvLLM V1 GPU model runner at v0.10.2FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning

Learning outcomes

  • Compute roofline arithmetic intensity (AI=FLOPs/BytesAI = \text{FLOPs}/\text{Bytes}) against hardware ridge points to distinguish compute-bound from HBM-bandwidth-bound execution.
  • Break down mixed-precision AdamW training memory (16Φ16\Phi 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 Πpeak\Pi_{\text{peak}} (FLOP/s) or off-chip HBM memory bandwidth βHBM\beta_{\text{HBM}} (Bytes/s). A workload's arithmetic intensity measures computational reuse per byte moved across HBM:

AI=FLOPsBytesHBM,Iridge=ΠpeakβHBMAI = \frac{\text{FLOPs}}{\text{Bytes}_{\text{HBM}}}, \qquad I_{\text{ridge}} = \frac{\Pi_{\text{peak}}}{\beta_{\text{HBM}}}

When AI≥IridgeAI \ge I_{\text{ridge}}, kernels are compute-bound; when AI<IridgeAI \lt I_{\text{ridge}}, Tensor Cores wait idle on HBM memory transfers (memory-bandwidth-bound).

Mixed-precision AdamW training sits firmly in the high-AIAI, memory-capacity-intensive regime. Across forward, backward, and activation-recomputation passes on dense transformers, total training work scales near 6ΦD6\Phi D FLOPs over DD tokens (versus 2ΦT2\Phi T FLOPs for an inference forward pass). Because BF16 gradients require FP32 optimizer accumulation to prevent underflow, static memory for Φ\Phi parameters totals 16Φ16\Phi bytes:

Mtrain_static=2Φ⏟BF16 weights+2Φ⏟BF16 grads+4Φ⏟FP32 master+4Φ⏟AdamW m+4Φ⏟AdamW v=16Φ bytesM_{\text{train\_static}} = \underbrace{2\Phi}_{\text{BF16 weights}} + \underbrace{2\Phi}_{\text{BF16 grads}} + \underbrace{4\Phi}_{\text{FP32 master}} + \underbrace{4\Phi}_{\text{AdamW } m} + \underbrace{4\Phi}_{\text{AdamW } v} = 16\Phi\text{ bytes}

On top of 16Φ16\Phi, 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 O(N2)O(N^2) 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 (2Φ2\Phi in BF16, 0.5Φ0.5\Phi in INT4), minimal runner CUDA-graph buffers (gpu_model_runner.py), and dynamic PagedAttention KV blocks. Crucially, inference splits into two opposite roofline phases:

  1. Prefill: Processes NpromptN_{\text{prompt}} tokens simultaneously via matrix-matrix (GEMM) multiplies, achieving AI∝NpromptAI \propto N_{\text{prompt}} and saturating compute cleanly.
  2. Decode: Generates one token per sequence per step (GEMV at batch B=1B = 1), streaming all 2Φ2\Phi weight bytes plus KV blocks from HBM to perform roughly 2Φ2\Phi FLOPs—yielding AI≈1 FLOP/byteAI \approx 1\text{ FLOP/byte} until continuous batching lifts effective token batch size toward IridgeI_{\text{ridge}}.

Worked quantitative example

Consider serving and training a 7-billion-parameter model (Φ=7×109\Phi = 7 \times 10^9, 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:

Iridge=989×1012 FLOP/s3.35×1012 B/s≈295 FLOP/byteI_{\text{ridge}} = \frac{989 \times 10^{12}\text{ FLOP/s}}{3.35 \times 10^{12}\text{ B/s}} \approx 295\text{ FLOP/byte}

  1. Mixed-Precision Training Static State: Mtrain_static=16×7 GB=112 GBM_{\text{train\_static}} = 16 \times 7\text{ GB} = 112\text{ GB}—exceeding a single 80 GB H100 before storing even one batch of activations! Full-parameter training therefore requires multi-GPU ZeRO sharding, tensor/pipeline parallelism, or parameter-efficient LoRA adapters (under 2% trainable parameters).
  2. BF16 Inference Memory: Frozen BF16 weights occupy Mw=2×7=14 GBM_{\text{w}} = 2 \times 7 = 14\text{ GB}. Reserving 6 GB for CUDA runtime, activation scratchpad, and CUDA graphs leaves 60 GB for vLLM KV blocks—storing roughly 491,520 concurrent context tokens (120 concurrent 4k-token sessions).
  3. Roofline Decode vs Prefill: Decoding at B=1B = 1 reads 14 GB weights to run 14 GFLOPs (AI≈1 FLOP/byte≪295AI \approx 1\text{ FLOP/byte} \ll 295), hitting a hard HBM read floor of 14 GB / 3.35 TB/s = 4.18 ms/token at 0.34% Tensor Core utilization. Batching B = 128 decode steps together pushes compute to 1,792 GFLOPs across roughly 14.5 GB HBM reads (AI≈124 FLOP/byteAI \approx 124\text{ FLOP/byte}), boosting throughput nearly 100x with barely higher step latency.

Training vs prefill vs decode workload comparison

Execution RegimeWeights & Optimizer VRAMDominant BottleneckApproximate Roofline AIAIPrimary Engineering Lever
Full BF16 AdamW Training16Φ16\Phi + backward activationsHBM capacity & Tensor Core FLOPs250+ (high batch GEMM)ZeRO-3 sharding, activation checkpointing, FlashAttention-2
Inference PrefillWeights + prompt KV blocksCompute-bound (GEMM)100–500 (scales with prompt tokens)Chunked prefill, FP8 Tensor Cores, prefix KV caching
Inference Decode (B = 1)Weights + active KV blocksHBM memory bandwidth (GEMV)~1 FLOP/byteContinuous 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 B=1B = 1 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 * Phi weight size alone. Neglecting 14 * Phi optimizer/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/token reflects 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 16k sequences 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 16Φ=112 GB16\Phi = 112\text{ GB} 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 (16Φ16\Phi), inference weight plus KV-cache capacity on a target GPU, and roofline arithmetic intensity for prefill versus batched decode against the hardware ridge point.

python
from dataclasses import dataclass
​
@dataclass(frozen=True)
class HardwareSpec:
vram_gb: float
bf16_tflops: float
hbm_tb_s: float
​
@property
def 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 * 1e9
train_static_gb, infer_weights_gb = (16.0 * phi) / 1e9, (2.0 * phi) / 1e9
usable_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"]
Reflect before revealing the guide

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?

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.