Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college lesson →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

Next-TokenUnderstand the moving parts.

Next-token prediction, learned patterns, and why measured capabilities depend on data, scale and evaluation.

Suggested preparation: 21, 12

WORKBENCH / CHANGE ONE THING

Multiply a sequence probability

Hold token probability constant and see how exact-match scoring changes with length.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

A sequence of five likely guesses can still be unlikely to be entirely right.

Where this deserves more time

Teacher forcing; exposure bias; metric-dependent emergence; data contamination.

Open the complete high-school reading

Moment 01 / 09

Introduction to Next-Token Prediction

Next-token prediction is the training objective underlying essentially every modern autoregressive language model. Understanding it reveals how complex linguistic behavior emerges from a remarkably simple predictive task.

The task is to predict the immediate next token given the entire preceding context. Optimizing this single objective forces the model to internalize syntax, semantics, and factual regularities of the training corpus.

Formally, the model estimates the probability of the token at position t, conditioned on every token that precedes it. The chain rule then factorizes the joint distribution of the full sequence into a product of these conditionals.

Training minimizes the cross-entropy loss: the sum over positions of the negative log likelihood of each token given its prefix, computed under teacher forcing on real text.

Distinguish carefully between the training objective and emergent capabilities. Reasoning, in-context learning, and instruction following are never explicitly optimized; they arise as byproducts of minimizing next-token loss at sufficient scale.

In summary, next-token prediction is the foundational driver of language model capability. From here, we examine how this simple objective yields generalization far beyond token-level statistics.

Equations, code and original cards

Introduction to Next-Token Prediction

• Autoregressive objective: predict each token from its full preceding context

• Training objective distinct from emergent capabilities at deployment

• Cross-entropy minimization yields reasoning and in-context learning

\hat{y}_t = P(x_t \mid x_{1:t-1}; \theta)
\mathcal{L}(\theta) = -\sum_{t=1}^T \log P(x_t \mid x_{1:t-1}; \theta)

Moment 02 / 09

Mathematical Formulation of Next-Token Prediction

We start with the objective behind language modeling: next-token prediction as maximum likelihood. This scalar loss is what turns text into gradients.

Formally, we minimize cross-entropy, equivalently the negative log likelihood of each token conditioned on its prefix. Lower loss means the softmax assigns higher probability mass to the observed continuation, not merely the argmax.

Each token begins as a one-hot row in vocabulary space; multiplying by the embedding matrix is just a lookup that places that symbol in a dense learned residual stream.

Backpropagation differentiates that objective through every layer: softmax and cross-entropy give a clean error signal, then the chain rule moves it into attention weights, feed-forward networks, normalization gains, and embeddings.

The diagram’s matrices make the shapes explicit: embeddings become a sequence matrix, logits appear only after the final linear map, and the Jacobian tracks how each parameter perturbs every position.

That embedding product is the first discrete-to-continuous bridge: sparse indices in, geometry out, with distances and directions now trainable rather than fixed by the tokenizer.

So the pipeline is exact: encode indices, map to embeddings, compute logits, score with negative log likelihood, backpropagate, and descend. Master this and transformer training becomes mechanics, not mystery.

Equations, code and original cards

Next-Token Prediction: Likelihood, Embeddings, Gradients

• Objective: minimize cross-entropy / maximize likelihood

• L(θ) = - \sum_{t=1}^{T} \log p_θ(x_t | x_{<t})

• Softmax logits: p_θ(·|x_{<t}) = softmax(z_t); target is one-hot x_t

• One-hot rows x_t ∈ {0,1}^V index vocabulary

• Embedding E ∈ R^{d×V}; e_t = E x_t (lookup)

• Sequence matrix X = [e_1, …, e_T] ∈ R^{d×T}

• Logits z_t = W h_t + b; softmax over V

• Backprop: ∇_θ L via chain rule through softmax, attention, MLP, LayerNorm

– softmax + CE Jacobian: ∂L/∂z_t = p_t - y_t

• Gradient norm clipping stabilizes updates; AdamW applies preconditioned steps

• Ablations: embeddings, temperature, and context length shift loss

Moment 03 / 09

Emergence Simulator: From Prediction to Reasoning

Today we examine how next-token prediction, trained on pure cross-entropy loss, gives rise to emergent reasoning. The Emergence Simulator visualizes the softmax distribution over the vocabulary at each decoding step, exposing the model's uncertainty over candidate continuations.

Now watch the simulator decode arithmetic sequences token by token. The model conditions on in-context exemplars and induces the underlying pattern without any gradient updates, the signature of in-context learning.

Notice that as we increase parameter count and training compute, capabilities such as multi-step arithmetic appear abruptly rather than gradually. These emergent abilities were never explicitly supervised; they surface as a consequence of scale.

Use the navigation controls to step through the prediction sequence. Observe how the logits sharpen as context accumulates, and how the model's latent reasoning unfolds incrementally across the residual stream.

Equations, code and original cards

Moment 04 / 09

Advanced Techniques and Optimization

Let's examine the optimization frontier for next-token prediction as it stands from 2024 onward: scaling, efficiency, and alignment.

First, scaling laws. Kaplan et al. 2020 showed that cross-entropy loss follows a power law in parameters, data, and compute; Hoffmann et al. 2022 refined this with Chinchilla, arguing most large models were undertrained.

The Chinchilla prescription is roughly twenty tokens per parameter: loss falls as a power law in both model size and dataset size, so compute-optimal training scales them together rather than growing parameters alone.

On efficiency, dense attention costs order n-squared times d in sequence length. Sparse and low-rank approximations, along with IO-aware kernels like FlashAttention, cut this dramatically.

Sparse attention restricts each query to a subset of keys, for example local windows plus strided patterns, reducing complexity toward order n times the square root of n while preserving most of the effective receptive field.

Finally, alignment: after supervised fine-tuning on demonstrations, RLHF fits a reward model to human preferences and optimizes the policy against it, as in Ouyang et al. 2022; DPO bypasses the reward model entirely.

The RLHF objective maximizes expected reward minus a KL penalty against the reference policy, which keeps the fine-tuned model from drifting off-distribution while still improving preference scores.

Together these methods define the modern recipe: scale compute-optimally, train and serve efficiently, and align the policy with human intent without sacrificing the base model's capabilities.

Clarification: Transpose the complete key projection and add the mask to logits.

Equations, code and original cards

Advanced Techniques and Optimization

• Scaling Laws: Kaplan et al. 2020; Chinchilla N ~ 20D

• Efficiency: Sparse Attention, FlashAttention, Pruning

• Alignment: SFT, RLHF (Ouyang et al. 2022), DPO

L(\theta) \propto N^{-\alpha}

Loss follows a power law in parameters and data

S=(XW_Q)(XW_K)^\top/\sqrt{d_k}+M,\quad A=\operatorname{softmax}(S)

Sparse attention: toward \(O(n \sqrt{n})\) vs. dense \(O(n^2 d)\)

\max_{\theta} \mathbb{E}_{x,y \sim D} \big[ \log p_{\theta}(y|x) + \lambda R(\theta) \big]

Maximize reward minus KL penalty to reference policy

Moment 05 / 09

Implementation Insights: Python & PyTorch

We now turn to the implementation of next-token prediction in Python and PyTorch. The slide walks through the three core stages of the training loop: embedding, the forward pass with cross-entropy loss, and gradient-based optimization.

We begin with token embedding and positional encoding, which inject token identity and sequence order into the residual stream. PyTorch's nn.Embedding maps discrete indices to dense vectors through a learned lookup table.

This snippet instantiates the embedding layer, parameterized by vocabulary size and embedding dimension. Adding the positional encoding to the token embeddings yields the input representation, because self-attention alone is permutation-equivariant.

Next, the forward pass and loss computation. The model maps the input sequence to logits, the unnormalized scores over the vocabulary, producing one prediction vector per position for the subsequent token.

We apply the model to the input tensor to obtain logits, then compute the cross-entropy loss against the shifted next-token targets. Note the reshape: logits are flattened to batch-times-sequence by vocabulary, matching the loss function's expected input.

Finally, the optimization step. We zero the gradients to prevent accumulation across mini-batches, backpropagate the loss through the computation graph, and update parameters with Adam, the standard adaptive optimizer for transformer pretraining.

Together, these snippets form the complete training step of a next-token prediction model, connecting the autoregressive maximum-likelihood objective directly to executable PyTorch code.

Equations, code and original cards

Implementation Insights: Python & PyTorch

Token Embedding
& Positional Encoding

import torch.nn as nntok_emb = nn.Embedding(vocab_size, d_model)pos_enc = sinusoidal_encoding(max_len, d_model)x = tok_emb(tokens) + pos_enc[:tokens.size(1)]

Forward Pass
& Loss Computation

logits = model(x)loss_fn = nn.CrossEntropyLoss()loss = loss_fn(logits.view(-1, vocab_size), targets.view(-1))

Gradient Computation & Optimizer Step

• Clear accumulated grads: optimizer.zero_grad()

• Backprop through graph: loss.backward()

• Adam parameter update: optimizer.step()

Moment 06 / 09

Whiteboard Derivation: Gradient Backpropagation

Let's derive the gradient backpropagation for next-token prediction: how the cross-entropy loss propagates from the logits back through softmax, embeddings, and attention projections.

We begin with the chain rule over the softmax output layer. The softmax maps logits to a probability distribution over the vocabulary, and we need the Jacobian of this map to move gradients through it.

The key result: with cross-entropy loss and softmax, the gradient of the loss with respect to the logits is exactly the predicted probability minus the one-hot target. This remarkably clean form, softmax minus label, is why this pairing is universal in language model training.

Next, gradients for the embedding and attention parameters. These updates shape the token representations and the query, key, and value projections that determine what each position attends to.

The partial derivative of the loss with respect to the embedding matrix is the logit gradient propagated backward through the output projection: each token vector is nudged in proportion to how its logit contributed to the prediction error.

Similarly, the gradient with respect to the query matrix flows through the attention scores: the softmax over Q K transpose scaled by the square root of d-k. This is where the Jacobian of attention gets expensive, since scores couple all pairs of positions.

The optimization intuition: each gradient measures the sensitivity of the loss to a parameter. Gradient descent steps against this sensitivity, and the gradient norm tells us how aggressively the model is still learning.

To summarize: we derived backpropagation from the softmax-cross-entropy logits, through the embedding matrix, and into the attention projections. This is the exact computation that trains every transformer language model.

Clarification: A final hidden-state gradient is not generally the embedding-table gradient.

Equations, code and original cards

Gradient Backpropagation Derivation

1. Chain Rule over Softmax Output

• Softmax \( \sigma(z)_i = \frac{e^{z_i}}{\sum_k e^{z_k}} \) over vocabulary logits

• Cross-entropy \( L = -\sum_i y_i \log \hat{y}_i \) with \( \hat{y} = \sigma(z) \)

• Gradient: \( \frac{\partial L}{\partial z_i} = \hat{y}_i - y_i \) (softmax minus one-hot)

\nabla_z L = \hat{y} - y

2. Gradients for Embedding & Attention

• Embedding grads: \( \frac{\partial L}{\partial E} \) via logit grad backpropagated through output projection

• Attention grads: chain rule through Q, K, V projections and the \( \mathrm{softmax}(QK^\top/\sqrt{d_k}) \) Jacobian

Z=HW_o,\quad \nabla_H L=(P-Y)W_o^\top;\quad \nabla_E L\text{ additionally follows the upstream network}
\frac{\partial L}{\partial Q} = \frac{\partial L}{\partial A} \frac{\partial A}{\partial Q}

3. Optimization Intuition

• Gradient = sensitivity of loss to each parameter

• Descent steps against the gradient; gradient norm tracks learning progress

Moment 07 / 09

Research Trends and Open Questions

Let's survey the open research frontier in next-token prediction as of 2026. The field is moving fast, and the central question has shifted from whether scale works to what scale alone cannot solve.

First, scaling. Since Kaplan and colleagues established neural scaling laws, and Hoffmann's Chinchilla analysis showed compute-optimal training demands roughly twenty tokens per parameter, frontier runs now exceed ten to the twenty-five FLOPs, straining budgets and motivating efficiency work.

Second, interpretability and alignment. Mechanistic interpretability, reverse-engineering features out of superposition, remains unsolved at scale, and alignment methods like RLHF and direct preference optimization still offer no guarantee that behavior tracks human intent under distribution shift.

Third, training-objective research. Multi-token prediction, auxiliary density losses, and curriculum variations all attempt to elicit emergent capabilities more sample-efficiently than plain next-token cross-entropy at ever-larger scale.

The takeaway: scaling buys capability, but interpretability, alignment, and objective design determine whether that capability is reliable. Hold these threads as we turn to architectures and optimization.

Equations, code and original cards

Research Trends and Open Questions

Scaling laws, interpretability, and alignment in next-token prediction

• Kaplan and Chinchilla scaling laws: compute-optimal token-to-parameter ratios

• Open problems: mechanistic interpretability, superposition, RLHF and DPO alignment

• Beyond cross-entropy: multi-token prediction and auxiliary objectives

Moment 08 / 09

Challenging Quiz: Theory and Computation

Time to test your command of the theory and the arithmetic behind next-token prediction. Work each problem independently before checking anything.

After you submit, we'll walk through each solution together, and I'll clarify any step where the mechanics still feel unclear.

Equations, code and original cards

Moment 09 / 09

Summary and Key Takeaways

Let's begin by revisiting why next-token prediction serves as the basis for emergent reasoning in large language models. Minimizing the cross-entropy loss, the negative log likelihood of each token given its prefix, forces the model to internalize syntax, semantics, and world structure, and complex behaviors emerge from that single objective.

Next, we emphasize the importance of mathematical rigor in understanding these models deeply. Precise derivations of the softmax Jacobian, gradient flow through attention, and the geometry of the loss landscape let us reason about how parameters shape behavior and how gradient-based optimization actually performs.

Finally, I encourage each of you to actively engage in research and experiment with advanced techniques. Ablations, scaling analyses, and fine-tuning studies consolidate theory and drive innovation in model development and deployment.

To summarize, we have covered why next-token prediction is pivotal for emergent reasoning, how mathematical rigor provides a solid foundation for understanding, and the value of hands-on research to push the boundaries of current models.

As we conclude this session, consider how these insights integrate and what further questions you might explore in projects or advanced study. Your journey into the intricacies of AI model behavior is just beginning.

Equations, code and original cards

Summary and Key Takeaways

• Next-token prediction underpins emergent reasoning: minimizing cross-entropy over each token given its prefix forces the model to internalize syntax, semantics, and world structure.

• Transformers model conditional dependencies via attention, building dynamic context representations in the residual stream.

• Mathematical rigor is essential for understanding parameter gradients, loss landscapes, and optimization dynamics.

• Formal derivations of the softmax Jacobian and backpropagation through attention reveal how gradient signal propagates.

• Pursue research engagement: run ablations, scaling analyses, and fine-tuning experiments on modern architectures.

• Hands-on implementation deepens theoretical comprehension and drives innovation.

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

3 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.