Highlights

Contents

Part III
03

Giving the decoder something to learn

Text supplies its own next-token targets. Correct alignment and causal visibility define the training task. Follow examples into loss and backpropagation, preserving the intended averaging when gradients accumulate.

THE TRAINING CHAPTER: TEN PARTS, ONE COMPLETE MODEL1. features2. output3. examples + loss4. optimizer5. precision6. resume + loop7. evaluation8. experiments9. decoding10. whole pipelineforward computation → learn parameters → measure results → generate

#Section 7Building training examples

Take the illustrative token stream [17, 23, 5, 81, 9, 44, 2, 7, 3]. The model receives [17, 23, 5, 81, 9, 44, 2, 7] and should predict [23, 5, 81, 9, 44, 2, 7, 3]. Each answer is already present in the text. No person has to annotate these next-token labels.

A corpus is the collection of text chosen for learning. A tokenized corpus is that text represented as the tokenizer’s IDs; the tokenizer guide explains how the IDs are constructed. A context window is a bounded contiguous sequence used as input. A target is the token ID that the loss asks a position to predict. For next-token learning, targets are shifted one position relative to inputs.

xt=si+t,yt=si+t+1,0≤t<T.x_t=s_{i+t},\qquad y_t=s_{i+t+1},\qquad 0\leq t<T.

Each input position predicts the following corpus token. A window therefore needs one extra source position to provide its last target.

ONE EXTRA SOURCE TOKEN SUPPLIES THE LAST LABELinput172358194427target23581944273each column predicts the next source token
Figure 3.11The illustrative nine-ID stream supplies eight inputs and eight next-token labels. Column arrows connect each input position to its answer; the last source token is a target even though it is not in the input window.

Why all positions can train in parallel

The answers are known before the forward pass, so every position can receive the true prefix. This is teacher forcing, providing actual earlier tokens when training a sequence predictor. Parallel computation is valid because the causal mask prevents the state at position tt from reading input positions beyond tt. The target for that position is at t+1t+1, which the mask hides. Batched matrix multiplies evaluate many separate causal dependencies at once.

Packing unrelated documents into one stream is a deliberate modeling choice. An EOS separator tells the model that one text ended, but it does not itself block attention between documents. If the intended objective conditions each document only on itself, reset the appropriate positions and use a document-boundary attention mask; also mask targets that would predict a different document's first token. If the objective is the concatenated stream, cross-boundary predictions are part of the objective. State which one you use.

A context window changes the conditioning available at its left edge. A token whose previous paragraph lies outside the window has less information than the same token evaluated with that paragraph. Document packing, EOS policy and context cropping therefore affect both the training objective and later evaluation. Dropping this detail can make equal "token counts" describe different tasks.

#Section 8Batching and data loading

Our window is ready, but a GPU can usually process several windows together. Stack two eight-token inputs into an integer tensor (2, 8) and stack their targets in the same order. The batch must preserve which label belongs to which position, while selecting windows according to the experiment's data policy. A microbatch is the group processed in one forward and backward pass; several can contribute to one optimizer update.

The data loader selects examples, groups them, and supplies tensors to the model. Random starts sample windows from a long stream; shuffling examples visits a permutation of a dataset. Sampling with replacement can revisit some examples and skip others, whereas a full shuffled epoch visits each example once. An epoch is one complete pass through a finite dataset under that traversal policy. Large streaming runs may be tracked by tokens and updates rather than an epoch count.

python
def sample_batch(tokens, B, T, generator):
    assert tokens.ndim == 1 and len(tokens) >= T + 1
    starts = torch.randint(len(tokens) - T, (B,), generator=generator)
    offsets = torch.arange(T + 1)
    rows = tokens[starts[:, None] + offsets]   # (B, T + 1)
    return rows[:, :-1], rows[:, 1:]           # each (B, T)

This sketch assumes a CPU token stream and CPU generator; move the resulting integer tensors to the model's device afterward. Token IDs must be in the model's vocabulary range, with a sufficiently wide storage dtype. Dataset ingestion should validate that once, rather than let a GPU embedding lookup discover corrupt IDs halfway through a run. Data-loader workers, pinned memory and asynchronous copies can improve supply rate, but correctness of labels and splits comes first.

BATCH AND TIME ARE SEPARATE AXESinput IDstarget IDs172358194427……………………shape (2, 8)23581944273……………………shape (2, 8)16 aligned predictions per microbatchthe second row is another sampled window
Figure 3.12Two illustrative length-eight rows become a (2, 8) input and target pair. Their 16 supervised positions form one microbatch; the same labels stay aligned through the model and loss.

Train, validation, test and leakage

The training split supplies gradient updates. The validation split guides model selection and development choices. The test split is held for the final assessment after those choices are settled. Data leakage means information from an evaluation set enters learning or selection in a way that makes the reported assessment unfair. Exact duplicates, nearby overlapping windows, copied passages and related documents can all create leakage.

Split and deduplicate at the appropriate source level before drawing windows. Randomly assigning overlapping windows after tokenization can put almost the same passage on both sides. Group related documents, users or time periods according to the intended generalization claim. Train a learned tokenizer on the permitted training source, or disclose that a frozen external tokenizer has its own provenance. A split called "test" is no longer untouched if you repeatedly tune decisions on it.

Keep stable held-out documents and check for near-duplicates across splits. A chosen split ratio alone does not prevent leakage.

SPLIT AT THE SOURCE, THEN MAKE WINDOWS1,000 documentstrain: 800windows from this splitvalidation: 100windows from this splittest: 100windows from this splitoverlapping windows stay with their source
Figure 3.13Split documents before producing overlapping windows. The orange boundary prevents windows from the same source from becoming both learning examples and apparent evidence of generalization.

#Section 9Cross-entropy during training

The model assigns the correct next token a probability of 0.25. That prediction should incur more loss than probability 0.5, and a confidently wrong prediction should incur much more. The earlier cross-entropy introduction explains the negative-log penalty; here we need its tensor mechanics and exact averaging rule.

Cross-entropy for a one-hot next-token target is the negative natural logarithm of that token's model probability. It is also the per-token negative log-likelihood, or NLL. A nat is an information unit using the natural logarithm. Minimizing the sum of these losses maximizes the assigned probability of the observed sequence under its declared conditioning contexts.

ℓb,t=logsumexp⁡v(Zb,t,v)−Zb,t,yb,t,L=∑b,tmb,tℓb,t∑b,tmb,t.\ell_{b,t}=\operatorname{logsumexp}_{v}(Z_{b,t,v})-Z_{b,t,y_{b,t}},\qquad \mathcal L=\frac{\sum_{b,t}m_{b,t}\ell_{b,t}}{\sum_{b,t}m_{b,t}}.

Read this as: at batch row bb and time tt, take the log of the summed exponentials of the vocabulary logits ZZ, then subtract the correct target logit. Average these losses only over positions whose validity indicator mb,tm_{b,t} equals one. The denominator counts supervised tokens. Log-sum-exp is the log of a sum of exponentials, evaluated by subtracting the largest input before exponentiating and adding it back afterward.

For illustrative logits [2,1,0][2,1,0] with target A, log-sum-exp is 2+ln⁡(1+e−1+e−2)=2.4076062+\ln(1+e^{-1}+e^{-2})=2.407606, so loss is 0.407606. The correct probability is 0.665241, and −ln⁡(0.665241)-\ln(0.665241) gives the same rounded loss. No sampled output token is needed to compute this objective.

Average prediction loss does not imply that every token improved, that the most likely token changed, or that a factual answer is correct.

THE TOKEN MEAN COMBINES ALL VALID NEXT-TOKEN LOSSESp = 0.50.693147-ln pp = 0.251.386294-ln pp = 0.1252.079442-ln pp = 0.1252.079442-ln psum 6.238325 / 4 = 1.559581 nats per tokenmasked labels contribute neither loss nor denominator
Figure 3.14Four illustrative correct-token probabilities become four losses and one mean. Loss aggregates all supervised positions, not only the last token and not the sampled prediction.
python
logits = model(x)                              # (B, T, V)
loss = F.cross_entropy(
    logits.float().reshape(-1, V),             # (B*T, V)
    y.reshape(-1),                            # (B*T,), integer IDs
    ignore_index=-100,
)

For an unweighted index-target loss, ignore_index removes those labels from both sum and mean denominator. It does not remove them from attention: padding or document isolation needs a separate attention mask. If every label is ignored, there is no defined token mean; reject or skip that batch deliberately. Label smoothing and class weighting change the objective and denominator, so their losses should not be silently reported as plain corpus NLL. PyTorch's loss contract.

A uniform distribution is a useful loss reference, not a guaranteed initialization result. Random logits, tied weights, and input-target correlations can shift the starting value.

CONFIDENT MISTAKES ARE EXPENSIVE-ln p0.1250.250.51correct-token probabilitya small probability carries a large penalty
Figure 3.15Correct-token probability maps to negative log-likelihood. The curve and marked points are computed; small probabilities produce much larger penalties.

#Section 10Backpropagation through the language model

The loss is a scalar, but Finch-24 has 40,509,952 parameters. Re-running the forward computation after separately perturbing every parameter would be an impractical way to find all its slopes. A single reverse traversal uses the operations' local derivative rules instead.

The gradient introduction describes the downhill direction. A computational graph records which values depend on which operations and parameters. Backpropagation traverses that graph backward, using the chain rule to combine local derivatives. A gradient is the collection of derivatives of the scalar loss with respect to a tensor's entries. It has the same shape as that tensor, so a projection weight receives a projection-shaped correction, not one scalar per layer.

For a softmax cross-entropy row with one-hot target vector qq:

∂ℓ∂zv=pv−qv.\frac{\partial\ell}{\partial z_v}=p_v-q_v.

The derivative is predicted probability minus the target indicator. Descending the loss raises the recorded target's score and lowers competing scores. A shared shift of every logit leaves probabilities unchanged.

A full scalar calculation

Use an illustrative binary head z=wxz=wx, with w=0.5w=0.5, x=2x=2 and target class one. The logit is 1, its sigmoid probability is 0.731059, and its loss is 0.313262. The derivative with respect to the logit is 0.731059−1=−0.2689410.731059-1=-0.268941. Multiplying by ∂z/∂w=x=2\partial z/\partial w=x=2 gives the weight derivative −0.537883-0.537883. An illustrative gradient-descent step of size 0.1 changes ww to 0.5−0.1(−0.537883)=0.5537880.5-0.1(-0.537883)=0.553788.

FORWARD VALUES AND REVERSE DERIVATIVESw × x0.5 × 2 = 1sigmoidp = 0.731059NLLloss = 0.313262dw = -0.537883dz = -0.268941incoming = 1multiply by x = 2p - targetSGD at η = 0.1 gives new w = 0.553788
Figure 3.16One illustrative binary prediction traced through its value and derivative. The backward route multiplies local derivatives; it does not guess a separate perturbation for every parameter.

Branches, residuals and accumulation

At an addition, the incoming derivative goes to both operands. At a shared value, contributions from all dependent uses add. At a residual block x+f(x)x+f(x), the derivative includes the identity route and the route through ff; the branch does not erase the identity contribution. The residual-stream chapter explains why that path helps depth. It is not a promise that gradients can never vanish or explode.

Gradient accumulation sums contributions before one update. PyTorch adds to .grad by default. Weight each microbatch by its valid-target count so accumulation represents the combined token mean, rather than an unequal average of batch means.

AVERAGE TOKENS, NOT MEANS OF UNEQUAL BATCHESbatch A: 2 valid tokensmean loss 2, sum loss 4batch B: 6 valid tokensmean loss 4, sum loss 24wrong: (2 + 4) / 2 = 3right: (4 + 24) / 8 = 3.5
Figure 3.17Two illustrative microbatches show why averaging their means gives the wrong token objective. The weighted mean is 3.5 nats per token.

The graph needs forward intermediates to compute backward. Detaching a tensor, converting the loss to a Python number, or running the forward pass under no_grad breaks derivative paths. Keep the tensor loss for backward. loss.item() can log its value before or after backward, but a Python number cannot supply backward. A loss gradient also does not perform an optimizer step by itself; Section 11 separates computing a correction from applying it.