AI Workflows

Part 2 — Understanding the LLM Training Process

CodeTips Academy
December 06, 2026
12 min read
8 views

Trace the causal Transformer training loop from tokenization and masked attention to cross-entropy, backpropagation, and an optimizer update.

The training loop for a decoder-only language model starts with text, converts that text to integer token IDs, and makes a next-token prediction at each eligible position. The prediction errors feed a backward pass that computes gradients. An optimizer uses those gradients to update parameters. It is the same sequence of operations whether you inspect a tiny teaching example or train a model with billions of weights. The size of the tensors, the architecture details, and the systems needed to run it differ substantially.

This lesson follows the dispatch example from Article 01. We want the model to continue a partial report with the token representing “urgent.” We will derive a full gradient step in a three-token model, then connect it to the forward and backward passes of a Transformer.

Learning objectives

  • Track tensor dimensions from token IDs through embeddings, attention, the output head, and the loss.
  • Explain how causal masking and the target shift work together.
  • Calculate a probability, loss, gradient, and optimizer update from small arrays.
  • Diagnose common bugs in a next-token training loop.

You should know vector multiplication and the chain rule. You can run the numerical companion with Python 3.10 or later on a CPU. It uses no external dependencies.

Tokenization and embedding lookup

A tokenizer maps strings to sequences of vocabulary indices. In a real vocabulary, “jammed” can be one token or split across pieces, and a leading space can affect token boundaries. A training checkpoint depends on the token-to-ID mapping and special tokens it was trained with. Two tokenizers can return arrays of the same length and still disagree about the meaning of every ID.

Let $B$ be the number of sequences in a batch, $T$ the padded sequence length, $V$ the vocabulary size, and $d$ the model width. The input IDs have shape $[B,T]$. An embedding table $E$ has shape $[V,d]$. Looking up one row of $E$ for each ID produces a floating-point tensor with shape $[B,T,d]$. The ID is an address. Numeric closeness between two IDs carries no semantic meaning. The row vectors are parameters whose values are learned during training.

Position information is required to distinguish permutations of otherwise identical tokens. Some architectures add a learned or fixed position vector to each input embedding. Others use rotary position encoding, which transforms attention queries and keys using token position. The placement depends on the model. In either case, padding position, attention masking, and token order must match the model's conventions.

Inside a decoder block

A common pre-normalized decoder block contains an attention sublayer and a feed-forward sublayer. Each sublayer receives a normalized input, transforms it, and adds its output back to the residual stream. A residual connection preserves a direct path for information and gradients. The exact normalization, activation, and attention grouping vary across model families.

For one attention head, write $X$ for the current sequence of token representations, shape $[T,d]$. Matrices $W_Q$, $W_K$, and $W_V$ project it to queries $Q=XW_Q$, keys $K=XW_K$, and values $U=XW_V$. Here $U$ names the value tensor so it is distinct from the vocabulary size $V$. If the query and key width is $d_h$, then $Q$ and $K$ each have shape $[T,d_h]$. With value width also equal to $d_h$, the output is

$$A=\operatorname{softmax}_{\mathrm{row}}(QK^{\top}/\sqrt{d_h}+M)U.$$

The score matrix has shape $[T,T]$. At row $i$ and column $j$, the dot product measures how much position $i$ attends to position $j$ before normalization. The causal mask $M$ adds negative infinity for $j>i$ and zero otherwise. Row softmax then gives future positions zero probability. Multiplication by $U$ mixes the visible value vectors. Multiple heads can perform different mixtures, and an output projection maps the assembled head outputs back to model width for the residual addition.

For a concrete attention calculation, take $d_h=2$, a query $q=[1,1]$, keys $[1,0]$ and $[0,1]$, and values $[2,0]$ and $[0,4]$. The scaled dot products are equal at $1/\sqrt{2}$. At the second position, both tokens are visible, their attention weights are $0.5$ each, and the output is $[1,2]$. At the first position, the second is in the future, so the weights are $[1,0]$ even though the unmasked scores match. If you skip that mask during training, the model can peek at a future target that will be unknown during generation.

The feed-forward network applies the same learned nonlinear transformation independently at each position. For a simple version, let $W_1$ map width $d$ to a hidden width $d_{\mathrm{ff}}$, apply a nonlinearity $\phi$, and let $W_2$ map back to $d$. The resulting function is $\phi(XW_1)W_2$. Many modern blocks use gated variants, with a second branch multiplying the activated features element by element. Attention moves information among positions, while the feed-forward sublayer changes the representation at each position using the mixed context.

From hidden state to next-token loss

The forward pass produces logits, shifted labels supply the targets, and the loss sends gradients back through the decoder.
A next-token training step. Green boxes mark example components with trainable weights.

The final hidden tensor has shape $[B,T,d]$. A language-model head maps the last dimension to vocabulary scores, producing $[B,T,V]$. If $h_t$ is a row vector for position $t$, an output weight matrix $W$ of shape $[V,d]$ yields logits $z_t=h_tW^{\top}$. Some models tie the output weight matrix to the input embedding table. Updating that shared parameter can change both input representations and output probabilities.

For a target token $y$ and a vector of logits $z$, softmax gives $p_j=e^{z_j}/\sum_k e^{z_k}$ for class $j$. Cross-entropy for the target ID is $L=-\log p_y$. Compute it directly from logits as $L=\log\sum_k e^{z_k}-z_y$. Subtract the largest logit before exponentiation to avoid overflow. An implementation such as PyTorch cross-entropy performs the equivalent stable computation internally and expects logits as input.

With token IDs for the sequence “door jam urgent,” the hidden state at “door” predicts “jam,” and the state at “jam” predicts “urgent.” The last input token has no following label in that example. The forward pass uses observed tokens at every position, called teacher forcing. It can score several adjacent positions in parallel because the causal mask protects the context boundary. In generation, the next input may be sampled from the model's output. A model can have a reasonable teacher-forced loss and still compound errors during long generation.

Assume the padding ID is 0 and three other IDs represent door, jam, and urgent. Here is what one padded example looks like:

PositionInput tokenVisible to attentionTarget at this position
0dooryesjam
1jamyesurgent
2urgentyesignored, unless an end token follows
3paddingnoignored

An attention mask answers which positions count as context. A loss mask answers which target positions contribute to the objective. An assistant-only training objective can leave user text visible to attention while excluding user tokens from the loss. In a PyTorch implementation the excluded targets often use index $-100$. A model wrapper may perform the target shift internally. Read its interface before manually shifting labels, or the effective objective may predict two tokens ahead.

One complete training step

Set vocabulary size to three and width to two. Use the vocabulary order door, jam, urgent. The input is the token jam and the target is urgent. The lookup for jam returns $h=[1,-1]$. For this mini-model the embedding lookup leads directly to the output head. We omit Transformer blocks so we can differentiate through every parameter by hand.

Take the output weight rows for door, jam, and urgent to be $[0.5,0]$, $[0,0.5]$, and $[0,0]$. Dotting each row with $h$ gives logits $[0.5,-0.5,0]$. The probabilities are about $[0.5065,0.1863,0.3072]$. The loss on urgent is about $1.1803$. These values are rounded, so use full precision when reproducing the update.

The gradient of the loss with respect to the logits is $g=p-e_y$, where $e_y=[0,0,1]$ is the target's one-hot vector. Therefore $g$ is approximately $[0.5065,0.1863,-0.6928]$. For row $j$ of $W$, its gradient is $g_jh$. For $h$, the gradient is $W^{\top}g$ using the weights from the forward pass. With the chosen $W$, its two elements are approximately 0.2532 and 0.0932.

Weight rowGradient of first elementGradient of second element
door0.5065−0.5065
jam0.1863−0.1863
urgent−0.69280.6928

Use stochastic gradient descent with learning rate $\eta=0.1$. Apply $W_{ji}\leftarrow W_{ji}-\eta\,g_jh_i$ and $h_i\leftarrow h_i-\eta(W^\top g)_i$. In the embedding table, only the row looked up for jam receives this direct gradient. The updated row is approximately $[0.9747,-1.0093]$. The updated urgent weight row is approximately $[0.0693,-0.0693]$, so its new logit is about 0.1375. Recomputing all logits gives the new loss. The companion program was run with the default configuration. It printed an initial loss of 1.180270 and an updated loss of 1.026164. Urgent probability rose from 0.307196 to 0.358379. Finite-difference estimates agreed with all eight analytical gradients to an absolute tolerance of $10^{-8}$.

Numerical training script
"""One exact causal-token training step on a tiny embedding and vocabulary head."""

from math import exp, isclose, log


def loss_and_probabilities(embedding, weights, target):
    logits = [sum(x * w for x, w in zip(embedding, row)) for row in weights]
    maximum = max(logits)
    exponentials = [exp(value - maximum) for value in logits]
    total = sum(exponentials)
    probabilities = [value / total for value in exponentials]
    return maximum + log(total) - logits[target], probabilities


def gradients(embedding, weights, target):
    _, probabilities = loss_and_probabilities(embedding, weights, target)
    logit_gradient = [value - (index == target) for index, value in enumerate(probabilities)]
    weight_gradient = [[gradient * value for value in embedding] for gradient in logit_gradient]
    embedding_gradient = [
        sum(gradient * row[column] for gradient, row in zip(logit_gradient, weights))
        for column in range(len(embedding))
    ]
    return embedding_gradient, weight_gradient


def numerical_gradient(values, index, measure, step=1e-5):
    left, right = values.copy(), values.copy()
    left[index] -= step
    right[index] += step
    return (measure(right) - measure(left)) / (2 * step)


def main():
    embedding = [1.0, -1.0]
    weights = [[0.5, 0.0], [0.0, 0.5], [0.0, 0.0]]
    target, rate = 2, 0.1
    before, probabilities = loss_and_probabilities(embedding, weights, target)
    embedding_gradient, weight_gradient = gradients(embedding, weights, target)

    def loss_for_embedding(candidate):
        return loss_and_probabilities(candidate, weights, target)[0]

    for index, gradient in enumerate(embedding_gradient):
        estimate = numerical_gradient(embedding, index, loss_for_embedding)
        assert isclose(estimate, gradient, abs_tol=1e-8)

    for row_index, row in enumerate(weights):
        def loss_for_row(candidate):
            candidate_weights = weights.copy()
            candidate_weights[row_index] = candidate
            return loss_and_probabilities(embedding, candidate_weights, target)[0]

        for column, gradient in enumerate(weight_gradient[row_index]):
            estimate = numerical_gradient(row, column, loss_for_row)
            assert isclose(estimate, gradient, abs_tol=1e-8)

    next_embedding = [value - rate * gradient for value, gradient in zip(embedding, embedding_gradient)]
    next_weights = [
        [value - rate * gradient for value, gradient in zip(row, row_gradient)]
        for row, row_gradient in zip(weights, weight_gradient)
    ]
    after, next_probabilities = loss_and_probabilities(next_embedding, next_weights, target)
    assert after < before
    print(f"Before: loss={before:.6f}, probabilities={[round(p, 6) for p in probabilities]}")
    print(f"After:  loss={after:.6f}, probabilities={[round(p, 6) for p in next_probabilities]}")
    print("Finite differences agree with all eight analytical gradients.")


if __name__ == "__main__":
    main()

In a Transformer, the backward pass extends through each earlier operation whose parameters are trainable or whose inputs lead to trainable parameters. For example, an output loss can affect a query weight through normalization, masked attention, and the residual stream. Autograd saves values from the forward pass or reconstructs them during backpropagation. It accumulates contributions where the same parameter appears more than once. That is why training memory includes activations and gradients as well as weights.

Optimizers and token-weighted batches

A plain SGD step scales the current gradient by the learning rate. Adam maintains a moving average of the gradient and a moving average of its squared values. The first tracks direction and the second tracks magnitude. For time step $t$, the updates are $m_t=\beta_1m_{t-1}+(1-\beta_1)g_t$ and $v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2$ elementwise. Starting both at zero biases early values toward zero. Adam divides them by $1-\beta_1^t$ and $1-\beta_2^t$ respectively to correct that bias. The update divides the corrected first moment by the square root of the corrected second moment plus a small stabilizing constant. AdamW applies weight decay as a separate parameter shrinkage step.

Every trainable parameter can therefore require storage for its gradient and two optimizer-state values in addition to the parameter itself. Mixed precision, gradient checkpointing, and sharding can change the memory budget. A learning rate of 0.1 is useful for showing a visible update on paper. Choose realistic training rates based on objective, batch, checkpoint, and validation behavior. A schedule or warmup changes the step size over training.

A batch loss should have a defined denominator. If example A contributes one token with loss 2.0 and example B contributes three tokens with loss 1.0 apiece, the token mean is $(2+1+1+1)/4=1.25$. The mean of their per-example means is $(2+1)/2=1.5$. These objectives weight examples differently. When accumulating gradients from batches with different numbers of valid tokens, averaging each batch independently and then averaging gradients can imply a different objective from a global token mean. Track the loss sum and the count of eligible tokens if you intend every scored token to have equal weight.

Practical implementation checklist

Start with a fixed, tiny batch and inspect the tokens, their target positions, and the supervised-token count. Log the shape of the logits and verify that the loss equals the average of a few manually computed token losses. A model should be able to overfit a clean tiny batch when enough parameters are trainable. That checks the mechanics of the loop. It says little about generalization.

In a direct PyTorch loop, clear accumulated gradients at the beginning of each optimizer step, compute the forward pass and loss, call backward, and step the optimizer. For gradient accumulation, clear at accumulation boundaries and normalize according to the loss you intend. Use evaluation mode and no gradient tracking when measuring validation loss. Record loss and supervised token counts along with the model and tokenizer revision.

Loss stays flat. Verify that targets survive truncation, trainable parameters are included in the optimizer, and the shifted labels point at the intended IDs. Check actual gradient norms on trained parameters.

Training loss falls unusually fast. Check whether future tokens are visible or whether scoring accidentally rewards reproducing the current token. Evaluate on unseen data after fixing the mask.

Loss is NaN. Inspect the denominator for a batch with zero supervised tokens, then check logits, gradient values, precision, and learning rate. A masked attention row with no visible positions can also be problematic depending on the implementation.

Generation quality disagrees with loss. Check the generation template, stopping rules, and sampling settings. Inspect end-of-sequence handling and evaluate task-level behavior under deployed settings.

Exercises and takeaways

  1. Change the target to jam. Calculate the new loss and predict the sign of the first gradient in the jam row.
  2. Freeze the embedding row. Recalculate the updated urgent logit and explain which gradient path no longer results in a weight update.
  3. For two sequences with five and eleven valid targets, derive how to combine their loss sums into a token mean. Compare it with the unweighted sequence mean.
  4. Replace the second key in the attention example with $[2,0]$. Compute the second position's weights and output while respecting the causal mask.

A causal model converts prefix representations to next-token logits. Correct attention masking blocks future context, target shifting aligns each prefix with its next token, and loss masking controls the positions whose errors are optimized. Gradients explain how parameters influence the objective. The optimizer turns those gradients into updates and can substantially change the training memory budget.

Frequently asked questions

Why use logits in cross-entropy? Stable implementations combine the log-softmax and target lookup. Applying softmax yourself before passing inputs to an interface that expects logits changes the loss.

Are all parameters updated by every training run? The backward pass can propagate through fixed operations, but the optimizer changes only the parameters it is configured to update. The next article separates update strategy from training objective.

Does a loss of zero mean the model understands the task? A low loss means the scoring distribution puts high probability on the observed targets. A held-out evaluation with task metrics is needed to tell whether this generalizes.

Academic references

Continue the series

Article 03 separates parameter-update strategies such as full fine-tuning and LoRA from objectives such as SFT and preference optimization. Open the series index to browse published lessons.


Related Articles

Back to Articles