Skip to content
ImagineWorld

How Weight Matrices Are Learned During Training

node_idnode-book_llm-systems-engineering_module-21-how-weight-matrices-are-learned-during-training
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num21
chapter_titleHow Weight Matrices Are Learned During Training
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Module 21 — How Weight Matrices Are Learned During Training

Section titled “Module 21 — How Weight Matrices Are Learned During Training”

Training a large language model means adjusting billions of numerical values until the model produces useful predictions. Each of those values sits inside a weight matrix, and the process by which they are updated follows a precise mathematical procedure. The model begins with random weights that produce meaningless outputs. Over the course of training, a systematic loop of error measurement and correction gradually transforms those weights into structured representations of language. This module explains how that loop works at the level of individual parameters, from the computation of prediction error through the mechanics of weight updates and the numerical considerations that keep the process stable.

How Prediction Error Drives Weight Updates

Section titled “How Prediction Error Drives Weight Updates”

Every weight update in a neural network begins with a prediction error. After the forward pass, the loss function compares that predicted distribution against the actual next token, producing a single scalar value that quantifies how wrong the prediction was. Loss value of cross-entropy (Module 05) is the starting point for all learning.

The challenge is translating that single error signal into specific adjustments for each of the billions of weights in the model. Backpropagation solves this problem through a systematic application of the chain rule from calculus (Rumelhart et al., 1986). Starting from the loss at the output layer, the algorithm works backward through the network, computing at each layer how much each weight contributed to the overall error. The result of this computation is a gradient for every weight in the model, a value that indicates both the direction and the magnitude of the change that would reduce the loss.

flowchart TB
    IT["Input tokens<br/>&quot;The cat sat on the&quot;"] -- activations --> L1["Layer 1<br/>Attention + feedforward"]
    L1 -- activations --> L2["Layer 2<br/>Attention + feedforward"]
    L2 -- activations --> L3["Layer 3<br/>Attention + feedforward"]
    L3 -- logits --> P["Prediction<br/>Probability distribution"]
    P -- compare --> CE["Cross-entropy loss<br/>Predicted vs actual: &quot;mat&quot;"]
    CE -. "∂L/∂output" .-> P
    P -. "∂L/∂W₃" .-> L3
    L3 -. "∂L/∂W₂" .-> L2
    L2 -. "∂L/∂W₁" .-> L1
    L1 -. gradients .-> IT

Solid arrows: forward pass (activations). Dotted arrows: backward pass (gradients).

Figure 4-3. Forward and Backward Passes Through a Transformer During Training

The gradient for a given weight can be understood as an answer to a specific question: if this weight were nudged slightly, how much would the loss change? A large gradient means the weight has a strong influence on the current error, while a gradient near zero means adjusting that weight would have little effect. Backpropagation computes all of these gradients in a single backward pass through the network, making it computationally tractable even for models with hundreds of billions of parameters. The efficiency of this procedure is what makes gradient-based training of large models feasible at all.

Gradient Descent and the Optimizer’s Role

Section titled “Gradient Descent and the Optimizer’s Role”

Once gradients have been computed for every weight, the next step is to use them to update the model. The simplest version of this process is gradient descent, where each weight is adjusted in the direction opposite to its gradient, scaled by a learning rate. If a weight’s gradient indicates that increasing the weight would increase the loss, the update decreases the weight, and vice versa. Repeating this process over many batches of training data is what drives the model toward better predictions.

In practice, plain gradient descent is too unreliable for training large language models. The loss landscape of a deep neural network is a high-dimensional surface with regions that vary enormously in curvature and slope (Li et al., 2018). Some directions in parameter space have steep gradients that would cause overshooting, while others have nearly flat gradients that would cause training to stall. A single learning rate applied uniformly to all parameters cannot navigate this terrain effectively.

Modern optimizers address this problem by maintaining additional state for each parameter. The Adam optimizer, which is the foundation of most large-scale training configurations, tracks two quantities for every weight: a running average of the gradient (the first moment) and a running average of the squared gradient (the second moment) (Kingma & Ba, 2015). The first moment acts as a form of momentum, smoothing out noisy gradient estimates by accumulating directional information over multiple steps. The second moment provides per-parameter scaling, effectively giving each weight its own adaptive learning rate based on the historical magnitude of its gradients.

The practical effect is that parameters with consistently large gradients receive smaller updates, while parameters with small or infrequent gradients receive proportionally larger ones. This adaptivity allows the optimizer to make progress across regions of the loss landscape that would be difficult for a fixed learning rate to navigate. AdamW, a widely used variant, further improves training by decoupling weight decay from the gradient-based update, which leads to better generalization performance and a more separable hyperparameter search space (Loshchilov & Hutter, 2019). Most large language model training runs use some form of AdamW as their default optimizer.

What Happens Inside the Weight Matrices as Training Progresses

Section titled “What Happens Inside the Weight Matrices as Training Progresses”

The gradients and optimizer mechanics described above operate on every weight in the model simultaneously, but the nature of the changes happening inside different weight matrices varies substantially across training. A transformer contains several distinct types of weight matrices, and each develops specialized structure over the course of a training run.

The embedding matrix, which converts token indices into dense vectors, undergoes some of its most significant changes early in training. In the initial random state, tokens that are semantically related have no particular proximity in the embedding space. Within the first few percent of training, the embedding matrix reorganizes so that tokens with similar roles in language occupy nearby regions of the vector space. This early reorganization establishes the representational foundation that deeper layers build upon.

The attention weight matrices, which include the query and key projections among others, develop specialized functions as training progresses. Research on the internal mechanics of transformers has revealed that attention heads undergo a process of functional differentiation during training (Olsson et al., 2022). Some heads specialize in attending to the immediately preceding token, while others learn to implement more complex patterns, such as induction heads that identify and continue repeated sequences. This specialization emerges through the gradient-driven update process, as the optimizer reinforces patterns that reduce prediction error and diminishes those that do not contribute.

The feed-forward weight matrices in each transformer block undergo their own form of specialization. These matrices effectively function as key-value memories, where the first matrix in the feed-forward pair learns to recognize specific input patterns and the second matrix learns what information to inject in response. As training progresses, individual neurons within these matrices become increasingly selective, responding to narrower categories of input. The overall trajectory of weight matrix evolution moves from disorganized initial values through a period of rapid structural formation, into a longer phase of gradual refinement where changes become smaller and more targeted.

Numerical Precision and Gradient Stability

Section titled “Numerical Precision and Gradient Stability”

The mathematical operations described in the preceding sections are all implemented using finite-precision floating-point arithmetic, and the choice of numerical precision has significant consequences for both the efficiency and stability of training. A standard 32-bit floating-point number (FP32) can represent values across a wide range with reasonable accuracy. A 16-bit floating-point number (FP16) uses half the memory and enables faster computation on modern hardware, but it has a narrower representable range and lower precision.

The reason for keeping FP32 weights is that gradient updates are often very small relative to the weight values themselves. In FP16, these small updates can round to zero, meaning the weight never actually changes. By accumulating updates in FP32, the training process preserves the effect of small gradients that would otherwise be lost.

Loss scaling is a complementary technique that addresses a different numerical problem. When gradients are computed in FP16, very small gradient values can underflow to zero before they are used in the backward pass. Loss scaling multiplies the loss value by a large constant before backpropagation, which proportionally scales up all gradients into a range that FP16 can represent. After the backward pass, the gradients are divided by the same constant to restore their original magnitude before the optimizer applies them to the FP32 master weights (Micikevicius et al., 2018).

Gradient clipping provides a further layer of stability by placing an upper bound on the magnitude of gradient updates. The technique, formalized by Pascanu et al. (2013), computes the global norm of the gradient vector across all parameters and rescales it if the norm exceeds a predefined threshold. This prevents any single batch of training data from producing an update so large that it destabilizes the model’s learned representations. Gradient clipping is especially important during the early phases of training, when the loss landscape is least stable and the model is most vulnerable to large, erratic updates. Together, mixed precision arithmetic and gradient clipping form the numerical infrastructure that allows modern training runs to proceed efficiently without sacrificing stability.

flowchart TB
    M["FP32 master weights<br/>Accumulate small updates"] -- Cast to FP16 --> W["FP16 weights<br/>Cast from master"]
    W --> F["Forward pass<br/>Activations in FP16"]
    F --> S["Scale loss × S<br/>Prevent underflow"]
    S --> B["Backward pass<br/>Scaled FP16 gradients"]
    B --> U["Unscale gradients ÷ S<br/>Restore magnitude"]
    U --> C["Gradient clipping<br/>Bound global norm"]
    C --> O["Optimizer step<br/>Update FP32 master"]
    O -- Write updates --> M

Figure 4-4. Mixed Precision Training Loop with Loss Scaling and Gradient Clipping