Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

2.1 Markov Chains to RNNs

Suppose a machine announces a color, says wait and ready, then repeats the color. You have two recordings, red wait ready red and blue wait ready blue. Pause each one just after ready. Which word comes next?

A model that looks back one word sees ready in both recordings. Looking back two words still gives the same clue, wait ready. A listener could answer both questions with a single bit of memory: “Did this recording start with red?” This is the difference between keeping the last few tokens and keeping a feature of the past.

Markov Chains: The Simplest Sequence Models

In 1913, Andrey Markov examined 20,000 letters in Pushkin’s Eugene Onegin. He counted how often a vowel followed another vowel and how often one followed a consonant. The counts let him study dependence between neighboring letters. [1]

The Markov Property

Let XtX_t denote the state at step tt and xtx_t its observed value. For a first-order Markov chain, knowing the current state is enough to specify the distribution of the next one.

P(Xt+1=x∣X1=x1,…,Xt=xt)=P(Xt+1=x∣Xt=xt)P(X_{t+1}=x \mid X_1=x_1,\ldots,X_t=x_t)=P(X_{t+1}=x \mid X_t=x_t)

In a bigram language model, the state is the last token. In the two recordings, red and blue each follow ready once. Estimating by relative frequency gives P(red∣ready)=1/2P(\text{red}\mid\text{ready})=1/2 in both cases. A trigram conditions on the last two tokens, which also coincide here. A 4-gram has enough context to distinguish these recordings. Insert one more wait into each and its last three tokens coincide again.

Why Markov Models Still Matter

A finite-order model can process a stream of any finite length by sliding its window one token at a time. The order limits which observed tokens can affect a prediction. With a vocabulary of VV tokens, a window of kk tokens has up to VkV^k distinct histories. Many have few or no observations, so a count-based model can fall back to shorter histories when estimating probabilities.

The choice of state matters. A hand-built Markov model could store the announced color as its state across any number of wait tokens. An RNN lets the training objective shape which features the state carries forward. Elman demonstrated this idea by feeding hidden activations back into a network that predicted successive inputs. [2]

Recurrent Neural Networks (RNNs): Adding Memory

One recurrent cell with a loop, shown again as successive copies passing a hidden state forward.

Each copy uses the same weights. Figure by Christopher Olah. [3]

At step tt, the input vector xt\mathbf{x}_t and the previous hidden state ht−1\mathbf{h}_{t-1} determine the new state ht\mathbf{h}_t. A separate output layer converts it into a distribution yt\mathbf{y}_t over the next token.

ht=tanh⁡(Whhht−1+Wxhxt+bh)\mathbf{h}_t=\tanh(\mathbf{W}_{hh}\mathbf{h}_{t-1}+\mathbf{W}_{xh}\mathbf{x}_t+\mathbf{b}_h) yt=softmax⁡(Whyht+by)\mathbf{y}_t=\operatorname{softmax}(\mathbf{W}_{hy}\mathbf{h}_t+\mathbf{b}_y)

The matrices Whh\mathbf{W}_{hh}, Wxh\mathbf{W}_{xh} and Why\mathbf{W}_{hy} map the previous state, input and new state respectively. The vectors bh\mathbf{b}_h and by\mathbf{b}_y are biases. At inference, a single cell needs just its current hidden vector to continue the stream. If two histories reach exactly the same hidden state, the network will give the same predictions for any identical continuation.

Training Reality: Unrolling Through Time

During next-token training with teacher forcing, each input is the observed token from the training sequence. The following observed token is its target. All the inputs are available at the start, yet the cell must compute h1\mathbf{h}_1 before h2\mathbf{h}_2. Different recordings can run side by side in a batch.

With full backpropagation through time (BPTT), a prediction error after ready can affect the update that processed red. Its gradient passes through every intervening state update. If each update shrinks that gradient, the first token receives a weak learning signal. The network may be able to represent a memory that the optimizer struggles to learn. Section 2.2 works through this gradient product. [4]

PyTorch RNN

Give the two recordings one hidden number each. Encode red as +1+1, blue as −1-1, and both wait and ready as zero. Set both recurrent-cell weights to one and omit biases. With h0=0h_0=0, the update becomes ht=tanh⁡(ht−1+xt)h_t=\tanh(h_{t-1}+x_t). The code runs the two recordings as a batch on the CPU. The weights are chosen by hand so the calculation can be checked without fitting a model. [5]

import torch
from torch import nn

cell = nn.RNNCell(input_size=1, hidden_size=1, bias=False)
steps = torch.tensor([[1., -1.], [0., 0.], [0., 0.]])
hidden = torch.zeros(2, 1)

with torch.no_grad():
    cell.weight_ih.fill_(1.)
    cell.weight_hh.fill_(1.)
    for inputs in steps:
        hidden = cell(inputs.reshape(2, 1), hidden)
        print([round(value, 3) for value in hidden[:, 0].tolist()])

The three rows printed are [0.762, -0.762], [0.642, -0.642] and [0.566, -0.566]. After ready, the sign still identifies the first color. Try changing the recurrent weight to zero. Both states then become zero at wait, showing exactly where the earlier color was lost.

Example: The Fading Memory of RNN

Follow both recordings to wait. With the recurrent weight set to 1, their states are still distinguishable. What will each state be at ready if the recurrent weight is 0 throughout the recording? Compare your answer with the trace.

Does the hidden state still distinguish the first color?

ht = tanh(xt + w ht−1), h0 = 0

Weight w on the previous state
Hidden state across both recordings−10+1t=0t=1t=2t=3
Hidden state after each token, rounded to three decimals
Step · input tokenStarts with redStarts with blue
1 · red / blue+0.762−0.762
2 · wait+0.642−0.642
3 · ready+0.566−0.566

After ready, the states have opposite signs. The sign still identifies the first color.

Quizzes

Quiz 1: Why does a trigram give the same distribution in both recordings? After ready both histories end in wait ready. A trigram uses these last two tokens to choose one distribution for both histories.

Quiz 2: Could a two-state Markov model remember the color across a thousand waits? Yes. Use one state for each color and have each wait leave the state unchanged. The choice of state determines which information survives.

Quiz 3: If a cell can read a million tokens, what does that tell you about its prediction at the last token? The update can be applied a million times. To test whether the first token still matters, change it and replay the same remaining tokens. Compare the final predictions.

Quiz 4: How could the output layer lose the color even if the two hidden states differ? If all its weights are zero, only the output bias affects the probabilities. Both hidden states then produce the same distribution.

Quiz 5: Why can the two recordings run together, while the steps within each recording must run in order? Each recording has its own state, so its update is independent of the other recording. Within a recording each update needs the state produced by the previous step.

Quiz 6: What is a sufficient condition for vanishing gradients in the BPTT Jacobian product? For column-vector states, let Jj=diag⁡(1−hj2)WhhJ_j=\operatorname{diag}(1-h_j^2)W_{hh} be the derivative of step jj with respect to the previous state, with the square taken elementwise. The derivative from step kk to step tt is Jt⋯Jk+1J_t\cdots J_{k+1}. If each operator norm satisfies ∥Jj∥2≤ρ<1\|J_j\|_2\le\rho<1, the product norm is at most ρt−k\rho^{t-k}. Backpropagation applies the transpose of that product to the loss gradient.

References

  1. Markov, A. A. (1913). An Example of Statistical Investigation of the Text Eugene Onegin Concerning the Connection of Samples in Chains. English translation, Science in Context (2006).
  2. Elman, J. L. (1990). Finding Structure in Time. Cognitive Science, 14, 179–211.
  3. Olah, C. (2015). Understanding LSTM Networks.
  4. Bengio, Y., Simard, P., & Frasconi, P. (1994). Learning Long-Term Dependencies with Gradient Descent Is Difficult. IEEE Transactions on Neural Networks, 5, 157–166.
  5. PyTorch. RNNCell.