How Models Learn Patterns in Language
local graph
Module 5 — How Models Learn Patterns in Language
Section titled “Module 5 — How Models Learn Patterns in Language”Having established what a transformer looks like and how information moves through its layers, what remains is to explain how any of those weights become useful. This module examines the training objective itself, the mathematical goal the model pursues during pretraining and the mechanism that causes a sea of random parameters to gradually organize itself into something capable of producing coherent language. The objective turns out to be simple in its mathematical form, yet its consequences run deep. Understanding what the model is actually trying to do during training clarifies why data composition matters so much, why certain behaviors emerge where others do not, and why language modeling has become the dominant paradigm for building general-purpose systems. The sections below trace this logic from the basic prediction task through the loss function to alternative formulations used elsewhere in the field.
Next-Token Prediction
Section titled “Next-Token Prediction”In transformer-based systems, an encoder is a stack of layers that reads an entire input sequence at once and produces contextualized representations for every position, with each token able to attend to every other token in both directions. A decoder is a stack of layers that generates output one position at a time, where each position can only attend to earlier positions through a causal mask that blocks information from the future from influencing the current prediction. Early transformer systems often combined both into an encoder-decoder architecture for tasks like translation, where the encoder digested the source sentence and the decoder produced the target. Modern general-purpose language models have largely converged on the decoder-only design, because the causal structure aligns naturally with next-token prediction and scales cleanly to very large parameter counts (Radford et al., 2019). Encoder-only models such as BERT remain useful for classification and retrieval workloads, though they represent a smaller share of current development effort.
Training a decoder-only model centers on a deceptively plain task. Given some sequence of tokens, the model is asked to produce a probability distribution over the vocabulary that describes how likely each possible token is to appear in the very next position. The correct answer is already present in the training data, because the training data is continuous text. For any sequence of length , the model receives positions 1 through minus 1 as input and is scored on how well it predicts positions two through . No human labeling is required. This property is why practitioners describe pretraining as self-supervised: the supervision signal is manufactured directly from the structure of natural text (Radford et al., 2019).
| Step | Input token | Context at each step | Predicted distribution (highest first) | Predicted token |
|---|---|---|---|---|
| 1 | The | The | cat · dog · man · old · big | cat |
| 2 | cat | The cat | sat · ran · ate · saw · is | sat |
| 3 | sat | … cat sat | on · in · near · by · at | on |
| 4 | on | … sat on | the · a · my · his · its | the |
| 5 | the | … on the | mat · floor · sofa · rug · bed | mat |
[!visual-conversion] In print each step is a column of boxes (token → context → a bar chart over five candidates → predicted token). The bars are drawn in decreasing length with no printed values; only their order is carried here.
Figure 1-10. Next-Token Prediction as Self-Supervised Training Signal
This framing carries a piece of mathematical machinery worth stating plainly. Language modeling is treated as unsupervised distribution estimation, and the joint probability of a sequence of tokens is factorized into a product of conditional probabilities, each one representing the likelihood of a token given everything that came before it (Radford et al., 2019). The model’s job is to approximate those conditional distributions. Because every position in every document provides a training example, a single paragraph of text yields dozens of supervision signals, and a corpus of trillions of tokens yields trillions.
What makes this objective powerful is the breadth of what a competent solution requires. To predict the token that follows “The capital of France is,” the model must have absorbed something about geography. To predict the next token in a mathematical proof, it must have absorbed something about inference rules. To predict the next word in a poem, it must have absorbed something about meter and rhyme. The prediction target never changes, but the knowledge required to succeed expands with the diversity of the training corpus. Empirical work has shown that models trained purely on next-token prediction over large web corpora begin to exhibit competence on tasks such as reading comprehension and translation without any task-specific supervision (Radford et al., 2019).
Recent theoretical work has begun to formalize how this objective gives rise to generalization. Analyses based on Rademacher complexity show that the ability of a decoder-only transformer to generalize under next-token prediction depends quantitatively on the volume of training sequences, the maximum sequence length, and the total parameter count. The intuition practitioners had from scaling experiments is now being matched by formal bounds that confirm why larger data and larger models tend to produce more reliable learners.
Loss Functions
Section titled “Loss Functions”The prediction task described above needs to be translated into a number that can drive weight updates. That number is the loss, and for language modeling the standard choice is cross-entropy. At each position, the model emits a probability distribution over the full vocabulary. The correct answer is a single token, which can be viewed as a one-hot distribution that places all of its mass on that token. Cross-entropy measures the disagreement between these two distributions, and it does so in a way that punishes the model heavily for assigning low probability to the correct answer while rewarding it for placing high probability on the right token.
The quantity being minimized has an intuitive reading. Cross-entropy at a given position is mathematically equivalent to the negative logarithm of the probability the model assigned to the correct next token. When the model is confident and correct, that probability is close to one and its logarithm is close to zero, so the loss contribution is tiny. When the model assigns only a small probability to the correct token, the logarithm becomes a large negative number, and the loss contribution grows accordingly. This is captured by
where is the correct token and the preceding context. Averaged across all positions in all sequences in a training batch, this yields a single scalar that summarizes how well the model is currently modeling the text.
There is a second way to read this same number. The exponential of the average cross-entropy loss is called perplexity, and it can be interpreted as the effective number of tokens among which the model is hesitating at each prediction step. A model with a perplexity of ten is behaving as if it were roughly choosing uniformly among ten candidate tokens at every position. Driving perplexity down is functionally identical to driving cross-entropy down, and practitioners often track whichever framing is more convenient for a given report.
The gradient of this loss with respect to the model’s output logits has a particularly convenient form. For a correct-class probability of , the gradient pushes that probability toward one and all other probabilities toward zero with a magnitude proportional to how wrong the model currently is. Because this gradient propagates cleanly through the softmax layer that produces the distribution, training signals move backward through the transformer without the numerical difficulties that plagued earlier architectures. Recent empirical work examining how contextualized embeddings evolve across the layers of pretrained transformers has shown that each layer contributes approximately equally to the final next-token prediction accuracy, a pattern the authors call the law of equi-learning, observed consistently across architectures trained with this objective (He & Su, 2025).
How the Objective Shapes What the Model Learns
Section titled “How the Objective Shapes What the Model Learns”A natural question arises from the simplicity of cross-entropy. If the model is only being asked to minimize a single scalar that measures prediction error, how does it end up knowing things about grammar, facts, arithmetic, and style? The answer lies in the observation that next-token prediction is an implicit multitask learner. Any linguistic or factual competence that reduces average loss becomes worth acquiring, because the gradient descent process will reinforce any internal circuit that produces better predictions on the training distribution.
Consider what this means in practice. If the training corpus contains many examples of capital cities appearing after the phrase “the capital of,” the model will develop representations that let it retrieve the right capital from context, because doing so lowers loss on those examples. If the corpus contains many examples of code where variable declarations are consistent with later variable references, the model will develop representations that track variable state, because doing so lowers loss on those examples. The objective does not actually specify which skills to acquire. It merely rewards any capability that improves prediction accuracy, and the composition of the training data determines which capabilities are most profitable to develop.
This emergent quality of language modeling has been documented extensively. Models trained exclusively on the next-token objective over diverse web text have been shown to perform zero-shot tasks including question answering and summarization when prompted appropriately, with performance scaling as model size grows (Radford et al., 2019). More recently, the same fundamental objective has been extended to multimodal settings. A unified decoder-only framework that tokenizes images and video into discrete sequences and trains on next-token prediction has been shown to match the performance of specialized architectures on both perception and generation tasks across modalities (Wang et al., 2026). The striking finding is that the objective is general enough to handle domains well outside text once the inputs are discretized appropriately.
There are, of course, limits. Minimizing prediction loss on existing text rewards the model for reproducing patterns found in that text, including any factual errors or biases the training distribution contains. The objective offers no built-in mechanism for verifying whether a prediction is true in any external sense; it only verifies whether the prediction matches what actually appeared in the training corpus. This is why alignment work, covered later in the book, exists as a separate stage after pretraining. The pretraining objective builds capability; additional processes are required to shape behavior.
Variations on the Pretraining Objective
Section titled “Variations on the Pretraining Objective”Next-token prediction is the dominant objective, yet it is one of several formulations that have been studied. The most historically important alternative is masked language modeling, introduced with BERT. In the masked setting, the model sees the full input sequence with some fraction of its tokens replaced by a special mask symbol, and the training objective is to recover the original identity of those hidden tokens using context from both sides. In the original formulation, roughly 15 percent of tokens were selected for masking, and among those selected, most were replaced by the mask token while smaller proportions were either swapped for a random token or left unchanged, a scheme designed to reduce the mismatch between training conditions and downstream usage (Devlin et al., 2019).
The practical consequence of this formulation is that masked language models process each position with access to both left and right context. This gives them strong bidirectional representations that are well suited for tasks that need to classify or extract information from an existing piece of text, including sentiment analysis and question answering over passages. The trade-off is that masked models are awkward to use for open-ended generation, because their training regime never required them to produce coherent continuations from a partial prefix. Decoder-only next-token models and masked encoder models therefore occupy complementary positions in the landscape, with generation tasks belonging to the former and representation-heavy tasks historically handled by the latter.
A family of more recent variations has explored training objectives that sit between these two poles. Multi-token prediction, for instance, asks the model to predict several future tokens at each position using multiple prediction heads, which has been shown to improve downstream performance on generative and reasoning tasks for sufficiently large models (Gloeckle et al., 2024). Token order prediction takes a related angle by training the model to rank upcoming tokens by how close they are to the current position, using a learning-to-rank loss as an auxiliary signal alongside standard next-token prediction. Empirical results at parameter counts ranging from hundreds of millions to several billion suggest that this auxiliary objective can improve general language modeling performance over pure next-token prediction.
Curriculum-based approaches have also been explored, where training begins with the simpler next-token objective and gradually introduces multi-token prediction, allowing smaller models to benefit from the richer signal once they have developed sufficient capability to handle it (Aynetdinov & Akbik, 2025). These directions share a common theme: the basic idea of predicting some function of upcoming tokens is being refined and extended, but the core insight that self-supervised prediction over natural text produces broadly capable models remains intact.
For practitioners planning a training run, the choice among objectives is less open than it once was. Decoder-only next-token prediction has become the default for general-purpose generative systems because of its scalability and the uniform way it handles training and inference. Masked objectives retain their place for specific representation tasks. Auxiliary multi-token or ranking objectives are available as optional refinements that may offer modest improvements at scale, though they add complexity that should be justified by concrete evaluation evidence on the target workload.