Stanford CS 336
Language Modeling from Scratch Lecture 2 — PyTorch & Resource Accounting

Memory, FLOPs, CUDA Fundamentals & Roofline Analysis on Blackwell
Stanford University · Spring 2026 material, rebuilt Nov 2026

Why Resource Accounting?

Core question: what is the best language model we can train given a fixed budget of compute and memory?

We start with two napkin calculations, then derive every piece from first principles.

Napkin Math I: Training Time on Blackwell

Question: How long to train a dense $70\text{B}$ model on $15\text{T}$ tokens using $1{,}024$ NVIDIA B200 GPUs at $\text{MFU} = 0.5$?

Historical baseline: 1,024 H100s (989.5 TFLOP/s dense BF16) take ~144 days. For 2026 sparse MoE models, substitute active parameters $N_{\text{active}}$ for $N$.

Napkin Math II: Model Size Upper Bound

Question: What is the largest model trainable on $8$ GPUs with BF16/FP32 AdamW?

Caveat: this is an upper bound—activations scale with batch size and context length, and sparse MoEs must store all $N_{\text{total}}$ parameters.

Tensors: The Universal Building Block

  • Every training object is a tensor:
    • Data batches & intermediate activations
    • Parameters & their gradients
    • Optimizer states (running moments)
  • Rank = number of axes (1D vector, 2D matrix, 4D attention)
  • Current 2026 models (e.g., DeepSeek-V4.1-Flash) organize weights as hundreds of sharded tensors across attention, routers, and sparse MoE experts
x = torch.zeros(4)        # rank 1
x = torch.zeros(4, 8)     # rank 2
x = torch.zeros(4, 8, 2)  # rank 3

# Rank-4 Transformer attention tensor
B = 32   # batch size
S = 16   # sequence length
H = 16   # attention heads
D = 64   # head dimension
q = torch.zeros(B, S, H, D)

Every memory and FLOP calculation reduces to tracking tensor shapes and element dtypes.

Tensor Memory Accounting

Memory footprint depends on exactly two numbers: element count and bytes per element.

$\text{Memory (bytes)} = \text{numel}(x) \times \text{element\_size}(x)$
x = torch.zeros(4, 8)         # default dtype: torch.float32 (4 bytes)
assert x.numel() == 32 and x.element_size() == 4
bytes_used = x.numel() * x.element_size()   # 128 bytes

Floating-Point Formats: FP32, FP16, and BF16

FP32 (4 B) S Exponent (8 bits) Mantissa / Fraction (23 bits) FP16 (2 B) S Exp (5) Mantissa (10 bits) 1e-8 → 0 (underflow!) BF16 (2 B) S Exponent (8 bits) Mantissa (7) FP32 dynamic range: 1e-8 ≠ 0 1 bit = sign (S); exponent sets dynamic range; mantissa sets numerical resolution.

Mixed Precision Training & PyTorch AMP

with torch.amp.autocast("cuda", dtype=torch.bfloat16):
    logits = model(x)   # casts matmuls to bf16, keeps exp/norms in fp32

Blackwell Tensor Cores natively accumulate low-precision matrix products in higher precision internally.

Low Precision on Blackwell: FP8 and NVFP4

FP8 E4M3 (1 B) S Exp (4) Mant (3) range [-448, 448] — weights & activations FP8 E5M2 (1 B) S Exp (5) M (2) range [-57344, 57344] — gradients NVFP4 (4 bits) Block Scaleshared factor × 4b 4b 4b … 4b 16 values: 0, ±0.5, ±1, ±1.5, ±2, ±3, ±4, ±6 Microscaling restores dynamic range across blocks while neighbors within a block share one scale.

CUDA Memory Spaces: Host (CPU) vs. Device (GPU)

Host (CPU) System DRAM default PyTorch allocation x.to("cuda") Host–Device Interconnect far slower than GPU HBM! Device (Blackwell GPU) SMs + Tensor Cores + SRAM GPU HBM tensor storage
  • CPU and GPU have separate physical memory spaces
  • Moving tensors across the host–device bus stalls the GPU
  • Allocate directly on CUDA whenever possible
x = torch.zeros(32, 32)       # CPU
x = x.to("cuda")              # H2D copy

# Better: create directly in GPU HBM
with torch.device("cuda"):
    w = torch.zeros(32, 32)

Blackwell GPU Architecture & Memory Hierarchy

Registers & TMEM per-SM Tensor Core state Shared Memory (SMEM) on-chip per-SM scratchpad L2 Cache shared across all SMs GPU HBM (Global Memory) largest capacity, slowest bandwidth ↑ faster, higher bandwidth, smaller  |  larger, slower ↓
  • Blackwell SMs contain two compute engines:
    • CUDA cores: scalar/vector ops (FP32, elementwise, indexing)
    • Tensor Cores: dedicated matrix multiply-accumulate (BF16, FP8, NVFP4)
  • Blackwell adds dedicated Tensor Memory (TMEM) inside each SM to hold Tensor Core accumulators without pressuring the register file
  • Every PyTorch tensor lives in HBM; high performance requires staging tiles on-chip and reusing them before writing back

Next: how PyTorch launches work onto these SMs—and why naive GPU timing breaks.

CUDA Asynchronous Execution & Benchmarking

CPU thread launch K1 launch K2 torch.cuda.synchronize() waits here read timer ✓ GPU stream Kernel 1 executing Kernel 2 executing Without synchronize(), Python finishes timing right after enqueueing K2—measuring launch latency, not GPU work.
  • CUDA kernel launches are asynchronous: the CPU enqueues work and moves on
  • Always synchronize before and after timed blocks (and warm up first)
def benchmark(func, num_trials=5):
    torch.cuda.synchronize()
    def run():
        func()
        torch.cuda.synchronize()
    return timeit.timeit(run, number=num_trials) / num_trials

Named Tensor Operations with einops

x = torch.ones(2, 3, 4)      # batch, seq1, hidden
y = torch.ones(2, 3, 4)      # batch, seq2, hidden
z = x @ y.transpose(-2, -1)  # what are -2 and -1?
z = einsum(x, y, "batch seq1 hidden, batch seq2 hidden -> batch seq1 seq2")
z = einsum(x, y, "... seq1 hidden, ... seq2 hidden -> ... seq1 seq2")

einops: reduce and rearrange

reduce — named aggregations (sum, mean, max, min):

# Old: fragile axis index
y = x.sum(dim=-1)

# Einops: self-documenting
y = reduce(x, "... hidden -> ...", "sum")

Why this matters for accounting:

  • Shape strings immediately reveal contraction dimensions and FLOP counts

rearrange — split & merge packed dimensions (e.g., multi-head projections):

x = torch.ones(3, 8)   # seq, (heads*d)
w = torch.ones(4, 4)   # hidden1, hidden2

x = rearrange(
    x, "... (heads h1) -> ... heads h1",
    heads=2)
x = einsum(
    x, w, "... h1, h1 h2 -> ... h2")
x = rearrange(
    x, "... heads h2 -> ... (heads h2)")

When contiguous, rearrange reshapes via tensor view metadata with zero HBM copies; transposes that break contiguity may require a copy before a GEMM.

FLOPs vs. FLOP/s and Training Scale

Next: count exact FLOPs for the operation that dominates every Transformer—matrix multiplication.

Counting FLOPs: Matrix Multiplication

X D B × W K D = Y K B 1 mul + 1 add per (i, j, k) triple
$\text{FLOPs}(X W) = \mathbf{2 B D K}$
  • $B \cdot K$ outputs, each an inner product of length $D$ ($D$ multiplies + $D$ adds)
  • Concrete GPU matmul:
    • $B = 16{,}384,\; D = 32{,}768,\; K = 8{,}192$
    • $2BDK \approx \mathbf{8.80 \times 10^{12}\text{ FLOPs}}$
  • Measured throughput: $$\text{actual FLOP/s} = \frac{2 B D K}{t_{\text{actual}}}$$

Blackwell Peak Compute: Precision & Sparsity

GPU (Architecture) FP32 Peak BF16 / FP16 Dense BF16 / FP16 Sparse (2:4) BF16 / FP32
A100 (Ampere, historical) 19.5 TFLOP/s 312 TFLOP/s — 16×
H100 (Hopper, historical) 67.5 TFLOP/s 989.5 TFLOP/s 1,979 TFLOP/s 14.7×
B200 (Blackwell, current) 75 TFLOP/s 2,250 TFLOP/s 4,500 TFLOP/s 30×

Model FLOPs Utilization (MFU)

$$\text{MFU} = \frac{\text{actual FLOP/s}}{\text{promised dense peak FLOP/s (for active dtype)}}$$

To diagnose why a kernel falls short of peak FLOP/s, we need the two-resource bottleneck model.

The Two-Resource Execution Model

GPU HBM Bandwidth BHBM (bytes / s) 1. Read inputs (bytes) 3. Write outputs (bytes) 2. Compute on Blackwell SMs Peak speed Fpeak (FLOP/s) Tensor Cores + CUDA Cores

Arithmetic Intensity vs. Accelerator Intensity

Arithmetic intensity (workload)
$$I_{\text{op}} = \frac{\text{FLOPs}}{\text{bytes moved}}\; \left[\frac{\text{FLOP}}{\text{byte}}\right]$$
Accelerator intensity (hardware)
$$I_{\text{hw}} = \frac{F_{\text{peak}}}{B_{\text{HBM}}}\; \left[\frac{\text{FLOP}}{\text{byte}}\right]$$

Elementwise Ops: Why ReLU Is Not Faster Than GELU

Input $x \in \mathbb{R}^n$ in BF16 ($n = 1024 \times 1024$): read $2n$ bytes, write $2n$ bytes $\implies \mathbf{4n\text{ bytes}}$.

ReLU: $y = \max(0, x)$
$\text{FLOPs} = n$
$I_{\text{op}} = \dfrac{n}{4n} = \mathbf{0.25\text{ FLOP/byte}}$
GELU: $0.5x(1+\tanh(\dots))$
$\text{FLOPs} \approx 20n$
$I_{\text{op}} = \dfrac{20n}{4n} = \mathbf{5\text{ FLOP/byte}}$

Dot Products & MatVec: Why LLM Decode Is Memory-Bound

Autoregressive inference decoding (1 token per sequence) is a chain of matrix–vector products plus KV-cache reads $\implies$ fundamentally HBM-bandwidth bound unless batched.

Matrix–Matrix Multiply: Reuse Unlocks Compute-Bound Speed

GPU HBM: X (n×n), W (n×n), Y (n×n) Total traffic: 6n² bytes (BF16) load tiles store tile Blackwell SM (SMEM + TMEM + Tensor Cores) X tile × W tile → Y tile
  • Square BF16 matmul ($n \times n$):
    • Bytes $= 6n^2$, $\;\text{FLOPs} \approx 2n^3$
    • $I_{\text{op}} \approx \mathbf{n / 3}$ — grows linearly with $n$!
    • At $n = 1024$: $I_{\text{op}} \approx \mathbf{341\text{ FLOP/byte}}$ (compute-bound!)
  • Rectangular GEMM $(B,D)\times(D,K)$ in $b$ B/elem: $$I_{\text{op}} = \frac{2 B D K}{b\,(BD + DK + BK)}$$
  • Staging tiles in SMEM/TMEM reuses each weight across many tokens $B$

Training and inference prefill process many tokens in parallel ($B \gg 1$), turning matvecs into compute-bound GEMMs.

The Roofline Model & MFU Ceiling

Arithmetic Intensity Iop (FLOP / byte, log scale) Attainable FLOP/s (log) H100 BF16 (historical, ridge ≈ 295) Blackwell B200 BF16 (2,250 TFLOP/s dense) Ihw (ridge) Memory-Bound Region (slope = HBM bandwidth) Compute-Bound (Tensor Core peak) ReLU (0.25) MatVec (1) GELU (5) Large GEMM
$$\text{MFU}_{\text{roofline}} = \min\!\left(1,\; \frac{\text{arithmetic intensity } I_{\text{op}}}{\text{accelerator intensity } I_{\text{hw}}}\right)$$

To improve MFU: move left-of-ridge ops right via batching, tiling, quantization, or fusion.

Arithmetic Intensity Across Core BF16 Operations

Operation (BF16) Bytes Moved FLOPs $I_{\text{op}}$ (FLOP/B) Regime
ReLU ($n$) $4n$ $n$ $0.25$ Memory-bound
Dot product ($n$) $4n + 2$ $2n - 1$ $\approx 0.5$ Memory-bound
Matrix–vector ($n\times n$) $2n^2 + 4n$ $2n^2 - n$ $\approx 1$ Memory-bound
GELU ($n$) $4n$ $\approx 20n$ $\approx 5$ Memory-bound
Matrix–matrix ($n\times n$) $6n^2$ $2n^3 - n^2$ $\approx n/3$ ($341$ at $n{=}1024$) Compute-bound

Training Accounting: Deep Network & Autograd

  • Model for exact accounting: $L$-layer network of width $D$ ($P = L D^2$ parameters)
  • Forward pass evaluates activations $h_1, \dots, h_L$ and builds the autograd graph
  • loss.backward() walks the graph in reverse to populate p.grad
  • Toy check: $L = \frac{1}{2}(x\cdot w - 5)^2$ with $x=[1,2,3],\, w=[1,1,1]$ $\implies$ $\nabla_w L = [1, 2, 3]$
class Block(nn.Module):
    def __init__(self, dim: int):
        super().__init__()
        self.weight = nn.Parameter(
            torch.randn(dim, dim) / math.sqrt(dim))

    def forward(self, x):
        return F.relu(x @ self.weight)

# Forward + backward
loss = F.mse_loss(model(x).mean(), y)
loss.backward()

Next: count the exact FLOPs and saved tensors required by the backward pass.

Backward Pass Anatomy: Two GEMMs per Layer

Forward h₁ (B,D) h₂ = h₁ W₂2 B D² FLOPs h₂ (B,D) saved h₁ in HBM! Backward ∇h₂ L ∇h₁ L = (∇h₂ L) W₂ᵀ2 B D² FLOPs (to prev layer) ∇W₂ L = h₁ᵀ (∇h₂ L)2 B D² FLOPs (weight update)
h1_grad = einsum(h2.grad, w2, "batch out, in out -> batch in")  # 2 B D^2
w2_grad = einsum(h2.grad, h1, "batch out, batch in -> in out")  # 2 B D^2

The $6 B P$ Rule — Dense Models vs. 2026 Architectures

Forward: $\;2 B P$ FLOPs   +   Backward: $\;4 B P$ FLOPs   $=$   $6 B P$ FLOPs per step

This is where our Slide 3 napkin formula ($6 N D$) came from.

Adaptive Optimizers: From SGD to AdamW

Optimizer Update Idea FP32 State / Param
SGD Step along raw gradient $- \eta g$ 0 B
Momentum SGD + exponential moving average of $g$ 4 B
AdaGrad (2011) SGD scaled by $1 / \sqrt{\sum g^2 + \epsilon}$ 4 B
RMSProp AdaGrad with exponential moving average of $g^2$ 4 B
Adam / AdamW RMSProp + Momentum (first & second moments) 8 B (4 + 4)

Optimizer Step & CUDA Memory Hygiene

class AdaGrad(torch.optim.Optimizer):
    def step(self):
        for group in self.param_groups:
            lr = group["lr"]
            for p in group["params"]:
                state = self.state[p]
                grad = p.grad.data
                g2 = state.get("g2", torch.zeros_like(grad))
                g2 += torch.square(grad)
                state["g2"] = g2
                p.data -= lr * grad / torch.sqrt(g2 + 1e-5)
  • Always clear grads via: optimizer.zero_grad(set_to_none=True)
  • Setting .grad = None releases HBM buffers immediately instead of keeping zeroed tensors alive
  • PyTorch's CUDA caching allocator recycles freed blocks without costly OS cudaMalloc calls

Failing to zero gradients silently sums them across steps (which we will intentionally exploit for gradient accumulation).

Complete Training Memory Breakdown

Static Model State (scales with parameters P) Params 2P B (BF16) Grads 2P B (BF16) Optimizer State (AdamW) 8P B (FP32 moments; 4P for AdaGrad) Activations (Dynamic) 2 B D L bytes (BF16; grows with B, L) 12 P bytes fixed by model size scales with batch B, depth L, length S

Keeping a separate FP32 master copy of parameters adds another $4P$ bytes on top of this baseline.

Why Activations Become the Memory Bottleneck

Inference
Discard layer $\ell$'s activation once layer $\ell+1$ completes $\implies O(1)$ activation layers in HBM (plus KV cache).
Training
Keep every layer's input $h_\ell$ alive until backward computes $\nabla_{W_\ell} L \implies O(L)$ activation layers in HBM.

Gradient Accumulation: Shrinking the Batch Factor

Micro-batch 1 (B/4)Fwd → Bwd (accum) Micro-batch 2 (B/4)Fwd → Bwd (accum) Micro-batch 3 (B/4)Fwd → Bwd (accum) Micro-batch 4 (B/4)Fwd → Bwd (accum) step()zero_grad() Activations are freed after each micro-batch backward → peak activation memory drops 4× Gradients sum into the same 2P-byte buffer; mathematical update equals one full batch of size B.

Activation Checkpointing (Rematerialization)

Store all: x g₁ h₁ g₂ h₂ g₃ h₃ g₄ h₄ Checkpointed: x g₁ h₁ g₂ h₂ g₃ h₃ g₄ h₄ recompute g₄ in backward from checkpoint h₃
  • Philosophy: trade extra compute for lower HBM usage
  • Forward keeps only checkpoint tensors; backward recomputes dropped intermediates on demand
for layer in self.layers:
    x = torch.utils.checkpoint.checkpoint(
        layer, x, use_reentrant=False)

How Often to Checkpoint? The $\sqrt{L}$ Tradeoff

Every layer: h₁ h₂ h₃ h₄ h₅ h₆ h₇ h₈ h₉ Every √L: h₁ h₂ h₃ h₄ h₅ h₆ h₇ h₈ h₉ No layers: keep only input x — recompute from start for every layer
Strategy ($L$ layers)Activation MemoryRecomputation CostTotal Step FLOPs
Store every layer$O(L)$$0$$6 B P$
Checkpoint every $\sqrt{L}$$O(\sqrt{L})$$O(L)$ (1 extra fwd)$\le 8 B P$
Store no layers$O(1)$$O(L^2)$prohibitive

On Blackwell GPUs with high compute-to-memory ratios, selective checkpointing of memory-heavy ops (activations, norms, attention) saves substantial HBM for minimal wall-clock cost.

Putting It Together: A Blackwell Training Step

for step in range(num_steps):
    for micro in range(accum_steps):
        x, y = get_batch()                 # directly on CUDA
        with torch.amp.autocast("cuda", dtype=torch.bfloat16):
            loss = F.mse_loss(model(x).mean(), y) / accum_steps
        loss.backward()                    # accumulates .grad
    optimizer.step()                       # FP32 state update
    optimizer.zero_grad(set_to_none=True)  # free grad HBM
  • Forward: $2 B P$ FLOPs; allocates (or checkpoints) activations
  • Backward: $4 B P$ FLOPs; reads activations, frees them, sums into .grad
  • Optimizer: elementwise update on FP32 state; then releases grad buffers
Every line maps directly to a concrete HBM allocation, HBM transfer, or Tensor Core GEMM.

Recap: Resource Accounting Checklist