Inside One Training Update: Compilation, FlashAttention and AdamW
One training update has to answer two sets of questions: how to compute the numbers, and how to change parameters once gradients are available. torch.compile and FlashAttention primarily address execution; AdamW, clipping and learning-rate scheduling address updates. Vocabulary padding can also affect the loss definition. Gradient accumulation determines how much data contributes to one update.
The setting is a GPT-2 causal language model: inputs and targets are Token IDs shifted by one position, and the forward pass runs through embeddings, Blocks and an output projection. See the training and inference overview for the complete network. Small arrays and animations here are illustrative examples, not measured GPT parameters or hardware benchmarks.
Compilation reuses a program that reads current parameters
A GPU kernel is a computation program dispatched to the GPU. The CPU runs Python and framework scheduling; the GPU performs numerical work. For y = (x + bias) * scale, an unfused implementation may add, write an intermediate result, then read it back to multiply. Fusion can perform the operations together, reducing launches and intermediate reads and writes.
One Python line does not necessarily mean one kernel. An operator may invoke several kernels, and several operations may fuse. Heavy arithmetic, heavy data movement and frequent launches of small operations are different bottlenecks.
torch.compile captures regions it can handle, passes them to a backend for optimization and caches execution programs. It can reduce Python overhead, fuse operations and avoid some intermediates. It does not cache one permanent answer from the model. Each call still reads the current input and parameters. PyTorch 2.2 compile API.
raw_model = GPT(config).to(device)train_model = torch.compile(raw_model) # Wrap once, outside the loop.optimizer = torch.optim.AdamW(raw_model.parameters(), lr=3e-4)
# In the loop: train_model(x) → loss → backward → optimizer.step()GPT refers to an already defined model class. The optimizer manages the original Parameters, which the compiled entry point also reads. An ordinary numerical update does not turn the model into a different architecture; the next batch uses the updated values.
| Situation | What happens | Why it matters |
|---|---|---|
| First execution | Capture, compilation and cache preparation may occur | First-step time is not steady-state speed |
| Graph break | A region cannot remain in the same graph, splitting execution | Less can be optimized; dispatch overhead can return |
| Recompilation | Shapes, types or other guards change, requiring another program | Later calls may incur compilation costs too |
Wrapping only the model does not imply that data loading, an external loss function and the optimizer are compiled. The scope depends on the function supplied and what is captured. Compare performance under fixed conditions; compilation does not promise bitwise-identical floating-point results either.
FlashAttention: the same formula, fewer large intermediates to move
For one attention head:
Q, K, V: [T,d]S = QKᵀ / √d [T,T]A = softmax(S + causal_mask) [T,T]O = AV [T,d]An explicit implementation forms scores S and weights A, then uses A to aggregate V. At T=1024, a single T×T matrix for one sample and one head contains 1,048,576 elements. Writing these intermediates and reading them again consumes memory bandwidth.
FlashAttention brings tiles of Q/K/V into on-chip storage and organizes local scores, masking, normalization and output accumulation together, avoiding full S/A matrices in high-bandwidth memory, HBM. The main arithmetic cost of dense attention still grows with T²; what changes is where intermediates live and how they are moved. Ordinary matrix multiplication also tiles. The key here is organizing multiple attention operations together. FlashAttention, §3.
★ How can we obtain the same O without a complete A?
Fix one query and one coordinate of V. All four positions are visible, with already scaled scores s=[ln 1, ln 2, ln 3, ln 4], so exp(s)=[1,2,3,4]. Their values are v=[10,20,30,40]. Dropout is zero in this example.
Denominator l = 1 + 2 + 3 + 4 = 10Unnormalized numerator u = 1×10 + 2×20 + 3×30 + 4×40 = 300Output o = u/l = 30Process the first two positions, then the last two:
| Positions processed | Accumulated l | Accumulated u | Current u/l |
|---|---|---|---|
| 0, 1 | 3 | 50 | 16.6667 |
| 0, 1, 2, 3 | 10 | 300 | 30 |
Accumulating numerator and denominator before dividing is equivalent to first computing every probability and then the weighted sum. With d value coordinates, u is a d-dimensional vector, with one shared denominator l for that query. Each query has separate accumulator state.
For numerical stability, subtract the largest score seen so far, m, instead of letting exp(s) grow without bound. When a tile introduces a new maximum, the old accumulators must change scale:
m_new = max(m_old, maximum visible score in the current tile)α = exp(m_old − m_new)p_j = exp(s_j − m_new) # Current tile; masked entries are 0.
l_new = α l_old + Σ_j p_ju_new = α u_old + Σ_j p_j v_jo = u_new / l_newWhy multiply both old accumulators by α? Every old exponential satisfies:
exp(s − m_new)= exp(s − m_old) × exp(m_old − m_new)Both old numerator and denominator must use the new scale. In this example, the first tile gives m=ln 2, l=1.5, u=25. The second raises the maximum to ln 4, so α=1/2:
l_new = 0.5×1.5 + 3/4 + 1 = 2.5u_new = 0.5×25 + (3/4)×30 + 1×40 = 75o = 75/2.5 = 30Adding independently normalized tile outputs would be wrong: each tile has a different denominator. A fully masked tile contributes nothing; real kernels must also handle boundary cases such as empty rows. During backward, saved Q/K/V, outputs and normalization statistics allow local reconstruction of attention weights, trading extra computation for less intermediate storage. Floating-point operation order can introduce small differences.
Change the query position to see future positions excluded. Add 1000 to every score: stable accumulation still produces the same output. Each step shows partial state; only the final result includes all visible positions.
The interface and the selected backend are separate
PyTorch’s SDPA can replace explicit scores, masking, softmax and multiplication by V:
heads = F.scaled_dot_product_attention( q, k, v, # [B,H,T,d] dropout_p=0.0, is_causal=True,)Head concatenation, output projection and the residual addition still follow. SDPA is an interface; FlashAttention is one possible backend. Device, dtype and shape affect selection, so a successful call does not establish that FlashAttention ran. With nonzero dropout, the caller must pass the appropriate probability for training or evaluation; the function does not read the enclosing model’s eval() state. PyTorch 2.2 SDPA documentation.
Why do 47 extra vocabulary rows affect the loss?
GPT-2 has 50,257 real vocabulary entries. The course pads the model dimension to 50,304=393×128, adding 47 rows to obtain a more favorable matrix shape. More logical arithmetic may still take less time when alignment improves utilization. The benefit depends on hardware and kernels; it is not a universal “all GPUs tile by 128” rule. The course’s vocabulary-padding change.
| Object | Original | Padded |
|---|---|---|
| Real tokenizer IDs | 0–50,256 | Unchanged |
| Shared E / lm_head | 50,257×768 | 50,304×768 |
| Hidden states | B×T×768 | Unchanged |
| Logits | B×T×50,257 | B×T×50,304 |
This adds 47×768=36,096 shared parameters, counted once. It does not add 47 text mappings to the tokenizer. Generation must exclude extra output IDs with no mapping.
The training issue is that extra classes participate in an unmasked softmax denominator even when they are never correct targets. At one position, with no label smoothing:
p_j = exp(z_j) / Σ_k exp(z_k)L = −log p_y∂L/∂z_j = p_j − 1[j=y]An extra class receives positive gradient p_j. Through the output projection it affects hidden states and the shared table; its probability is not automatically zero. Consider three valid classes, with target ID 2:
| Logits and treatment | Loss | Gradients of the three valid columns | Extra gradients |
|---|---|---|---|
[1,2,3] | 0.407606 | [0.090031, 0.244728, −0.334759] | — |
Add [4,5], include all | 2.451914 | [0.011656, 0.031685, −0.913871] | [0.234122, 0.636409] |
Add [4,5], exclude before loss | 0.407606 | [0.090031, 0.244728, −0.334759] | [0,0] |
The original course change computes cross-entropy over the padded width. To preserve the original valid-class objective, complete the wide projection and then slice the valid logits for the loss:
logits = model(x) # The model still computes all 50304 projection columns.valid = logits[..., :50257]loss = F.cross_entropy(valid.reshape(-1, 50257), y.reshape(-1))Alternatively, set extra logits to −∞ before cross-entropy without label smoothing. Setting them to zero fails because exp(0)=1. ignore_index ignores target positions, not selected output classes at every position. Label smoothing over all classes, including −∞ logits, causes problems; define the loss over valid classes instead. Cross-entropy definition.
Given identical valid logits, slicing recovers the same mathematical objective. Slicing, potential copies and loss computation have performance costs that need separate assessment. Zero current loss gradient for an extra column does not mean its parameters are permanently frozen: existing momentum and weight decay can still act.
Gradients describe local change; AdamW chooses the update
The calculation has now produced a loss and parameter gradients. backward() writes contributions into .grad; optimizer.step() changes the parameters.
For a scalar parameter w, ordinary SGD uses w ← w−ηg. Adam maintains two histories: m is an exponential moving average of gradients, and v an exponential moving average of squared gradients. Every element has its own m/v. For a 768×768 parameter, both state tensors have that shape too.
| Symbol | Meaning |
|---|---|
| g_t | Gradient used for parameter update t |
| m_t | Recent direction history, retaining signs |
| v_t | Recent squared-gradient scale; an uncentered second moment |
| β₁, β₂ | History retention coefficients in [0,1) |
| η_t, λ, ε | Learning rate, weight decay and denominator stabilizer |
v is neither a variance nor a second derivative. Adam stands for Adaptive Moment Estimation; m and v estimate first and second moments. Adam paper.
Standard AdamW, without AMSGrad, updates elementwise:
m_t = β₁m_(t−1) + (1−β₁)g_tv_t = β₂v_(t−1) + (1−β₂)g_t²
m̂_t = m_t / (1−β₁ᵗ)v̂_t = v_t / (1−β₂ᵗ)
w_t = (1−η_tλ)w_(t−1) − η_t m̂_t / (√v̂_t + ε)t starts at 1 and counts optimizer updates for that parameter. Squares, roots and division are elementwise for matrices as well. The next recurrence uses raw m/v; do not overwrite them with corrected estimates. PyTorch 2.2.2 AdamW implementation.
W means decoupled Weight Decay: decay acts directly on parameters instead of entering m/v as part of the gradient. With adaptive optimizers this generally differs from adding an L2 penalty to the loss. Parameter groups can set λ=0 for selected parameters, which can still receive Adam updates. AdamW paper.
Two updates: a gradient reversal need not reverse the history
Use teaching values w₀=1, m₀=v₀=0, β₁=0.9, β₂=0.95, η=0.01, λ=0.1, ε=10⁻⁸, with gradients 0.2, −0.1. These are convenient arithmetic choices, not GPT hyperparameter recommendations.
Step 1: m₁=0.02, v₁=0.002Corrected: m̂₁=0.2, v̂₁=0.04w₁ ≈ 1 − 0.001 − 0.01×0.2/0.2 = 0.989
Step 2: m₂ = 0.9×0.02 + 0.1×(−0.1) = 0.008 v₂ = 0.95×0.002 + 0.05×0.01 = 0.0024| t | g_t | m̂_t | v̂_t | w_t, including ε |
|---|---|---|---|---|
| 1 | 0.2 | 0.2 | 0.04 | 0.9890000005 |
| 2 | −0.1 | 0.042105 | 0.024615 | 0.9853273062 |
The second gradient is negative, but m remains positive, so the parameter still decreases in this example. m smooths sudden changes but introduces lag. Both numerator and denominator depend on gradient history; “larger gradients always make AdamW move more slowly” is too simple.
★ Where the bias-correction denominator comes from
The correction addresses m/v starting at zero. Set β=β₁, m₀=0 and expand three updates:
m₁ = (1−β)g₁m₂ = β(1−β)g₁ + (1−β)g₂m₃ = β²(1−β)g₁ + β(1−β)g₂ + (1−β)g₃
m_t = (1−β) Σ_(i=1…t) β^(t−i) g_iGradient i has coefficient (1−β)β^(t−i). To sum them, let S=1+β+⋯+β^(t−1) and subtract its shifted copy:
S − βS = (1+β+…+β^(t−1)) − (β+β²+…+βᵗ) = 1−βᵗS = (1−βᵗ)/(1−β)
Total gradient coefficient C_t = (1−β)S = 1−βᵗThe remaining βᵗ multiplies the initial m₀, which is zero. Dividing by 1−βᵗ normalizes the coefficients of the gradients actually observed.
At β=0.9, the second update gives:
m₂ = 0.09g₁ + 0.10g₂m̂₂ = m₂/0.19 = (9/19)g₁ + (10/19)g₂With g₁=2, g₂=4, we get m₂=0.58, m̂₂≈3.052632. The coefficients sum to one; the gradient estimate need not equal one or lie between zero and one. Distributing division over the sum shows that normalizing the coefficients first and dividing the whole weighted sum are the same operation.
An expected gradient is not the number observed this time
In a separate example, the gradient is 0.1 or 0.3 with equal probability. Thus μ=E[g]=0.2. The first observed gradient is 0.1 or 0.3, giving m₁ of 0.01 or 0.03; E[m₁]=0.02.
If gradients at all steps have the same expectation μ, linearity of expectation gives:
E[m_t] = (1−β) Σ_i β^(t−i) E[g_i] = (1−βᵗ)μ
E[m̂_t] = E[m_t]/(1−βᵗ) = μUnder that assumption, the corrected estimate is unbiased; the argument does not require independent gradients. Real training changes parameters and typically the gradient distribution too. In general the corrected value estimates a normalized weighted average of historical expectations, not necessarily the current gradient expectation. Coefficients sum to one for any sequence; individual estimates do not have to equal μ.
Replace g by g² to derive the correction for v, but do not replace E[g²] with E[g]²:
E[g²] = 0.5×0.1² + 0.5×0.3² = 0.05E[g]² = 0.2² = 0.04Their difference is the variance. Statements about the separate expectations of m̂ and v̂ also do not imply that a nonlinear update involving a square root and ratio is unbiased. AdamW never needs μ as an input; it is used to analyze the recurrence.
Four backward passes, one update: where accumulation lives
A larger batch lets one update use more examples, but increases peak activation storage. Gradient accumulation divides the data into microbatches, runs forward and backward with the same parameters, adds the gradients and updates once at the end.
Use one device with B=2, T=32, K=4. Each microbatch has 64 valid prediction positions; one update covers eight sequences and 256 positions. Splitting along the batch dimension preserves each sequence’s length of 32. Cutting one long sequence into four pieces changes its context and is a different operation.
If each L_i already averages its 64 positions:
L_i = (1/64) Σ_(b,u) ℓ_(i,b,u)L_effective = (L₁+L₂+L₃+L₄)/4 = (1/256) Σ_(i,b,u) ℓ_(i,b,u)
G = ∂L_effective/∂W = (1/4) Σ_i ∂L_i/∂W = (g₁+g₂+g₃+g₄)/4Call (loss/4).backward() for each microbatch. Averaging within a microbatch and across microbatches addresses two different dimensions. PyTorch adds every contribution to the same W.grad; four complete computation graphs need not be retained. Gradient-accumulation usage.
The top-left entry accumulates 0.5+1+1.5+2=5, equal to (2+4+6+8)/4. Every entry adds independently; the matrix shape stays the same.
With zero_grad(set_to_none=True), the program starts at .grad=None; the first backward creates the gradient and later passes add to it. The zero matrix in the diagram is a mathematical starting point. Clearing every microbatch discards earlier contributions. Stepping every microbatch changes parameters and m/v in between, producing four small-batch updates instead.
Three conditions matter:
- Unequal valid-position counts require weighting, not blindly dividing by K. If microbatch i contains n_i valid positions and N is the total, accumulate gradients of
(n_i/N)L_i. Padding, ignored targets and incomplete final windows can all matter. - Equivalence assumes the same parameters and an objective decomposable over examples. Dropout choices and floating-point summation order affect results; operations using cross-example statistics, such as BatchNorm, require separate analysis.
- The main saving is peak activation memory. Parameters, accumulated gradients and optimizer state still occupy memory. Total usage does not simply fall to one quarter, nor is execution guaranteed faster.
.grad combines contributions within one update. m/v track history across parameter updates. AdamW’s v receives the square of the final gradient, not the average of the four squared microbatch gradients.
Clip after accumulation; the bound is on gradient length
After accumulation, conceptually concatenate all participating nonempty parameter gradients into a vector g. Global L2 norm clipping is:
G = √(Σ_j g_j²)α = min(1, c/G) # Leave a zero gradient unchanged.g′ = αgFor g=[3,4], c=1, G=5, α=0.2, g′=[0.6,0.8]. The vector [0.3,0.4] has length 0.5 and stays unchanged. One common factor preserves the overall direction. This is neither elementwise clipping nor independently normalizing every parameter matrix to length one.
PyTorch 2.2.2 uses min(1,c/(G+10⁻⁶)) for numerical protection. clip_grad_norm_ modifies .grad in place and returns the pre-clipping total norm; it has not changed parameters yet. Clipping implementation.
Clipping must follow accumulation because it is nonlinear. With threshold one and scalar contributions 2 and −1, separately clipping and adding gives 1−1=0; adding and then clipping gives 1. AdamW updates its histories using the clipped gradient. The threshold bounds this gradient’s norm, not the final parameter-update norm.
Schedule by parameter updates, not microbatches
A learning-rate schedule supplies η for each step. Here it has three parts: linear warmup, cosine decay and a floor. It follows a predefined update index rather than choosing stages from the current loss.
Let the code index s start at zero, warm up for W=10 updates and reach the decay endpoint at s=D=50. Set η_max=0.0006, η_min=0.00006:
Warmup, 0 ≤ s < W:η(s) = η_max × (s+1)/W
Decay, W ≤ s ≤ D:r = (s−W)/(D−W)η(s) = η_min + (1+cos(πr))/2 × (η_max−η_min)
Floor, s > D:η(s) = η_minAs r goes from zero to one, cos(πr) traverses half a period from 1 to −1. The coefficient (1+cos(πr))/2 falls from one to zero, smoothly moving the learning rate from maximum to minimum.
| s | Position | η |
|---|---|---|
| 0 | First update | 0.000060 |
| 9 | Last warmup update | 0.000600 |
| 10 | Start of cosine decay | 0.000600 |
| 30 | Halfway through decay | 0.000330 |
| 50 | Reaches the floor | 0.000060 |
| 60 | Holds the floor | 0.000060 |
This expands the course’s schedule. Its original range(50) runs s=0–49, never reaching the holding segment. The diagram and animation extend to s=60 to explain the rule. At s=49, η is approximately 0.0000608323.
Learning-rate warmup and benchmark warmup are different. The former changes η; the latter excludes startup effects from speed statistics while still potentially performing real updates. With accumulation, four microbatches share one parameter-update index. Both the schedule and AdamW’s update counter advance once.
All four tabs support step playback and direct navigation. Change β₁ and the gradient sequence in bias correction; inspect when W, .grad and m/v change during accumulation; adjust the vector and threshold in clipping; and inspect each learning-rate index. Each tab uses an independent teaching setup, not a shared GPT execution trace.
Connect the pieces into one loop
The following illustrates execution order. The model, optimizer, loader and get_lr are assumed to exist. Every window contains K equally sized microbatches with equal valid-position counts, using mean cross-entropy without label smoothing. FP32 keeps the control flow explicit; mixed precision must also respect its scaling and clipping order.
train_model = torch.compile(raw_model) # raw_model can also be used directly.raw_model.train()K = 4
for step in range(max_updates): optimizer.zero_grad(set_to_none=True) loss_for_log = torch.zeros((), device=device)
for micro_step in range(K): x, y = loader.next_batch() x, y = x.to(device), y.to(device) logits = train_model(x)
# Keep the loss over valid IDs even if the model pads its projection. valid_logits = logits[..., :valid_vocab_size] loss = F.cross_entropy( valid_logits.reshape(-1, valid_vocab_size), y.reshape(-1) ) scaled_loss = loss / K loss_for_log += scaled_loss.detach() scaled_loss.backward() del logits, valid_logits, loss, scaled_loss
grad_norm = torch.nn.utils.clip_grad_norm_(raw_model.parameters(), 1.0) for group in optimizer.param_groups: group["lr"] = get_lr(step) optimizer.step()For logging, detach() avoids retaining connections to old graphs; it does not accumulate gradients. Ordinary backward releases saved intermediates, so this accumulation pattern does not need retain_graph=True. The final step does not clear .grad; the next window does.
| Object | Between four microbatches | After one step |
|---|---|---|
| Parameters θ | Same values | Updated by the optimizer |
.grad | Accumulates | Remains until the next clear |
| m/v and AdamW counter | Unchanged | One recurrence and one increment |
| Activations and graphs | Created for each batch | No need to retain all four graphs |
| Compiled program | Reused while guards hold | Reads new parameters next time |
Decay groups decide which parameters use λ; fused AdamW changes lower-level execution. Neither changes the boundary of this single update. PyTorch AdamW skips parameters whose .grad is None. A numerical zero gradient can still allow movement from history and decay. AdamW options and behavior.
Return to the overview: compilation and tiling determine how computations execute; the valid vocabulary determines which classes the loss compares; accumulation and clipping determine which gradient reaches the optimizer; and the learning rate and AdamW determine how parameters change. Placing an optimization in this route makes its consequences easier to inspect.