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.
#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.
Each input position predicts the following corpus token. A window therefore needs one extra source position to provide its last target.
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 from reading input positions beyond . The target for that position is at , 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.
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.
(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.
#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.
Read this as: at batch row and time , take the log of the summed exponentials of the vocabulary logits , then subtract the correct target logit. Average these losses only over positions whose validity indicator 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 with target A, log-sum-exp is , so loss is 0.407606. The correct probability is 0.665241, and 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.
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.
#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 :
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 , with , 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 . Multiplying by gives the weight derivative . An illustrative gradient-descent step of size 0.1 changes to .
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 , the derivative includes the identity route and the route through ; 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.
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.