LLM Training

Estimated guided hours: 52

Course overview

LLM Training explains how a large language model learns and how a training step uses compute, memory and communication. Learn to preserve the learning objective while improving correctness, recoverability, precision, data flow and throughput.

Read GPU Performance Tools before practical work. Complete GPU Fundamentals and GPU Performance Optimization first, or bring their execution, timing and profiling skills. The course develops training mechanics through worked examples and controlled experiments; inference serving has its own course.

Local GPU practice uses one full H100; distributed-training experiments belong to Advanced Labs. These bounded, often synthetic workloads do not establish production convergence or large-model scaling. Follow the shared Lab Preparation and read the single setup command's completion summary before practice. Software preparation includes optional runtimes; their GPU checks remain separate.

For a tensor-reading refresher, use PyTorch for GPU Performance Engineering, a concise visual course with commented examples and no labs.

How to use this course

Learn

Read the objective and explanation, then use the mental model to review the mechanism. Explain what the technique is, why it is useful and how it works before following the Practice links.

Practice

Follow Lab Preparation to prepare the available lab software with one command. Check its completion summary before submitting a lab. Each practical lab explains its purpose and concepts, then gives the commands and comparison to make. Check the results before interpreting performance.

Review

Compare correctness, repeated measurements, and profiler observations. Use the glossary and detailed diagrams when a term or relationship needs a second look.

Use the benchmark worksheet to record what your environment demonstrates and what remains to be tested.

1. Model learning and training objectives

Objective

Distinguish pretraining, continued pretraining, supervised fine-tuning, parameter-efficient tuning, and reward-guided post-training.

How it works

What model training is

A model is a parameterized computation: it takes an input and uses stored numbers, called parameters or weights, to produce an output. Training is the process of changing those numbers using examples and an objective that scores the model's behavior. We do not write a separate rule for every possible answer. Instead, we choose a model structure, a dataset and an update procedure. The resulting behavior is learned from data, so it must be evaluated rather than assumed correct.

A large language model (LLM) works with tokens: pieces of text represented by integer IDs. A token need not be a whole word. A decoder-only language model assigns scores to possible next tokens given a preceding sequence. It can be trained from known examples of which token actually followed a prefix. This course explains that learning process first, then how to make its computation, memory use and communication efficient on H100 GPUs. Basic Python and the two GPU prerequisite courses provide the programming and device foundation.

Why train, and when not to

Training is useful when a model must learn a predictive relationship or adapt its behavior to a domain or task. LLM pretraining learns broad language patterns from a large corpus, usually starting from random weights. Continued pretraining reuses an existing checkpoint and a similar objective; fine-tuning adapts a pretrained model using selected examples. Not every model trained from scratch is undergoing LLM pretraining. These choices differ greatly in required data, compute and evaluation. They are introduced in the rest of this lesson and explored later.

Training is not the default solution to every application problem. Using an existing model is inference; supplying documents in a prompt changes its context without necessarily changing its parameters. If prompting or retrieving current facts solves the need, changing weights may add cost and risk without benefit. Training requires suitable permitted data, an evaluation set separate from the update data, and checks for overfitting: performing well on examples seen during training but poorly on new ones.

How one learning step works

Supervised fine-tuning (SFT) trains an existing model on selected input/target examples. Parameter-efficient fine-tuning (PEFT) limits the amount of trainable state; an adapter is an added trainable component attached to a base model. Low-rank adaptation (LoRA) is one PEFT technique: smaller matrix factors represent an update to selected frozen weights. Reward-guided training instead scores generated answers and adjusts the policy, the model's distribution over possible tokens. These terms identify different choices about supervision and trainable parameters, not one universal training procedure. A checkpoint is saved model or training state; later lessons distinguish a model export from a snapshot sufficient for exact resumption.

Take a small batch of examples. The forward pass computes predictions using the current weights. For next-token training, the model produces logits, which are unnormalized scores for vocabulary entries. Softmax converts scores into probabilities. A loss turns the probability assigned to each known target into a scalar penalty; cross-entropy penalizes low probability on the correct token. The backward pass calculates gradients: how sensitive that loss is to small changes in each trainable weight. An optimizer uses those gradients to change the weights. Repeat with more batches, evaluate on held-out data, and save checkpoints so the state can be used or resumed.

Training lifecycle Follow the loop from examples and an objective through predictions, gradients and a parameter update. Evaluation checks held-out behavior, and a complete checkpoint preserves the state needed to continue. These stages are not all required on every individual step. Diagram concepts: Data and objective; Forward, loss, backward; Update, evaluate, checkpoint. Data and objectiveForward, loss, backwardUpdate, evaluate,checkpoint
Training lifecycle

Follow the loop from examples and an objective through predictions, gradients and a parameter update. Evaluation checks held-out behavior, and a complete checkpoint preserves the state needed to continue. These stages are not all required on every individual step.

The model's forward pass computes predictions and the loss function assesses their error. Backward does not itself update the weights; the optimizer performs the update. Labels are used to assess predictions during training; the answer for the next generated token is not supplied during ordinary inference. During a causal training forward, many known sequence positions can be processed in parallel while the attention mask prevents a position from seeing its future. Generation must instead obtain later tokens from earlier outputs.

The CPU prepares batches and submits operations. GPU kernels perform the large tensor operations in forward, backward and the update. Weights persist between batches; activations are intermediate values, gradients carry the current learning signal, and an optimizer may keep additional history. This is why training memory is more than a model-file size. GPU optimization must preserve the learning task, not merely make a different or incomplete update finish faster.

Mean squared error (MSE) averages squared prediction-minus-target differences. Plain stochastic gradient descent (SGD) updates a weight by subtracting learning_rate × gradient. The learning rate controls the size of each update.

Execution and dependencies

GPU courses explain how operations execute; training adds the learning contract that decides which values change and why. Every optimization later must preserve this data-to-update lifecycle.

A training procedure connects examples to a parameter update. Text becomes a tokenized batch; the model turns that batch into logits; a scalar objective scores those predictions; backward computes gradients; and the optimizer changes the trainable parameters. A learning-rate scheduler controls the update scale over time. Evaluation and checkpoints then assess and preserve the resulting state.

The training stage changes what enters this loop and what is allowed to change. Pretraining commonly learns next-token prediction from broad corpora while updating the full model. Continued pretraining starts from existing weights and applies a similar objective to another domain or distribution. Supervised fine-tuning uses curated input-response examples. Its loss policy determines whether prompt tokens, response tokens or both contribute; padding is normally excluded.

Parameter-efficient methods change the trainable state rather than defining a separate kind of supervision. They freeze base weights and update smaller adapter components, so they can be combined with SFT. Reward-guided methods instead generate candidate responses, score them and use comparative signals to construct the policy objective. They add generation and scoring to the loop before the update.

LLM training lifecycle Data is curated and tokenized, a model runs forward to logits and loss, backward computes gradients, an optimizer updates trainable parameters, and evaluation plus checkpoints govern repeated training. Pretraining, supervised fine-tuning, and reward-based post-training use different data and objectives. curate data split + govern tokenize IDs + masks forward logits + loss backward gradients optimizer parameter update evaluate save / decide repeat with new batches; resume from complete checkpoint state pretraining /continued pretraining large unlabeled or domain corpus next-token objective broad capability or domain adaptation SFT / LoRA curated demonstrations selected-token supervised loss full or adapter-only updates preference / rewardpost-training candidate generation + scoring policy objective + constraints quality and stability gates Each stage changes the data contract, objective, trainable state, evaluation, and performance profile.
LLM training lifecycle

Data is curated and tokenized, a model runs forward to logits and loss, backward computes gradients, an optimizer updates trainable parameters, and evaluation plus checkpoints govern repeated training. Pretraining, supervised fine-tuning, and reward-based post-training use different data and objectives.

To know which procedure a result describes, identify the trainable parameters, the examples and their provenance, the loss denominator, the held-out evaluation split and the checkpoint lineage. Two runs with the same architecture can still be performing different learning tasks if any of these differ.

“Training an LLM” can mean fundamentally different objectives, datasets, trainable state, checkpoints, and evaluation signals. Mixing them makes memory estimates, throughput comparisons, and quality claims meaningless.

Try a small example

Before a transformer, use the scalar model prediction = weight × input. For inputs 1 and 2 with targets 2 and 4, weight 0 predicts zero. The mean squared error is (4 + 16)/2 = 10 and its gradient is -10. A learning rate of 0.1 makes the next weight 0 - 0.1 × (-10) = 1. The new loss is 2.5. Repetition approaches weight 2; input 3, never used for updates, should then produce approximately 6. This demonstrates the update mechanism, not language understanding.

Mental model

Data, tokenization, objective, trainable state, evaluation, and checkpoint content change across stages even when the decoder architecture stays fixed.

2. Causal training data

Objective

Produce correct shifted labels, ignored positions, attention masks, and packed examples.

How it works

A training batch groups examples for one computation. Tokens are the model's discrete input symbols, represented by integer IDs; labels specify the answers used to calculate the learning error. In next-token training, each eligible position predicts the following token. Padding fills unused positions so examples fit a rectangular tensor, while truncation discards positions beyond a length limit. A loss mask excludes selected labels from the objective; an attention mask determines which input positions can influence each prediction. They control different things.

Sequence packing places several examples in one tensor row to reduce padding. Position IDs describe positions within the intended sequence, and document boundaries determine whether one example may read another. Packing therefore requires a context policy as well as a storage plan: placing two texts next to each other does not automatically preserve the learning task. Start by tracing which tokens provide context and which labels contribute to loss.

The selected training stage defines which text contributes to learning. A token ID is a vocabulary index; the model will output logits, one unnormalized score per possible next token. Cross-entropy turns those scores and the correct label into a scalar penalty; ignored labels do not contribute to its sum or valid-token denominator. A causal mask prevents a position from attending to future tokens, and a packed-example boundary also prevents it from attending to unrelated examples. A block-diagonal causal mask places one causal region per example along the diagonal of the token-to-token attention matrix. Tokens may read earlier positions within their own region; entries connecting different examples are blocked. Here construct the tensors; Lessons 3 and 4 explain their model and gradient paths.

Text first passes through a tokenizer's vocabulary and normalization rules to become token IDs. The model's embedding table maps those IDs to learned vectors. In causal language modeling, the logits at position t predict the next token at t+1; the loss must align each prediction with that next-token target rather than the token already supplied at the same position.

A loss mask decides which predictions contribute to the objective. Padding and any excluded prompt positions receive an ignore label and are left out of both the loss sum and the valid-token denominator. An attention mask answers a separate question: which input positions may influence each prediction? Ignoring a label does not stop other positions from attending to its input token.

Text, tokens, token IDs, embeddings, and shifted labels Text passes through a pinned tokenizer to token pieces and integer IDs. IDs index learned embedding rows. A shifted copy of the ID sequence supplies next-token labels, and a mask removes padding or prompt targets from the loss. text “GPU training” tokenizer pinned rules+ vocabulary tokens piece A · piece B· piece C token IDs [i, j, k] embedding lookup rows E[i], E[j], E[k] model input IDs [i, j, k] positions 0, 1, 2; T = 3 next-token labels [j, k, ignore] prompt or padding targets may also be ignored loss is averaged over selected target positions token identity, position, attention visibility, and loss visibility are separate contracts The numeric IDs are identifiers; learned meaning begins with embedding vectors and later context.
Text, tokens, token IDs, embeddings, and shifted labels

Text passes through a pinned tokenizer to token pieces and integer IDs. IDs index learned embedding rows. A shifted copy of the ID sequence supplies next-token labels, and a mask removes padding or prompt targets from the loss.

Packing puts several examples into fewer tensor rows. If those examples must remain independent, their attention regions need boundaries: a block-diagonal causal mask, or explicit packed-sequence metadata understood by the selected backend, blocks cross-example attention. Position IDs must follow the intended positional scheme. Resetting positions alone does not isolate examples unless that backend explicitly converts the resets into attention boundaries.

Causal batch Read downward from input construction to the objective. Labels select target tokens, the loss mask selects contributions, and the attention mask controls accessible context. Packed examples need real attention boundaries as well as correct labels. Diagram concepts: Tokenize each example; Assign labels and masks; Compute valid-token loss. Tokenize each exampleAssign labels and masksCompute valid-token loss
Causal batch

Read downward from input construction to the objective. Labels select target tokens, the loss mask selects contributions, and the attention mask controls accessible context. Packed examples need real attention boundaries as well as correct labels.

First-fit packing supplies a concrete storage plan. Process example lengths in order, place each in the first bin with enough capacity, and open a new bin if none fits. With capacity 8 and lengths 5, 3 and 4, lengths 5 and 3 share the first bin; length 4 starts a second. This simple rule need not find the fewest bins. Each stored example span must still receive its own lower-triangular causal region. Lab 25 checks the allocation and mask structure; constructing labels and validating an actual packed learning objective remain separate work.

Example identity, token count, retained or truncated regions, unmasked tokens and packed boundaries connect the batch back to the source data. Licensing, privacy, deduplication and strict train/evaluation separation remain part of the learning contract even when packing makes the storage more efficient.

Padding, prompt masking, truncation, chat templates, and packing change the loss denominator and sometimes which tokens can attend to one another. A faster pipeline with a different batch is not equivalent training.

For tokens [A, B, C], a causal next-token objective pairs the representation after A with label B and the representation after B with label C. It must not train the position after C to predict the first token of an unrelated packed document. An attention boundary prevents reading the other document, while a loss mask excludes invalid prediction targets; those two controls solve different problems.

Mental model

A causal model predicts the next token. Padding and prompt regions may be excluded from loss; packing combines examples while preventing attention and labels from crossing example boundaries.

3. Decoder architecture and information flow

Objective

Follow embeddings, normalization, attention, residual paths, MLP, and logits with shapes.

How it works

A decoder-only transformer is a neural-network architecture that builds a representation for each token using the context it is allowed to read, then scores possible next tokens. An embedding turns a token ID into a vector. Each transformer block combines attention, a feed-forward network and residual connections. Attention mixes information from permitted positions; a head is one attention component with its own learned projections. A projection is a learned linear transformation. The feed-forward network, often called a multilayer perceptron (MLP), transforms each position's vector through additional learned operations. An activation function introduces a nonlinear change: its output cannot be expressed as just a weighted sum plus bias. Placing it between learned linear operations prevents the MLP from collapsing into a single matrix-and-bias operation. An activation function is the transformation; activations are the values produced by the network.

Activations are intermediate values produced during a forward pass. Normalization rescales them using statistics of the vector, and residual addition adds an earlier representation to a transformed one. Attention creates query, key and value vectors through learned projections: queries seek relevant context, keys supply information for matching, and values supply the information mixed into the result. Rotary positional embeddings (RoPE) encode relative position through rotations of query/key components. The final projection produces logits—unnormalized vocabulary scores. This architecture description explains the stages before the lesson follows their tensor shapes and memory costs.

Decoder-only language model from token IDs to logits Token IDs select embeddings. Position information is used by the model, including within attention for RoPE. N decoder blocks with distinct weights preserve hidden width; final normalization and the language-model head produce vocabulary logits. In a pre-normalized block, y=x+Attention(Norm(x)), then output=y+MLP(Norm(y)). Each residual addition has both the transformed branch and the incoming residual as inputs. Token IDs [B,T] Embeddings [B,T,H] N decoder blocks Position-aware attention Distinct block weights Final norm [B,T,H] LM head Vocabulary logits [B,T,V] Position handling is architecture-specific: RoPE acts on attention coordinates, not by adding a token. Inside one pre-normalized decoder block Norm Causal attention Plus outputprojection Add x Norm MLP Per position Add y x: incoming hidden state y: first residual result y = x + Attention(Norm(x)); output = y + MLP(Norm(y)) Training uses many positions for loss; generation selects the newest position's output distribution.
Decoder-only language model from token IDs to logits

Token IDs select embeddings. Position information is used by the model, including within attention for RoPE. N decoder blocks with distinct weights preserve hidden width; final normalization and the language-model head produce vocabulary logits. In a pre-normalized block, y=x+Attention(Norm(x)), then output=y+MLP(Norm(y)). Each residual addition has both the transformed branch and the incoming residual as inputs.

Batches contain IDs, masks, positions, and labels. The transformer maps those tensors into logits while retaining intermediate activations needed by backward.

From token IDs to attention inputs

Let B be batch size, S sequence length, H hidden width and V vocabulary size. Input IDs have shape [B,S]. Looking them up in the embedding table produces [B,S,H]: one H-value vector for each token position. Positional information tells the model where that vector occurs in the sequence.

The concrete decoder example uses learned positional embeddings, added to token embeddings. Its LayerNorm subtracts a vector's mean, divides by sqrt(variance + epsilon), and applies a learned scale and offset. Other architectures make different choices: RoPE rotates query/key components rather than adding a learned position vector. The walkthrough must follow the actual architecture instead of treating these methods as interchangeable.

Mix information from allowed positions

From normalized hidden values, learned projections form queries Q, keys K and values V. Here V names the value tensor, not the vocabulary size above. Here, heads is the number of attention heads and head_dim is the number of values in each head's vector. These tensors are commonly arranged as [B,heads,S,head_dim]. A query describes what a position seeks, a key contributes a matching score, and a value supplies content to combine.

For one head, scaled dot-product attention is softmax(Q @ K.T / sqrt(head_dim) + mask) @ V. Query-key products give scores; scaling controls their magnitude; the mask excludes forbidden positions; softmax converts allowed scores into weights; and those weights mix the value vectors. In square causal attention, each position can use itself and earlier positions. A fused implementation can perform this calculation without storing the entire score matrix. PyTorch's scaled_dot_product_attention expresses the operation and selects a supported implementation. Grouped-query attention (GQA) uses fewer K/V heads shared across more query heads.

Return to the hidden representation and produce logits

The attention output projection returns to width H so it can be added to the residual path. The MLP expands the hidden dimension, applies a nonlinear activation and contracts it again before another residual addition. This example uses Gaussian error linear unit (GELU), x*Phi(x), where Phi is the standard normal cumulative probability. Final normalization and a vocabulary projection produce logits [B,S,V].

Causal self-attention and MLP data flow Input x feeds normalization and the first residual bypass. Normalized states form Q, K and V. Scaled QK scores receive a causal mask before softmax, then probability weights mix V and the output projection restores the hidden width. Adding x forms y. Normalization and a position-wise MLP transform y; adding the bypassed y produces the block output. Hidden state x [B,T,H] Norm Q: queries K: keys V: values Scaled QKᵀ Causal mask Then softmax Attention output Weights × V → output projection [B,T,H] Add x y = x + attention output Norm MLP Expand → activation/gate Project back to H Add y Block output Projected attention result x Residual y bypasses norm and MLP Attention mixes allowed positions; the MLP transforms features independently at each position.
Causal self-attention and MLP data flow

Input x feeds normalization and the first residual bypass. Normalized states form Q, K and V. Scaled QK scores receive a causal mask before softmax, then probability weights mix V and the output projection restores the hidden width. Adding x forms y. Normalization and a position-wise MLP transform y; adding the bypassed y produces the block output.

A logit is a score, not a probability. Softmax exponentiates the scores and divides by their sum, producing nonnegative probabilities that sum to one. Cross-entropy for a known next token is the negative natural logarithm of its probability, so assigning that token more probability lowers the loss.

Backward traces how that loss depends on each trainable parameter and computes its gradient. Simple gradient descent subtracts learning rate times gradient. AdamW instead uses running averages of gradients and squared gradients to adapt the update, with decoupled weight decay separately shrinking parameters toward zero. It does not mix that decay into the gradient used for the adaptive calculation.

Decoder training step Read downward: model blocks transform embedded tokens into logits, the objective scores the known targets, and backward computes gradients for the optimizer. A residual path carries earlier representations inside each block. Diagram concepts: Embeddings and blocks; Logits and loss; Gradients and update. Embeddings and blocksLogits and lossGradients and update
Decoder training step

Read downward: model blocks transform embedded tokens into logits, the objective scores the known targets, and backward computes gradients for the optimizer. A residual path carries earlier representations inside each block.

Shape reasoning reveals compute, activation memory, communication, and kernel efficiency. It also separates parameters that persist across steps from activations whose size grows with microbatch and sequence length.

Mental model

Token IDs select embeddings; repeated decoder blocks transform [batch, sequence, hidden]; the language-model head maps hidden states to vocabulary logits.

4. The parameter-update lifecycle

Objective

Order forward, loss, backward, gradient handling, optimizer update, and zeroing correctly.

How it works

A training step performs a parameter update. The forward pass computes predictions from current parameters; the loss turns prediction error into a scalar objective; backward computes gradients describing sensitivity of that loss to parameters; the optimizer then changes the parameters using those gradients and its update rule. Backward does not itself update the weights. PyTorch autograd is the automatic-differentiation system that records supported operations and applies their derivative rules.

A microbatch is a smaller group processed within a larger intended update. Several microbatches may contribute before the optimizer runs, provided their losses are normalized consistently. Gradient clipping limits the gradient's magnitude, while a learning-rate scheduler changes the update scale over training. These operations have an order because later stages consume earlier results. The distributed averaging and precision-scaler cases below are extensions of this basic loop, not prerequisites for understanding why one weight changes.

The decoder produces logits and the batch supplies valid labels. Training converts their scalar loss into parameter updates through autograd and optimizer state.

Build gradients, then update parameters

Forward computes logits from the current parameters, and the loss combines errors over valid labels. Backward differentiates that scalar and accumulates gradients into parameter buffers. The optimizer consumes those gradients to change the weights. Clearing gradients after the update, or before the next intended backward, prevents an earlier step from unintentionally contributing to the next one.

Forward, backward, optimizer, and next training step Batch IDs, attention metadata, and current parameters are separate inputs to the forward pass. The loss calculation takes logits, target labels and loss masks as inputs. Backward uses loss and the forward graph to accumulate gradients. The optimizer reads the current parameters, gradients, moment state and learning rate. Updated parameters become next-step parameters; clear gradients before the next accumulation window. Batch IDs + attention metadata Targets Labels + loss mask Forward Saved/recomputedactivations Logits [B,T,V] Loss Valid-token normalization Parameters θ Current trainable values Backward Chain rule Gradients Accumulate ∂loss/∂θ Optimizer state Moments + learning rate Decay and schedule Optimizer step θ′ = update(θ, gradients, state) Updated θ′ Next forward's parameters Forward graph State update for the next step; clear gradients before the next accumulation window
Forward, backward, optimizer, and next training step

Batch IDs, attention metadata, and current parameters are separate inputs to the forward pass. The loss calculation takes logits, target labels and loss masks as inputs. Backward uses loss and the forward graph to accumulate gradients. The optimizer reads the current parameters, gradients, moment state and learning rate. Updated parameters become next-step parameters; clear gradients before the next accumulation window.

Lab 01 runs forward and loss inside CUDA bfloat16 (BF16) autocast, then exits the context before backward. Autocast selects computation formats for supported operations; it does not convert every stored parameter to BF16. This BF16 recipe does not use 16-bit floating point (FP16) loss scaling. When a separate FP16 recipe does use scaling, gradients must be unscaled before their true magnitudes are checked or clipped.

Control gradient magnitude at the correct point

Gradient-norm clipping acts on the combined parameter-gradient vector before the optimizer update. A gradient [3,4] has Euclidean (L2) norm 5. A limit of 1 scales it to [0.6,0.8], preserving direction while reducing magnitude. clip_grad_norm_ modifies the gradients and reports their pre-clipping norm. Non-finite gradients must be rejected before updating. Clipping bounds the gradient, not necessarily the adaptive optimizer's parameter-update norm.

The optimizer may also maintain persistent state. AdamW keeps first and second moments; a separate higher-precision master-weight copy depends on the mixed-precision implementation and is not an automatic extra allocation in every recipe. The learning-rate scheduler advances according to its declared unit, such as optimizer updates. These states belong in memory and restart accounting. Lab 01's optional save is only a partial snapshot; Lesson 5 explains complete resume state.

Keep the same objective across microbatches and ranks

Several microbatches can contribute before one update. With unequal valid-token counts, averaging their mean losses equally gives short microbatches too much weight. Instead, combine loss sums and valid-token counts, or weight each contribution so the accumulated gradient matches the intended reference batch.

The same issue occurs across ranks. Under ordinary DistributedDataParallel (DDP) averaging over R ranks, each rank can backpropagate R × local_loss_sum / global_valid_tokens. DDP's later division by R cancels that factor, leaving the global token-weighted gradient. Count valid tokens across all ranks and the entire intended accumulation window. With two ranks holding 100 and 300 valid labels, this gives the concatenated 400-token objective; averaging their two local means does not.

DDP's no_sync can suppress intermediate communication while microbatches accumulate, with synchronization at the final microbatch. It does not choose the correct loss denominator for the program. This derivation assumes default averaging, not a custom hook or rank-joining policy with different semantics. It is a preview for Lesson 11; the first single-GPU pass needs only the forward, loss, backward and update sequence.

A loop can run quickly while applying the wrong gradient scale, clipping at the wrong time, accumulating stale gradients, or stepping its scheduler on the wrong cadence. Performance evidence is invalid until update semantics are tested.

Mental model

Autograd records the forward graph, backward accumulates gradients into parameter buffers, and the optimizer updates parameters from those buffers and its state.

5. Training evaluation and recovery

Objective

Save every state needed to reproduce the next training step after interruption.

How it works

Evaluation measures a model's behavior on examples not used for the current parameter updates. A checkpoint is a saved snapshot of training state; resuming means restoring enough state to perform the intended next update. Saving model weights alone can support inference or a new fine-tuning run, but does not necessarily reproduce a paused training run. Optimizer history, learning-rate position and random choices can affect what happens next.

A random-number generator (RNG) produces reproducible pseudorandom sequences from its state. An epoch is a pass through a dataset; a sampler chooses examples and their order; a data cursor records how far consumption has progressed. Atomic checkpoint publication makes a completed snapshot become visible as a unit rather than exposing a partly written file. This saved restart checkpoint differs from activation checkpointing, which later recomputes intermediate values during backward to save GPU memory.

A correct step is a state transition. Exact resume means restoring the complete pre-transition state and consuming the same next data, not merely loading similar weights.

A resumable checkpoint captures the state just before a well-defined next transition. The model weights are only one part. The optimizer's moments and step counts affect the next update; the scheduler's position affects its scale; and a precision scaler or 8-bit floating point (FP8) recipe can affect the arithmetic. Adapters and their configuration must also match the base model.

The next batch is state too. CPU and accelerator RNG states affect random choices, while the distributed sampler epoch and data cursor determine which examples come next. If a checkpoint is taken inside an accumulation window, the accumulated gradients and current microbatch position must be retained. Version, configuration and artifact identity establish how these values are interpreted.

Saving should expose only a complete snapshot. Data is written to a temporary private location, participating ranks coordinate at the declared boundary, and completeness is checked before the snapshot is made visible atomically. A partially written file or a mix of states from different updates cannot define a valid restart.

Restoration is tested by continuing both an uninterrupted run and a restored run from the same boundary with the same next data. A deterministic supported recipe may require bitwise equality; a nondeterministic kernel path needs an explicit tolerance-based continuation claim. Merely loading the file proves neither. Evaluation separately uses held-out data and weights loss by valid tokens so unequal batch lengths do not distort the reported mean.

Exact resume The arrows show a saved-state transition. Model weights, optimizer history, RNG, data position and any partial accumulation must agree before a restored run can reproduce the next update. Diagram concepts: Capture complete state; Restore the same boundary; Perform the next update. Capture complete stateRestore the same boundaryPerform the next update
Exact resume

The arrows show a saved-state transition. Model weights, optimizer history, RNG, data position and any partial accumulation must agree before a restored run can reproduce the next update.

For example, save immediately after update 40 with no partial gradients. The checkpoint records the model and optimizer after that update, the scheduler position, the RNG states and the cursor for the next batch, B41. Both an uninterrupted run and a restored run must now consume B41 and use the same update-41 learning rate and random choices. Restoring only the weights can instead restart optimizer moments, replay an earlier batch or draw different dropout masks. Compare the next update under the declared deterministic or tolerance-based contract; these update numbers illustrate the boundary, not a measured run.

Missing optimizer, scheduler, scaler, RNG, sampler, or partial-accumulation state can silently fork the run. A checkpoint that loads successfully may still fail continuation equivalence.

Mental model

Exact resume may require model, optimizer, scheduler, scaler, RNG, data position, sampler, and accumulation state. Evaluation uses held-out data and must not update training state.

6. Training memory and state lifetimes

Objective

Account for weights, gradients, optimizer state, activations, temporaries, communication buffers, and allocator reserve.

How it works

A training memory ledger accounts for the values that must exist at each stage and for how long they are needed. Persistent state survives between steps, including parameters and optimizer history. Activations are intermediate forward values, some of which backward needs. Temporary state, such as an operation's workspace, may exist only while that operation runs. Peak memory is the greatest simultaneous requirement, not the sum of every allocation made over the entire run.

Allocated memory is storage currently held by tensors; reserved memory also includes blocks retained by the allocator for reuse. Some mixed-precision recipes keep wider master weights for updates alongside lower-precision computation values. Offload moves selected state to another storage tier, usually host memory, and introduces transfer costs. Distributed buffers add another lifetime to the ledger. Their detailed sharding rules come later; first identify which values must coexist even for one ordinary training step.

The correct update and resume lessons established model parameters, gradients, optimizer buffers and saved activations. A phase-aware ledger now places persistent and temporary state in forward, backward, optimizer and checkpoint time; distributed replication/sharding will build on this ledger later.

Start with state that survives between updates. Parameter count multiplied by bytes per stored value gives parameter storage. Apply the same reasoning to gradients and each optimizer moment, using their actual dtypes. Count a separate master-weight copy only when the chosen implementation maintains one; do not assume every mixed-precision optimizer does.

Forward adds activations and temporary workspaces. Some activations remain until backward uses them; others can be discarded or recomputed. Their sizes depend on the layer, microbatch, sequence length and format. Attention and MLP temporaries can create a peak even when persistent state is modest.

Distributed or specialized execution adds more intervals: Fully Sharded Data Parallel (FSDP) all-gather buffers, DistributedDataParallel (DDP) buckets, 8-bit floating point (FP8) metadata and graph pools. Place each allocation on a timeline from creation to last use. The forward, backward and optimizer peaks are the totals that coexist at those moments, not the sum of everything allocated during the step.

Allocator accounting overlaps this tensor ledger. Reserved bytes already include active allocations plus capacity retained for reuse. Add only additional unused reservation or other uncounted overhead when reconciling against reserved memory; adding the entire reserved total to live tensor bytes double-counts them. Snapshots and peak APIs help compare calculated, measured and still-unknown quantities.

Training memory Compare state lifetimes, then count what coexists at the peak. Do not sum every allocation made during a step, or add total reserved memory on top of the live bytes it already includes. Diagram concepts: Persistent model state; Activations and temporaries; Peak simultaneous storage. Persistent model stateActivations andtemporariesPeak simultaneous storage
Training memory

Compare state lifetimes, then count what coexists at the peak. Do not sum every allocation made during a step, or add total reserved memory on top of the live bytes it already includes.

Checkpoint loading has a separate peak: model files, optimizer shards and temporary load or staging buffers can coexist differently from training. A model-file size therefore cannot stand in for either the training peak or the load-time peak.

Checkpoint file size is not live training footprint. Optimizer moments, master weights, saved activations, temporary workspaces, gathers, reduction buckets, graph pools, and allocator headroom can exceed visible parameter bytes.

As a deliberately simplified ledger, one million parameters stored in 32-bit floating point (FP32) need 4 million bytes. An equally sized FP32 gradient needs another 4 million bytes, and two FP32 optimizer moment arrays add 8 million, giving 16 million bytes before activations, temporary buffers or allocator overhead. Changing the parameter dtype alone does not halve all four terms. Master weights, sharding and the actual optimizer recipe can change this accounting, so enumerate the state that the implementation really retains.

High-bandwidth memory (HBM) is the GPU’s device memory. This ledger concerns live storage there; moving or sharding state changes ownership and communication costs rather than making the state disappear.

Mental model

Persistent model/optimizer states scale with parameters; activations scale with batch and sequence; temporaries and collectives create phase-specific peaks. Activation or optimizer offload trades HBM for host-memory capacity and transfer latency, so it is a capacity escape hatch rather than a default speed optimization.

7. Numerical precision in training

Objective

Select state-specific precision and verify loss, gradients, updates, and kernels.

How it works

Mixed precision uses different numerical formats for different parts of a training calculation. FP32 means 32-bit floating point, FP16 means 16-bit floating point, BF16 means bfloat16, and FP8 denotes an 8-bit floating-point format. Range describes the largest and smallest magnitudes represented, while precision describes the spacing between representable values. A smaller format can reduce storage or enable faster supported arithmetic, but can also alter losses, gradients and updates.

Autocast selects operation-appropriate formats within a region; it does not simply convert all model state to one dtype. Loss scaling multiplies the loss before backward and later unscales gradients to help small gradients survive limited range. NVIDIA Transformer Engine is a library for supported low-precision transformer operations and scaling state. An amax value is an observed maximum absolute magnitude, and a recipe defines how such measurements select scales and formats. These mechanisms must be checked across the complete update, not only its forward output.

The memory ledger shows where bytes live; mixed precision chooses formats for individual states and operations without changing the mathematical training objective.

Choose formats for operations and state separately

Mixed precision changes selected representations along the update path. TensorFloat-32 (TF32) permits particular reduced-precision matrix arithmetic on FP32 inputs without changing their storage type. BF16 retains an FP32-like exponent range with fewer fraction bits. FP16 has a narrower range, so small gradients can disappear or large values can overflow more readily. Normalization, reductions, accumulation and optimizer state may need suitable higher precision even when matrix inputs use a smaller format.

Loss scaling helps FP16 gradients survive that range. Multiply the loss before backward, compute scaled gradients, then unscale them before finite checks, clipping and the optimizer update. Scaling does not create more precision; it changes magnitudes during the vulnerable calculation. BF16 often needs no such scaling, but its coarser precision still requires checking the update.

Follow the FP8 recipe

Transformer Engine's te.autocast applies a selected low-precision recipe to supported forward modules. Backward uses the corresponding precision context recorded by forward. A scale maps a tensor's values into a representable range. Delayed scaling uses prior maximum-absolute-value (amax) history; current or block recipes choose scales using different data and support requirements. Warmed recipe state and its history can therefore affect results as well as speed.

FP8 is a family of encodings. E4M3 uses four exponent bits and three fraction bits; E5M2 uses five and two. The exponent controls range and the fraction controls precision within that range. Both also have a sign bit, and their special-value rules are format-specific. E4M3 retains more fraction precision, while E5M2 offers greater exponent range. A hybrid recipe can use different encodings for forward tensors and gradients. Block scaling, outlier handling and higher-precision operations complete the recipe; saying “FP8” alone does not describe the calculation.

Stochastic rounding probabilistically selects adjacent representable values to reduce systematic rounding bias over repeated conversions. It cannot guarantee an individual value's accuracy or recover a saturated value. NVIDIA NVFP4 recipes can combine rounding and transforms, but those Blackwell-specific training paths are comparison-only here, not H100 lab capabilities.

Check the resulting update

Matching initial parameters and inputs allow loss, gradients and parameter changes to be compared across recipes. Relative Euclidean (L2) error divides the candidate-minus-reference vector magnitude by the reference magnitude; it describes aggregate discrepancy rather than the worst element. Finite checks, scaling/amax behavior and selected kernels explain what happened along the path. A short correct update test can detect a broken recipe, but cannot establish training convergence.

Precision ledger Read downward from representation to arithmetic to the resulting update. Stored dtype does not uniquely determine multiplication or accumulation precision. A smaller format needs finite, gradient and update checks as well as kernel evidence. Diagram concepts: Storage dtypes; Compute and accumulation; Loss and update gates. Storage dtypesCompute and accumulationLoss and update gates
Precision ledger

Read downward from representation to arithmetic to the resulting update. Stored dtype does not uniquely determine multiplication or accumulation precision. A smaller format needs finite, gradient and update checks as well as kernel evidence.

“FP8 training” does not mean every tensor is FP8. Unsupported shapes, cast/scaling overhead, overflow/underflow, cold scaling history, or a changed optimizer can erase performance or learning equivalence.

FP8 weight caching retains a quantized copy of unchanged weights across microbatches in an accumulation window, avoiding repeated conversions. Fused weight-gradient accumulation writes matrix-product gradients directly into an accumulation buffer, combining gradient production and addition instead of requiring a separate temporary gradient and addition step. These techniques can remove conversions or launches only for supported recipes, modules and shapes. Weight caching still needs numerical checks because changing scale history can make cached and freshly converted values differ.

Mental model

Choose a representation for each kind of computation and state. Scaling protects useful numerical range, while accumulation and sensitive operations may need greater precision; the full training result decides whether the recipe is acceptable.

8. Memory savings through accumulation and recomputation

Objective

Compare microbatching and selective/full activation recomputation at fixed effective tokens.

How it works

Gradient accumulation and activation checkpointing are two different ways to change a training step's memory needs. Accumulation processes smaller microbatches, combines their correctly weighted gradients and performs one optimizer update for the intended effective batch. It saves memory by not holding every example's activations at once. The global batch counts the work contributing to that update across microbatches and, where used, ranks; variable valid-token counts require token-aware weighting.

Activation checkpointing retains selected forward values and recomputes missing intermediates when backward needs them. It trades extra computation for fewer saved activations. Selective recomputation repeats chosen operations or regions; full-block recomputation repeats a larger region. This is not saving a restart checkpoint to disk. The two techniques can be combined, but each changes a different part of the step, so measure memory, total work and update equivalence separately.

Two ways to save training memory Compare complementary choices. Small microbatches reduce activation demand. Accumulation retains and combines gradients before one update. Checkpointing retains selected activations and recomputes missing ones during backward. They change different lifetimes and must preserve the declared global objective. Diagram concepts: Small microbatches; Accumulated gradients; Recomputed activations. Small microbatchesAccumulated gradientsRecomputed activations
Two ways to save training memory

Compare complementary choices. Small microbatches reduce activation demand. Accumulation retains and combines gradients before one update. Checkpointing retains selected activations and recomputes missing ones during backward. They change different lifetimes and must preserve the declared global objective.

The training step defines effective tokens and update cadence; the memory ledger identifies saved activations that dominate peak capacity. Accumulation and checkpointing change different parts of that ledger.

Accumulation divides one intended update into smaller microbatches. Each forward/backward pair needs activations for only its microbatch, while gradients accumulate until the optimizer runs once. Global valid tokens per update must remain fixed, and unequal microbatches need token-weighted contributions. DistributedDataParallel (DDP) may use no_sync for intermediate microbatches, but that controls communication rather than objective weighting.

Activation checkpointing changes what is saved within each forward. It retains selected values and omits other intermediates that backward will need. During backward, those missing values are produced again by repeating part of forward. Selective recomputation targets intermediates that are large to store and relatively cheap to recreate; full-layer checkpointing is simpler but can repeat expensive attention and MLP work.

Here reentrant refers to invoking a nested differentiation execution during backward. PyTorch's non-reentrant implementation records the autograd dependency graph during forward while omitting selected saved tensors. Backward recreates the tensors needed by that graph; with early stopping enabled, recomputation stops once those intermediates exist. The qualified path selects it explicitly with use_reentrant=False.

Re-execution must preserve semantics. Random operations, stateful modules, autocast/8-bit floating point (FP8) state and side effects can behave differently when run again unless the chosen implementation handles them correctly. The resulting trade includes bytes no longer retained, added floating-point operations (FLOPs) or kernels, peak memory, step-time distribution and valid tokens/s. Numerical update equivalence establishes whether the smaller-memory execution still performs the same learning task.

For a matched-work example, suppose one update uses 64 examples with equal valid-token counts. A microbatch of 16 needs four forward/backward passes; a microbatch of 8 needs eight. Weight each mean loss by one quarter or one eighth respectively, then apply the optimizer once. With unequal valid-token counts, use each microbatch’s share of the total valid tokens instead. Hold that microbatch plan fixed when studying recomputation: checkpointing a block keeps its chosen inputs but recreates omitted intermediates during backward. It does not add new training examples or authorize an extra optimizer update. The memory saved and computation added must be measured.

Accumulation reduces per-microbatch activations but does not remove parameter/optimizer state. Checkpointing removes selected saved activations but executes forward work again during backward. Comparing different effective batches hides the real exchange.

Mental model

Accumulation reduces per-microbatch activation size but adds launches and delays updates; checkpointing discards selected activations and recomputes them during backward.

9. Training input readiness

Objective

Keep training data ready without changing sample order or semantics.

How it works

The training input pipeline turns stored examples into GPU-ready batches. It reads and transforms examples, assembles them through collation, and transfers the resulting tensors from host to device (H2D). Workers are processes or threads preparing data. Prefetch means preparing future batches before the trainer requests them; queue depth counts prepared batches waiting for consumption. Starvation occurs when the GPU has reached its next step but the needed batch is not ready.

Pinned host memory supports suitable asynchronous transfers, and nonblocking submission allows the CPU to continue before a copy finishes. Neither removes the need for correct buffer lifetime and dependencies. More workers can prepare faster or compete for the same storage and CPU resources. In training, sample identity and order are part of the workload: feeding different examples or dropping slow ones is not a valid optimization of the same learning task.

Accumulation and recomputation optimize the GPU step only when a valid next batch is available. The input pipeline is a distributed producer system whose correctness includes exact sample ownership.

A dataset maps an index to sample content. Workers read, decompress, parse and tokenize that content; packing and collation assemble the selected examples into tensors; pinning and H2D copies make those tensors available to the GPU. A delay at any producer stage can leave the trainer waiting for its next batch.

Input pipeline Arrows show the order for one batch: read/tokenize, assemble and transfer, then execute its GPU step. Preparing a later batch can overlap current computation only while sample ownership and copy dependencies remain correct. Diagram concepts: Read and tokenize; Pack and transfer; GPU step. Read and tokenizePack and transferGPU step
Input pipeline

Arrows show the order for one batch: read/tokenize, assemble and transfer, then execute its GPU step. Preparing a later batch can overlap current computation only while sample ownership and copy dependencies remain correct.

Prefetch lets workers prepare future batches while the current batch runs. It can absorb variation, but its queue consumes memory and eventually empties if production is consistently slower than consumption. Persistent workers avoid restarting their processes. Offline tokenization removes repeated CPU work but creates a prepared artifact tied to the tokenizer, configuration and data revision.

Training correctness follows the examples through these changes. Worker seeds, distributed sampler ownership and epoch updates must preserve the intended global sample IDs, order, content and unmasked-token counts. Dropping a slow example or giving two ranks the same sample changes the task even if the device becomes busier.

Ready-time distributions and queue depth beside GPU steps reveal where waiting occurs. Synthetic inputs remove the real source path; resident inputs remove preparation and transfer as well. These controls distinguish loader starvation from later delays. On shared storage, adding workers may increase contention instead of readiness, so per-node behavior matters. Pinned source batches must remain valid and unchanged until their nonblocking copies complete.

Loader starvation creates idle gaps; careless tuning can duplicate, omit, reorder, or retokenize data differently. Throughput gained by changing examples is not an optimization.

Mental model

Storage, tokenization, collation, packing, pinning, and transfer form a staged producer. Queue depth and worker count trade latency hiding against memory and contention.

10. Training execution optimization

Objective

Reduce launch and intermediate traffic while respecting autograd and optimizer semantics.

How it works

Fusion combines operations so a program may launch fewer kernels and avoid writing some intermediate tensors. Compilation transforms a program region into executable implementations. A CUDA Graph represents GPU operations and their dependencies as a reusable execution plan; capture records compatible work, and replay submits that plan again with less repeated host setup. Replay is not a saved numerical result and does not itself fuse kernels. These are related but distinct techniques.

For training, the replayed work can change parameter, gradient and optimizer-state values while using retained storage. A graph memory pool manages allocations associated with captured work. Compiler guards check assumptions such as shape; a graph break ends a compiler-captured region and is not the same thing as a failed CUDA Graph capture. A profiler records execution activity, and NVIDIA Tools Extension (NVTX) annotations name regions in a trace. The lesson applies these tools to the complete update rather than assuming an optimized forward pass guarantees faster training.

A correct update, explicit memory/precision policy and a supplied next batch establish the single-GPU baseline. Fusion, compilation and graph replay now target local launch gaps and intermediates before distributed placement and communication are introduced.

A training update contains more than forward kernels. Input preparation, forward, loss, backward, optimizer work and communication each create dependencies. A short profiler window with named NVTX ranges connects those phases to repeated pointwise chains, intermediate allocations and CPU submission gaps.

Fusion can combine compatible operations and avoid writing some intermediates. Maintained fused operators or a qualified torch.compile region may provide that change, but guards and graph breaks limit which operations the compiler can transform. The generated forward and backward kernels, remaining allocations and gradient results reveal whether the intended fusion happened without changing the update.

CUDA Graph replay addresses repeated submission of stable work. After warm-up, capture records operations whose addresses, control flow and dependencies remain compatible across replays. Parameters and optimizer state can change values in their retained storage. Graph pools retain memory, and a bounded set of captures can handle selected microbatch or sequence-shape buckets. Unsupported cases need an explicitly supported fallback.

Training execution strategies Compare execution strategies for the same parameter update. Eager execution submits operations individually, compilation may fuse eligible work, and a CUDA Graph replays a prepared dependency plan. Gradients and parameters still change; stable storage does not mean constant values. Diagram concepts: Eager: submit operations; Compile: transform regions; Graph: replay dependencies. Eager: submit operationsCompile: transform regionsGraph: replay dependencies
Training execution strategies

Compare execution strategies for the same parameter update. Eager execution submits operations individually, compilation may fuse eligible work, and a CUDA Graph replays a prepared dependency plan. Gradients and parameters still change; stable storage does not mean constant values.

These transformations must preserve random number generator (RNG) advancement, gradient zeroing, scaler or 8-bit floating point (FP8) state and collective ordering. A faster forward fragment does not establish a faster complete update. Compilation, capture and steady replay have separate time and memory costs, and backward/update equivalence must be checked alongside the final step time.

Training graphs include autograd, mutation, RNG, optimizer state, dynamic shapes, and collective boundaries. A transformation that works for an inference fragment can produce graph breaks or incorrect gradients in training.

Mental model

Compilation can fuse forward/backward operators; CUDA Graphs can replay stable step regions. Dynamic shapes, optimizer branches, and allocation changes require buckets or fallbacks.

11. Distributed training-state ownership

Objective

Compare replicated and sharded training state with one rank on each advanced worker.

How it works

Distributed Data Parallel (DDP) keeps a complete model replica on each participating process. The input pipeline supplies each process its assigned data; DDP combines gradients so updates stay consistent. A rank is a process identifier; a replica is a complete copy; a shard is one piece of a larger tensor or state. Fully Sharded Data Parallel version 2 (FSDP2) divides parameters and associated training state across ranks and gathers needed parameter pieces for computation. It targets state capacity as well as distributed execution.

A collective involves a group of ranks: all-reduce combines values and returns the result to all; all-gather assembles their pieces; reduce-scatter combines values but returns a different reduced piece to each rank. ZeRO, the Zero Redundancy Optimizer family, describes related stages of training-state sharding. These terms explain where state lives and how it moves; they do not imply that adding ranks always reduces step time.

The memory ledger divides model, gradient, and optimizer state; distributed data parallelism decides which ranks own copies or shards and which collectives reconstruct a consistent update.

Begin with one training rank and its state. In DDP, adding ranks creates complete model replicas with their own optimizer state. The application assigns each rank its input; DDP does not split a batch automatically. Each replica computes local gradients, then ordinary DDP all-reduces and averages them so every replica can apply the same update.

All-reduce returns the complete reduced gradient to every rank. Reduce-scatter alone instead returns one reduced shard per rank, which is insufficient for an ordinary optimizer that owns the full replicated model. An all-reduce may internally use reduce-scatter followed by all-gather, but its externally visible result remains a full gradient on every rank.

FSDP2 changes ownership. It shards selected parameters, gradients and optimizer state. Before computation needs a full parameter group, all-gather assembles its pieces; after gradients are computed, reduce-scatter returns the reduced pieces to their owners. This reduces persistent per-rank state while introducing temporary gathered parameters and communication. Its mixed-precision policy can also distinguish parameter-computation and gradient-reduction formats.

Replicated and sharded state Compare persistent ownership, then the computation boundary. Replication keeps full model state on every rank. Sharding distributes selected persistent state; each computation gathers missing parameter values when required and gradient reduction returns contributions to their owners. Temporary full values still consume memory. Diagram concepts: Replicas retain full state; Shards retain owned pieces; Gather needed values. Replicas retain full stateShards retain owned piecesGather needed values
Replicated and sharded state

Compare persistent ownership, then the computation boundary. Replication keeps full model state on every rank. Sharding distributes selected persistent state; each computation gathers missing parameter values when required and gradient reduction returns contributions to their owners. Temporary full values still consume memory.

ZeRO-style stages describe progressively sharding optimizer state, gradients and parameters. Actual implementations differ in when they gather or retain tensors, so the persistent ledger alone cannot predict peak memory or step time. Global non-padding tokens, sample ownership, loss reduction and optimizer semantics must remain the same in a comparison. Transient buffers, bucket overlap, the slowest-rank step and checkpoint/restart behavior describe the resulting execution.

DDP and FSDP2 solve different constraints. A small two-rank job may run faster with replication, while a larger model may require sharding merely to fit.

Megatron Core's distributed optimizer separately shards optimizer state and coordinates reduce-scatter/update/all-gather, but this two-rank PyTorch course does not qualify its production implementation.

Mental model

Replication gives each rank full persistent state; sharding assigns persistent pieces to different owners. Communication supplies the temporary full values or combined gradients needed at each computation boundary.

12. Model partitioning and communication

Objective

Map tensor, pipeline, context, and expert parallelism to partitioned state and communication.

How it works

Model parallelism divides one model's work when replication alone is not the desired layout. Tensor parallelism (TP) splits tensors and parts of an operation across ranks. Pipeline parallelism (PP) puts groups of layers on different stages and passes intermediate activations between them. Context parallelism (CP) partitions sequence context and coordinates the attention information needed across those partitions. Expert parallelism (EP) distributes the experts in a mixture-of-experts (MoE) layer: a router selects which expert networks process each token.

A pipeline bubble is idle time while a stage waits for work or results. All-to-all communication exchanges different pieces between ranks, often for expert routing. Grouped matrix multiplication, also called grouped general matrix multiplication (GEMM), executes several matrix problems together. A capacity factor sets an expert's token-capacity allowance relative to a stated average. Sequence parallelism can instead partition particular non-attention activations or operations within another parallel layout; it is not a universal synonym for CP. Each scheme changes a different ownership boundary.

Parallelism map Compare ownership choices, not a chain of transformations. Replication/sharding assigns state, TP/PP partitions computation or layers, and CP/EP distributes context or experts. Each creates different communication dependencies. Diagram concepts: Replicate or shard state; Partition operators or layers; Route context or experts. Replicate or shard statePartition operators orlayersRoute context or experts
Parallelism map

Compare ownership choices, not a chain of transformations. Replication/sharding assigns state, TP/PP partitions computation or layers, and CP/EP distributes context or experts. Each creates different communication dependencies.

DistributedDataParallel (DDP) and Fully Sharded Data Parallel (FSDP) partition data and training state. Model parallel strategies partition computation or model structure when one rank cannot efficiently own the full layer, sequence, pipeline, or expert set.

A parallel layout first assigns ownership: which rank holds a tensor, computes a layer or processes an expert's tokens? Communication then supplies the values that computation needs from other owners. The useful distinction is what crosses that boundary and when its consumer can proceed.

Partition one matrix operation

Tensor parallelism divides an operation's dimensions. Each rank computes its assigned output or a partial contribution, then an all-gather, all-reduce or reduce-scatter forms the representation needed next. Sequence parallelism can shard compatible activation work alongside TP.

Use matrix algebra to derive a partition before launching it. For Y = X @ W, splitting W into output-column shards gives each rank different columns of Y; all-gather concatenates them in the declared order. Splitting X's features and matching rows of W instead gives partial products whose sum is Y, so all-reduce reconstructs it. If G is the output gradient, the full derivatives are dW = X.T @ G and dX = G @ W.T. A column shard produces a weight-gradient shard and one contribution to dX; sum those input-gradient contributions. Normalize each partial loss by the global output-element count so summing contributions preserves the original mean objective. Validate reconstructed outputs, gradients and one update; retained full references must stay in the memory accounting.

Pass activations and gradients between stages

Pipeline parallelism assigns groups of layers to stages. Microbatches move forward through those stages and their gradients travel back, creating fill and drain bubbles when some stages have no ready work. Context parallelism instead partitions sequence context and communicates the K/V or attention state needed across partitions.

Point-to-point communication sends a tensor from one rank to another instead of involving the whole group. In a pipeline, the receiving rank starts its local differentiation from that activation and sends its activation gradient back. A plain send/receive is not a distributed autograd graph: the sender must apply the returned gradient to its retained local activation. In the context mechanics example, sum local squared values and divide by the full context's element count to preserve the global mean; gathering context shards checks reconstruction, not distributed attention.

Route tokens to their expert owners

Expert parallelism places MoE experts on ranks. Grouped GEMM can batch several local expert operations. Router balance, capacity factors, dropped or padded tokens and slow experts affect how much useful work each rank completes.

Expert routing groups tokens by owner, exchanges those groups with all-to-all, applies each owner's expert, then reverses the routing to restore input order. The training path must also return token gradients and update expert weights. Advanced Lab 17 explicitly carries these values across communication boundaries rather than assuming communication builds an autograd connection. Batched matrix multiplication (bmm) computes corresponding matrix products in a batch; padding unequal expert groups to a common size permits that comparison but performs extra work. Keep padding costs and the actual grouped implementation visible.

Make completion and correctness a group decision

A distributed acceptance decision must reach the same verdict on every rank. Advanced Lab 18 converts any non-finite tensor, norm or relative error into a failing infinite error, then reduces the integer pass flags with MIN across all ranks. One failed rank therefore prevents publication everywhere. This infinite error is a rejection marker, not a valid measurement. Keep ranks participating through the verdict collective rather than raising on just one rank before its peers reach that operation.

The same parallel degree can produce very different communication, bubbles, memory, and load balance. A topology choice must begin from what is sharded and when consumers need it.

A virtual pipeline stage is a logical chunk of layers; one physical rank can own several chunks and interleave their microbatch work. An asymmetric layout assigns different numbers or types of layers to physical stages to balance their costs. These choices change assignment and scheduling, not the model's required layer order. Each strategy targets a different capacity, bubble, or scaling constraint.

For a context-parallel attention example, split a four-token sequence so one rank owns positions 1–2 and another owns 3–4. The query at position 4 still needs allowed keys and values from all four positions; the query at position 2 must not see later positions. Exchanging key/value blocks lets each owner accumulate its local queries' attention contributions while maintaining the causal mask. The normalization must include all allowed keys, not a separate softmax average per rank. Backward must also return gradient contributions to the owners of those keys and values. This explains the communication dependency; the scalar context-partition lab only checks ownership, reconstruction and global normalization, not a distributed attention implementation.

Mental model

Partitioning changes who owns tensors, layers, context or experts. The model's dependencies remain, so each consumer must receive the missing values and backward must return the corresponding gradients.

13. Gradient readiness and communication overlap

Objective

Measure exposed communication rather than total collective duration.

How it works

Communication overlap means a transfer or collective progresses while independent useful computation also runs. In training, backward produces gradients at different times, so an already-ready group can communicate while later gradients are still being computed. A gradient bucket is a group of gradient values communicated together. Readiness means all inputs needed by that communication are available. A dependency says one operation must wait for another; the critical path is the chain of dependencies that determines completion time.

Exposed communication is the portion that still delays completion after available overlap. Returning from an asynchronous application programming interface (API) call does not prove that the network and useful arithmetic overlapped. NVIDIA Scalable Hierarchical Aggregation and Reduction Protocol (SHARP) is network-assisted collective processing on supported infrastructure, not a feature supplied merely by an H100 GPU. This course first teaches software scheduling and observed overlap on the actual two-node path.

Each parallel strategy creates a collective dependency. Overlap is possible only after a chunk becomes ready and before a consumer needs its result.

Start communication when its inputs are ready

Backward produces different gradients at different times. DistributedDataParallel (DDP) assigns gradients to buckets; a bucket can communicate when every gradient it needs is ready. Its collective can then progress while independent backward work computes other gradients. The optimizer must wait for all reduced gradients it consumes, so an unfinished collective at that point still extends the step.

Communication overlap Time runs downward. Communication starts after its bucket is ready while other backward work continues; the part below compute completion is exposed. Resource contention may also slow the overlapped work. Heights are schematic. Diagram concepts: Backward work; Ready bucket; Exposed wait. ComputeCollectiveBackward workReady bucketExposed waitBucket readyCompute endsTime ↓
Communication overlap

Time runs downward. Communication starts after its bucket is ready while other backward work continues; the part below compute completion is exposed. Resource contention may also slow the overlapped work. Heights are schematic.

Smaller buckets may become ready earlier but create more calls and fixed latency. Larger buckets amortize that overhead but start later, leaving less independent computation available to overlap their transfer. Parameter sizes, readiness order and topology determine the trade-off. A rank-aligned timeline connects readiness, launch, transfer, completion and the optimizer wait; a fast-returning API call cannot establish overlap.

Other layouts expose different opportunities. Fully Sharded Data Parallel (FSDP) can schedule gradient reduce-scatter or parameter all-gather alongside suitable independent work. TP collectives, EP all-to-all and PP point-to-point communication each have their own producer and consumer dependencies. Rank arrival skew and contention matter because communication and computation can compete for memory or fabric resources.

Change the communication representation deliberately

The allreduce hook averages 32-bit floating point (FP32) buckets. 16-bit floating point (FP16) and bfloat16 (BF16) hooks cast communication buffers down, reduce them and cast back; they reduce nominal payload precision, not the model's stored parameter dtype. FP16 can overflow sooner, while BF16 has coarser precision. PowerSGD approximates sufficiently large matrix-shaped gradients with low-rank factors. Forming and reducing those factors costs compute and extra collectives; small tensors may remain uncompressed. Error feedback retains approximation residuals, and warm start reuses factor information. These are lossy algorithms, not lossless transport compression. Finite values, declared update-error and task-quality checks, and compatible collective behavior on every rank remain acceptance requirements.

PowerSGD approximates a large gradient matrix using two smaller matrices whose product reconstructs an approximation. Communicating these low-rank factors can require fewer values than communicating the full matrix. Error feedback stores the omitted residual and adds it to a later gradient before compression so the same information is not silently discarded every step. SGD means stochastic gradient descent. Lower communication volume still has to repay factorization work and preserve acceptable training behavior.

Distinguish readiness observation from a replacement reduction

A gradient hook is a callback triggered at a defined point in differentiation. A post-accumulate hook runs after a parameter's gradient has been accumulated, allowing an already-complete gradient to be reduced while independent backward work continues. It must not communicate an unfinished accumulation window. A DDP communication hook instead replaces the bucket's communication path and returns a future for its result. Keep the framework's averaging contract and identical collective order on every rank; observing readiness is different from silently changing the reduction.

Observe DDP before choosing a hook Read downward through one assigned bucket. Communication can begin only when all of its gradients are ready, and can overlap independent backward work. The optimizer waits for the reduced gradients it needs. Smaller buckets add calls; lossy hooks also need numerical, collective and task-quality checks. Arrows show dependencies, not measured overlap. Backward fills an assigned bucket All of its gradients are now ready Communicate while other backward runs Optimizer waits; check reduced update
Observe DDP before choosing a hook

Read downward through one assigned bucket. Communication can begin only when all of its gradients are ready, and can overlap independent backward work. The optimizer waits for the reduced gradients it needs. Smaller buckets add calls; lossy hooks also need numerical, collective and task-quality checks. Arrows show dependencies, not measured overlap.

Total collective duration can remain unchanged while step time improves, or an “asynchronous” collective can remain fully exposed. The optimization target is critical-path wait, not merely a shorter communication bar.

Mental model

Gradients become ready from later to earlier layers. Buckets can launch collectives as soon as their gradients are complete while backward continues elsewhere. Lower-precision collective buffers change bandwidth and error, while SHARP can offload supported reductions to the fabric; both require topology- and recipe-specific qualification.

14. Parameter-efficient adaptation

Objective

Measure trainable-state reduction and evaluate adapter behavior independently from throughput.

How it works

Supervised fine-tuning (SFT) continues training an existing model on selected input/target examples, such as instructions paired with desired responses. Low-rank adaptation (LoRA) changes how an update is represented: selected base weights stay frozen while smaller trainable matrix factors contribute an additional transformation. A frozen parameter participates in computation but is not changed by the optimizer. The base model is the starting model, and an adapter is the added trainable component or its saved state.

LoRA's rank is the limited dimension through which the update factors are composed; it is unrelated to a distributed process's rank number. SFT specifies the supervision, while LoRA specifies which parameters express the change, so they can be used together. LoRA is not automatically quantization, and freezing weights does not eliminate every activation or backward cost. End-of-sequence (EOS) labels and response masks determine which behavior the fine-tuning objective actually teaches.

For an input column vector x, a bias-free projection produces Wx. LoRA adds a second path: y = Wx + s * B(Ax). A maps input width to the smaller rank r, B maps that r-dimensional result to output width, and s scales the update. Train A and B while W stays fixed. For a hand calculation, let W be the 2-by-2 identity, A=[1, 0], B=[0, 2] as a column, s=0.5 and x=[3, 4]. Then Ax=3, B(Ax)=[0, 6], the scaled update is [0, 3], and y=[3, 7]. This illustrates composition, not the library's initialization. Standard scaling is alpha/r unless a different recipe is explicitly selected; the lab's configuration defines it. The shapes of A and B explain the parameter count below.

Frozen base and trainable adapter paths An input x splits into a frozen base matrix path and a trainable low-rank A then B path. Their outputs add to form y. Arrows carry values; only adapter matrices update during training. Input x Frozen base WWx Trainable AAx Trainable Bs B(Ax) Add outputsy = Wx + s B(Ax)
Frozen base and trainable adapter paths

An input x splits into a frozen base matrix path and a trainable low-rank A then B path. Their outputs add to form y. Arrows carry values; only adapter matrices update during training.

The core training path now explains updates, optimizer memory, precision, data flow and distributed placement. Apply that ledger to SFT, which changes the supervised-data contract, and LoRA, which changes the trainable parameterization. The supplied single-GPU adapter lab does not require a distributed run; the preceding distributed lessons provide context for scaling it later.

SFT first determines the supervised examples and the tokens that contribute to loss. The model and tokenizer revision, chat template, EOS handling, truncation, prompt-loss policy and held-out split define that objective. A prompt mask is a recipe choice; it must not be assumed merely because a run uses LoRA.

LoRA then changes how selected weight updates are represented. For a projection W with shape d_out × d_in, the frozen base path remains in the computation. A trainable input factor maps into rank r, and a second factor maps back to the output width. Their scaled result is added to the base output. Together they contain r(d_in+d_out) trainable parameters instead of d_in*d_out for a full matrix update.

Backward still passes through the computation needed to train those factors, but the optimizer does not update the frozen base weights. Adapter weights, gradients and optimizer state can therefore be much smaller. Base weights, activations, workspaces and temporary tensors still consume memory, so total savings need not match the reduction in trainable parameter count.

Reconstructing the effective model requires the adapter values and configuration plus the matching base revision. Evaluation checks whether that model performs the intended task and avoids regressions on held-out cases. Throughput describes a separate system outcome; a fast adapter update is not evidence of useful fine-tuning by itself.

Small trainable state is often confused with proportionally smaller total memory or faster steps. The frozen base still occupies memory and participates in forward/backward activation computation.

Mental model

LoRA learns low-rank updates while base weights remain frozen. It reduces trainable parameters and optimizer state but does not automatically remove base-model activations or all compute.

15. Reward-guided policy optimization

Objective

Compute group-relative advantages and locate rollout, reward, policy, and synchronization costs.

How it works

Group Relative Policy Optimization (GRPO) is a reinforcement-learning method that adjusts a model using several scored answers to the same prompt. The policy is the model's distribution over possible actions—in this case generated tokens. A rollout is a sampled answer, a reward is its score, and an advantage expresses how favorable it was relative to a baseline, here derived from the group. This provides a learning signal without requiring a desired token at every position as supervised training does.

The old policy generated the sampled answers; a reference policy can separately anchor behavior. A probability ratio compares a sampled token's new and old probabilities. The surrogate objective is a tractable training expression using these sampled quantities. Clipping moderates that expression; it is not a hard bound on every policy change. Kullback–Leibler (KL) divergence measures a difference between probability distributions. Reward hacking means improving the score without improving the intended behavior, so successful optimization of the toy objective is not proof of answer quality.

Supervised fine-tuning (SFT) learns from fixed target tokens. GRPO-style post-training samples several outputs from the current or near-current policy and learns from relative reward within each group.

Generate candidates and turn scores into advantages

For one prompt, the recorded behavior policy generates a group of candidate responses. A reward function scores them. Subtracting the group's mean reward expresses whether each response performed better or worse than its peers. A common recipe divides that difference by a stabilized standard deviation to form an advantage. A zero-variance group needs an explicit rule so normalization does not divide by zero.

Compare the new policy with the policy that sampled the data

The old policy is the frozen behavior policy that generated the rollouts. The new policy is the one being optimized. For a sampled token, ratio = exp(new_log_probability - old_log_probability) expresses how its probability changed. A ratio above one means the new policy assigns it more probability.

For advantage A and clip width epsilon, the maximized surrogate is min(ratio × A, clamp(ratio, 1-epsilon, 1+epsilon) × A). It limits the incentive from some large probability changes in the sampled objective; it is not a hard bound on every change to the complete policy. A separate reference policy, often the initial model, can anchor behavior through a divergence penalty with a declared coefficient. That reference need not be the old sampling policy.

Keep the system synchronized with the objective

The full loop includes generation, reward or verifier execution, objective computation and a trainer update. Colocating generation and training avoids some weight transfers; separating them allows independent scaling but adds queues and synchronization. Policy versions identify which weights produced each sample and prevent stale rollouts from being interpreted as fresh ones.

Post-training rollout and update loop An orchestrator sends prompts to rollout generation, reward or sandbox verification, and policy training; updated versioned weights return to the rollout engine. orchestrator rollout engine policy version N reward / verifier isolated sandbox training backend policy update checkpoint / weight transfer record rollout tokens, reward validity, stragglers, weight version, transfer time, and update cadence
Post-training rollout and update loop

An orchestrator sends prompts to rollout generation, reward or sandbox verification, and policy training; updated versioned weights return to the rollout engine.

Candidate lengths, filtering, reward components, rollout latency, verifier latency and trainer time explain where work is spent. Held-out and adversarial cases test whether the score rewards the intended behavior. Improving the surrogate or reward alone cannot rule out reward hacking.

The objective is only one part of the system. Rollout generation, verifier/reward execution, variable output lengths, policy weight transfer, and stale samples can dominate time or corrupt learning.

Consider three completions with rewards 1, 2 and 3. Their group mean is 2. If this illustration uses a population standard deviation, it is sqrt(2/3), about 0.816, so the normalized advantages are approximately −1.225, 0 and +1.225 before any stabilizing epsilon. The chosen estimator and reward grouping are part of the objective. With clipping width 0.2, probability ratio 1.4 and advantage +1, the smaller of 1.4 and clipped 1.2 contributes 1.2. With advantage −1 and ratio 0.6, the smaller of −0.6 and clipped −0.8 is −0.8. The sign matters: clipping limits the incentive to move too far in the favorable direction.

Mental model

A rollout system generates candidates, scores them, normalizes relative rewards, and updates a policy under clipping or divergence constraints.

16. Evidence-based training optimization

Objective

Select one verified training change from profiler evidence and defend keep or reject.

How it works

A causal training-optimization report argues that one controlled change affected performance while preserving the learning task. The baseline is the reference implementation; the candidate contains the change; a control helps test whether the proposed cause really explains the observation. An independent trial starts a separate run, rather than taking another sample from the same warmed process. Counterbalanced order alternates which variant runs first so startup or time-dependent effects do not consistently favor one side.

Uncertainty describes how much the evidence leaves unresolved, including run-to-run variation and measurement limits. Model FLOPs utilization (MFU), where FLOPs means floating-point operations, compares an estimate of useful model arithmetic per second with an appropriate hardware ceiling; hardware FLOPs utilization (HFU) also accounts for extra executed arithmetic under its stated convention. Neither ratio diagnoses a bottleneck by itself. This capstone connects these definitions to a scoped keep-or-reject decision, not a requirement to produce a speedup.

Every earlier lesson supplied one causal model and evidence type. The capstone joins them into a complete training decision rather than a collection of unrelated speed tips.

A causal report connects an observed delay to one change that should remove it. The baseline defines model, tokenizer and data revisions, global valid tokens, sequence distribution, optimizer, precision and which operations must finish before timing stops. At least three independent runs expose variation in step time, valid tokens/s, phase memory peaks and per-rank timing.

A short profiler window identifies a plausible limiting stage. The candidate changes that stage, while a disconfirming control tests whether the proposed explanation survives an alternative. DistributedDataParallel (DDP) versus Fully Sharded Data Parallel, second-generation interface (FSDP2) or eager versus checkpointed comparisons are meaningful only when they preserve the same work and update semantics. A keep/reject decision combines numerical gates, the complete-step result, uncertainty and the next unresolved question.

Training decision Read downward through the acceptance process. Check correctness and complete-step performance under the same learning objective; keep, reject or report uncertainty. A larger utilization ratio alone cannot justify a change. Diagram concepts: Profile an equivalent baseline; Change one causal factor; Check the complete update. Profile an equivalentbaselineChange one causal factorCheck the complete update
Training decision

Read downward through the acceptance process. Check correctness and complete-step performance under the same learning objective; keep, reject or report uncertainty. A larger utilization ratio alone cannot justify a change.

Utilization ratios summarize work under a stated counting convention. MFU uses useful model arithmetic and measured useful token rate; HFU may also count extra executed arithmetic. Neither ratio identifies the bottleneck. The following calculation explains why they can move in opposite directions.

For a purely illustrative calculation, suppose a step performs 100 trillion useful floating-point operations in 1 second against a matching 200-trillion-operations/second peak: both ratios are 50 percent under this counting convention. Recomputing another 50 trillion operations while taking 1.2 seconds raises HFU to 150/(1.2 × 200) = 62.5 percent, but MFU falls to 100/(1.2 × 200) ≈ 41.7 percent. More hardware work did not produce more useful updates. State the exact FLOP convention, precision, dense/sparse peak, time boundary and measured inputs. These hypothetical numbers are not H100 results.

Tokens per second and MFU summarize outcomes but do not diagnose causes. A credible report preserves failed hypotheses, numerical gates, workload identity, and limitations alongside a successful or rejected change.

Mental model

A report connects equivalent-work correctness to step time, tokens/s, memory, communication, and an explicitly bounded MFU estimate.

17. Scaling a fixed training workload

Objective

Preserve the global training objective while comparing microbatching and rank counts, and validate parameter updates before interpreting scaling.

How it works

Strong scaling holds useful global work fixed while changing available resources. A rank is one training process; an accumulation window is the set of microbatches whose gradients contribute to one optimizer update. DistributedDataParallel (DDP) keeps a model replica on each rank and synchronizes gradients across the group. For data parallel training, global batch equals rank count times microbatch size times accumulation count. A 128-example batch on 16 ranks with microbatch 4 needs two accumulation steps; on eight ranks it needs four. Divide each microbatch loss consistently and reduce accumulated gradients before the optimizer step. DDP’s no_sync context suppresses intermediate gradient synchronization, but must wrap both forward and backward; leave the context for the final microbatch that synchronizes the accumulated gradients. Check the parameter update against a full-batch reference. Step time uses the slowest rank, throughput counts global examples once, and memory uses the maximum rank. The controlled multilayer perceptron (MLP), a sequence of learned linear layers and activations, is a mechanism experiment; production large language model (LLM) efficiency additionally depends on attention, optimizer state, checkpointing and the input pipeline.

The linked advanced labs require the separate two-node, sixteen-H100 cluster. Confirm eight full GPUs per worker, healthy NVLink/NVSwitch and active InfiniBand. Capture each rank separately; profiler overhead belongs to diagnostic evidence. Grafana provides measured comparison summaries and job-window context. State what the evidence can establish before choosing the next change.

For the small workload, 128 global examples on eight ranks means 16 examples per rank. At microbatch 4, each rank accumulates four gradients; on sixteen ranks it accumulates two. This changes the communication-to-compute balance while preserving the global objective. A valid strong-scaling report states speedup as the eight-rank step duration divided by the sixteen-rank duration, and efficiency as that speedup divided by two. For example, 20 ms becoming 12 ms yields about 1.67 times speedup and 83 percent efficiency. A faster run with half the global examples is not that experiment. Recheck update equivalence and loss before interpreting the ratio.

Scaling a fixed training workload Compare two accumulation plans with the same global work. Each rank processes four examples per microbatch; four or two passes per rank supply the same 128-example global update. Correct weighting and gradient synchronization must preserve that update before step times can be compared. Diagram concepts: 8 ranks × 4 examples × 4 passes; 16 ranks × 4 examples × 2 passes; 128 examples per global update. 8 ranks × 4 examples × 4passes16 ranks × 4 examples × 2passes128 examples per globalupdate
Scaling a fixed training workload

Compare two accumulation plans with the same global work. Each rank processes four examples per microbatch; four or two passes per rank supply the same 128-example global update. Correct weighting and gradient synchronization must preserve that update before step times can be compared.

Mental model

Strong scaling keeps global work fixed. Microbatching, accumulation and gradient reduction must preserve the same update before step time or efficiency becomes meaningful.

Practical labs

Download results

Download all lab results:
Grafana dashboards, Small and Large results

Setup the lab environment:
Lab setup guide

Lab 01: Trace a complete tiny-transformer training step

A training step transforms token IDs into predictions, evaluates their error, propagates gradients, and updates parameters. This lab makes that entire cycle small enough to inspect on one H100.

Complete source: labs/01_tiny_transformer_train.py
"""Train a small decoder-only language model with BF16 Tensor Core computation."""

from __future__ import annotations

import argparse
import math
import statistics

from common import (
    add_common_args,
    load_torch,
    open_private_exclusive,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation
from tiny_lm import build_tiny_lm, make_language_batch


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--save-checkpoint", action="store_true")
    parser.add_argument(
        "--zero-grad-fill",
        action="store_true",
        help="Zero existing gradient buffers instead of releasing them; keep all work fixed.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)

    hidden, layers, heads, sequence, batch = (
        (512, 4, 8, 256, 8) if args.workload == "small" else (2_048, 12, 16, 1_024, 4)
    )
    vocab_size = 4_096
    model = build_tiny_lm(
        torch,
        vocab_size=vocab_size,
        hidden_size=hidden,
        layers=layers,
        heads=heads,
        max_sequence=sequence,
    ).to("cuda")
    optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
    forward = annotated_operation(model, "forward")
    # Differentiate the loss to populate parameter gradients.
    backward = annotated_operation(lambda loss: loss.backward(), "backward")
    update = annotated_operation(optimizer.step, "optimizer")
    clear_gradients = annotated_operation(optimizer.zero_grad, "zero_grad")
    inputs, labels = make_language_batch(
        torch,
        batch_size=batch,
        sequence=sequence,
        vocab_size=vocab_size,
        device="cuda",
    )
    samples: list[float] = []
    losses: list[float] = []
    gradient_norms: list[float] = []
    trainable_parameters = [
        parameter for parameter in model.parameters() if parameter.requires_grad
    ]

    def train_step() -> tuple[object, object]:
        with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
            logits = forward(inputs)
            loss = torch.nn.functional.cross_entropy(
                logits.reshape(-1, vocab_size), labels.reshape(-1)
            )
        backward(loss)
        if any(parameter.grad is None for parameter in trainable_parameters):
            raise SystemExit("At least one trainable parameter has no gradient.")
        gradient_norm = torch.nn.utils.clip_grad_norm_(
            trainable_parameters,
            1.0,
            error_if_nonfinite=True,
        )
        update()
        clear_gradients(set_to_none=not args.zero_grad_fill)
        return loss.detach(), gradient_norm.detach()

    for _ in range(args.warmup):
        train_step()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    tracked_parameter = trainable_parameters[0]
    parameter_before = tracked_parameter.detach().float().cpu().clone()
    torch.cuda.synchronize()
    baseline_allocated_bytes = int(torch.cuda.memory_allocated())
    baseline_reserved_bytes = int(torch.cuda.memory_reserved())
    torch.cuda.reset_peak_memory_stats()
    for _ in range(args.iterations):
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
        loss, gradient_norm = train_step()
        end.record()
        end.synchronize()
        samples.append(float(start.elapsed_time(end)))
        losses.append(float(loss))
        gradient_norms.append(float(gradient_norm))

    peak_allocated_bytes = int(torch.cuda.max_memory_allocated())
    peak_reserved_bytes = int(torch.cuda.max_memory_reserved())
    parameter_after = tracked_parameter.detach().float().cpu()
    parameter_delta_l2 = float((parameter_after - parameter_before).norm().item())
    finite_losses = all(math.isfinite(loss) for loss in losses)
    finite_gradients = all(
        math.isfinite(gradient_norm) and gradient_norm > 0
        for gradient_norm in gradient_norms
    )
    parameter_updated = math.isfinite(parameter_delta_l2) and parameter_delta_l2 > 0
    if not finite_losses:
        raise SystemExit("Training produced a non-finite loss.")
    if not finite_gradients:
        raise SystemExit("Training produced a missing, zero, or non-finite gradient.")
    if not parameter_updated:
        raise SystemExit("The optimizer did not update the tracked parameter.")
    tokens = batch * sequence * args.iterations
    if args.save_checkpoint:
        checkpoint = (
            args.output_dir / f"tiny-transformer-checkpoint-run-{args.run_id}.pt"
        )
        with open_private_exclusive(checkpoint, binary=True) as stream:
            torch.save(
                {
                    "model": model.state_dict(),
                    "optimizer": optimizer.state_dict(),
                    "run_id": args.run_id,
                    "step": args.warmup + args.iterations,
                },
                stream,
            )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="01_tiny_transformer_train",
        environment=environment,
        measurements={
            "model_shape": {
                "hidden": hidden,
                "layers": layers,
                "sequence": sequence,
                "batch": batch,
                "vocab_size": vocab_size,
            },
            "precision": "bf16-forward-fp32-parameters",
            "parameters": sum(parameter.numel() for parameter in model.parameters()),
            "tokens": tokens,
            "initial_loss": round(losses[0], 5),
            "final_loss": round(losses[-1], 5),
            "median_step_ms": round(statistics.median(samples), 4),
            "tokens_per_second": round(tokens / (sum(samples) / 1_000), 1),
            "gradient_norm": {
                "initial": round(gradient_norms[0], 6),
                "final": round(gradient_norms[-1], 6),
                "median": round(statistics.median(gradient_norms), 6),
            },
            "memory": {
                "baseline_allocated_bytes": baseline_allocated_bytes,
                "baseline_reserved_bytes": baseline_reserved_bytes,
                "peak_allocated_bytes": peak_allocated_bytes,
                "peak_reserved_bytes": peak_reserved_bytes,
                "incremental_peak_allocated_bytes": (
                    peak_allocated_bytes - baseline_allocated_bytes
                ),
                "incremental_peak_reserved_bytes": (
                    peak_reserved_bytes - baseline_reserved_bytes
                ),
            },
            "parameter_delta_l2": round(parameter_delta_l2, 8),
        },
        correctness={
            "finite_loss": True,
            "finite_gradients": True,
            "all_trainable_parameters_had_gradients": True,
            "parameter_updated": True,
        },
    )
    print(f"Completed tiny-transformer training: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/01_tiny_transformer_train.sbatch --workload small

# Optional profiling
sbatch slurm/01_tiny_transformer_train.sbatch --workload small --profiler all

Lab 02: Trade microbatch size for peak memory

When a full batch does not fit, gradient accumulation can split its work across smaller microbatches before an update. This lab compares full-batch and accumulated gradients on a fixed-shape MLP regression problem.

Complete source: labs/02_gradient_accumulation.py
"""Compare full-batch and microbatch gradient accumulation memory use."""

from __future__ import annotations

import argparse
import math
import statistics
import time

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def validate_gradient_samples(
    torch: object, expected_samples: list[object], observed_gradients: list[object]
) -> float:
    """Require finite, matching samples before certifying accumulation."""
    if not expected_samples or len(expected_samples) != len(observed_gradients):
        raise SystemExit("Gradient comparison requires matching nonempty samples.")
    errors = []
    for expected, gradient in zip(expected_samples, observed_gradients, strict=True):
        if gradient is None:
            raise SystemExit("Accumulated gradient is missing.")
        observed = gradient.detach().flatten()[:4_096].cpu()
        if expected.shape != observed.shape or expected.numel() == 0:
            raise SystemExit("Gradient sample shapes must match and be nonempty.")
        if not bool(torch.isfinite(expected).all() and torch.isfinite(observed).all()):
            raise SystemExit("Gradient samples must be finite.")
        error = float((expected - observed).abs().max())
        if not math.isfinite(error) or error > 2e-3:
            raise SystemExit(
                f"Accumulated gradient samples diverged: max error {error}"
            )
        errors.append(error)
    return max(errors)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)

    width = 2_048 if args.workload == "small" else 8_192
    total_batch, microbatch = (64, 16) if args.workload == "small" else (128, 16)
    reference = torch.nn.Sequential(
        torch.nn.Linear(width, 4 * width, bias=False),
        torch.nn.GELU(),
        torch.nn.Linear(4 * width, width, bias=False),
    ).to("cuda")
    # Create the synthetic tensors used by this experiment.
    inputs = torch.randn((total_batch, width), device="cuda")
    targets = torch.randn((total_batch, width), device="cuda")

    def one_pass(model: object, split: int) -> None:
        model.zero_grad(set_to_none=True)
        for start in range(0, total_batch, split):
            with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
                prediction = model(inputs[start : start + split])
                loss = torch.nn.functional.mse_loss(
                    prediction, targets[start : start + split]
                )
                loss = loss * (split / total_batch)
            # Differentiate the loss to populate parameter gradients.
            loss.backward()

    one_pass = annotated_operation(one_pass, "gradient_pass")

    def run(model: object, split: int) -> dict[str, float]:
        for _ in range(args.warmup):
            one_pass(model, split)
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        elapsed_samples: list[float] = []
        peak_samples: list[float] = []
        for _ in range(args.iterations):
            torch.cuda.reset_peak_memory_stats()
            started = time.perf_counter()
            one_pass(model, split)
            torch.cuda.synchronize()
            elapsed_samples.append((time.perf_counter() - started) * 1_000)
            peak_samples.append(torch.cuda.max_memory_allocated() / 2**20)
        return {
            "median_elapsed_ms": round(statistics.median(elapsed_samples), 4),
            "median_peak_allocated_mib": round(statistics.median(peak_samples), 2),
        }

    full_metrics = run(reference, total_batch)
    full_gradients = [
        parameter.grad.detach().flatten()[:4_096].cpu().clone()
        for parameter in reference.parameters()
    ]
    reference.zero_grad(set_to_none=True)
    torch.cuda.empty_cache()
    micro_metrics = run(reference, microbatch)
    sampled_gradient_error = validate_gradient_samples(
        torch, full_gradients, [parameter.grad for parameter in reference.parameters()]
    )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="02_gradient_accumulation",
        environment=environment,
        measurements={
            "total_batch": total_batch,
            "microbatch": microbatch,
            "full_batch": full_metrics,
            "accumulated": micro_metrics,
            "sampled_max_gradient_error": round(sampled_gradient_error, 7),
        },
        correctness={"sampled_gradients_match": True},
    )
    print(f"Completed gradient-accumulation experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/02_gradient_accumulation.sbatch --workload small

# Optional profiling
sbatch slurm/02_gradient_accumulation.sbatch --workload small --profiler all

Lab 05: Fine-tune a small model with LoRA adapters

LoRA trains low-rank adapter parameters while leaving most pretrained weights frozen. This lab performs a short supervised fine-tuning exercise on a pinned public model and checks that adapters receive gradients and actually change.

Complete source: labs/05_lora_sft.py
"""Fine-tune a small public language model with a lightweight LoRA adapter."""

from __future__ import annotations

import argparse
import hashlib
import math
import time

from common import (
    DEFAULT_MODEL,
    DEFAULT_REVISION,
    add_common_args,
    load_torch,
    require_course_gpu,
    require_hf_commit_revision,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--model", default=DEFAULT_MODEL)
    parser.add_argument("--revision", default=DEFAULT_REVISION)
    parser.add_argument(
        "--zero-grad-fill",
        action="store_true",
        help="Zero existing gradient buffers instead of releasing them; keep all work fixed.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    require_hf_commit_revision(args.revision)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    try:
        from peft import LoraConfig, get_peft_model
        from transformers import AutoModelForCausalLM, AutoTokenizer
    except ImportError as exc:
        raise SystemExit(
            "Install the pinned training extras: transformers and peft."
        ) from exc

    examples = [
        "Question: Why synchronize before CPU wall-clock timing? Answer: CUDA launches are asynchronous.",
        "Question: What does the KV cache hold? Answer: Attention keys and values for processed tokens.",
        "Question: When is a kernel memory bound? Answer: When data movement limits throughput.",
        "Question: Why use BF16 on H100? Answer: It uses tensor cores while retaining a wide exponent range.",
    ]
    tokenizer = AutoTokenizer.from_pretrained(
        args.model, revision=args.revision, trust_remote_code=False
    )
    if tokenizer.pad_token_id is None:
        tokenizer.pad_token = tokenizer.eos_token
    encoded = tokenizer(
        examples,
        return_tensors="pt",
        padding=True,
        truncation=True,
        max_length=128,
    )
    model = AutoModelForCausalLM.from_pretrained(
        args.model,
        revision=args.revision,
        dtype=torch.bfloat16,
        attn_implementation="sdpa",
        trust_remote_code=False,
    ).to("cuda")
    model = get_peft_model(
        model,
        LoraConfig(
            r=8,
            lora_alpha=16,
            lora_dropout=0.05,
            bias="none",
            task_type="CAUSAL_LM",
            target_modules=["q_proj", "v_proj"],
        ),
    )
    trainable = sum(
        parameter.numel() for parameter in model.parameters() if parameter.requires_grad
    )
    total = sum(parameter.numel() for parameter in model.parameters())
    optimizer = torch.optim.AdamW(
        (parameter for parameter in model.parameters() if parameter.requires_grad),
        lr=2e-4,
    )
    forward = annotated_operation(model, "forward")
    # Differentiate the loss to populate parameter gradients.
    backward = annotated_operation(lambda loss: loss.backward(), "backward")
    update = annotated_operation(optimizer.step, "optimizer")
    clear_gradients = annotated_operation(optimizer.zero_grad, "zero_grad")
    input_ids = encoded["input_ids"].to("cuda")
    attention_mask = encoded["attention_mask"].to("cuda")
    labels = input_ids.masked_fill(attention_mask == 0, -100)
    losses: list[float] = []
    gradient_norms: list[float] = []
    adapter_before = {
        name: parameter.detach().clone()
        for name, parameter in model.named_parameters()
        if parameter.requires_grad
    }

    held_out = tokenizer(
        "Question: Why record immutable model revisions? Answer:",
        return_tensors="pt",
    )
    held_out = {name: value.to("cuda") for name, value in held_out.items()}

    def held_out_evidence() -> tuple[int, str]:
        model.eval()
        with torch.no_grad():
            logits = model(**held_out).logits[:, -1, :].float().cpu()
        model.train()
        return (
            int(logits.argmax(dim=-1).item()),
            hashlib.sha256(logits.numpy().tobytes()).hexdigest(),
        )

    held_out_before = held_out_evidence()

    def train_step() -> tuple[object, float]:
        clear_gradients(set_to_none=not args.zero_grad_fill)
        output = forward(
            input_ids=input_ids, attention_mask=attention_mask, labels=labels
        )
        backward(output.loss)
        gradient_norm = math.sqrt(
            sum(
                float(parameter.grad.float().square().sum().item())
                for parameter in model.parameters()
                if parameter.requires_grad and parameter.grad is not None
            )
        )
        update()
        return output.loss.detach(), gradient_norm

    for _ in range(args.warmup):
        train_step()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    started = time.perf_counter()
    for _ in range(args.iterations):
        loss, gradient_norm = train_step()
        losses.append(float(loss))
        gradient_norms.append(gradient_norm)
    torch.cuda.synchronize()
    elapsed_ms = (time.perf_counter() - started) * 1_000
    if not all(math.isfinite(loss) for loss in losses):
        raise SystemExit("LoRA training produced a non-finite loss.")
    if not all(math.isfinite(value) and value > 0 for value in gradient_norms):
        raise SystemExit("LoRA adapter gradients were zero or non-finite.")
    adapter_max_delta = max(
        float((parameter.detach() - adapter_before[name]).abs().max().item())
        for name, parameter in model.named_parameters()
        if parameter.requires_grad
    )
    if not math.isfinite(adapter_max_delta) or adapter_max_delta <= 0:
        raise SystemExit("LoRA adapter parameters did not update.")
    held_out_after = held_out_evidence()
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="05_lora_sft",
        environment=environment,
        measurements={
            "model": args.model,
            "revision": args.revision,
            "trainable_parameters": trainable,
            "total_parameters": total,
            "trainable_percent": round(100 * trainable / total, 4),
            "initial_loss": round(losses[0], 5),
            "final_loss": round(losses[-1], 5),
            "gradient_norm_min": round(min(gradient_norms), 6),
            "gradient_norm_max": round(max(gradient_norms), 6),
            "adapter_max_parameter_delta": adapter_max_delta,
            "held_out_next_token_before": held_out_before[0],
            "held_out_next_token_after": held_out_after[0],
            "held_out_logits_digest_before": held_out_before[1],
            "held_out_logits_digest_after": held_out_after[1],
            "held_out_prompt_published": False,
            "elapsed_ms": round(elapsed_ms, 4),
            "peak_allocated_mib": round(torch.cuda.max_memory_allocated() / 2**20, 2),
        },
        correctness={
            "finite_loss": True,
            "nonzero_finite_adapter_gradients": True,
            "nonzero_adapter_parameter_update": True,
            "bounded_held_out_evaluation_recorded": True,
            "adapter_is_parameter_efficient": trainable < total / 10,
        },
    )
    print(f"Completed LoRA SFT practice: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/05_lora_sft.sbatch --workload small

# Optional profiling
sbatch slurm/05_lora_sft.sbatch --workload small --profiler all

Lab 06: Work through a group-relative policy objective

GRPO uses rewards from multiple completions of the same prompt to construct a relative training signal. This lab isolates the objective on small GPU tensors without loading a language model.

Complete source: labs/06_grpo_objective.py
"""Unpack group-relative advantages and a clipped policy objective on the GPU."""

from __future__ import annotations

import argparse

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    parser.add_argument("--group-size", type=int, default=8)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if args.group_size < 2:
        raise SystemExit(
            "--group-size must be at least 2 for within-group normalization"
        )
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)

    prompts = 4
    # Create the synthetic tensors used by this experiment.
    old_log_probs = torch.randn((prompts, args.group_size), device="cuda") * 0.1
    new_log_probs = (
        old_log_probs + torch.randn_like(old_log_probs) * 0.02
    ).requires_grad_()
    rewards = torch.randn((prompts, args.group_size), device="cuda")

    def objective() -> tuple[object, object, object]:
        advantages = (rewards - rewards.mean(dim=1, keepdim=True)) / (
            rewards.std(dim=1, keepdim=True, unbiased=False) + 1e-4
        )
        ratio = (new_log_probs - old_log_probs).exp()
        clipped_ratio = ratio.clamp(0.8, 1.2)
        surrogate = torch.minimum(ratio * advantages, clipped_ratio * advantages)
        reference_log_probs = old_log_probs - 0.01
        log_ratio = reference_log_probs - new_log_probs
        approximate_kl = log_ratio.exp() - log_ratio - 1
        loss = -(surrogate - 0.02 * approximate_kl).mean()
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        return advantages, approximate_kl, loss

    advantages, approximate_kl, loss = annotated_operation(
        objective, "grpo_objective"
    )()
    group_mean_error = float(advantages.mean(dim=1).abs().max())
    if group_mean_error > 1e-5 or not torch.isfinite(loss):
        raise SystemExit(
            "The normalized advantages or policy objective failed validation."
        )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="06_grpo_objective",
        environment=environment,
        measurements={
            "prompts": prompts,
            "group_size": args.group_size,
            "loss": round(float(loss.detach()), 6),
            "mean_approximate_kl": round(float(approximate_kl.mean()), 7),
            "max_group_advantage_mean_error": round(group_mean_error, 8),
        },
        correctness={
            "zero_mean_advantages": True,
            "finite_gradients": bool(torch.isfinite(new_log_probs.grad).all()),
        },
    )
    print(f"Completed GRPO-objective unpacking: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/06_grpo_objective.sbatch --workload small

# Optional profiling
sbatch slurm/06_grpo_objective.sbatch --workload small --profiler all

Lab 07: Verify the GRPO generation-to-update loop

An objective formula is only one part of reward-guided training: the system must generate completions, score them, compute a loss, propagate gradients, and update parameters. This lab exercises that loop with a small pinned model and LoRA adapters.

Complete source: labs/07_grpo_trainer.py
"""Run a few GRPO steps with a small public model and a local deterministic reward."""

from __future__ import annotations

import argparse
import math
import statistics

from common import (
    DEFAULT_MODEL,
    DEFAULT_REVISION,
    add_common_args,
    load_torch,
    require_course_gpu,
    require_hf_commit_revision,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    parser.add_argument("--model", default=DEFAULT_MODEL)
    parser.add_argument("--revision", default=DEFAULT_REVISION)
    parser.add_argument("--steps", type=int, default=3)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    require_hf_commit_revision(args.revision)
    if args.steps < 1:
        raise SystemExit("--steps must be positive")
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    try:
        from datasets import Dataset
        from peft import LoraConfig
        from transformers import AutoTokenizer
        from trl import GRPOConfig, GRPOTrainer
    except ImportError as exc:
        raise SystemExit(
            "Install the pinned training extras: datasets, peft, and trl."
        ) from exc

    dataset = Dataset.from_list(
        [
            {"prompt": "Reply with the single word CUDA."},
            {"prompt": "Reply with the single word tensor."},
            {"prompt": "Reply with the single word profiler."},
            {"prompt": "Reply with the single word bandwidth."},
        ]
    )

    reward_group_stddevs: list[float] = []

    def controlled_reward(completions: list[str], **_: object) -> list[float]:
        if len(completions) % 2:
            raise ValueError("The controlled exercise requires completion pairs.")
        scores = [float(index % 2) for index in range(len(completions))]
        reward_group_stddevs.extend(
            statistics.pstdev(scores[start : start + 2])
            for start in range(0, len(scores), 2)
        )
        return scores

    trainer_output = args.output_dir / f"grpo-trainer-run-{args.run_id}"
    if trainer_output.exists():
        raise SystemExit(
            f"Refusing to reuse an existing trainer output: {trainer_output}"
        )
    config = GRPOConfig(
        output_dir=str(trainer_output),
        max_steps=args.steps,
        per_device_train_batch_size=2,
        num_generations=2,
        max_completion_length=32,
        bf16=True,
        seed=args.seed,
        logging_steps=1,
        save_strategy="no",
        report_to="none",
        model_init_kwargs={
            "dtype": torch.bfloat16,
            "attn_implementation": "sdpa",
            "trust_remote_code": False,
            "revision": args.revision,
        },
    )
    tokenizer = AutoTokenizer.from_pretrained(
        args.model,
        revision=args.revision,
        trust_remote_code=False,
        padding_side="left",
    )
    trainer = GRPOTrainer(
        model=args.model,
        reward_funcs=controlled_reward,
        args=config,
        train_dataset=dataset,
        processing_class=tokenizer,
        peft_config=LoraConfig(
            r=8,
            lora_alpha=16,
            task_type="CAUSAL_LM",
            target_modules=["q_proj", "v_proj"],
        ),
    )
    trainable_before = {
        name: parameter.detach().clone()
        for name, parameter in trainer.model.named_parameters()
        if parameter.requires_grad
    }
    observed_gradient_norms: list[float] = []

    def record_gradient(gradient: object) -> object:
        observed_gradient_norms.append(float(gradient.float().norm().item()))
        return gradient

    gradient_hooks = [
        parameter.register_hook(record_gradient)
        for parameter in trainer.model.parameters()
        if parameter.requires_grad
    ]
    result = annotated_operation(trainer.train, "trainer_train")()
    for hook in gradient_hooks:
        hook.remove()
    loss = result.metrics.get("train_loss")
    if loss is None or not math.isfinite(float(loss)):
        raise SystemExit("GRPO did not report a finite training loss.")
    if not reward_group_stddevs or min(reward_group_stddevs) <= 0:
        raise SystemExit("GRPO reward groups contained no learning signal.")
    positive_gradient_norms = [
        value for value in observed_gradient_norms if math.isfinite(value) and value > 0
    ]
    if not positive_gradient_norms:
        raise SystemExit("GRPO produced no finite nonzero adapter gradient.")
    adapter_max_delta = max(
        float((parameter.detach() - trainable_before[name]).abs().max().item())
        for name, parameter in trainer.model.named_parameters()
        if parameter.requires_grad
    )
    if not math.isfinite(adapter_max_delta) or adapter_max_delta <= 0:
        raise SystemExit("GRPO adapter parameters did not update.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="07_grpo_trainer",
        environment=environment,
        measurements={
            "model": args.model,
            "revision": args.revision,
            "steps": args.steps,
            "train_runtime_seconds": round(
                float(result.metrics.get("train_runtime", 0.0)), 4
            ),
            "train_loss": round(float(loss), 6),
            "controlled_reward_rule": "alternating rank within each pair",
            "minimum_reward_group_stddev": round(min(reward_group_stddevs), 6),
            "positive_adapter_gradient_samples": len(positive_gradient_norms),
            "maximum_observed_adapter_gradient_norm": round(
                max(positive_gradient_norms), 6
            ),
            "adapter_max_parameter_delta": adapter_max_delta,
        },
        correctness={
            "trainer_completed": True,
            "finite_train_loss": True,
            "nonzero_within_group_reward_signal": True,
            "nonzero_finite_adapter_gradient": True,
            "nonzero_adapter_parameter_update": True,
        },
    )
    print(f"Completed GRPO trainer practice: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/07_grpo_trainer.sbatch --workload small --steps 3

# Optional profiling
sbatch slurm/07_grpo_trainer.sbatch --workload small --steps 3 --profiler all

Lab 13: Decide which tokens contribute to the training loss

Prompt text and padding may appear in a batch without being intended training targets. This lab constructs two short causal sequences and explicitly masks selected labels.

Complete source: labs/13_loss_masking.py
"""Show how prompt and padding masks choose which tokens train an LLM."""

from __future__ import annotations

import argparse

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from tiny_lm import build_tiny_lm


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    return parser.parse_args()


def main() -> None:
    # Read the experiment controls before allocating inputs.
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    vocab_size = 128
    model = build_tiny_lm(
        torch,
        vocab_size=vocab_size,
        hidden_size=256,
        layers=2,
        heads=4,
        max_sequence=16,
    ).to(device="cuda", dtype=torch.bfloat16)
    # Create explicit input values on the selected device.
    token_ids = torch.tensor(
        [
            [11, 12, 13, 41, 42, 43, 44, 0],
            [21, 22, 51, 52, 53, 0, 0, 0],
        ],
        device="cuda",
        dtype=torch.long,
    )
    labels = token_ids[:, 1:].clone()
    inputs = token_ids[:, :-1]
    unmasked_labels = labels.clone()
    labels[0, :2] = -100
    labels[1, :1] = -100
    labels[0, -1:] = -100
    labels[1, -3:] = -100
    logits = model(inputs)
    masked_loss = torch.nn.functional.cross_entropy(
        logits.reshape(-1, vocab_size), labels.reshape(-1), ignore_index=-100
    )
    unmasked_loss = torch.nn.functional.cross_entropy(
        logits.reshape(-1, vocab_size), unmasked_labels.reshape(-1)
    )
    # Differentiate the loss to populate parameter gradients.
    masked_loss.backward()
    trained_tokens = int((labels != -100).sum().item())
    ignored_tokens = int((labels == -100).sum().item())
    finite_gradients = all(
        parameter.grad is None or bool(torch.isfinite(parameter.grad).all().item())
        for parameter in model.parameters()
    )
    if trained_tokens != 7 or ignored_tokens != 7 or not finite_gradients:
        raise SystemExit("Loss-mask invariants failed.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="13_loss_masking",
        environment=environment,
        measurements={
            "trained_tokens": trained_tokens,
            "ignored_tokens": ignored_tokens,
            "masked_loss": round(float(masked_loss.item()), 6),
            "unmasked_loss": round(float(unmasked_loss.item()), 6),
        },
        correctness={
            "ignore_index_applied": True,
            "finite_gradients": True,
        },
    )
    print(f"Completed loss-masking exercise: {target}")


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/13_loss_masking.sbatch --workload small

# Optional profiling
sbatch slurm/13_loss_masking.sbatch --workload small --profiler all

Lab 14: Compare checkpointing on alternate blocks and all blocks

Activation checkpointing saves memory by recomputing selected forward work during backward instead of retaining every intermediate. This lab compares three matched tiny-transformer paths and checks loss plus all trainable parameter gradients.

Complete source: labs/14_activation_checkpointing.py
"""Measure the memory savings and compute cost of activation checkpointing."""

from __future__ import annotations

import argparse
import copy
import statistics

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation
from tiny_lm import build_tiny_lm, make_language_batch


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    return parser.parse_args()


def checkpointed_forward(
    torch: object, model: object, token_ids: object, *, mode: str
) -> object:
    from torch.utils.checkpoint import checkpoint

    if mode not in {"selective", "full"}:
        raise ValueError(f"unsupported checkpoint mode: {mode}")
    positions = torch.arange(token_ids.shape[1], device=token_ids.device)
    hidden = model.token_embedding(token_ids) + model.position_embedding(positions)
    for block_index, block in enumerate(model.blocks):
        should_checkpoint = mode == "full" or block_index % 2 == 1
        hidden = (
            checkpoint(block, hidden, use_reentrant=False)
            if should_checkpoint
            else block(hidden)
        )
    return model.lm_head(model.final_norm(hidden))


def train_samples(
    torch: object,
    model: object,
    inputs: object,
    targets: object,
    *,
    mode: str,
    warmup: int,
    iterations: int,
) -> tuple[list[float], list[int], list[object], object]:
    def step() -> object:
        logits = (
            model(inputs)
            if mode == "baseline"
            else checkpointed_forward(torch, model, inputs, mode=mode)
        )
        loss = torch.nn.functional.cross_entropy(
            logits.reshape(-1, logits.shape[-1]), targets.reshape(-1)
        )
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        return loss.detach()

    step = annotated_operation(step, "checkpoint_step")

    for _ in range(warmup):
        model.zero_grad(set_to_none=True)
        loss = step()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()

    timings = []
    incremental_peaks = []
    gradients = []
    for _ in range(iterations):
        model.zero_grad(set_to_none=True)
        torch.cuda.empty_cache()
        baseline_bytes = int(torch.cuda.memory_allocated())
        torch.cuda.reset_peak_memory_stats()
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
        loss = step()
        end.record()
        end.synchronize()
        timings.append(float(start.elapsed_time(end)))
        incremental_peaks.append(
            int(torch.cuda.max_memory_allocated()) - baseline_bytes
        )
        if any(
            parameter.requires_grad and parameter.grad is None
            for parameter in model.parameters()
        ):
            raise SystemExit(
                "Checkpoint probe did not produce every trainable parameter gradient."
            )
        gradients = [
            parameter.grad.detach().float().cpu().clone()
            for parameter in model.parameters()
            if parameter.grad is not None
        ]
    return timings, incremental_peaks, gradients, loss.float().cpu().clone()


def require_checkpoint_equivalence(
    torch: object,
    baseline_loss: object,
    baseline_gradients: list[object],
    candidate_loss: object,
    candidate_gradients: list[object],
) -> dict[str, bool]:
    """Require loss and every parameter gradient before accepting timing evidence."""
    losses_match = bool(
        torch.isfinite(baseline_loss).all()
        and torch.isfinite(candidate_loss).all()
        and torch.allclose(baseline_loss, candidate_loss, rtol=1e-2, atol=1e-2)
    )
    gradients_match = (
        bool(baseline_gradients)
        and len(baseline_gradients) == len(candidate_gradients)
        and all(
            torch.isfinite(left).all()
            and torch.isfinite(right).all()
            and torch.allclose(left, right, rtol=1e-2, atol=1e-2)
            for left, right in zip(baseline_gradients, candidate_gradients, strict=True)
        )
    )
    if not losses_match or not gradients_match:
        raise SystemExit(
            "Checkpoint loss or full parameter gradients diverged from baseline."
        )
    return {"loss_allclose": losses_match, "gradients_allclose": bool(gradients_match)}


def main() -> None:
    # Read the experiment controls before allocating inputs.
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    sequence = 256 if args.workload == "small" else 1_024
    hidden = 512 if args.workload == "small" else 1_024
    layers = 4 if args.workload == "small" else 8
    vocab_size = 2_048
    base = build_tiny_lm(
        torch,
        vocab_size=vocab_size,
        hidden_size=hidden,
        layers=layers,
        heads=8,
        max_sequence=sequence,
    )
    inputs, targets = make_language_batch(
        torch,
        batch_size=4,
        sequence=sequence,
        vocab_size=vocab_size,
        device="cuda",
    )
    eager_model = copy.deepcopy(base).to(device="cuda", dtype=torch.bfloat16)
    eager_times, eager_peaks, eager_grads, eager_loss = train_samples(
        torch,
        eager_model,
        inputs,
        targets,
        mode="baseline",
        warmup=args.warmup,
        iterations=args.iterations,
    )
    del eager_model
    torch.cuda.empty_cache()
    selective_model = copy.deepcopy(base).to(device="cuda", dtype=torch.bfloat16)
    selective_times, selective_peaks, selective_grads, selective_loss = train_samples(
        torch,
        selective_model,
        inputs,
        targets,
        mode="selective",
        warmup=args.warmup,
        iterations=args.iterations,
    )
    del selective_model
    torch.cuda.empty_cache()
    full_model = copy.deepcopy(base).to(device="cuda", dtype=torch.bfloat16)
    full_times, full_peaks, full_grads, full_loss = train_samples(
        torch,
        full_model,
        inputs,
        targets,
        mode="full",
        warmup=args.warmup,
        iterations=args.iterations,
    )
    selective_checks = require_checkpoint_equivalence(
        torch, eager_loss, eager_grads, selective_loss, selective_grads
    )
    full_checks = require_checkpoint_equivalence(
        torch, eager_loss, eager_grads, full_loss, full_grads
    )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="14_activation_checkpointing",
        environment=environment,
        measurements={
            "shape": {"batch": 4, "sequence": sequence, "hidden": hidden},
            "eager": {
                "loss": float(eager_loss),
                "step_time": summarize_ms(eager_times),
                "median_incremental_peak_bytes": int(statistics.median(eager_peaks)),
            },
            "selective": {
                "loss": float(selective_loss),
                "checkpointed_block_indices": list(range(1, layers, 2)),
                "step_time": summarize_ms(selective_times),
                "median_incremental_peak_bytes": int(
                    statistics.median(selective_peaks)
                ),
            },
            "full": {
                "loss": float(full_loss),
                "checkpointed_block_indices": list(range(layers)),
                "step_time": summarize_ms(full_times),
                "median_incremental_peak_bytes": int(statistics.median(full_peaks)),
            },
        },
        correctness={
            "selective_loss_allclose": selective_checks["loss_allclose"],
            "full_loss_allclose": full_checks["loss_allclose"],
            "selective_gradients_allclose": selective_checks["gradients_allclose"],
            "full_gradients_allclose": full_checks["gradients_allclose"],
            "gradient_scope": "all trainable parameters, including token and position embeddings; token IDs are integers and have no input gradient",
        },
    )
    print(f"Completed activation-checkpointing experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/14_activation_checkpointing.sbatch --workload small

# Optional profiling
sbatch slurm/14_activation_checkpointing.sbatch --workload small --profiler all

Lab 21: Validate precision changes across a full training update

A precision change affects more than forward logits: gradients and optimizer updates can also change. This lab compares FP32, BF16, and scaled FP16 tiny-transformer steps from identical initial state and data.

Complete source: labs/21_mixed_precision_training.py
"""Compare matched FP32, BF16, and scaled-FP16 tiny-LLM training steps."""

from __future__ import annotations

import argparse
import copy
import math
import statistics
import time
from typing import Any

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation
from tiny_lm import build_tiny_lm, make_language_batch


def relative_error(candidate: float, reference: float) -> float:
    """Return scalar relative error with a stable near-zero denominator."""
    return abs(candidate - reference) / max(abs(reference), 1e-12)


def state_relative_l2(
    candidate: dict[str, Any],
    reference: dict[str, Any],
) -> float:
    """Compute relative L2 over matching named tensors without concatenation."""
    if candidate.keys() != reference.keys():
        raise SystemExit("Numerical comparison encountered different parameter sets.")
    difference_squared = 0.0
    reference_squared = 0.0
    for name, reference_value in reference.items():
        candidate_value = candidate[name]
        difference_squared += float((candidate_value - reference_value).square().sum())
        reference_squared += float(reference_value.square().sum())
    return math.sqrt(difference_squared) / max(math.sqrt(reference_squared), 1e-12)


def numerical_step(
    torch: Any,
    *,
    autocast_dtype: Any | None,
    initial_state: dict[str, Any],
    inputs: Any,
    labels: Any,
    vocab_size: int,
    model_shape: dict[str, int],
    seed: int,
) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
    """Capture one update from identical weights, data, and random state."""
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, seed)
    model = build_tiny_lm(
        torch,
        vocab_size=vocab_size,
        hidden_size=model_shape["hidden"],
        layers=model_shape["layers"],
        heads=model_shape["heads"],
        max_sequence=model_shape["sequence"],
    ).to("cuda")
    model.load_state_dict(initial_state)
    model.train()
    optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
    use_fp16_scaler = autocast_dtype == torch.float16
    scaler = torch.amp.GradScaler("cuda", enabled=use_fp16_scaler)
    # Clear the previous step’s gradients before differentiating again.
    optimizer.zero_grad(set_to_none=True)
    with torch.autocast(
        device_type="cuda",
        dtype=autocast_dtype,
        enabled=autocast_dtype is not None,
    ):
        logits = model(inputs)
        loss = torch.nn.functional.cross_entropy(
            logits.reshape(-1, vocab_size), labels.reshape(-1)
        )
    scaler.scale(loss).backward()
    scaler.unscale_(optimizer)

    gradients: dict[str, Any] = {}
    finite = bool(torch.isfinite(loss))
    for name, parameter in model.named_parameters():
        if parameter.grad is None:
            raise SystemExit(f"Missing gradient for {name} in numerical comparison.")
        value = parameter.grad.detach().float().cpu()
        gradients[name] = value
        finite = finite and bool(torch.isfinite(value).all())
    gradient_l2 = math.sqrt(
        sum(float(value.square().sum()) for value in gradients.values())
    )

    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    scaler.step(optimizer)
    scaler.update()
    updates: dict[str, Any] = {}
    for name, parameter in model.named_parameters():
        value = parameter.detach().float().cpu() - initial_state[name].float()
        updates[name] = value
        finite = finite and bool(torch.isfinite(value).all())
    update_l2 = math.sqrt(
        sum(float(value.square().sum()) for value in updates.values())
    )
    if not finite or update_l2 <= 0:
        raise SystemExit(
            "A numerical comparison path was non-finite or did not update."
        )
    record = {
        "pre_update_loss": float(loss.detach()),
        "unclipped_gradient_l2": gradient_l2,
        "parameter_update_l2": update_l2,
        "parameters_remain_fp32": all(
            parameter.dtype == torch.float32 for parameter in model.parameters()
        ),
        "uses_dynamic_gradient_scaling": use_fp16_scaler,
        "gradient_scale_after_step": float(scaler.get_scale()),
        "finite_loss_gradients_and_update": finite,
    }
    return record, {"gradients": gradients, "updates": updates}


def train_mode(
    torch: Any,
    *,
    name: str,
    autocast_dtype: Any | None,
    initial_state: dict[str, Any],
    inputs: Any,
    labels: Any,
    vocab_size: int,
    model_shape: dict[str, int],
    seed: int,
    warmup: int,
    iterations: int,
) -> dict[str, Any]:
    """Measure a warmed multi-step run separately from the equivalence step."""
    seed_everything(torch, seed)
    model = build_tiny_lm(
        torch,
        vocab_size=vocab_size,
        hidden_size=model_shape["hidden"],
        layers=model_shape["layers"],
        heads=model_shape["heads"],
        max_sequence=model_shape["sequence"],
    ).to("cuda")
    model.load_state_dict(initial_state)
    model.train()
    optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
    use_fp16_scaler = autocast_dtype == torch.float16
    scaler = torch.amp.GradScaler("cuda", enabled=use_fp16_scaler)
    first_parameter = next(model.parameters())
    initial_parameter = first_parameter.detach().clone()

    def one_step() -> tuple[Any, Any]:
        optimizer.zero_grad(set_to_none=True)
        with torch.autocast(
            device_type="cuda",
            dtype=autocast_dtype,
            enabled=autocast_dtype is not None,
        ):
            logits = model(inputs)
            loss = torch.nn.functional.cross_entropy(
                logits.reshape(-1, vocab_size), labels.reshape(-1)
            )
        scaler.scale(loss).backward()
        scaler.unscale_(optimizer)
        gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        scaler.step(optimizer)
        scaler.update()
        return loss.detach(), gradient_norm.detach()

    one_step = annotated_operation(one_step, "mixed_precision_step")

    for _ in range(warmup):
        one_step()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    device_samples: list[float] = []
    end_to_end_samples: list[float] = []
    losses: list[float] = []
    gradient_norms: list[float] = []
    for _ in range(iterations):
        torch.cuda.synchronize()
        wall_started = time.perf_counter()
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
        loss, gradient_norm = one_step()
        end.record()
        end.synchronize()
        end_to_end_samples.append((time.perf_counter() - wall_started) * 1_000)
        device_samples.append(float(start.elapsed_time(end)))
        losses.append(float(loss))
        gradient_norms.append(float(gradient_norm))

    parameter_delta = float(
        (first_parameter.detach() - initial_parameter).float().norm()
    )
    finite = all(
        torch.isfinite(torch.tensor(values)).all().item()
        for values in (losses, gradient_norms)
    )
    if not finite or parameter_delta <= 0:
        raise SystemExit(f"{name} failed the finite-update correctness gate.")
    tokens = int(inputs.numel()) * iterations
    result = {
        "autocast_dtype": str(autocast_dtype).removeprefix("torch."),
        "parameters_remain_fp32": all(
            parameter.dtype == torch.float32 for parameter in model.parameters()
        ),
        "uses_dynamic_gradient_scaling": use_fp16_scaler,
        "final_gradient_scale": float(scaler.get_scale()),
        "median_device_region_ms": round(statistics.median(device_samples), 4),
        "median_end_to_end_step_ms": round(statistics.median(end_to_end_samples), 4),
        "p90_end_to_end_step_ms": round(
            sorted(end_to_end_samples)[
                max(0, math.ceil(0.9 * len(end_to_end_samples)) - 1)
            ],
            4,
        ),
        "end_to_end_tokens_per_second": round(
            tokens / (sum(end_to_end_samples) / 1_000), 1
        ),
        "first_timed_loss_after_warmup": round(losses[0], 6),
        "final_measured_loss": round(losses[-1], 6),
        "final_gradient_norm": round(gradient_norms[-1], 6),
        "parameter_delta_l2": round(parameter_delta, 6),
        "peak_allocated_mib": round(torch.cuda.max_memory_allocated() / 2**20, 1),
        "peak_reserved_mib": round(torch.cuda.max_memory_reserved() / 2**20, 1),
    }
    return result


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--max-loss-relative-error", type=float, default=0.05)
    parser.add_argument("--max-gradient-relative-l2", type=float, default=0.2)
    parser.add_argument("--max-update-relative-l2", type=float, default=0.2)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    thresholds = (
        args.max_loss_relative_error,
        args.max_gradient_relative_l2,
        args.max_update_relative_l2,
    )
    if any(not math.isfinite(value) or value <= 0 for value in thresholds):
        raise SystemExit(
            "All numerical-equivalence thresholds must be finite and positive."
        )
    torch = load_torch()
    environment = require_course_gpu(torch)
    seed_everything(torch, args.seed)
    torch.set_float32_matmul_precision("highest")

    model_shape = (
        {"hidden": 384, "layers": 3, "heads": 6, "sequence": 128, "batch": 4}
        if args.workload == "small"
        else {
            "hidden": 1_024,
            "layers": 6,
            "heads": 16,
            "sequence": 512,
            "batch": 8,
        }
    )
    vocab_size = 2_048 if args.workload == "small" else 8_192
    base = build_tiny_lm(
        torch,
        vocab_size=vocab_size,
        hidden_size=model_shape["hidden"],
        layers=model_shape["layers"],
        heads=model_shape["heads"],
        max_sequence=model_shape["sequence"],
    )
    initial_state = copy.deepcopy(base.state_dict())
    del base
    inputs, labels = make_language_batch(
        torch,
        batch_size=model_shape["batch"],
        sequence=model_shape["sequence"],
        vocab_size=vocab_size,
        device="cuda",
    )
    modes = {
        "fp32": None,
        "bf16": torch.bfloat16,
        "fp16": torch.float16,
    }
    numerical_records: dict[str, dict[str, Any]] = {}
    reference_record, reference_state = numerical_step(
        torch,
        autocast_dtype=None,
        initial_state=initial_state,
        inputs=inputs,
        labels=labels,
        vocab_size=vocab_size,
        model_shape=model_shape,
        seed=args.seed,
    )
    numerical_records["fp32"] = {
        **reference_record,
        "loss_relative_error_vs_fp32": 0.0,
        "gradient_relative_l2_vs_fp32": 0.0,
        "update_relative_l2_vs_fp32": 0.0,
    }
    torch.cuda.empty_cache()
    for name, dtype in (("bf16", torch.bfloat16), ("fp16", torch.float16)):
        candidate_record, candidate_state = numerical_step(
            torch,
            autocast_dtype=dtype,
            initial_state=initial_state,
            inputs=inputs,
            labels=labels,
            vocab_size=vocab_size,
            model_shape=model_shape,
            seed=args.seed,
        )
        loss_error = relative_error(
            candidate_record["pre_update_loss"], reference_record["pre_update_loss"]
        )
        gradient_error = state_relative_l2(
            candidate_state["gradients"], reference_state["gradients"]
        )
        update_error = state_relative_l2(
            candidate_state["updates"], reference_state["updates"]
        )
        equivalence_errors = (loss_error, gradient_error, update_error)
        candidate_record.update(
            {
                "loss_relative_error_vs_fp32": loss_error,
                "gradient_relative_l2_vs_fp32": gradient_error,
                "update_relative_l2_vs_fp32": update_error,
            }
        )
        if (
            any(not math.isfinite(value) for value in equivalence_errors)
            or loss_error > args.max_loss_relative_error
            or gradient_error > args.max_gradient_relative_l2
            or update_error > args.max_update_relative_l2
        ):
            raise SystemExit(f"{name} failed the declared FP32 equivalence gates.")
        numerical_records[name] = candidate_record
        del candidate_state
        torch.cuda.empty_cache()
    del reference_state

    measurements: dict[str, dict[str, Any]] = {}
    for name, dtype in modes.items():
        timed_record = train_mode(
            torch,
            name=name,
            autocast_dtype=dtype,
            initial_state=initial_state,
            inputs=inputs,
            labels=labels,
            vocab_size=vocab_size,
            model_shape=model_shape,
            seed=args.seed,
            warmup=args.warmup,
            iterations=args.iterations,
        )
        measurements[name] = {
            "one_step_numerical_acceptance": numerical_records[name],
            "warmed_timing": timed_record,
        }
        torch.cuda.empty_cache()
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="21_mixed_precision_training",
        environment=environment,
        measurements={
            "model_shape": model_shape,
            "vocab_size": vocab_size,
            "identical_initial_state_and_batch": True,
            "numerical_thresholds": {
                "max_loss_relative_error": args.max_loss_relative_error,
                "max_gradient_relative_l2": args.max_gradient_relative_l2,
                "max_update_relative_l2": args.max_update_relative_l2,
            },
            "modes": measurements,
        },
        correctness={
            "all_modes_finite": all(
                record["finite_loss_gradients_and_update"]
                for record in numerical_records.values()
            ),
            "all_modes_update_parameters": all(
                record["parameter_update_l2"] > 0
                for record in numerical_records.values()
            ),
            "bf16_and_fp16_match_fp32_within_declared_thresholds": True,
            "parameters_remain_fp32": all(
                record["parameters_remain_fp32"]
                for record in numerical_records.values()
            ),
            "fp16_uses_dynamic_gradient_scaling": numerical_records["fp16"][
                "uses_dynamic_gradient_scaling"
            ],
        },
    )
    print(f"Completed matched mixed-precision training comparison: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
Teaching diagram
Training memory ledger across one optimizer step Persistent parameters and optimizer state remain across the step. Forward creates saved activations, backward creates gradients and consumes or recomputes activations, and the optimizer uses gradients and moment state. Temporary workspaces, allocator reservation, and communication buffers may peak in different phases. persistent state parameters possibly mixed storage formats optimizer state moments, master copies, step state phase-dependent state forward saved activations grow backward gradients + recompute optimizer update workspace temporary and distributed state operator workspaces · gradient buckets· gather buffers · allocator reservation Ask which entry each technique changes smaller microbatch activation peak checkpointing saved activations → recompute lower precision selected stored/compute tensors FSDP2 shard state; gather for compute Calculated bytes, allocated bytes, reserved bytes, and peak bytes answer different questions.
Training memory ledger across one optimizer step

Persistent parameters and optimizer state remain across the step. Forward creates saved activations, backward creates gradients and consumes or recomputes activations, and the optimizer uses gradients and moment state. Temporary workspaces, allocator reservation, and communication buffers may peak in different phases.

# Normal execution
sbatch slurm/21_mixed_precision_training.sbatch --workload small

# Optional profiling
sbatch slurm/21_mixed_precision_training.sbatch --workload small --profiler all

Lab 22: Qualify a warmed Transformer Engine FP8 recipe

FP8 execution relies on scaling and quantization state, not simply changing a tensor dtype. This optional lab compares BF16 and FP8 forward/backward behavior for a Transformer Engine linear layer using a delayed-scaling recipe.

Complete source: labs/22_transformer_engine_fp8.py
"""Compare BF16 and optional Transformer Engine FP8 forward/backward paths."""

from __future__ import annotations

import argparse
import math
import statistics
from typing import Any, Callable

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def relative_l2(torch: Any, candidate: Any, reference: Any) -> float:
    numerator = (candidate.float() - reference.float()).norm()
    denominator = reference.float().norm().clamp_min(1e-12)
    return float(numerator / denominator)


def measure_steps(
    torch: Any,
    operation: Callable[[], tuple[Any, Any]],
    *,
    warmup: int,
    iterations: int,
) -> tuple[list[float], dict[str, float]]:
    for _ in range(warmup):
        operation()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    steady_state_bytes = torch.cuda.memory_allocated()
    torch.cuda.reset_peak_memory_stats()
    samples: list[float] = []
    for _ in range(iterations):
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
        operation()
        end.record()
        end.synchronize()
        samples.append(float(start.elapsed_time(end)))
    peak_bytes = torch.cuda.max_memory_allocated()
    memory = {
        "steady_state_allocated_mib": steady_state_bytes / 2**20,
        "incremental_peak_above_baseline_mib": max(0, peak_bytes - steady_state_bytes)
        / 2**20,
    }
    return samples, memory


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--max-output-relative-l2", type=float, default=0.2)
    parser.add_argument("--max-gradient-relative-l2", type=float, default=0.3)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    thresholds = (args.max_output_relative_l2, args.max_gradient_relative_l2)
    if any(not math.isfinite(value) or value <= 0 for value in thresholds):
        raise SystemExit("Relative-L2 thresholds must be finite and positive.")
    if args.warmup < 1:
        raise SystemExit(
            "--warmup must be at least one so BF16 and FP8 use warmed boundaries."
        )
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    try:
        import transformer_engine
        import transformer_engine.pytorch as te
        from transformer_engine.common.recipe import DelayedScaling, Format
    except ImportError as exc:
        raise SystemExit(
            "Optional lab blocked: activate a cluster-approved Transformer "
            "Engine environment compatible with the pinned PyTorch/CUDA stack."
        ) from exc

    rows, hidden = (1_024, 1_024) if args.workload == "small" else (4_096, 4_096)
    layer = te.Linear(
        hidden,
        hidden,
        bias=True,
        params_dtype=torch.bfloat16,
    ).cuda()
    # Create the synthetic tensors used by this experiment.
    inputs = torch.randn(rows, hidden, device="cuda", dtype=torch.bfloat16)
    recipe = DelayedScaling(
        fp8_format=Format.HYBRID,
        amax_history_len=16,
        amax_compute_algo="max",
    )

    def bf16_step() -> tuple[Any, Any]:
        layer.zero_grad(set_to_none=True)
        output = layer(inputs)
        loss = output.float().square().mean()
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        return output.detach(), layer.weight.grad.detach()

    def fp8_step() -> tuple[Any, Any]:
        layer.zero_grad(set_to_none=True)
        with te.autocast(enabled=True, recipe=recipe):
            output = layer(inputs)
            loss = output.float().square().mean()
        loss.backward()
        return output.detach(), layer.weight.grad.detach()

    bf16_step = annotated_operation(bf16_step, "bf16_step")

    # Measure the BF16 path before an FP8 call can allocate scaling metadata.
    # Each path reports its warmed allocation baseline and only the incremental
    # peak above that baseline, not a standalone full-model footprint.
    bf16_samples, bf16_memory = measure_steps(
        torch,
        bf16_step,
        warmup=args.warmup,
        iterations=args.iterations,
    )

    # Delayed scaling needs prior observations. Validate the same warmed recipe
    # state used by the timing path instead of accepting a cold first call.
    for _ in range(args.warmup):
        fp8_step()

    def compare_warmed_once() -> dict[str, float | bool]:
        bf16_output, bf16_gradient = bf16_step()
        fp8_output, fp8_gradient = fp8_step()
        finite = all(
            bool(torch.isfinite(value).all())
            for value in (bf16_output, bf16_gradient, fp8_output, fp8_gradient)
        )
        return {
            "output_relative_l2": relative_l2(torch, fp8_output, bf16_output),
            "gradient_relative_l2": relative_l2(torch, fp8_gradient, bf16_gradient),
            "finite": finite,
        }

    validation_iterations = max(3, min(args.iterations, 8))
    numerical_samples = [compare_warmed_once() for _ in range(validation_iterations)]

    fp8_samples, fp8_memory = measure_steps(
        torch,
        fp8_step,
        warmup=args.warmup,
        iterations=args.iterations,
    )
    numerical_samples.append(compare_warmed_once())
    output_errors = [
        float(sample["output_relative_l2"]) for sample in numerical_samples
    ]
    gradient_errors = [
        float(sample["gradient_relative_l2"]) for sample in numerical_samples
    ]
    finite = all(bool(sample["finite"]) for sample in numerical_samples)
    errors_finite = all(
        math.isfinite(value) for value in (*output_errors, *gradient_errors)
    )
    max_output_error = max(output_errors)
    max_gradient_error = max(gradient_errors)
    if (
        not finite
        or not errors_finite
        or max_output_error > args.max_output_relative_l2
        or max_gradient_error > args.max_gradient_relative_l2
    ):
        raise SystemExit("Warmed FP8 numerical acceptance gate failed.")
    environment["transformer_engine_version"] = getattr(
        transformer_engine, "__version__", "unknown"
    )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="22_transformer_engine_fp8",
        environment=environment,
        measurements={
            "rows": rows,
            "hidden_size": hidden,
            "recipe": "DelayedScaling",
            "fp8_format": "HYBRID",
            "amax_history_len": 16,
            "bf16_median_device_region_ms": round(statistics.median(bf16_samples), 4),
            "fp8_median_device_region_ms": round(statistics.median(fp8_samples), 4),
            "memory_scope": (
                "per-path incremental peak above its warmed allocation baseline; "
                "not a standalone full-model footprint"
            ),
            "bf16_steady_state_allocated_mib": round(
                bf16_memory["steady_state_allocated_mib"], 1
            ),
            "bf16_incremental_peak_above_baseline_mib": round(
                bf16_memory["incremental_peak_above_baseline_mib"], 1
            ),
            "fp8_steady_state_allocated_mib": round(
                fp8_memory["steady_state_allocated_mib"], 1
            ),
            "fp8_incremental_peak_above_baseline_mib": round(
                fp8_memory["incremental_peak_above_baseline_mib"], 1
            ),
            "numerical_sample_count": len(numerical_samples),
            "validation_state": "warmed delayed-scaling recipe before and after timing",
            "median_output_relative_l2": round(statistics.median(output_errors), 6),
            "max_output_relative_l2": round(max_output_error, 6),
            "median_gradient_relative_l2": round(statistics.median(gradient_errors), 6),
            "max_gradient_relative_l2": round(max_gradient_error, 6),
        },
        correctness={
            "finite_outputs_gradients_and_errors": finite and errors_finite,
            "output_relative_l2_within_declared_threshold": True,
            "gradient_relative_l2_within_declared_threshold": True,
            "backward_outside_fp8_autocast": True,
        },
    )
    print(f"Completed optional Transformer Engine FP8 comparison: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/22_transformer_engine_fp8.sbatch --workload small

# Optional profiling
sbatch slurm/22_transformer_engine_fp8.sbatch --workload small --profiler all

Lab 24: Reproduce the next update after checkpoint restoration

Saving weights alone does not guarantee that resumed training follows the same trajectory. Optimizer state and random-number generators also affect the next batch and update.

Complete source: labs/24_checkpoint_resume.py
"""Prove that a complete checkpoint reproduces the next training update."""

from __future__ import annotations

import argparse
import io

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from tiny_lm import build_tiny_lm, make_language_batch


def make_rng_language_batch(
    torch: object, *, batch_size: int, sequence: int, vocab_size: int
) -> tuple[object, object]:
    """Build a batch whose exact contents depend on both CPU and CUDA RNG state."""
    cpu_tokens = torch.randint(
        0, vocab_size, (batch_size, sequence), device="cpu", dtype=torch.long
    )
    cuda_tokens = torch.randint(
        0, vocab_size, (batch_size, sequence), device="cuda", dtype=torch.long
    )
    inputs = (cpu_tokens.to("cuda") + cuda_tokens).remainder(vocab_size)
    labels = torch.roll(inputs, shifts=-1, dims=1)
    return inputs, labels


def step(
    torch: object, model: object, optimizer: object, inputs: object, labels: object
) -> float:
    # Clear the previous step’s gradients before differentiating again.
    optimizer.zero_grad(set_to_none=True)
    logits = model(inputs)
    loss = torch.nn.functional.cross_entropy(
        logits.reshape(-1, logits.shape[-1]), labels.reshape(-1)
    )
    # Differentiate the loss to populate parameter gradients.
    loss.backward()
    # Update the parameters using the gradients from this step.
    optimizer.step()
    return float(loss.detach())


def move_optimizer_state(torch: object, optimizer: object, device: str) -> None:
    """Move tensor-valued optimizer state after a CPU checkpoint load."""
    for state in optimizer.state.values():
        for name, value in state.items():
            if isinstance(value, torch.Tensor):
                state[name] = value.to(device)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    torch.use_deterministic_algorithms(True)
    torch.backends.cuda.matmul.allow_tf32 = False
    model = build_tiny_lm(
        torch, vocab_size=256, hidden_size=128, layers=2, heads=4, max_sequence=64
    ).to("cuda")
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
    inputs, labels = make_language_batch(
        torch, batch_size=4, sequence=32, vocab_size=256, device="cuda"
    )
    first_loss = step(torch, model, optimizer, inputs, labels)
    checkpoint = io.BytesIO()
    torch.save(
        {
            "model": model.state_dict(),
            "optimizer": optimizer.state_dict(),
            "cpu_rng": torch.get_rng_state(),
            "cuda_rng": torch.cuda.get_rng_state().cpu(),
        },
        checkpoint,
    )
    reference_inputs, reference_labels = make_rng_language_batch(
        torch, batch_size=4, sequence=32, vocab_size=256
    )
    reference_loss = step(torch, model, optimizer, reference_inputs, reference_labels)
    reference_state = {
        name: value.detach().clone() for name, value in model.state_dict().items()
    }
    without_restore_inputs, without_restore_labels = make_rng_language_batch(
        torch, batch_size=4, sequence=32, vocab_size=256
    )
    omitted_rng_restore_diverges = not bool(
        torch.equal(reference_inputs, without_restore_inputs)
        and torch.equal(reference_labels, without_restore_labels)
    )
    if not omitted_rng_restore_diverges:
        raise SystemExit(
            "Negative control failed: the advanced RNG state repeated a batch."
        )
    checkpoint.seek(0)
    saved = torch.load(checkpoint, map_location="cpu", weights_only=False)
    resumed = build_tiny_lm(
        torch, vocab_size=256, hidden_size=128, layers=2, heads=4, max_sequence=64
    ).to("cuda")
    resumed_optimizer = torch.optim.AdamW(resumed.parameters(), lr=1e-3)
    resumed.load_state_dict(saved["model"])
    resumed_optimizer.load_state_dict(saved["optimizer"])
    move_optimizer_state(torch, resumed_optimizer, "cuda")
    torch.set_rng_state(saved["cpu_rng"].cpu())
    torch.cuda.set_rng_state(saved["cuda_rng"].cpu())
    resumed_inputs, resumed_labels = make_rng_language_batch(
        torch, batch_size=4, sequence=32, vocab_size=256
    )
    generated_batch_exact = bool(
        torch.equal(reference_inputs, resumed_inputs)
        and torch.equal(reference_labels, resumed_labels)
    )
    resumed_loss = step(
        torch, resumed, resumed_optimizer, resumed_inputs, resumed_labels
    )
    max_error = max(
        float((reference_state[name] - value).abs().max())
        for name, value in resumed.state_dict().items()
    )
    exact = (
        generated_batch_exact and reference_loss == resumed_loss and max_error == 0.0
    )
    if not exact:
        raise SystemExit(
            "Checkpoint resume did not reproduce the next loss and parameter update."
        )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="24_checkpoint_resume",
        environment=environment,
        measurements={
            "first_loss": first_loss,
            "reference_next_loss": reference_loss,
            "resumed_next_loss": resumed_loss,
            "max_parameter_error": max_error,
            "post_checkpoint_batch_digest_inputs_equal": generated_batch_exact,
            "checkpoint_state": ["model", "optimizer", "cpu_rng", "cuda_rng"],
            "negative_control_omitted_rng_restore_diverged": (
                omitted_rng_restore_diverges
            ),
        },
        correctness={
            "rng_generated_next_batch_exact": generated_batch_exact,
            "omitted_rng_restore_diverges": omitted_rng_restore_diverges,
            "exact_next_update": exact,
        },
    )
    print(f"Wrote resume-equivalence evidence: {target}")


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/24_checkpoint_resume.sbatch --workload small

# Optional profiling
sbatch slurm/24_checkpoint_resume.sbatch --workload small --profiler all

Lab 25: Pack variable-length examples without crossing boundaries

Padding reserves positions that may contribute no useful training target, while packing can place several short examples into one fixed-capacity row. This lab constructs a packing plan and a boundary-safe causal mask.

Complete source: labs/25_sequence_packing.py
"""Compare padded and boundary-safe packed causal-language-model batches."""

from __future__ import annotations

import argparse

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)


def first_fit_bins(lengths: list[int], capacity: int) -> list[list[int]]:
    """Pack sequence lengths without splitting an example."""
    bins: list[list[int]] = []
    used: list[int] = []
    for length in sorted(lengths, reverse=True):
        for index, consumed in enumerate(used):
            if consumed + length <= capacity:
                bins[index].append(length)
                used[index] += length
                break
        else:
            bins.append([length])
            used.append(length)
    return bins


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    parser.add_argument("--capacity", type=int, default=256)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if args.capacity < 32:
        raise SystemExit("--capacity must be at least 32")
    torch = load_torch()
    environment = require_course_gpu(torch)
    lengths = [31, 48, 63, 77, 91, 113]
    if max(lengths) > args.capacity:
        raise SystemExit("capacity is smaller than an example")
    bins = first_fit_bins(lengths, args.capacity)
    padded_tokens = len(lengths) * max(lengths)
    packed_tokens = len(bins) * args.capacity
    valid_tokens = sum(lengths)
    boundary_mask = torch.zeros(
        (packed_tokens, packed_tokens), device="cuda", dtype=torch.bool
    )
    cursor = 0
    spans: list[tuple[int, int, int]] = []
    for bin_id, group in enumerate(bins):
        for length in group:
            start = cursor
            boundary_mask[cursor : cursor + length, cursor : cursor + length] = (
                torch.ones((length, length), device="cuda", dtype=torch.bool).tril()
            )
            cursor += length
            spans.append((bin_id, start, cursor))
        cursor = ((cursor + args.capacity - 1) // args.capacity) * args.capacity
    backward_boundary_checks = [
        not bool(boundary_mask[start, prior_end - 1].item())
        for (prior_bin, _prior_start, prior_end), (bin_id, start, _end) in zip(
            spans, spans[1:]
        )
        if bin_id == prior_bin and start == prior_end
    ]
    within_example_controls = [
        bool(boundary_mask[end - 1, start].item())
        and bool(boundary_mask[start, start].item())
        and bool(boundary_mask[end - 1, end - 1].item())
        for _bin_id, start, end in spans
    ]
    no_cross_example_attention = bool(backward_boundary_checks) and all(
        backward_boundary_checks
    )
    valid_within_example_attention = all(within_example_controls)
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="25_sequence_packing",
        environment=environment,
        measurements={
            "lengths": lengths,
            "bins": bins,
            "valid_tokens": valid_tokens,
            "padded_tokens": padded_tokens,
            "packed_capacity_tokens": packed_tokens,
            "padding_efficiency": round(valid_tokens / padded_tokens, 4),
            "packing_efficiency": round(valid_tokens / packed_tokens, 4),
        },
        correctness={
            "every_adjacent_packed_boundary_checked": len(backward_boundary_checks)
            == sum(max(0, len(group) - 1) for group in bins),
            "no_cross_example_attention": no_cross_example_attention,
            "within_example_causal_controls_pass": valid_within_example_attention,
            "all_examples_assigned": sum(map(len, bins)) == len(lengths),
        },
    )
    print(f"Wrote packing evidence: {target}")


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/25_sequence_packing.sbatch --workload small --capacity 256

# Optional profiling
sbatch slurm/25_sequence_packing.sbatch --workload small --capacity 256 --profiler all

Lab 26: Diagnose a slow training-data producer

A training accelerator can wait because its next batch is not ready, even when the model itself is efficient. This lab compares a serial producer with worker-prefetched loading using deterministic sample identities and a configurable producer delay.

Complete source: labs/26_input_pipeline.py
"""Compare deterministic serial and worker-prefetched training input pipelines."""

from __future__ import annotations

import argparse
import hashlib
import statistics
import time
from typing import Any

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


class DeterministicSlowDataset:
    """Generate index-derived token rows with a controlled producer delay."""

    def __init__(self, samples: int, sequence_length: int, delay_ms: float) -> None:
        self.samples = samples
        self.sequence_length = sequence_length
        self.delay_ms = delay_ms

    def __len__(self) -> int:
        return self.samples

    def __getitem__(self, index: int) -> tuple[int, list[int], float]:
        cpu_started = time.process_time()
        tokens = [
            (index * 131 + position * 17) % 32_000
            for position in range(self.sequence_length)
        ]
        cpu_ms = (time.process_time() - cpu_started) * 1_000
        time.sleep(self.delay_ms / 1_000)
        return index, tokens, cpu_ms


def collate_samples(
    samples: list[tuple[int, list[int], float]],
) -> dict[str, Any]:
    import torch

    return {
        "indices": torch.tensor([sample[0] for sample in samples]),
        "tokens": torch.tensor([sample[1] for sample in samples], dtype=torch.int64),
        "producer_cpu_ms": torch.tensor([sample[2] for sample in samples]),
    }


def percentile(values: list[float], fraction: float) -> float:
    ordered = sorted(values)
    index = min(len(ordered) - 1, max(0, round((len(ordered) - 1) * fraction)))
    return ordered[index]


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--batches", type=int, default=8)
    parser.add_argument("--workers", type=int, default=2)
    parser.add_argument("--prefetch", type=int, default=2)
    parser.add_argument("--producer-delay-ms", type=float, default=3.0)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if args.batches < 2:
        raise SystemExit("--batches must be at least 2")
    if args.workers < 1 or args.prefetch < 1 or args.producer_delay_ms < 0:
        raise SystemExit("workers/prefetch must be positive and delay non-negative")
    torch = load_torch()
    environment = require_course_gpu(torch)
    batch_size = 8 if args.workload == "small" else 32
    sequence_length = 256 if args.workload == "small" else 2_048
    sample_count = args.batches * batch_size

    def run_case(*, workers: int, prefetch: int | None) -> dict[str, Any]:
        dataset = DeterministicSlowDataset(
            sample_count, sequence_length, args.producer_delay_ms
        )
        options: dict[str, Any] = {
            "dataset": dataset,
            "batch_size": batch_size,
            "shuffle": False,
            "num_workers": workers,
            "pin_memory": True,
            "collate_fn": collate_samples,
        }
        if workers:
            options["prefetch_factor"] = prefetch
        loader = torch.utils.data.DataLoader(**options)
        iterator = iter(loader)
        digest = hashlib.sha256()
        batch_ready_ms: list[float] = []
        h2d_ms: list[float] = []
        step_ms: list[float] = []
        producer_cpu_ms: list[float] = []
        queue_depth_before_fetch: list[int | None] = []
        total_started = time.perf_counter()
        for _ in range(args.batches):
            queue = getattr(iterator, "_data_queue", None)
            try:
                queue_depth_before_fetch.append(
                    queue.qsize() if queue is not None else None
                )
            except (AttributeError, NotImplementedError):
                queue_depth_before_fetch.append(None)
            ready_started = time.perf_counter()
            batch = next(iterator)
            ready_finished = time.perf_counter()
            batch_ready_ms.append((ready_finished - ready_started) * 1_000)
            indices = batch["indices"]
            tokens = batch["tokens"]
            digest.update(indices.numpy().tobytes())
            digest.update(tokens.numpy().tobytes())
            producer_cpu_ms.extend(float(value) for value in batch["producer_cpu_ms"])
            copy_started = torch.cuda.Event(enable_timing=True)
            copy_finished = torch.cuda.Event(enable_timing=True)
            step_finished = torch.cuda.Event(enable_timing=True)
            copy_started.record()
            device_tokens = tokens.to("cuda", non_blocking=True)
            copy_finished.record()
            value = device_tokens.float().square().mean()
            step_finished.record()
            step_finished.synchronize()
            if not bool(torch.isfinite(value)):
                raise SystemExit("Input-pipeline consumer produced a non-finite value.")
            h2d_ms.append(float(copy_started.elapsed_time(copy_finished)))
            step_ms.append(float(copy_started.elapsed_time(step_finished)))
        wall_seconds = time.perf_counter() - total_started
        total_tokens = sample_count * sequence_length
        return {
            "workers": workers,
            "prefetch_factor": prefetch,
            "configured_queue_capacity_batches": workers * (prefetch or 0),
            "queue_depth_before_fetch": queue_depth_before_fetch,
            "sample_order_and_content_digest": digest.hexdigest(),
            "batch_ready_ms": batch_ready_ms,
            "batch_ready_p50_ms": round(statistics.median(batch_ready_ms), 4),
            "batch_ready_p90_ms": round(percentile(batch_ready_ms, 0.9), 4),
            "producer_cpu_ms_per_sample_p50": round(
                statistics.median(producer_cpu_ms), 4
            ),
            "configured_producer_service_delay_ms_per_sample": args.producer_delay_ms,
            "h2d_ms": h2d_ms,
            "h2d_p50_ms": round(statistics.median(h2d_ms), 4),
            "consumer_step_ms": step_ms,
            "gpu_idle_gap_proxy_ms": batch_ready_ms,
            "tokens_per_second": round(total_tokens / wall_seconds, 3),
            "wall_seconds": round(wall_seconds, 4),
        }

    serial = run_case(workers=0, prefetch=None)
    prefetched = run_case(workers=args.workers, prefetch=args.prefetch)
    equivalent = (
        serial["sample_order_and_content_digest"]
        == prefetched["sample_order_and_content_digest"]
    )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="26_input_pipeline",
        environment=environment,
        measurements={
            "batch_size": batch_size,
            "sequence_length": sequence_length,
            "serial_slow_producer": serial,
            "worker_prefetched": prefetched,
            "interpretation_boundary": (
                "batch-ready time is a host-side starvation proxy; confirm GPU idle "
                "gaps and queue behavior with a profiler before publishing a claim"
            ),
        },
        correctness={
            "identical_sample_order_and_content": equivalent,
            "all_batches_consumed_in_both_cases": len(serial["batch_ready_ms"])
            == len(prefetched["batch_ready_ms"])
            == args.batches,
            "all_timings_positive": all(
                value > 0
                for case in (serial, prefetched)
                for value in case["consumer_step_ms"]
            ),
        },
    )
    print(f"Wrote input-pipeline evidence: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/26_input_pipeline.sbatch --workload small --workers 2 --prefetch 2

# Optional profiling
sbatch slurm/26_input_pipeline.sbatch --workload small --workers 2 --prefetch 2 --profiler all

Lab 27: Separate compiled expressions from captured training steps

Compilation and CUDA Graphs optimize different parts of execution and should not be treated as one indistinguishable feature. This lab checks a compiled expression separately from a captured fixed-shape training update.

Complete source: labs/27_fused_graph_trace.py
"""Trace compiled fusion and capture a fixed-shape CUDA Graph training step."""

from __future__ import annotations

import argparse
import time
from contextlib import nullcontext

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    sgd_updates_match,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--external-only", action="store_true", help="Skip the internal CUDA profiler during a separate Nsight capture.")
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    environment = require_course_gpu(torch)
    width = 256 if args.workload == "small" else 1_024
    batch = 64 if args.workload == "small" else 256
    # Create the synthetic tensors used by this experiment.
    x = torch.randn((batch, width), device="cuda", dtype=torch.bfloat16)
    target = torch.randn_like(x)
    base_weight = (
        torch.randn((width, width), device="cuda", dtype=torch.bfloat16) / width**0.5
    )
    base_bias = torch.zeros(width, device="cuda", dtype=torch.bfloat16)

    def expression(value: object, weight: object, bias: object) -> object:
        prediction = torch.nn.functional.gelu(torch.addmm(bias, value, weight))
        return torch.nn.functional.mse_loss(prediction.float(), target.float())

    compiled = torch.compile(expression, fullgraph=True)
    compile_started = time.perf_counter()
    compiled_loss = compiled(x, base_weight, base_bias)
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    first_compiled_call_ms = (time.perf_counter() - compile_started) * 1_000
    eager_loss = expression(x, base_weight, base_bias)
    expression_close = bool(
        torch.allclose(eager_loss, compiled_loss, rtol=1e-2, atol=1e-2)
    )

    eager_weight = base_weight.detach().clone().requires_grad_(True)
    eager_bias = base_bias.detach().clone().requires_grad_(True)
    graph_weight = base_weight.detach().clone().requires_grad_(True)
    graph_bias = base_bias.detach().clone().requires_grad_(True)
    eager_optimizer = torch.optim.SGD(
        [eager_weight, eager_bias], lr=1e-3, foreach=False
    )
    graph_optimizer = torch.optim.SGD(
        [graph_weight, graph_bias], lr=1e-3, foreach=False
    )

    def training_step(weight: object, bias: object, optimizer: object) -> object:
        # Clear the previous step’s gradients before differentiating again.
        optimizer.zero_grad(set_to_none=False)
        loss = expression(x, weight, bias)
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        # Update the parameters using the gradients from this step.
        optimizer.step()
        return loss

    warm_weight = base_weight.detach().clone().requires_grad_(True)
    warm_bias = base_bias.detach().clone().requires_grad_(True)
    warm_optimizer = torch.optim.SGD([warm_weight, warm_bias], lr=1e-3, foreach=False)
    warm_stream = torch.cuda.Stream()
    warm_stream.wait_stream(torch.cuda.current_stream())
    with torch.cuda.stream(warm_stream):
        for _ in range(max(3, args.warmup)):
            training_step(warm_weight, warm_bias, warm_optimizer)
    torch.cuda.current_stream().wait_stream(warm_stream)

    graph_weight.grad = torch.zeros_like(graph_weight)
    graph_bias.grad = torch.zeros_like(graph_bias)
    graph = torch.cuda.CUDAGraph()
    with torch.cuda.graph(graph):
        graph_loss = training_step(graph_weight, graph_bias, graph_optimizer)
    with torch.no_grad():
        graph_weight.copy_(base_weight)
        graph_bias.copy_(base_bias)
    graph_weight.grad.zero_()
    graph_bias.grad.zero_()

    reference_loss = training_step(eager_weight, eager_bias, eager_optimizer)
    graph.replay()
    torch.cuda.synchronize()
    step_close = bool(
        torch.allclose(reference_loss, graph_loss, rtol=1e-2, atol=1e-2)
        and sgd_updates_match(
            torch,
            (base_weight, base_bias),
            (eager_weight, eager_bias),
            (graph_weight, graph_bias),
            learning_rate=1e-3,
        )
    )
    if not expression_close or not step_close:
        raise SystemExit("Compiled or CUDA Graph training path failed equivalence.")

    eager_step_timing = summarize_ms(
        cuda_times_ms(
            torch,
            lambda: training_step(eager_weight, eager_bias, eager_optimizer),
            warmup=args.warmup,
            iterations=args.iterations,
        )
    )
    graph_step_timing = summarize_ms(
        cuda_times_ms(
            torch,
            graph.replay,
            warmup=args.warmup,
            iterations=args.iterations,
        )
    )
    with (nullcontext() if args.external_only else torch.profiler.profile(
        activities=[
            torch.profiler.ProfilerActivity.CPU,
            torch.profiler.ProfilerActivity.CUDA,
        ]
    )) as profile:
        graph.replay()
        torch.cuda.synchronize()
    dispatch = sorted(
        event.key
        for event in (profile.key_averages() if profile is not None else [])
        if "cuda" in event.key.lower() or "gemm" in event.key.lower()
    )[:20]

    # Save the actual measurements together with their correctness checks.
    target_path = write_result(
        args,
        lab_id="27_fused_graph_trace",
        environment=environment,
        measurements={
            "shape": [batch, width],
            "compiled_first_call_ms": round(first_compiled_call_ms, 4),
            "compile_fullgraph_required": True,
            "cuda_graph_scope": "fixed-shape forward, backward, zero-grad, and SGD update",
            "eager_training_step": eager_step_timing,
            "cuda_graph_training_step": graph_step_timing,
            "profile_dispatch_keys": dispatch,
        },
        correctness={
            "compiled_expression_close": expression_close,
            "captured_next_update_close": step_close,
        },
    )
    print(f"Wrote fusion/CUDA-Graph evidence: {target_path}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/27_fused_graph_trace.sbatch --workload small

# Optional profiling
sbatch slurm/27_fused_graph_trace.sbatch --workload small --profiler all

Lab 30: Inspect the operators in a tiny training step

A training-step profile helps connect forward, loss, backward, and optimizer work to expensive operators. This lab captures a bounded tiny-model step and emits a short operator summary. Normal execution uses the built-in PyTorch collector; external captures disable it.

Complete source: labs/30_training_profiler.py
"""Profile a tiny H100 training step and emit a bounded operator summary."""

from __future__ import annotations

import argparse
import os
from contextlib import nullcontext

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation
from tiny_lm import build_tiny_lm, make_language_batch


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    parser.add_argument(
        "--external-only",
        action="store_true",
        help="Skip the internal CUDA profiler during a separate Nsight capture.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    model = build_tiny_lm(
        torch, vocab_size=512, hidden_size=256, layers=2, heads=4, max_sequence=128
    ).to("cuda")
    inputs, labels = make_language_batch(
        torch, batch_size=4, sequence=64, vocab_size=512, device="cuda"
    )
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)

    def training_step() -> object:
        # Clear the previous step’s gradients before differentiating again.
        optimizer.zero_grad(set_to_none=True)
        logits = model(inputs)
        loss = torch.nn.functional.cross_entropy(
            logits.reshape(-1, 512), labels.reshape(-1)
        )
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        # Update the parameters using the gradients from this step.
        optimizer.step()
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        return loss

    training_step = annotated_operation(training_step, "training_step")
    if not args.external_only:
        os.environ["COURSE_PROFILE_TOOL"] = "torch"
    with (
        nullcontext()
        if args.external_only
        else torch.profiler.profile(
            activities=[
                torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA,
            ],
            record_shapes=True,
            profile_memory=True,
        )
    ) as profile:
        loss = training_step()
    events = sorted(
        (profile.key_averages() if profile is not None else []),
        key=lambda event: event.self_device_time_total,
        reverse=True,
    )
    top = [
        {
            "name": event.key,
            "cuda_time_us": round(event.device_time_total, 3),
            "cpu_time_us": round(event.cpu_time_total, 3),
        }
        for event in events[:10]
    ]
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="30_training_profiler",
        environment=environment,
        measurements={
            "loss": float(loss.detach()),
            "top_operators": top,
            "top_operator_sort": "self_device_time_total_descending",
            "raw_trace_published": False,
        },
        correctness={"finite_loss": bool(torch.isfinite(loss))},
    )
    print(f"Wrote bounded profiler evidence: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/30_training_profiler.sbatch --workload small

# Optional profiling
sbatch slurm/30_training_profiler.sbatch --workload small --profiler all

Lab 31: Validate an optimization across complete training updates

This capstone compares a baseline linear training step with a candidate using a library bias path while preserving the intended update. You will combine correctness, repeated timing, peak memory, and explicit FLOP accounting into a bounded decision.

Complete source: labs/31_training_capstone.py
"""Measure one fresh-process training capstone trial with equivalent updates."""

from __future__ import annotations

import argparse
import math

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    sgd_updates_match,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def linear_step_flops(tokens: int, width: int, input_requires_grad: bool) -> int:
    """Count forward and requested backward GEMMs; exclude elementwise work."""
    if tokens < 1 or width < 1:
        raise ValueError("tokens and width must be positive")
    # XW, dW = X.T @ dY, and only when requested dX = dY @ W.T.
    gemms = 2 + int(input_requires_grad)
    return gemms * 2 * tokens * width * width


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--variant-order",
        choices=("baseline-first", "candidate-first"),
        required=True,
        help="Counterbalanced order selected by the three-trial launcher.",
    )
    parser.add_argument(
        "--peak-tflops",
        type=float,
        default=None,
        help="Optional dense BF16 peak for a matmul-only utilization estimate.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if args.peak_tflops is not None and (
        not math.isfinite(args.peak_tflops) or args.peak_tflops <= 0
    ):
        raise SystemExit("--peak-tflops must be finite and positive")
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    width = 256 if args.workload == "small" else 2_048
    tokens = 512 if args.workload == "small" else 4_096
    # Create the synthetic tensors used by this experiment.
    inputs = torch.randn((tokens, width), device="cuda", dtype=torch.bfloat16)
    targets = torch.randn_like(inputs)
    base_weight = (
        torch.randn((width, width), device="cuda", dtype=torch.bfloat16) / width**0.5
    )
    base_bias = torch.zeros(width, device="cuda", dtype=torch.bfloat16)

    def make_state() -> tuple[object, object, object]:
        weight = base_weight.detach().clone().requires_grad_(True)
        bias = base_bias.detach().clone().requires_grad_(True)
        optimizer = torch.optim.SGD([weight, bias], lr=1e-3, foreach=False)
        return weight, bias, optimizer

    def step(
        weight: object, bias: object, optimizer: object, *, fused_bias: bool
    ) -> object:
        # Clear the previous step’s gradients before differentiating again.
        optimizer.zero_grad(set_to_none=True)
        hidden = (
            torch.addmm(bias, inputs, weight) if fused_bias else inputs @ weight + bias
        )
        loss = torch.nn.functional.mse_loss(
            torch.nn.functional.gelu(hidden).float(), targets.float()
        )
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        # Update the parameters using the gradients from this step.
        optimizer.step()
        return loss

    check_baseline = make_state()
    check_candidate = make_state()
    reference_loss = step(*check_baseline, fused_bias=False)
    candidate_loss = step(*check_candidate, fused_bias=True)
    close = bool(
        torch.allclose(reference_loss, candidate_loss, rtol=1e-2, atol=1e-2)
        and sgd_updates_match(
            torch,
            (base_weight, base_bias),
            check_baseline[:2],
            check_candidate[:2],
            learning_rate=1e-3,
        )
    )
    if not close:
        raise SystemExit("Baseline and candidate training updates diverged.")

    baseline_state = make_state()
    candidate_state = make_state()
    operations = {
        "baseline": lambda: step(*baseline_state, fused_bias=False),
        "candidate": lambda: step(*candidate_state, fused_bias=True),
    }
    order = (
        ("baseline", "candidate")
        if args.variant_order == "baseline-first"
        else ("candidate", "baseline")
    )
    timing: dict[str, dict[str, float]] = {}
    incremental_peak: dict[str, int] = {}
    for name in order:
        timing[name] = summarize_ms(
            cuda_times_ms(
                torch,
                operations[name],
                warmup=args.warmup,
                iterations=args.iterations,
            )
        )
        torch.cuda.empty_cache()
        memory_before = int(torch.cuda.memory_allocated())
        torch.cuda.reset_peak_memory_stats()
        operations[name]()
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        incremental_peak[name] = int(torch.cuda.max_memory_allocated()) - memory_before

    minimum_step_flops = linear_step_flops(tokens, width, inputs.requires_grad)
    candidate_tflops = (
        minimum_step_flops / (timing["candidate"]["median_ms"] / 1_000) / 1e12
    )
    provisional_observation = (
        "candidate-median-lower-in-this-trial"
        if timing["candidate"]["median_ms"] < timing["baseline"]["median_ms"]
        else "candidate-median-not-lower-in-this-trial"
    )
    # Save the actual measurements together with their correctness checks.
    target_path = write_result(
        args,
        lab_id="31_training_capstone",
        environment=environment,
        measurements={
            "shape": [tokens, width],
            "warmup": args.warmup,
            "iterations": args.iterations,
            "peak_tflops_reference": args.peak_tflops,
            "trial_kind": "one fresh Python process",
            "variant_order": args.variant_order,
            "timing": timing,
            "incremental_peak_bytes": incremental_peak,
            "candidate_tokens_per_second": round(
                tokens / (timing["candidate"]["median_ms"] / 1_000), 2
            ),
            "candidate_minimum_step_tflops": round(candidate_tflops, 4),
            "candidate_matmul_utilization_percent": (
                round(100 * candidate_tflops / args.peak_tflops, 4)
                if args.peak_tflops is not None
                else None
            ),
            "minimum_step_flops_note": (
                "two GEMMs: forward XW and weight gradient X.T @ dY; "
                "inputs require no gradient, so no dX GEMM; elementwise work "
                "excluded from numerator, full step included in denominator; "
                "matmul-only lower-bound utilization, not full-model LLM MFU"
            ),
            "minimum_step_flops": minimum_step_flops,
            "input_requires_grad": inputs.requires_grad,
            "communication_scope": (
                "single GPU; use Advanced Labs 19 and 21 for communication evidence"
            ),
            "provisional_observation": provisional_observation,
            "publication_decision": "pending three independent run records",
        },
        correctness={"full_update_close": True},
    )
    print(f"Wrote one training capstone trial: {target_path}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/31_training_capstone.sbatch --workload small --variant-order baseline-first

# Optional profiling
sbatch slurm/31_training_capstone.sbatch --workload small --variant-order baseline-first --profiler all

Lab 32: Learn a weight and separate training from inference

This first exercise makes learning visible without a transformer, downloaded model or service. A scalar model predicts weight × input. Normal execution defaults to CPU; use --device cuda for the optional GPU path, which external diagnostics capture.

Complete source: labs/32_learning_basics.py
"""Observe one learned weight, autograd, an update and held-out inference."""

from __future__ import annotations

import argparse
from typing import Any

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def run_experiment(torch: Any, device: str) -> dict[str, Any]:
    # Create explicit input values on the selected device.
    inputs = torch.tensor([1.0, 2.0], device=device)
    targets = 2 * inputs
    weight = torch.nn.Parameter(torch.tensor(0.0, device=device))
    optimizer = torch.optim.SGD([weight], lr=0.1)
    loss_before = float(((weight * inputs - targets) ** 2).mean().detach())
    first_gradient = None
    for step in range(30):
        # Clear the previous step’s gradients before differentiating again.
        optimizer.zero_grad(set_to_none=True)
        predictions = weight * inputs
        loss = ((predictions - targets) ** 2).mean()
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        if step == 0:
            first_gradient = float(weight.grad)
        # Update the parameters using the gradients from this step.
        optimizer.step()
    optimizer.zero_grad(set_to_none=True)
    trained = weight.detach().clone()
    with torch.inference_mode():
        loss_after = float(((weight * inputs - targets) ** 2).mean())
        held_out = weight * torch.tensor(3.0, device=device)
    # Compare the computed values with the numerical reference.
    torch.testing.assert_close(
        weight, torch.tensor(2.0, device=device), rtol=1e-5, atol=1e-6
    )
    torch.testing.assert_close(
        held_out, torch.tensor(6.0, device=device), rtol=1e-5, atol=1e-6
    )
    if not torch.equal(weight.detach(), trained) or weight.grad is not None:
        raise AssertionError("Inference changed parameters or created gradients")
    return {
        "initial_weight": 0.0,
        "first_gradient": first_gradient,
        "final_weight": float(trained),
        "loss_before": loss_before,
        "loss_after": loss_after,
        "held_out_input": 3.0,
        "held_out_prediction": float(held_out),
        "weight_after_inference": float(weight.detach()),
        "updates": 30,
        "scope": "scalar FP32 mechanics; no transformer quality or performance claim",
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = (
        require_course_gpu(torch)
        if args.device == "cuda"
        else {"device": "cpu", "torch_version": torch.__version__}
    )
    operation = annotated_operation(run_experiment, "lab_workload")
    measurements = operation(torch, args.device)
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="32_learning_basics",
        environment=environment,
        measurements=measurements,
        correctness={
            "learned_expected_weight": True,
            "held_out_prediction_matches": True,
            "inference_preserves_parameters": True,
        },
    )
    print(f"Completed learning-mechanics experiment: {target}")


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/32_learning_basics.sbatch --device cpu --workload small

# Optional profiling
sbatch slurm/32_learning_basics.sbatch --workload small --profiler all

Course guides

Getting started

Read the course · Estimated guided time: 52 hours.

Connect the training objective to correct updates, memory use and GPU performance. Take GPU Fundamentals and GPU Performance Optimization first. Use GPU Performance Tools for profiler concepts and PyTorch for GPU Performance Engineering for a tensor-reading refresher.

Learning route

Begin with learning a weight, tokenization, the decoder and one correct update. Then study resume, memory, precision, recomputation and data pipelines before distributed training, adaptation and the capstone.

  • After Lesson 4, explain the path from labels to parameter updates and check masking and packing boundaries.
  • After Lesson 10, attribute single-GPU time and memory before adding ranks.
  • After Lesson 13, draw state placement and the communication critical path.
  • SFT/LoRA and GRPO practice can run locally; distributed practice has its own qualification in Advanced Labs.

Before the first lab

Follow the Lab Guide and Versions and environment for the approved runtime. Local GPU labs use one full H100; a qualified advanced cluster can supply that allocation.

Start Lesson 1 with Lab 32, a download-free CPU exercise: "$COURSE_PYTHON" labs/32_learning_basics.py --device cpu in the prepared course environment. After Lessons 1–4, follow Lab 01 for the first transformer run:

sbatch slurm/01_tiny_transformer_train.sbatch --workload small

Lab 22 is an optional FP8 extension. Default preparation includes its isolated Transformer Engine runtime. Qualify its matching PyTorch/CUDA environment and hardware separately; installation alone does not pass that gate.

Completion

Use Lab 31's trials experiment for at least three independent, unprofiled runs. Require finite gradients, valid updates, equivalent work and matching hardware/software before writing a causal report. DDP and FSDP2 practice continues in Advanced Labs 15–16 on the qualified fabric.

Use Where to Go Next for optional reading after the core route.

Reference guides

Versions and environment

Completed prepared-environment runs

All 16 practical labs completed both small and large profiles (32 verified exports) on the prepared NVIDIA H200 cluster. See lab results and the catalog validation record for evidence scope and limitations.

The recorded framework is PyTorch 2.14.0+cu130 with CUDA runtime 13.0. Lab 22 used Transformer Engine 2.19.0 in its separately prepared, compatible environment.

The observed profiler CLI/viewer pairs were Nsight Systems 2026.4.1 and Nsight Compute 2026.2.1; the scheduler reported Slurm 25.11.3. These runs qualify the recorded experiments in their prepared environments. They do not establish a clean installation, every optional extension, or performance on H100.

H100 target and installation candidates

The following targets and pending checks describe the H100 teaching environment. Keep them separate from the completed H200 evidence above.

The introductory Lab 32 was executed locally on CPU with the existing PyTorch 2.13.0 environment. This is algorithmic smoke evidence only: it does not qualify the clean target environment, authorize a dependency fallback or establish CUDA/H100 behavior. No additional dependency is needed for the lab.

ComponentCourse targetEvidence status
Python3.12Local environment exists; cluster parity pending
PyTorch2.14.0 manifest authorityClean Linux/H100 install and qualification pending; no fallback approved
Transformers, PEFT, TRL, datasets, accelerateExact candidate pins in requirements.txtClean target installation and joint compatibility pending
Transformer Engine2.19.0, isolated for Lab 22 using te.autocastH100 ABI and runtime pending
GPU and SlurmOne full H100; distributed qualification belongs to Advanced LabsLive validation pending

Do not use deprecated fp8_autocast examples. Record the actual Transformer Engine recipe, warm-up, PyTorch ABI, and kernels with FP8 results.

DDP bucket and hook qualification

Advanced Lab 21 uses the prepared PyTorch environment and the site-qualified NCCL stack. Hook support, actual bucket behavior and numerical trajectories require two-node H100 qualification. The Nsight launcher needs a compatible profiler on both nodes. CPU reference and launcher tests do not establish these live behaviors or training convergence.

Shared profiling qualification

Use the Lab Guide for the preparation and cluster-managed profiling route. Keep the matching CLI/viewer identities recorded with each run. Installation does not qualify the driver, either worker, the selected native runtime or optional container, or hardware-counter access; those claims require the relevant canaries and report inspections. Keep the existing AI runtime identities above; changing a profiler does not authorize changing those environments or adding collectors and metrics databases.

Prepared H200 runtime and applicable live profiler captures are recorded above. This campaign did not rerun the complete infrastructure installer or qualify the H100 target.

Advanced fabric qualification

The documented base target uses two one-H100 workers; all distributed GPU experiments now belong to the separate two-eight-H100 route. Eight-/sixteen-rank launchers require full devices with MIG disabled, NVLink peer paths and active InfiniBand. Physical topology checks do not replace Fabric Manager health, MPI/NCCL compatibility or GPUDirect registration qualification. No live 16-H100 qualification is claimed by these source changes.

The advanced course owns these fabric experiments and their selected native tool dependencies. Use the Lab Guide for preparation, retain the component build receipts, and qualify the same runtime on both nodes before accepting a comparison.

Readiness checks

Hardware scope: local GPU checks use one full, non-MIG H100. A qualified advanced cluster can supply one-GPU allocations. Distributed work follows the advanced course's separate fabric qualification.

This is a target-qualification checklist, not the lesson execution order. Follow the course for the learning route and complete each exercise's relevant safety/setup gate before running it. Distributed and optional checks qualify those paths; they are not prerequisites for earlier single-GPU lessons that do not use them.

Run from this course root after the Lab Guide has prepared the available lab software. Check its completion summary for failures or hardware skips affecting the selected lab. Launchers restore the saved runtime automatically; VERSIONS.md describes its scope. Preparation creates private log directories before Slurm opens its output. For these read-only local dependency checks, select the ordinary lab runtime:

source tools/course_env.sh 01_tiny_transformer_train --lab
"$COURSE_PYTHON" -m pip check
python3 tools/validate_course.py

Raw logs, checkpoints, traces, and result JSON remain private. Use evidence-security.md to prepare a separately reviewed aggregate report.

Causal objective and one-GPU correctness

sbatch slurm/32_learning_basics.sbatch --device cuda
sbatch slurm/13_loss_masking.sbatch --workload small
sbatch slurm/01_tiny_transformer_train.sbatch --workload small
sbatch slurm/02_gradient_accumulation.sbatch --workload small
sbatch slurm/14_activation_checkpointing.sbatch --workload small
sbatch slurm/21_mixed_precision_training.sbatch --workload small

Lab 32 can first be studied locally with --device cpu. Require a learned weight near 2, held-out prediction near 6 and unchanged parameters during inference. That CPU result does not qualify this explicit CUDA run and has no timing or language-quality interpretation.

Stop on invalid masks, non-finite gradients, missing gradients for any trainable parameter, or a failed update comparison. Lab 01 reports nonzero finite gradient norms, a tracked-parameter update delta, baseline allocation, and incremental timed peak allocation. Lab 21 compares loss, gradients, and updates from identical state under explicit precision tolerances.

Lab 01 checks gradient presence for every trainable parameter, but measures the update delta only for its first tracked parameter. This is not an all-parameter update-equivalence test.

Lab 14 compares no checkpointing, alternate-block checkpointing and all-block checkpointing. Loss and every trainable parameter gradient, including token and position embedding weights, must agree at BF16 rtol 0.01 and atol 0.01. Its inputs are integer token IDs: there is no continuous input gradient to compare. Check the loss and every trainable parameter gradient independently; agreement in one is not evidence that the other is correct.

Adaptation and reward-guided objectives

sbatch slurm/05_lora_sft.sbatch --workload small
sbatch slurm/06_grpo_objective.sbatch --workload small
sbatch slurm/07_grpo_trainer.sbatch --workload small

External model exercises require pinned, approved artifacts. Check trainable state, label/response boundaries, reward variance, and finite updates. Tiny runs demonstrate the objective and implementation; they do not establish held-out model quality or production training efficiency.

Precision, resume, and data efficiency

sbatch slurm/24_checkpoint_resume.sbatch --workload small
sbatch slurm/25_sequence_packing.sbatch --workload small
sbatch slurm/26_input_pipeline.sbatch --workload small
sbatch slurm/27_fused_graph_trace.sbatch --workload small

Resume must reproduce the next batch and update under the stated deterministic contract. Lab 25 proves packing capacity and attention-boundary mechanics; it does not execute packed-model loss. Add a corresponding model/label reference before claiming preserved valid-token loss or packed training throughput. A faster loader must preserve sample completeness; graph and fusion experiments retain unprofiled timing and their capture/compile costs.

Run the conditional FP8 gate only after a compatible Transformer Engine build and its recipe have been qualified in the approved environment:

sbatch slurm/22_transformer_engine_fp8.sbatch --workload small

Record the resolved version and recipe. Collect warmed delayed-scaling samples before and after timing, and require every output and gradient relative-L2 sample to remain within its declared threshold. The lab defaults are 0.2 for outputs and 0.3 for gradients; record any recipe-specific change explicitly. These FP8 thresholds are not the BF16 allclose tolerance used in Lab 14. A missing dependency leaves this extension pending.

Profiler and causal capstone

sbatch slurm/30_training_profiler.sbatch --workload small
sbatch slurm/31_training_capstone.sbatch --experiment trials --workload small

Retain all three fresh-process capstone records and confirm the launcher alternates candidate order. Separate profiling from acceptance timing; report each lab's actual time and memory fields and a rejected hypothesis. Lab 30 is a profiler exercise. Lab 31 measures a single-GPU linear update, logical row/token throughput and peak memory; its optional utilization uses a matmul-only FLOP numerator, not full-model MFU. Communication measurements belong to the separate distributed labs. A pending environment or H100 gate is never passed.

Distributed practice

Use Advanced Labs for placement, transport, collective and application checks on its qualified two-worker, sixteen-H100 fabric. Follow its lab-specific acceptance criteria; two one-GPU TCP workers do not establish fabric performance. These checks are not gates for the local experiments above.

Lab mechanisms and evidence

Lab 31: derive the work before reporting utilization

Objective: compare equivalent training updates and explain exactly what the reported FLOP numerator counts. The training capstone uses a small BF16 linear layer followed by GELU and an FP32 loss. It compares matrix multiplication followed by a separate bias addition with torch.addmm. This is a controlled optimization experiment, not a complete transformer MFU benchmark.

Follow the autograd graph

Let the input X have shape [T, H], weights W have shape [H, H], and output gradient dY have shape [T, H]. A multiply-accumulate convention counts one multiplication and one addition as two FLOPs. The forward product XW therefore costs approximately 2 × T × H² FLOPs. Training the weights needs dW = X.T @ dY, another product with the same work. Computing dX = dY @ W.T would add a third product, but only if the input requires a gradient.

The capstone inputs are fixed sampled data with requires_grad=False. Weights and bias require gradients. Consequently, the matrix-work numerator is 4 × T × H², not 6 × T × H². For T=16, H=8, that is 4096 rather than 6144 FLOPs. The latter overstates this workload by 50 percent. In a multilayer network an interior activation usually does require a gradient, so blindly applying the two-GEMM formula to every layer would also be wrong. Inspect the actual graph. The PyTorch autograd guide explains how gradient requirements affect recording and backward execution.

OperationCounted here?Reason
Forward matrix productYesProduces the hidden activations
Weight-gradient matrix productYesWeights are trainable
Input-gradient matrix productNoThis lab's sampled inputs require no gradient
Bias, GELU, loss and optimizer arithmeticNo; excluded from numeratorThe deliberately limited convention counts only GEMMs
Full training-step timeYes; used in denominatorIncludes the actual update operation
Run the comparison
  1. Predict the GEMM count and inspect input/parameter gradient flags in the source. Do not enable an unnecessary gradient just to match a formula.
  2. Run the three-trial capstone procedure. Every trial checks loss and complete parameter updates, warms both variants, and records repeated CUDA-event timings with alternating variant order across processes.
  3. Read minimum_step_flops, input_requires_grad, candidate_minimum_step_tflops, and the accompanying accounting note. Tokens/s is a separate rate; it does not require a peak-FLOP assumption.
  4. Supply --peak-tflops only with a disclosed, appropriate dense BF16 peak for the actual SKU/clock convention. Do not substitute a sparse marketing peak for this dense workload. Without a peak, utilization remains unset.
  5. Interpret candidate_matmul_utilization_percent as the counted matrix work divided by full-step time and the stated peak. It is a lower-bound, matmul-only utilization estimate, not full-model LLM MFU or a hardware counter.
Evidence, failure, and review

Retain shapes, precision, gradient flags, the FLOP expression, peak source, measurement boundary, numerical checks, distributions, and all three trial records. Extend the benchmark worksheet with these fields. The local regression profiles actual CPU autograd operations for both input gradient settings; it proves the counting logic, not BF16 H100 performance.

If utilization rises while tokens/s falls, check whether the work convention changed or extra recomputation was counted. If it exceeds 100 percent, check units, peak type, clock assumptions, included timed operations, and double counting before claiming exceptional hardware behavior. A low estimate alone does not identify memory, launch, input-pipeline, or communication bottlenecks: use the profiler and training phase evidence to distinguish them.

Review answer: the numerator follows the graph actually executed, while the denominator includes completion of the stated operations. General transformer MFU analysis must account for architecture, active parameters, token counts and the chosen recomputation convention; this small capstone does not establish it.

Interpret diagnostics and capstone evidence

Compute captures select one named operation, often a matrix kernel; Lab 06 selects objective reduction. A baseline or BF16 diagnostic does not characterize every backward pass, precision mode or update. Use Systems for the full schedule and retain separate numerical checks and unprofiled timings.

Labs 27 and 31 check finite gradients and reconstruct the expected plain-SGD update from each initial state. The capstone rejects missing or diagnostic timing provenance, requires experiment.instrumented to be exactly false, and checks matching hardware/software across independent trials.

Benchmark worksheet

Record stage, model/revision, tokenizer, dataset or synthetic-data contract, global tokens/update, microbatch and accumulation, shapes, dtypes, precision recipe, parallel placement, checkpoint boundary, software/H100 environment, loss/gradient/update checks, step-time samples, tokens/s, phase memory, communication, MFU formula, profiler evidence, and keep/reject decision.

Raw data, checkpoints, logs, prompts, and scheduler details remain private.

Comparison worksheet

Copy this worksheet into the private experiment record before changing one factor. Fill both columns for equivalent work; mark unavailable evidence explicitly. Retain raw artifacts privately and publish only separately reviewed aggregates following evidence-security.md.

FieldBaselineCandidate / observation
Date and random course run ID (keep artifact location private)To recordTo record
Lab, source/commit identity, exact arguments, single changeTo recordTo record
H100 SKU, node/rank count, MIG state, topology class (no asset IDs)To recordTo record
Approved environment lock or immutable image; driver/CUDA/framework/NCCL/Slurm versionsTo recordTo record
Input shapes, layouts, dtype, seeds, batch/workload semanticsTo recordTo record
Primary metric, timer, included operations, completion condition, correctness/quality tolerancesTo recordTo record
Warm-up, measured iterations, three independent trial IDs and orderTo recordTo record
Correctness result and maximum error; missing/non-finite dataTo recordTo record
Raw timing distribution, minimum, median, p90/p95 and dispersionTo recordTo record
Baseline allocated memory, peak allocated/reserved memory, incremental peakTo recordTo record
Sanitized profiler observation, selected range/kernel, tool versionTo recordTo record
Supporting observation and disconfirming controlTo recordTo record
Decision: keep, reject, or investigate; limitation and next experimentTo recordTo record
Training stage, model/tokenizer immutable revisions, dataset/license or synthetic contractTo recordTo record
Global valid tokens/update, microbatch, accumulation, sequence distributionTo recordTo record
Loss, every parameter gradient and full update checks; checkpoint/resume boundaryTo recordTo record
Weights, gradients, optimizer, activations, communication and phase-specific peaksTo recordTo record
Step time, valid tokens/s, MFU formula/peak denominator and HFU distinctionTo recordTo record
Lab 31 input requires-grad, two-GEMM 4TH² numerator, excluded elementwise work, dense BF16 peak source, matmul-only utilization (not full-model MFU)To recordTo record
Precision/FP8 recipe, parallel placement, slowest-rank and communication evidenceTo recordTo record
Lab 33 cap/hook, actual startup/measured buckets, slowest-rank step samples, reference/trajectory errors and pending convergence gateTo recordTo record

A faster result is accepted only when its declared correctness, workload, timed operations, and environment constraints all hold. Record rejected hypotheses and slower candidates; they are useful evidence for the next choice.

Evidence and privacy

The course source is designed to be public, but runtime evidence is sensitive by default. Slurm output, checkpoints, model-cache paths, server logs, metrics, and request traces can contain infrastructure identifiers, filesystem paths, model names, prompts, or environment details.

Collect privately

  1. Use synthetic or explicitly public prompts, datasets, and models. Do not use customer prompts, credentials, proprietary model inputs, or regulated data.
  2. Complete software preparation in the Lab Guide and review its completion summary. Follow the Lab Guide’s guidance for any failures or hardware skips before submitting. Its private parent directories protect scheduler logs even when Slurm opens them before the job body starts.
  3. Keep results/, checkpoints, model caches, metrics, server logs, and Slurm output in storage that only approved course participants can read.
  4. Do not pass credentials on command lines or enable shell tracing. Remove unrelated secret-bearing environment variables according to site policy.
  5. Never commit generated evidence. The course .gitignore is not an access-control or redaction boundary.

Shared viewer copies

A successful profiling stage automatically delivers a verified copy of its native reports to the installed Nsight viewer directory. These copies are readable by the existing shared viewer audience; the viewer does not provide per-user report isolation. Submit only workloads whose report contents are approved for that audience. Private originals, logs and other results remain in the job directory. Check viewer_delivery and use the exact viewer paths printed by the job; no manual copy or permission change is needed after sbatch.

Share summaries, not raw artifacts

Before material leaves the approved environment, create a separate summary that excludes:

  • hostnames, node lists, job IDs, GPU UUIDs, serial numbers, and account or project identifiers;
  • usernames, home directories, executable paths, internal endpoints, and private repository or model-cache paths;
  • environment-variable values, tokens, cookies, request headers, credentials, and command lines that expose them;
  • customer data, private prompts, unpublished model names, raw traces, raw server logs, and generated text that is not explicitly public.

Report only the evidence needed for the learning decision: anonymized run ID, node count, GPU family, software versions, public workload definition, correctness result, aggregate training or serving metrics, and a written interpretation. Redact by creating a new file; do not overwrite the private original.

Course-specific safeguards

  • JSON, checkpoints, client results, server logs, and metrics use a random run ID instead of a Slurm job ID.
  • New private artifacts are created exclusively with owner-only permissions; verified viewer copies use the shared access described above.
  • Serving endpoints are loopback-only; distributed worker traffic still requires a trusted private fabric and site-approved network controls.
  • The normal course validator performs static validation and does not execute Python labs, load models, start servers, or submit Slurm launchers.
  • The portable tree rejects generated caches, and launchers disable Python bytecode creation before Python starts.

Live site policy remains authoritative. If model access, serving, or evidence collection is not approved, record a sanitized blocker and ask the cluster owner rather than weakening permissions.

Where to Go Next

These optional directions extend the training course without adding required experiments, changing its H100 environment or implying production-scale qualification. They include both recent tooling and established concepts with evolving implementations. Start with model interoperability or numerical recipes; study the distributed topics after you can explain the course's checkpoint and parallelism mechanics.

Choose one direction and apply the course’s reasoning to a new example. Keep its stated scope and qualification limits in your comparison.

  • Megatron Bridge and checkpoint interoperability

    Megatron Bridge connects Hugging Face model representations with Megatron Core's distributed training representations through checkpoint conversion and training recipes. Moving a model involves more than copying tensor files: configuration, parameter naming and partitioning must preserve the same computation. Investigate: Which configuration and numerical checks would demonstrate that a conversion to Megatron and back preserved a model? Scope: Evolving NVIDIA tooling; the documentation records a 0.5.0 release on June 22, 2026. Conversion support and memory requirements are model-specific; an available recipe need not fit one or two H100s. Explore Megatron Bridge.

  • Block-scaled low-precision training

    A low-precision recipe specifies scaling, rounding and the representations of forward and backward tensors, not just a dtype. Block-scaled formats assign scales to groups of values, introducing additional metadata and layout decisions. This extends the FP8 lesson into the relationship between numerical accuracy, transposition and buffer storage. Investigate: Why can transposing a block-scaled tensor require requantization, and which extra buffers belong in the memory budget? Scope: Established FP8 foundation with newer formats. Ordinary FP8 paths can target H100; the documented native MXFP8 and NVFP4 training paths target Blackwell. Do not treat those formats as interchangeable H100 settings. Study Transformer Engine's FP8 and FP4 primer.

  • Training resiliency and recovery boundaries

    Resiliency combines detecting failed or stalled work, preserving recoverable state and restarting from a valid point. It extends checkpoint correctness into an operational question: who detects the failure, coordinates workers and decides which state can be trusted? Investigate: How would you distinguish a slow but healthy training step from a hang without repeatedly discarding useful work? Scope: Established problem with evolving recovery tooling. Megatron Bridge documents Slurm-only fault-tolerance/preemption integrations and experimental rerun or in-process-restart features. These require independent qualification, not changes to the course's learner-managed scheduler. Read the training resiliency guide.

  • DeepEP and specialized expert dispatch

    DeepEP provides token-dispatch and combine communication for mixture-of-experts (MoE) models. Replacing a general dispatcher can change communication buffers, routing metadata and overlap while leaving the expert computation conceptually unchanged. The engineering task is to preserve token accounting and training semantics while measuring the complete step. Investigate: Which output, gradient and routing checks must remain valid when the dispatcher changes? Scope: Evolving implementation. Current upstream requirements include Hopper-compatible hardware and appropriate NVLink/RDMA connectivity. Do not infer support from H100 ownership or a broader integration-page claim; check the exact dispatcher revision and topology. Read DeepEP's requirements and NVIDIA's expert-parallel integration guidance.

  • Hierarchical context parallelism

    Hierarchical context parallelism partitions long-context work using different communication patterns within and between GPU groups. It makes network topology part of the execution plan: a fast local group and a slower inter-group link need not use the same exchange strategy. Investigate: When would local all-to-all exchange plus inter-group ring communication be preferable to gathering every key/value tensor everywhere? Scope: Advanced distributed study with evolving support. Group sizes, sequence divisibility, key/value-head counts and Transformer Engine versions constrain valid configurations. The course's two-rank mechanics lab does not demonstrate production hierarchical scaling. Study hierarchical context parallelism.

  • Hybrid state-space and attention models

    A state-space sequence layer summarizes earlier inputs in a state carried from one sequence step to the next. Each new input updates that state and produces an output from it. Mamba uses input-dependent rules to control which information the state retains. Hybrid models combine such layers with attention. Their computation and state requirements differ from those of an all-attention transformer. Studying them tests which activation-memory, recomputation and parallelism assumptions generalize beyond the model used in the labs. Investigate: Which stored activations and backward computations change when an attention layer is replaced by a state-space layer? Scope: Evolving model recipes, not an equivalent-computation optimization. Changing architecture requires suitable weights or training, and model-specific kernels and parallelism support. No single-H100 fit is implied. Explore NVIDIA's Nemotron 3 Nano hybrid-architecture guide.

Glossary

Activation checkpointing
Discarding selected forward activations and recomputing them during backward to trade compute for memory.
AdamW
An adaptive optimizer that tracks moving averages of gradients and squared gradients while applying weight decay separately from the gradient-based update.
Attention mask
A rule selecting which token positions may attend to which others, such as blocking future tokens or separating packed examples.
Autocast
PyTorch's operation-specific choice of computation dtype inside a mixed-precision region; it does not uniformly convert every operation to the same dtype.
Autograd
Automatic differentiation that records operations and computes gradients during the backward pass.
Backward pass
Propagating loss derivatives through recorded operations to compute gradients for trainable parameters.
BF16
Bfloat16, a 16-bit floating-point format with a wide exponent range and fewer significand bits than FP32.
Checkpoint
Saved training state used to restore and continue a computation.
Collation
Combining individual examples into the batch structure consumed by the model.
Communication hook
A registered DDP operation that transforms and communicates ready gradient buckets, returning their eventual result.
Context parallelism
Sharding long sequence context or attention work across ranks to reduce activation pressure, with communication of key/value or partial-attention state.
Cross-entropy
For a known target token, minus the natural logarithm of its predicted probability; aggregate over valid labels only.
CUDA Graph
A graph of operations and dependencies that can be instantiated and launched repeatedly. CUDA supports explicit construction and stream capture; these labs use PyTorch capture with its storage and operation constraints.
DCGM
NVIDIA Data Center GPU Manager; provides GPU health and telemetry facilities.
DDP
DistributedDataParallel; one model replica per rank with gradient synchronization, commonly by all-reduce.
DP
Data parallelism: replicas process different examples while synchronizing gradients to preserve the same global optimizer update.
Effective batch
All examples or tokens contributing to one optimizer update.
Embedding
A learned vector representation retrieved for a token ID before the model processes the sequence.
EOS
End-of-sequence token; a signal that may terminate generation, distinct from reaching a length limit.
EP
Expert parallelism; distributing the experts in a mixture-of-experts model across ranks and routing tokens to their owners.
Epoch
One complete pass through the training dataset under the declared sampling policy.
Error feedback
State that carries a previous compression residual into later gradient communication.
Exposed communication
Communication that remains on the critical path after useful overlap.
FLOP / FLOP/s
Floating-point operation / floating-point operations per second; a work count and a rate, respectively.
Forward pass
Computing model outputs from inputs using the current parameters.
FP16
16-bit floating point; its limited exponent range can require gradient scaling during training.
FP32
32-bit floating point; used here for reference calculations and selected parameter, gradient or optimizer state.
FP8
Eight-bit floating-point formats used with suitable scaling and supported arithmetic paths.
FSDP2
PyTorch fully sharded data parallel APIs based on per-parameter sharding, used to distribute parameter, gradient, and optimizer-state storage.
Fusion
Combining operations so intermediate traffic or launch overhead is reduced.
GELU
Gaussian error linear unit; a smooth nonlinear activation used in transformer feed-forward layers.
Generalization
Performance on relevant data not used to fit the evaluated model; lower training loss alone does not establish it.
GQA
Grouped-query attention; multiple query heads share a smaller set of key/value heads, changing the attention architecture and K/V storage.
Gradient
The derivative of loss with respect to a parameter, indicating its local sensitivity.
Gradient accumulation
Summing gradients from multiple microbatches before one optimizer step to increase effective batch size without storing all activations together.
Gradient clipping
Limiting gradient magnitude, for example by a maximum global norm, before the optimizer update.
Gradient scaling
Multiplying an FP16 loss before backward, then unscaling gradients before inspection or update, to reduce underflow risk while skipping unsafe updates.
Grouped GEMM
Grouped general matrix multiplication; executing several matrix products through one grouped implementation, for example to process local experts with fewer separate launches.
GRPO
Group relative policy optimization; a reinforcement-learning objective using relative rewards within sampled groups. The course's small objective lab is instructional, not a full production recipe.
HBM
High-bandwidth memory attached to the GPU and used for model state, activations, workspaces, and caches.
HFU
Hardware FLOP utilization; executed hardware FLOP/s divided by a declared aggregate peak. It can include recomputation or other work that does not increase useful model progress.
Host-to-device transfer
Copying input bytes from CPU-accessible memory into GPU memory; distinct from submitting the command that starts a kernel.
KL divergence
Kullback–Leibler divergence, a directional measure of the difference between probability distributions; a sampled estimator is not exact full-policy divergence.
Learning rate
The step-size factor in an optimizer's update, not a guaranteed rate of useful learning.
Length bucketing
Grouping examples or requests with similar token lengths to reduce padding while balancing extra batches and launches.
LLM
Large language model; a model trained to process and generate language tokens.
Logit
An unnormalized model score for a vocabulary candidate.
LoRA
Low-rank adaptation, which freezes base weights and trains small low-rank update matrices.
Loss mask
Labels set to an ignore value so padding or selected prompt positions do not contribute to training loss.
MFU
Model FLOP utilization; estimated useful model FLOP/s divided by a declared aggregate peak, with the model-FLOP formula and precision denominator disclosed.
Microbatch
A smaller group of examples processed in one forward/backward pass; several microbatches can accumulate gradients for one optimizer update.
MLP
Multilayer perceptron; learned linear layers with nonlinear activations that transform each token position’s representation.
MoE
Mixture of experts; a model layer that routes tokens to a subset of specialized expert networks.
MSE
Mean squared error; the average squared difference between predictions and targets.
Nsight Compute
A kernel profiler used for selected-kernel metrics, including roofline, traffic, instruction, scheduler, stall, and occupancy evidence.
Nsight Systems
A system profiler used to inspect the temporal relationship among CPU work, CUDA APIs, kernels, copies, synchronization, NVTX ranges, and communication.
NVTX
NVIDIA Tools Extension Library, an annotation API for named markers and ranges; it does not synchronize or time GPU work by itself.
Old policy
Frozen behavior policy used to sample the rollout whose probability ratios enter the update.
Optimizer
An update rule, such as SGD or Adam, that uses gradients and possibly stored state to change parameters.
Padding
Extra positions that make variable-length examples fit a common tensor shape; padded positions must be handled correctly by attention and loss masks.
Parameter / weight
A learned numeric value that affects a model's output; activations are intermediate values computed from inputs and parameters.
PEFT
Parameter-efficient fine-tuning; adapting a subset of parameters or added small parameter sets instead of updating every base weight.
Pinned buffer
Page-locked host memory used for asynchronous host/device transfers; pinning and allocation have costs.
Policy ratio
exp(new log probability minus old log probability) for a sampled action/token.
PowerSGD
Low-rank gradient compression for stochastic gradient descent (SGD), with configurable startup, rank, error feedback and warm start.
PP
Pipeline parallelism; placing different layer ranges on different ranks and scheduling microbatches through the stages.
Prefetch
Preparing future batches before the consumer requests them.
PyTorch Profiler
The framework profiler that attributes CPU and CUDA activity, calls, shapes, memory, and stacks to PyTorch operators.
Queue depth
The number of prepared batches waiting for consumption.
Reference policy
Separate anchor used by a recipe's divergence penalty; not necessarily the old policy.
RNG
Random-number generator; its state helps reproduce stochastic operations when saving and restoring training.
RoPE
Rotary positional embeddings; rotations of query/key components that encode position in attention.
Sequence packing
Placing multiple examples into less padded storage while preserving boundaries.
SFT
Supervised fine-tuning on prompt/target or instruction/response examples.
SGD
Stochastic gradient descent; an optimizer family that updates parameters using gradients estimated from sampled data.
SHARP
Scalable Hierarchical Aggregation and Reduction Protocol; NVIDIA networking technology that can offload supported reduction work into a qualified fabric.
Softmax
Transformation of scores into nonnegative probabilities summing to one.
Starvation
A wait caused by the next required input batch not being ready.
Strong scaling
Adding ranks while total useful work remains fixed.
TF32
TensorFloat-32; a reduced-mantissa compute mode for selected FP32 matrix operations on supported NVIDIA hardware, not a tensor storage dtype.
Throughput
Completed requests or tokens per second for a declared workload and boundary.
Token
A model’s unit of text representation, mapped to an integer by its tokenizer; it need not be a whole word.
Token-weighted loss
Loss aggregated by the number of valid labels rather than by equally averaging batches with different valid-token counts.
Tokenization
Converting text into token IDs using the selected vocabulary and tokenization rules.
TP (tensor parallelism)
Splitting selected tensor operations within model layers across ranks, requiring communication during inference or training.
Training
Adjusting model parameters using data and an objective, then checking whether the resulting model generalizes to examples not used for those updates.
Transformer Engine
NVIDIA library for optimized transformer layers and low-precision recipes.
ZeRO
Zero Redundancy Optimizer; techniques that partition optimizer states, gradients and, at later stages, parameters across data-parallel ranks.

Official references

  1. PyTorch beginner tutorial: optimizing model parameters
  2. PyTorch beginner tutorial: automatic differentiation
  3. Transformer Engine NVFP4 and stochastic rounding: Blackwell comparison, not an H100 lab
  4. PyTorch cross-entropy loss, logits and ignored labels
  5. PyTorch automatic mixed precision
  6. PyTorch distributed overview
  7. PyTorch DistributedDataParallel gradient semantics
  8. Hugging Face padding-free training and sample boundaries
  9. PyTorch FSDP2 tutorial
  10. PyTorch activation checkpointing
  11. NVIDIA Transformer Engine
  12. Transformer Engine PyTorch API
  13. Transformer Engine low-precision training introduction
  14. Transformer Engine FP8 recipes
  15. Megatron Core parallelism guide
  16. Megatron Core distributed optimizer
  17. Megatron Core mixture-of-experts guidance
  18. NVIDIA CUTLASS grouped GEMM scheduling
  19. Hugging Face PEFT LoRA
  20. Hugging Face TRL GRPO Trainer
  21. Slurm sbatch
  22. DDP communication hooks and PowerSGD state
  23. DDP bucket sizing and hook contract
  24. NVIDIA Megatron activation recomputation: full and selective granularity
  25. CUDA Graphs: explicit construction and stream capture
  26. Nebius GPU platforms and presets
  27. NVIDIA nvbandwidth, reviewed source
  28. RDMA perftest, reviewed source
  29. GPUDirect RDMA
  30. PyTorch profiler recipe
  31. Nsight Systems user guide
  32. Explore Megatron Bridge
  33. Study Transformer Engine's FP8 and FP4 primer
  34. Read the training resiliency guide
  35. Read DeepEP's requirements
  36. NVIDIA's expert-parallel integration guidance
  37. Study hierarchical context parallelism
  38. Explore NVIDIA's Nemotron 3 Nano hybrid-architecture guide
  39. PyTorch autograd guide