← All notes
Course chapters
On this page

Lesson 29 · Large language models

From N-grams to Transformers: a recap

Reconnect local counts, learned representations, recurrent memory and attention. Follow each modelling problem to its mechanism and remaining trade-offs, with links back to the earlier lessons.

1. Connect the problems, not just the names

The course has introduced many components. This lesson adds no new model family: it connects the questions that made those components useful.

Three recurring difficulties help organise the story:

  • Order: “cat chases dog” and “dog chases cat” contain the same words but express different relationships.
  • Context: “apple” can refer to a fruit or a company, depending on its surroundings.
  • Sparse observations: a finite corpus cannot contain every reasonable sentence or token combination.

The route below is a conceptual teaching sequence. It is not a claim that research followed one unavoidable line, that every idea appeared in this exact order, or that later methods made every earlier approach obsolete.

Throughout the language-model examples, we seek a distribution over continuations:

p(x1,…,xn)=∏t=1np(xt∣x<t).p(x_1,\ldots,x_n)=\prod_{t=1}^{n}p(x_t\mid x_{<t}).

Different methods estimate those conditional probabilities in different ways. Embeddings, memory mechanisms and attention are components used to build such models, rather than interchangeable names for the same thing.

2. N-grams: begin with local counts

An N-gram model approximates the next-token distribution using a suffix of the preceding history. A bigram uses one previous token; a trigram uses two.

For an unsmoothed count estimate:

p^(w∣h)=C(h,w)C(h),C(h)>0,\widehat p(w\mid h)=\frac{C(h,w)}{C(h)},\qquad C(h)>0,

where hh is the chosen context suffix. The model can offer a fast, inspectable estimate when useful patterns recur in the data.

But exact combinations become sparse as the context order grows. An unseen continuation can receive zero under the unsmoothed estimate; an unseen history has no directly defined ratio. Smoothing and backoff redistribute probability and borrow evidence from shorter contexts, so “N-grams always assign zero to new sentences” would be incorrect.

The fixed-order approximation also cannot directly use information beyond its chosen history. A clue such as “grew up in France” may lie outside the suffix used to predict a later language name.

Mechanism: count local contexts. Remaining limits: sparse estimates, restricted context and little built-in sharing between distinct token identities.

Revisit N-grams.

3. Word vectors: share useful features

Instead of treating every word only as an unrelated identifier, an embedding lookup provides learned coordinates. A neural model can reuse these features across different contexts.

Distributional training uses patterns of surrounding words to shape the representations. Similar usage can lead to similar vectors, but proximity is an outcome of the data and objective, not a guarantee of identical meaning. Antonyms can also occur in similar contexts.

Vector analogies can illustrate regularities in a learned space. They are not exact algebraic laws for language, and their success depends on the embeddings, vocabulary and evaluation.

A static embedding gives the same lookup vector to a word whenever it appears. “Apple” therefore starts from the same row in different contexts. Later contextual computation can produce different representations for those occurrences.

Mechanism: dense learned features. Remaining limits: static lookup vectors do not alone resolve every word sense, and embeddings by themselves are not a complete next-token model.

Revisit Word vectors.

4. Feed-forward language models: predict from shared representations

The illustrated neural language model looks up context embeddings, concatenates a fixed number of them, transforms the result and projects to vocabulary probabilities:

p(⋅∣h)=softmax⁡ ⁣(Wo f(Concat⁡(e1,…,em))+bo).p(\cdot\mid h)=\operatorname{softmax}\!\left(W_o\,f(\operatorname{Concat}(e_1,\ldots,e_m))+b_o\right).

This schematic formula uses column-vector convention; the operations can equivalently be written with row vectors and corresponding transposes.

Shared parameters let related contexts influence one another. Evidence learned from sentences about apples can help with a new combination involving pears, if the representations and training support that transfer. It is not an automatic promise that every unseen combination receives a correct prediction.

With finite logits and a standard full Softmax, vocabulary probabilities are positive. Avoiding exact zero probabilities does not itself establish good calibration or an understanding of a sentence.

The model still receives a fixed-sized context window in this example. Earlier information outside that window is unavailable to its prediction.

Mechanism: nonlinear prediction with shared embedding features. Remaining limit: a fixed direct input window.

Revisit Feed-forward neural language models.

5. RNNs: carry an evolving state

A recurrent model processes a sequence using a hidden state:

ht=fθ(ht−1,et).h_t=f_\theta(h_{t-1},e_t).

The same recurrent parameters are reused at successive positions. There is no fixed suffix length built into this recurrence, and the state can in principle depend on earlier inputs across a variable-length sequence.

However, the state is finite. It is not a complete transcript of unlimited history. Repeated transformations and Jacobian products can make it difficult to retain or learn the influence of a distant clue. Exploding gradients are also possible.

Each state update depends on the previous one, limiting parallel computation across sequence positions. Work within a step and across independent examples can still run in parallel, so saying that RNNs cannot use a GPU would be wrong.

Mechanism: shared recurrent state updates. Remaining limits: retention and optimisation difficulties, plus the sequential state dependency.

Revisit Recurrent neural networks.

6. LSTMs: control retention and new writes

An LSTM introduces a cell state and learned gates. Its additive cell update is:

ct=ft⊙ct−1+it⊙c~t,ht=ot⊙tanh⁡(ct).c_t=f_t\odot c_{t-1}+i_t\odot\widetilde c_t, \qquad h_t=o_t\odot\tanh(c_t).

The forget gate controls direct retention of the old cell, the input gate controls a candidate write, and the output gate controls how the cell contributes to the hidden output.

Along the direct cell-state path, retention involves products of forget-gate values. Values near one can preserve a signal for longer; repeated smaller values can still reduce it. Additional dependencies through the gates also affect the total gradient.

A clue about growing up in France might be retained until a later prediction about language. Whether it actually is retained depends on learned behaviour and the input, not merely on the presence of an LSTM label.

The comparison with residual connections is useful: both introduce additive paths. But an LSTM's gated time path and a Transformer's depth-wise residual path are different computations with different derivatives.

Mechanism: gated cell updates. Remaining limits: finite memory, imperfect retention and the same recurrent dependency across steps.

Revisit Long short-term memory.

7. Transformers: exchange context through attention

Attention gives a position direct access to permitted key/value representations rather than requiring every clue to travel through successive recurrent states:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QKTdk+M)V.\operatorname{Attention}(Q,K,V) =\operatorname{softmax}\!\left(\frac{QK^{\mathsf T}}{\sqrt{d_k}}+M\right)V.

The mask MM specifies which connections are allowed. An encoder can use bidirectional input access; a causal decoder excludes future target positions.

A short computational path between allowed positions can help model distant relationships. It does not guarantee that a trained model will attend to the right token, resolve a pronoun or retain every long-range fact.

For a known training sequence, query rows within one layer can be calculated together with matrix operations. Causal masking still prevents future-target leakage. Layers depend on earlier layers, and ordinary autoregressive generation still needs each selected token before producing the next one.

Attention is also not the whole architecture. The course connected it with:

Dense full-sequence attention has quadratic pairwise work. KV caching, sparse attention and FlashAttention address reuse, connectivity and memory traffic in different ways. MoE separates stored expert capacity from selected expert work, while distillation trains a student from teacher signals.

Scaling computation and data can improve performance, but scale alone does not guarantee truthfulness, useful instruction following or better results on every task.

Mechanism: contextual attention plus position-wise transformations in a stack. Remaining limits: finite context, attention costs and imperfect learned behaviour.

8. Reassemble the route

  1. 01N-grams

    Question: Estimate continuations from observed counts

    Use a short suffix of the history to estimate a next-token distribution.

    Still limited by: Sparse counts and a fixed context order; smoothing helps but does not add unrestricted context.

  2. 02Word vectors

    Question: Share information between distinct word identities

    Learn dense representations so related contexts can support shared features.

    Still limited by: Static embeddings are components, not complete language models, and one lookup vector cannot by itself distinguish every sense.

  3. 03Feed-forward language models

    Question: Generalise predictions beyond exact count-table matches

    Combine context embeddings with learned nonlinear transformations and a vocabulary output.

    Still limited by: The illustrated model still uses a fixed-size input window; generalisation depends on training.

  4. 04Recurrent neural networks

    Question: Carry information beyond a fixed input window

    Update a hidden state using the current input and previous state, with shared recurrent parameters.

    Still limited by: The hidden state is finite, and recurrent updates depend sequentially on earlier steps.

  5. 05LSTMs

    Question: Control what recurrent memory keeps and replaces

    Use a cell state and learned gates for retention, writing and reading.

    Still limited by: Gates improve retention paths without guaranteeing perfect memory or removing the recurrent dependency.

  6. 06Transformers

    Question: Exchange context without a token-by-token recurrent state update

    Use attention, position information and feed-forward processing in stacked blocks.

    Still limited by: Dense full-sequence attention has quadratic pairwise work; ordinary autoregressive generation remains sequential.

Figure 29-1. A conceptual route from local counts to contextual attention. Embeddings are a component within neural models; these are overlapping ideas, not six mutually exclusive inventions in a complete historical timeline.

The recurring pattern is problem → mechanism → remaining limitation. These questions overlap: embeddings appear inside recurrent and Transformer models, and attention can also be combined with recurrence.

What happens when an exact token combination was not observed?

Mechanism: Use a short suffix of the history to estimate a next-token distribution.

Remaining limit: Sparse counts and a fixed context order; smoothing helps but does not add unrestricted context.

A guide to the mechanisms already covered, not an automatic model-selection rule or a performance ranking.

Review 29-A. Select a modelling question, inspect its mechanism and limitation, then jump to the recap or the original course lesson.
Pause and think

If an application only needs a fast estimate from short, familiar contexts, must it always use the newest and largest model?

I've thought about it — show the answerHide answer

No. The task, data, accuracy requirements, latency and resource budget determine what is useful. A simple baseline can be appropriate and can reveal whether a more expensive model actually adds value.

The recap explains modelling trade-offs; it does not establish a universal ordering of architectures from worst to best.

Keep three distinctions clear when returning to the earlier lessons:

  1. Representation versus model: an embedding is a useful component; a language model also needs a prediction mechanism and objective.
  2. Training versus generation: parallel calculations over a known sequence do not make all future generated tokens independent.
  3. Capacity versus outcome: model size and context access offer opportunities, not guarantees of correct learned behaviour.

Next, we will look at frontiers and the road ahead, using these same questions to understand which limitations newer research tries to address.

Check your understanding

1. What is the most useful way to read this lesson's progression?
2. Which mechanism directly helps share learned evidence between related word identities?