Transformers/Large Language Models

Lesson 5.31,962 words

Large Language Models

A large language model is a decoder-only transformer trained on one objective — predict the next token. This first part assembles the inference side: the language-modeling head that turns a hidden state into a distribution over the vocabulary, autoregressive generation, and the decoding strategies — greedy, beam, and sampling with temperature, top-k, and nucleus — that read text back out of that distribution.

╌╌╌╌

The transformer gave us a block that reads a sequence and, at every position, produces a vector that has attended to everything before it. A large language model is a decoder-only stack of those blocks trained on the single task of predicting the next word, over a large fraction of the written web, at large scale. The ingredients are one architecture, one objective, and scale; nothing else is new.

The objective is the same one the n-gram model and the neural language model were built around: assign a probability to the next token given the tokens so far. Writing for the prefix, the model estimates

and the probability of a whole sequence factors, by the chain rule, into a product of these conditionals:

The transformer's only job is to compute the right-hand side well. Everything in this lesson is either how the block turns its hidden state into that distribution, how we read text out of the distribution, or how we drive the distribution to be accurate by training on enough text.

The language-modeling head

A stack of transformer blocks maps an input sequence to a sequence of hidden vectors. At position the top block emits , a -dimensional summary of the prefix that has attended, through the causal mask, to and no further.1 To turn that vector into a prediction we need a map from to a probability distribution over the vocabulary . This map is the language-modeling head, and it is two operations: a linear projection followed by a softmax.

The projection is called the unembedding. A matrix scores every word in the vocabulary against the hidden state, producing one logit per word:

Each entry measures how well word matches the evidence in ; the -th row of is effectively a second embedding of word , and the logit is its inner product with the hidden state. The softmax then normalizes the logits into a distribution:

The language-modeling head. The top transformer block emits a hidden state ; the unembedding scores every word in the vocabulary, giving a logit vector , and a softmax normalizes it into the next-token distribution .

The unembedding matrix is where most of a model's parameters can pile up, since is large — tens of thousands of subword tokens is typical. A standard trick is weight tying: reuse the input embedding matrix as the unembedding, setting .2 The rows of already learn a vector per word at the input; the rows of must learn one per word at the output; there is no reason to learn two. Tying them improves perplexity and removes an entire block of parameters.

Autoregressive generation

The head gives us a distribution over the next token. To generate text we sample one token from it, append that token to the context, and run the model forward again — now conditioned on the token we just produced. Repeating this is autoregressive generation: the word chosen at each step becomes part of the input for the next.3

The word autoregressive is borrowed loosely. A true autoregressive model predicts a value from a linear function of its own past values; a transformer language model is deeply non-linear, but it shares the defining feature — each output is conditioned on the outputs already produced.

Algorithm:Generate\textsc{Generate} — autoregressive decoding from a language model
  1. 1
    input: model PθP_\theta, prompt tokens w1:kw_{1:k}, max length nn
  2. 2
    tkt \gets k
  3. 3
    repeat
  4. 4
    ytPθ(w1:t)\mathbf{y}_t \gets P_\theta(\cdot \mid w_{1:t})
    next-token distribution from the head
  5. 5
    wt+1Decode(yt)w_{t+1} \gets \textsc{Decode}(\mathbf{y}_t)
    pick a token: argmax, sample, ...
  6. 6
    append wt+1w_{t+1} to the context
  7. 7
    tt+1t \gets t + 1
  8. 8
    until wtw_{t} is the end-of-sequence token or t=nt = n
  9. 9
    return wk+1:tw_{k+1:t}

The line $\textsc{Decode}(\mathbf{y}_t)$ is the only free choice, and it is the whole subject of the next section. Priming the context is what makes generation practically useful. Instead of starting from a bare start-of-sequence marker, seed the model with a task-appropriate prefix: a source sentence for translation, a long article for summarization, a question for question answering.4 The model does not know it is doing a task — it only continues the text — but a prefix that makes the desired output the most probable continuation turns next-token prediction into a general-purpose interface.

Decoding strategies

Given the distribution , how do we commit to an actual token? The choice trades off two failure modes. Always take the most probable token and the text is fluent but flat, and often globally suboptimal; sample too freely from the tail and the text drifts into incoherence. Decoding strategies sit on that spectrum.

Greedy decoding

The simplest rule takes the single most probable token at every step:

This is greedy decoding.5 It is fast and deterministic, but greedy is a local choice, and the locally best token can strand the model on a globally worse sequence. A token that looks best now may leave no good continuation, while a slightly-less-probable token now might open onto a much more probable completion. Greedy search cannot see that far ahead.

Beam search addresses this by keeping the best partial sequences at once instead of one.6 The number is the beam width. At each step, every surviving sequence — a hypothesis — is extended by every possible next token, all candidates are scored by their total log-probability, and only the best are kept. A hypothesis that ends in the end-of-sequence token is complete and set aside; the search runs until the beam empties.

Beam search with width . From each of the two surviving hypotheses (thick blue), all vocabulary extensions are scored by cumulative log-probability; only the best two survive to the next column, while greedy (dashed) commits to a single locally-best path and cannot recover.

Because probabilities of long strings are tiny, hypotheses are scored in log-space, where the product becomes a sum that can be extended incrementally:

One wrinkle: because every term is negative, longer sequences score lower purely for being long, so a naive beam favors short outputs. The usual fix is length normalization — divide the score by the number of tokens before comparing:7

Beam search is standard in machine translation, where there is a single correct answer to search for and widths of to are common. For open-ended generation it is a poor fit: maximizing probability produces bland, repetitive text. Open-ended generation calls for sampling.

Sampling

Instead of maximizing, we can sample the next token from the distribution itself, choosing each word with probability proportional to . This is the same weighted-die idea used to visualize an n-gram model back in the foundations: lay every word out on the unit interval with width equal to its probability, throw a dart, and read off the word it lands in.8 Pure sampling matches the model's distribution exactly, which is both its strength and its problem — the long tail of low-probability tokens is collectively heavy, so even a well-trained model occasionally samples a bizarre word and the text derails. The remaining strategies all reshape or truncate the distribution before sampling to control that tail.

Temperature

Temperature rescales the logits before the softmax by a factor :

Dividing by a small stretches the logits apart, sharpening the distribution toward its peak — in the limit sampling becomes greedy. A large compresses the logits, flattening the distribution toward uniform and making rare words more likely. Temperature does not remove any word; it only reweights the distribution, from sharper () to flatter ().

Truncated sampling distributions. Temperature (low ) sharpens the full distribution; top-k keeps the k highest-probability words and renormalizes; top-p / nucleus keeps the smallest set whose probabilities sum to p. The kept mass is shaded; everything to the right of the cut is discarded.

Top-k and top-p (nucleus) sampling

The tail is heavy because it is long, not because any one word in it is likely. Truncated sampling cuts the tail off and renormalizes what remains, then samples from that.

  • Top-k sampling keeps the highest-probability words, zeros the rest, and renormalizes. Sampling then never strays outside the most plausible continuations. The weakness is that is fixed: when the model is confident, words include junk; when it is unsure, words cut off good options.
  • Top-p sampling, also called nucleus sampling, fixes that by cutting on probability mass instead of count. Sort the vocabulary by probability and keep the smallest set — the nucleus — whose cumulative probability first reaches a threshold (say ), discarding the rest. The cutoff adapts: a peaked distribution keeps few words, a flat one keeps many.

In practice temperature, top-k, and top-p compose: a generation call might set and together, sharpening slightly and then clipping the tail. Greedy and beam sit at one end (deterministic, probability-maximizing); temperature and truncated sampling occupy the other (stochastic, diversity-seeking).

A worked decoding step

Carry one step through with numbers. Suppose the head has produced logits over six candidate next words after the prefix the cat:

At the default temperature the softmax gives probabilities . Greedy takes sat. Pure sampling takes sat about of the time but leaves real mass on the rest, including on the implausible purple. Now apply each knob:

  • Temperature divides the logits by before the softmax, sharpening the distribution to sat gains, the tail shrinks. Temperature does the reverse, flattening to , which raises every rare word.
  • Nucleus () at sorts by probability and accumulates: sat (), ran (), slept (). The nucleus is ; the other three words are discarded and the kept three are renormalized to sum to one. Even a single unlucky draw of purple is now impossible, while the plausible alternatives ran and slept stay available.

The two mechanisms are orthogonal: temperature reshapes the whole distribution, truncation deletes the tail. Composing then would first sharpen, then cut — the usual production setting for text that is varied but never derails.

One decoding step over six candidates. Default softmax () leaves a long tail; low temperature () sharpens toward the top word; nucleus sampling () keeps the top three words whose mass first reaches 0.9 (shaded) and discards the rest.

From reading text out to putting it in

Everything so far assumes the distribution is already good — the head shapes it, autoregression rolls it forward, and a decoding strategy reads text out of it. But that distribution is only as good as the parameters behind it, and those come from training on an enormous amount of text. The next part is where the parameters come from: self-supervised pretraining at web scale, the scaling laws that make its loss predictable, the KV cache that makes long-context inference affordable, and how the finished model is evaluated. This continues in Large Language Models: Pretraining and Scaling.

Footnotes

  1. Jurafsky & Martin, Speech and Language Processing (3rd ed.), §9.8 — Transformers as Language Models: at each position the final transformer layer produces an output distribution over the vocabulary, trained by teacher forcing to predict the next word.
  2. Jurafsky & Martin, §9.4 — Weight Tying: the input embedding matrix and the final projection both hold a set of word vectors of shape ; tying them () improves perplexity and reduces parameter count.
  3. Jurafsky & Martin, §9.3 (Autoregressive Generation): incrementally generate by sampling the next word from the softmax, feeding each sampled word back as the next input, until an end-of-sequence marker or a length limit is reached.
  4. Jurafsky & Martin, §9.9 — Contextual Generation and Summarization: priming autoregressive generation with a task-appropriate context (a source sentence, an article) drives translation, summarization, and question answering from the same next-token machinery.
  5. Jurafsky & Martin, §10.5 — Beam Search: choosing the single most probable token at each step, , is greedy decoding; it is locally optimal and can miss the globally most probable sequence.
  6. Jurafsky & Martin, §10.5 — Beam Search: keep hypotheses (the beam width), extend each by every vocabulary item, score by cumulative log-probability, and prune back to the best ; production MT uses widths of roughly .
  7. Jurafsky & Martin, §10.5 — Beam Search: because models assign lower probability to longer strings, hypotheses are length-normalized by dividing the summed log-probability by the number of tokens before comparison.
  8. Jurafsky & Martin, §3.3 — Sampling Sentences from a Language Model; §10.7.3 (Monte Carlo decoding): sampling chooses each word with probability proportional to its likelihood, as with rolling a weighted die over the softmax distribution.

╌╌ END ╌╌