Skip to content
ImagineWorld

Language Modeling Fundamentals

node_idnode-book_building-frontier-llm-from-scratch_chapter-04-language-modeling-fundamentals
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleLanguage Modeling Fundamentals
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — Language Modeling Fundamentals

Section titled “Chapter 4 — Language Modeling Fundamentals”

Strip a large language model down to its definition and it is almost embarrassingly simple: a function that, given some text so far, returns a probability distribution over what comes next. Everything else in this book — attention, experts, latent caches, reinforcement learning — exists to make that one function better. This chapter pins down the definition, the objective that trains it, and the input/output contract the rest of the architecture must satisfy, and ends with a baseline language model you can train in seconds.

A language model assigns a probability to a sequence of tokens x1,…,xTx_1, \ldots, x_T. By the chain rule of probability, that joint probability factors exactly into a product of next-token conditionals:

p(x1,…,xT)=∏t=1Tp(xt∣x1,…,xt−1).p(x_1, \ldots, x_T) = \prod_{t=1}^{T} p(x_t \mid x_1, \ldots, x_{t-1}).

This factorization is the reason language models are autoregressive: predict one token at a time, each conditioned on everything before it, then feed the prediction back in to continue. The model never has to represent the astronomically large space of whole sequences — only the manageable problem of scoring the next token given a context. Figure 4.1 shows the pattern.

[!visual-conversion] Diagram, PDF 053 (printed 55). Five context tokens, labelled “input context (tokens 1..t)”, each feed into one wide box, “language model p(next | context)”. An arrow runs to a small bar chart headed “distribution over next tok[en]” with three labelled bars, mat .61, rug .22 and sofa .09, plus one shorter unlabelled bar. A note beneath reads “sample or take the argmax → append → repeat (autoregression)”.

flowchart LR
    subgraph ctx["input context (tokens 1..t)"]
        direction LR
        t1["the"] ~~~ t2["cat"] ~~~ t3["sat"] ~~~ t4["on"] ~~~ t5["the"]
    end
    ctx --> lm["language model p(next | context)"]
    lm --> dist["distribution over next token<br/>mat .61 · rug .22 · sofa .09 · …"]
    dist -. "sample or take the argmax → append → repeat (autoregression)" .-> ctx

Figure 4.1. Autoregressive language modeling. The model maps a context to a probability distribution over the vocabulary; a decoding rule picks the next token, which is appended and fed back in. Training simply asks the model to put high probability on the token that actually came next.

Historically these conditionals were estimated by counting — an n-gram model tallies how often each token follows the previous n-1. Counting cannot generalize across contexts it has never seen, so the field moved to neural models that learn a continuous representation of context, and then discovered that scaling those models on self-supervised next-token prediction over enormous corpora produces general capability. That single objective, applied at scale, is the engine behind every model in Chapter 1.

Training data needs no labels: the text is its own supervision. For a token sequence, the input is the sequence and the target is the same sequence shifted left by one — at every position the model must predict the following token. This is called teacher forcing: during training the model always conditions on the true history, not its own past predictions.

The loss is the cross-entropy between the model’s predicted distribution and the one-hot true token, averaged over every position — precisely the maximum-likelihood objective of Section 2.2. In code it is the shift plus a single cross-entropy call:

data = tokens[:block_size + 1] # a chunk of token ids
x = data[:-1] # context: tokens 0 .. T-1
y = data[1:] # target: tokens 1 .. T (shifted)
logits = model(x) # (T, vocab)
loss = F.cross_entropy(logits, y) # average negative log-likelihood

Python — inputs and targets are the same stream, shifted by one

Because each position is supervised independently, a single sequence of length T yields T training signals at once — one reason language models are so sample-efficient to pretrain. Two metrics summarize the loss, and the distinction matters for honest comparison (Table 4.1).

MetricDefinitionComparable across models?
Perplexitye(cross-entropy per token)e^{(\text{cross-entropy per token})}only if they share a tokenizer
Bits-per-bytecross-entropy in bits per UTF-8 byteyes — tokenizer-independent

Table 4.1 — Two ways to report the same loss

Perplexity is per token, so a model with a larger vocabulary can look better simply by using fewer, bigger tokens. Bits-per-byte normalizes by raw bytes and is the fairer cross-model measure; we use it in Chapter 29.

Every model in this book obeys the same input/output contract, and it is worth stating once so the architecture chapters can focus on the middle. The input is a tensor of integer token ids of shape (B, T). An embedding table maps each id to a vector, giving (B, T, d). The body of the model — whatever it is — transforms that into a context-aware (B, T, d). Finally an unembedding (the “language-model head,” a linear layer of shape (d, V)) projects back to (B, T, V) logits, one distribution per position. A common trick called weight tying shares the embedding and unembedding matrices, saving parameters and often improving quality. Everything from Chapter 7 onward is about making the middle transformation better; the two ends stay the same.

4.4 Decoding: Turning Distributions into Text

Section titled “4.4 Decoding: Turning Distributions into Text”

At generation time we repeatedly sample from the model’s next-token distribution. How we sample trades off coherence against diversity, and the same model can feel robotic or unhinged depending on the rule. Table 4.2 lists the standard options; Chapters 9 and 25 return to them in depth.

StrategyRuleEffect
Greedytake the argmax each stepdeterministic; tends to loop and flatten
Temperature Tdivide logits by T before softmaxT<1 sharper/safer; T>1 more random
Top-kkeep the k highest, renormalizehard cap on the tail
Top-p (nucleus)smallest set with cumulative prob ≥ padaptive tail; the common default
Min-pkeep tokens with prob ≥ p·maxtail scales with the model’s confidence
Repetition penaltydown-weight already-seen tokensreduces verbatim loops

Table 4.2 — Decoding strategies

To make all of this concrete, here is a complete language model — the bigram model, where the prediction depends only on the single previous token. It is too weak to be useful, but it is a real, trainable language model in a dozen lines, and it establishes the exact scaffolding (embedding → logits, the shifted loss, sampling) that the GPT in Chapter 10 will reuse without change.

import torch, torch.nn as nn, torch.nn.functional as F
class BigramLM(nn.Module):
def __init__(self, vocab_size):
super().__init__()
# row i holds the logits for the token that follows token i
self.logit_table = nn.Embedding(vocab_size, vocab_size)
def forward(self, idx): # idx: (B, T) token ids
return self.logit_table(idx) # logits: (B, T, vocab_size)
@torch.no_grad()
def generate(model, idx, n_new):
for _ in range(n_new):
logits = model(idx)[:, -1, :] # distribution after the last token
probs = logits.softmax(dim=-1)
nxt = torch.multinomial(probs, num_samples=1)
idx = torch.cat([idx, nxt], dim=1) # append and continue
return idx
# --- train with the loop from Chapter 3 ---
model = BigramLM(vocab_size)
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
for step in range(2000):
x, y = get_batch('train') # (B, T) and its left-shift
logits = model(x)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1))
opt.zero_grad(set_to_none=True); loss.backward(); opt.step()

Python — a complete bigram language model and sampler

Run it and the loss falls from ln(V) — the perplexity of random guessing — toward the entropy of the bigram statistics, and samples shift from noise to vaguely word-shaped strings. That gap between “random” and “bigram” is the easiest win in language modeling; every later chapter is about the much harder gains beyond it, which require context longer than one token. That need is exactly what attention provides, and it is where Part III begins.

It is worth seeing the other bigram model — the one that learns nothing at all — because the contrast is illuminating. Karpathy’s makemore (MIT-licensed) begins not with the neural model above but with a pure counting bigram: tally how often each token follows each other token, normalize the counts into probabilities, and sample. Reproduced here, it is the n-gram idea from Section 4.1 in its entirety:

import torch
# N[a, b] = number of times token b follows token a
N = torch.zeros((vocab_size, vocab_size), dtype=torch.int32)
for a, b in zip(tokens, tokens[1:]):
N[a, b] += 1
# counts -> probabilities, with +1 smoothing so nothing is impossible
P = (N + 1).float()
P = P / P.sum(dim=1, keepdim=True) # each row sums to 1
# sampling: from the current token's row, draw the next token
nxt = torch.multinomial(P[current], num_samples=1)

Python — karpathy/makemore · the count-based bigram (reproduced, MIT licence)

This model has no parameters and no training — only a table of counts — and that is precisely its ceiling. It captures which token tends to follow which, but it cannot use any context beyond the single previous token, and it cannot generalize to pairs it never saw (only the +1 smoothing keeps those from being flatly impossible). The neural bigram above replaces the count table with a learned logit_table and reaches essentially the same quality; neither can do better, because both are blind to all but one token of history. That shared ceiling is the whole point. The only way past it is to condition on more context — and doing that efficiently, for contexts of thousands of tokens, is the problem attention solves. makemore itself walks exactly this path, growing the bigram into an MLP and then a transformer one commit at a time; it and nanoGPT are the gentlest companions to Part III, which we begin now.

With the objective, the input/output contract, and a working baseline in hand, Part I is complete. We have the mathematics, the autograd machinery, and the language-modeling problem itself. Part II builds the two things the model consumes before it can learn anything: a tokenizer, and a pretraining data pipeline.

4.6 Perplexity: Measuring a Language Model

Section titled “4.6 Perplexity: Measuring a Language Model”

[…] a language model assigns probabilities to tokens, the natural question is how good those probabilities are, and the standard intrinsic answer is perplexity. It is simply the exponential of the mean cross-entropy loss, and it has a concrete interpretation: the effective number of equally likely tokens the model is choosing among at each step:

# perplexity is the exponential of the mean cross-entropy
loss = F.cross_entropy(logits.view(-1, V), targets.view(-1))
perplexity = loss.exp() # lower is better

Python — eval/perplexity.py: perplexity from cross-entropy

A perplexity of 10 means the model is, on average, as uncertain as if it were guessing uniformly among ten possibilities for each token; a perplexity of 2 means it has narrowed the field to roughly a coin flip. As training proceeds and the model learns the structure of language, perplexity falls — which is why it is the workhorse metric for tracking pretraining progress (Chapter 17). Its limits are equally important to know: perplexity measures prediction, not usefulness, and a model can have excellent perplexity while being unhelpful or unsafe, which is exactly the gap that post-training (Part VI) and task evaluation (Chapter 29) exist to close. It is a measure of how well the model models text, nothing more — but for that purpose it is precise and indispensable.

Perplexity counts the model’s uncertainty Exponentiate the cross-entropy and you get the effective number of choices the model weighs per token. It tracks pretraining beautifully and says nothing about helpfulness — a low-perplexity model can still be useless, which is why it is necessary but never sufficient.

4.7 The Generation Gap: Teacher Forcing versus Autoregression

Section titled “4.7 The Generation Gap: Teacher Forcing versus Autoregression”

There is a fundamental asymmetry between how a language model is trained and how it generates, and it is worth naming because it explains a class of failures. During training the model uses teacher forcing: at every position it is shown the true previous tokens and asked only to predict the next one. During generation (Section 10.6) it has no such luxury — it must condition on its own previously generated tokens, which may already contain mistakes.

This mismatch, sometimes called exposure bias, means the model is never trained on the situation it actually faces at inference: a context partly of its own making, possibly flawed. A small early error can then compound, because the model conditions on it and drifts further from anything it saw in training — the same error-compounding dynamic that makes long-horizon agents fragile (Section 39.5). The mitigations are limited and imperfect, and in practice the dominant remedy is simply scale: a model trained on enough data learns distributions robust enough that it mostly recovers from its own small errors. Understanding the gap matters less for fixing it than for reading model behavior correctly — it is why generation quality can degrade over a long output in ways the training loss never revealed, and why teacher-forced perplexity (Section 4.6) is an optimistic estimate of how the model will actually perform when it must stand on its own outputs.

Trained on truth, deployed on its own words Teacher forcing shows the model true history; autoregression makes it condition on its own, possibly wrong, outputs. The gap lets early errors compound and makes perplexity an optimistic guide to real generation — scale, not a clean fix, is what mostly closes it.

There is something that should strike you as surprising about this entire enterprise: the training objective is to predict the next token, an almost trivial-sounding task, and yet it produces models that reason, translate, write code, and hold conversations. How does so simple an objective yield such rich capability? The resolution is the conceptual heart of why language modeling works.

The objective is simple, but the task is not. To predict the next token well across the entirety of human text — not on a narrow corpus but on encyclopedias, code, dialogue, arguments, stories — a model is forced to learn an enormous amount, because all of it is needed to reduce prediction error on real text. Predicting the next word of a grammatical sentence requires learning grammar; continuing a factual statement requires learning facts; finishing a chain of reasoning requires learning to reason; completing a line of code requires learning the language’s rules. The model is not told to learn these things, but it cannot minimize its loss without them, so they emerge as the means to the end of prediction. In the limit, predicting what comes next in all of human writing demands, in some real sense, understanding it. This is the deep insight that licenses the whole approach: a single, simple, scalable objective — applied to enough text with enough capacity — induces general capability as a side effect of getting good at prediction. Every later chapter, from architecture to alignment, is in service of this one idea working at scale.

A simple objective, an impossibly rich task Predicting the next token sounds trivial, but doing it well across all human text requires grammar, facts, reasoning, and code — learned not by instruction but as the only way to reduce the loss. General capability emerges as a side effect of prediction at scale.