Search

Search papers and lessons

Autoregressive Model

Level 3 · 12 min read

An autoregressive model scores a sequence as a product of next-element probabilities, so it is trained to predict each element from those before it and generates by sampling one at a time.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • Losses & regularization
  • Neural network basics
  • Pre-training
  • Sign in to see your progress

TL;DR

An autoregressive model describes a sequence by predicting each element from all the elements before it. The probability of the whole sequence is the product of these one-step predictions, so the model only has to learn one kind of question: given what came before, what comes next? It is trained by making those predictions as accurate as possible on real data, and it generates new sequences by sampling one element, appending it, and repeating.

Where you'll see it: the next-token prediction behind GPT-style chat models and code completion, and the decoder that writes text, audio tokens or image tokens one at a time in many generative systems.

Intuition

Writing one step at a time

Think of finishing a sentence someone has started. You do not plan the whole sentence at once. You look at the words so far, think about what usually follows, pick a word, and then look again at the longer sentence. Each choice is conditioned on everything already written, and nothing after the current point has been decided yet.

An autoregressive model does exactly this, with probabilities. For each position it outputs a distribution over the possible next elements. When it is used to generate, one element is drawn from that distribution and appended. When it is trained, the true next element is known from the data, so the model is scored on how much probability it put on that true element.

The word "autoregressive" comes from regression on its own past. The model regresses each value on the previous values of the same sequence. A forecaster who predicts tomorrow's temperature from the last few days is doing the same thing with numbers.

Why one step at a time works

Modelling a whole sequence in one go means assigning a probability to every possible sequence, and there are far too many to write down. Predicting one element given a context is a small, fixed-size problem. It repeats at every position, so each training sentence provides many such problems for free. The sentence "the cat sat on the mat" yields six of them, one at each position, and every one of them teaches the model something.

The cost is that generation is sequential. Element number 500 cannot be produced before element 499, because it depends on it. Much of the engineering around these models is about making that loop cheap.

flowchart LR
  A[Sequence so far] --> B[Model]
  B --> C[Distribution over next element]
  C --> D[Sample one element]
  D --> A

The math

Definition

Let x1,x2,…,xTx_1, x_2, \dots, x_T be a sequence where each xtx_t takes values in a finite set V\mathcal{V} (the vocabulary). Write x<t=(x1,…,xt−1)x_{\lt t} = (x_1, \dots, x_{t-1}) for the prefix before position tt.

Definition: Autoregressive model

A model is autoregressive if it defines the joint probability of a sequence through its one-step conditionals:

pθ(x1,…,xT)=∏t=1Tpθ(xt∣x<t),p_\theta(x_1, \dots, x_T) = \prod_{t=1}^{T} p_\theta(x_t \mid x_{\lt t}),

where θ\theta denotes the learned parameters and each factor is a distribution over V\mathcal{V} that depends only on the prefix.

The factorisation is not an extra assumption. It is the chain rule of probability applied in a fixed order. For three events, P(a,b,c)=P(a) P(b∣a) P(c∣a,b)P(a, b, c) = P(a)\,P(b \mid a)\,P(c \mid a, b), because P(a,b)=P(a) P(b∣a)P(a, b) = P(a)\,P(b \mid a) and the same step applies to the third event. What the autoregressive model chooses is the parametrisation: each conditional is produced by one network that reads the prefix. The architecture that reads the prefix can be a recurrent network, a Transformer with a causal mask, or something else. The defining property is only that position tt cannot see positions after tt.

The one-step distribution

For a neural model, the prefix is first encoded into a vector ht\mathbf{h}_t. A linear layer maps it to one raw score (a logit) per vocabulary element, and the Softmax turns the scores into probabilities:

pθ(v∣x<t)=exp⁡(zt,v)∑u∈Vexp⁡(zt,u),zt=Wht+b.p_\theta(v \mid x_{\lt t}) = \frac{\exp(z_{t,v})}{\sum_{u \in \mathcal{V}} \exp(z_{t,u})}, \qquad \mathbf{z}_t = W\mathbf{h}_t + \mathbf{b}.

Here zt,vz_{t,v} is the logit for element vv at position tt. Every output is positive and the outputs sum to 1, so each position yields a valid distribution.

Training by maximum likelihood

Given a dataset of sequences, we choose θ\theta to maximise the probability of the data. This is maximum likelihood estimation. Taking logarithms turns the product into a sum, and minimising the negative log-likelihood gives the loss

L(θ)=−∑t=1Tlog⁡pθ(xt∣x<t).\mathcal{L}(\theta) = -\sum_{t=1}^{T} \log p_\theta(x_t \mid x_{\lt t}).

When the target at each position is a single known element, this is the cross-entropy at that position, which equals −log⁡-\log of the probability given to the true element. The loss is measured in nats when the logarithm is natural. A confident correct prediction costs little; a confident wrong one costs a lot.

0.20.40.60.81012345probability given to the true elementloss (nats)
  • loss = -log p
The per-position loss falls as the model gives the true element more probability. Each dot is one example value.

Perplexity

Average the per-position loss over a sequence, Lˉ=L/T\bar{\mathcal{L}} = \mathcal{L}/T, and exponentiate:

PPL=exp⁡(Lˉ).\mathrm{PPL} = \exp(\bar{\mathcal{L}}).

Perplexity is the effective number of equally likely choices the model is weighing at each step. A model that guesses uniformly over a vocabulary of size ∣V∣|\mathcal{V}| has perplexity exactly ∣V∣|\mathcal{V}|.

Generation by sampling

To generate, start from a prefix (possibly empty), compute the one-step distribution, draw xtx_t from it, append it, and repeat until a stop element or a length limit. Drawing from the full distribution is called ancestral sampling. Two common variations change how the draw is made:

  • Greedy decoding takes the most probable element each time. It is deterministic and often repetitive.
  • Temperature τ>0\tau > 0 divides the logits before the softmax: p∝exp⁡(zv/τ)p \propto \exp(z_v / \tau). Values below 1 sharpen the distribution toward its favourite; values above 1 flatten it.

Exposure and teacher forcing

During training the model is always given the true prefix. At generation time it is given its own earlier samples. These differ as soon as one sample is wrong, and the gap between the two regimes is the source of Exposure Bias. The standard training recipe, feeding the true prefix at each step, is called Teacher Forcing. It makes training parallel across positions, because every position's target is known in advance.

Worked examples

Example
A three-token sentence by hand

Suppose a tiny model has learned these one-step probabilities for the sentence "the cat sat":

  1. p(the∣start)=0.5p(\text{the} \mid \text{start}) = 0.5
  2. p(cat∣the)=0.2p(\text{cat} \mid \text{the}) = 0.2
  3. p(sat∣the cat)=0.4p(\text{sat} \mid \text{the cat}) = 0.4

The sequence probability is the product of the three factors:

  1. p(the cat sat)=0.5×0.2×0.4=0.04p(\text{the cat sat}) = 0.5 \times 0.2 \times 0.4 = 0.04.

The training loss is the sum of the per-position losses in nats:

  1. −ln⁡0.5=0.6931-\ln 0.5 = 0.6931, −ln⁡0.2=1.6094-\ln 0.2 = 1.6094, −ln⁡0.4=0.9163-\ln 0.4 = 0.9163, which add to 3.21893.2189.

Check: −ln⁡0.04=3.2189-\ln 0.04 = 3.2189, the same number.

Average loss per token is 3.2189/3=1.07303.2189 / 3 = 1.0730 nats, so the perplexity is e1.0730=2.92e^{1.0730} = 2.92. Interpretation: on this sentence the model is, on average, as uncertain as a fair choice among about 2.9 options at each step. The weakest step is "cat" after "the", where the model gave only 0.2 to the correct word.

Example
From logits to a sampled token

A model's final layer produces logits z=(2.0,1.0,0.0)z = (2.0, 1.0, 0.0) for the vocabulary {cat,dog,fish}\{\text{cat}, \text{dog}, \text{fish}\}.

  1. Exponentiate: e2.0=7.389e^{2.0} = 7.389, e1.0=2.718e^{1.0} = 2.718, e0=1e^{0} = 1.
  2. Sum: 7.389+2.718+1=11.1077.389 + 2.718 + 1 = 11.107.
  3. Divide: p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090). These add to 1.

Now sample with temperature. At τ=0.5\tau = 0.5 the logits become (4,2,0)(4, 2, 0):

  1. Exponentiate: 54.59854.598, 7.3897.389, 11; the sum is 62.98762.987.
  2. p=(0.867,0.117,0.016)p = (0.867, 0.117, 0.016). The favourite has become much more dominant.

At τ=2\tau = 2 the logits become (1,0.5,0)(1, 0.5, 0):

  1. Exponentiate: 2.7182.718, 1.6491.649, 11; the sum is 5.3675.367.
  2. p=(0.506,0.307,0.186)p = (0.506, 0.307, 0.186). The distribution is flatter and "fish" is now a real possibility.

If the true next token in the training data is "dog" at τ=1\tau = 1, its loss is −ln⁡0.245=1.41-\ln 0.245 = 1.41 nats. A model that knew nothing would give every element probability 1/∣V∣1/|\mathcal{V}|. For a 50,000-element vocabulary that is ln⁡50000=10.82\ln 50000 = 10.82 nats per token, so a loss far below that is evidence the model has learned something.

Example
Next-word prediction in a realistic context

Consider the prefix "The weather today is" and a real vocabulary of tens of thousands of tokens. The numbers below are illustrative, not measured from any model:

  1. Candidate next tokens: "sunny" (0.12), "cold" (0.09), "great" (0.05), "banana" (0.00001).
  2. The model spreads most of its mass over plausible words, and almost none over ones that never follow "is" in this setting.
  3. Generation draws "cold" with probability 0.09 under plain sampling, and then conditions the next step on "The weather today is cold".

The second step is where the autoregressive structure matters. Had the sampler picked "banana", every later prediction would be conditioned on that odd prefix, and the model would now be extrapolating from text it never saw in training. This is why generation quality depends on what the model has already committed to.

Tradeoffs and failure modes

Autoregressive modelling is simple, exact in its likelihood, and scales well with data. It is not free.

SituationWhat goes wrongBetter choice
Long outputs need many stepsLatency grows linearly with length, because each step waits for the lastKey-value caching so each step reuses earlier work; speculative decoding for speed
The task needs context on both sides, such as filling in a blankA left-to-right model cannot see the words after the blankA masked or bidirectional model, trained to predict hidden tokens from both sides
Greedy decoding on open-ended textRepetitive loops, bland outputSampling with a temperature, or nucleus (top-p) sampling
Long generations driftEarly mistakes compound, since the model conditions on its own errors (Exposure Bias)Training on model-generated prefixes, or verification and resampling steps
The model is used to rank whole alternativesSumming log-probabilities favours short outputsLength normalisation, or scoring with a separate model
Very high-dimensional data, such as raw pixelsSequences become enormous and sampling is slowModel a compressed token sequence first, then decode it

Two failure modes deserve a warning. First, a likelihood that looks good does not always mean a useful sample; a model can assign high probability to fluent but unhelpful text. Second, perplexity compares models only on the same tokenisation and the same test data. Two models with different tokenisers report perplexities on different units, so the numbers are not comparable.

History

The idea of predicting the next symbol from the previous ones is old. Andrey Markov studied letter sequences in the early 1900s, in work that led to what are now called Markov chains. Claude Shannon used letter and word models of English in his 1948 work on information theory to estimate how much information is in the language. These were count-based models over short windows.

Neural versions followed. Bengio and colleagues in 2003 used a neural network to estimate next-word probabilities and showed it beat count-based models, a result often treated as the start of modern neural language modelling. Recurrent networks extended the idea to context of unlimited length in principle, and sequence-to-sequence systems used them for translation in the mid-2010s.

The transformer, introduced in 2017, replaced recurrence with attention and made it practical to train on very large corpora. Using a causal mask so that each position sees only its past, models trained this way became the standard autoregressive generators. The large-scale results reported in 2020 showed that a single next-token objective, trained at scale, could be steered to many tasks by putting examples in the prompt.

Check yourself

QuestionA model assigns probability 0.25 to the correct next token at one position. What is the loss at that position in nats, and what is the perplexity if every position had this loss?Show answer

The loss is −ln⁡0.25=1.3863-\ln 0.25 = 1.3863 nats. If every position had this loss, the average is also 1.3863, and perplexity is e1.3863=4e^{1.3863} = 4. That matches intuition: a model giving 0.25 to the right answer is as uncertain as a choice among four equally likely options.

QuestionCompute the probability of the sequence in which the three one-step probabilities are 0.5, 0.2 and 0.4. Why does the chain rule let us use these numbers and not a probability for every possible three-token sequence?Show answer

The product is 0.5×0.2×0.4=0.040.5 \times 0.2 \times 0.4 = 0.04. The chain rule says the joint probability of any sequence equals the product of each element's probability given its prefix. So the model only needs to store one conditional distribution per prefix, not a table over every full sequence. Because the vocabulary is finite and each prefix defines one distribution, the factorisation is exact, not an approximation.

QuestionWhy does temperature below 1 make generated text more predictable, and what happens to the probability of rare tokens?Show answer

Dividing logits by a temperature below 1 scales the differences between them up. The exponential then amplifies the gap between the highest logit and the rest, so the top element takes more of the total mass and rare elements take less. Rare elements are not impossible, but they are sampled much less often, which is why low temperature gives safer and more repetitive output.

QuestionYou are building a model that fills in a missing word in the middle of a sentence. Why is a standard left-to-right autoregressive model a poor fit, and what changes?Show answer

A left-to-right model conditions each position only on what comes before it, so it cannot use the words after the gap, which often carry most of the information about the missing word. A masked or bidirectional model is trained to predict hidden tokens using context on both sides. It gives up the simple one-pass sampling of autoregressive generation in exchange for using the full surrounding text.

Sources