Part II · Branches & Language
Chapter 6
Language Before Transformers
Counting words, embedding meaning, and the bottleneck that attention broke.
In one sentenceLanguage modeling moved from counting word sequences to learned embeddings and recurrent networks, and attention appeared to fix their long-distance memory problem.
The problem
Words become data
Chapter 4 gave us networks that learn their own features. Now give one a sentence. A network cannot read letters directly: first we decide what counts as a unit, assign each unit a vocabulary ID, and turn the IDs into numerical inputs. Early language models often used whole words; a modern tokenizer may use word pieces. The choice changes how long a sequence is and what happens to a word never seen before.
An ID is an address, not a measurement. If cat = 17 and dog = 18, the network must not infer that a dog is one more cat. A one-hot vector avoids that false arithmetic: each word owns one coordinate. But in a 50,000-word vocabulary every vector has 50,000 coordinates, and cat is just as orthogonal to dog as to carburettor.
A language model receives a sequence of discrete text units and must map each unit to a vocabulary ID before any neural computation can begin.
Open the concept page →
A one-hot vector represents a vocabulary item with a 1 in its own position and 0 everywhere else.
Open the concept page →
The first idea
Predict one word
Instead of writing rules for language, ask one measurable question again and again: given the words so far, what comes next? A language model must assign a probability to every candidate. After "the cat sat on the", mat ought to get more probability than moon. Training compares those probabilities with what the text actually did.
The chain rule says that a sentence probability is the product of these next-word probabilities:
The models in this chapter differ mainly in what they keep from that history. The first practical answer was to keep almost none of it. A bigram counts what followed one word; a trigram counts what followed two. Divide a continuation's count by the total count for that context and you have a probability.
A tiny worked example, using the 12-sentence corpus in the lab below. Start from the and score the rest of "the cat sat on the mat". The first step has only one word of context, so it uses a bigram; after that, a trigram:
| Step | Context | Count evidence | Probability |
|---|---|---|---|
cat | the | 4 of 20 words after "the" | 1/5 |
sat | the cat | 1 of 3 | 1/3 |
on | cat sat | 1 of 1 | 1 |
the | sat on | 3 of 3 | 1 |
mat | on the | 2 of 5 | 2/5 |
Multiply them: . The certain steps cost nothing; the uncertain ones (which animal? which surface?) carry all the doubt. This toy corpus is far too small for the numbers to mean anything about English.
Try it · toy model
Build a sentence with a count-based model: see exactly which words it looks at, which corpus lines it counts, and how the chain rule multiplies each step.
A language model assigns a probability to each possible next text unit given the units before it.
Open the concept page →
An n-gram model predicts the next word by counting what followed the previous n−1 words in a corpus.
Open the concept page →
The obstacle
Where counts fail
Try the cat as a trigram context in the lab. The tiny corpus has a few continuations. Now try the mouse. The corpus contains those words but never a following word: the exact context has zero matches. Add-one smoothing removes the zero probability by adding a small count to every candidate, but with no evidence it gives every word the same guess. More careful n-gram systems back off to shorter contexts and smooth more intelligently; exact-count sparsity still grows rapidly as the context gets longer.
The escape is to let similar words share evidence. Bengio and colleagues' 2003 neural language model learned a short vector for each word while learning next-word probabilities. If kitten and cat are used similarly, their vectors can become close, and the model can generalize from a seen phrase to a related unseen one. Its context window was still fixed, but the representation was no longer an exact-match table.
A neural language model learns word vectors and a probability function together, so similar contexts can support one another.
Open the concept page →
The representation
Words become nearby points
A learned embedding gives each word a dense vector. Training can place words used in similar contexts near one another, so a model can use evidence from neighbouring parts of the space.
An embedding is a learned vector for an item — a word, token, document or image — positioned so that items used in similar ways end up close together.
Open the concept page →
Word2vec made learning such vectors fast at large scale. In CBOW, nearby words predict a centre word. In skip-gram, a centre word predicts nearby words. A later word2vec paper introduced negative sampling, which contrasts real word-context pairs with a few sampled non-pairs rather than calculating a full-vocabulary probability for every pair. GloVe took another route: fit word vectors to global word co-occurrence statistics collected across the corpus.
The lab below trains a miniature skip-gram model with negative sampling while you watch. coffee and tea never appear in the same sentence, but both sit next to hot and cup, so training pulls their vectors in the same direction. Start it a few times from different random positions: the picture rotates and flips, but the neighbourhoods come back.
Try it · toy model
Train a tiny 2-D word2vec live in your browser and watch words that share neighbours drift together; compare with one-hot IDs, where nothing transfers.
Word2vec trains compact word vectors with simple local-context prediction tasks rather than a full neural language model.
Open the concept page →
GloVe learns word vectors from global word co-occurrence statistics, providing another route to distributional geometry.
Open the concept page →
Sequence memory
Remembering a sequence
An n-gram can see only a fixed suffix. A recurrent neural network (RNN) instead reads one word at a time. It combines the current word vector with its previous hidden state to produce a new state:
The same weights are reused at every step. The hidden state can, in principle, carry a clue from much earlier in the sentence. It is a learned summary, though, not a lossless transcript. To train the network, unfold the repeated cell into a chain and send error backward through the steps: backpropagation through time. The path from a late prediction back to an early word can be long; gradients multiply along it and often vanish or explode. Chapter 4's gradient problem has returned, now across time.
An RNN reads a sequence one step at a time, updating a hidden state that carries information from earlier steps.
Open the concept page →
A better memory
Gates help, but time still passes one step at a time
An LSTM adds a cell state and learned gates that control what old information to keep, what new information to write and what to expose. A GRU is a more compact gated recurrent unit with a similar goal. A gate is a number between 0 and 1 multiplied into an information path; the network learns its values from data. This gives useful information and training gradients a better route through many steps.
Try it · toy model
Read a long sentence one word at a time and watch how much of an early clue survives in a plain RNN versus a gated memory cell.
Gating improved long-range sequence learning. It did not change the ordering constraint: to compute step 20, an RNN or LSTM still needs the state from step 19.
LSTMs and GRUs add learned gates to a recurrent network so it can keep, discard and update information more deliberately.
Open the concept page →
Translation
Translating with one vector
The next challenge was mapping one sequence to another. English "the blue house" becomes French "la maison bleue": a different order, possibly a different length. In a sequence-to-sequence model, an encoder reads the source and a decoder generates the target one word at a time. Influential 2014 recurrent systems from Cho and colleagues and from Sutskever and colleagues made this pattern concrete.
Early versions passed the decoder only the encoder's final state: one fixed-size vector for the whole source.
Whether the source has 3 words or 300, the decoder gets one vector, the encoder's final state, and it is the same one for every output word. Switch to attention to see the alternative.
A sequence-to-sequence model uses an encoder to read one sequence and a decoder to produce another, possibly of a different length.
Open the concept page →
For a short sentence, that summary can work. For a long one, a decoder may need a precise source detail that the final state failed to retain. This is the fixed-vector bottleneck. It is a practical information-path problem, not a claim that a vector can never encode a long sentence. The encoder has been asked to put every useful detail into one suitcase before the decoder even knows which detail it will need next.
Early encoder-decoder models compressed every detail of the source sequence into one fixed-size vector before decoding.
Open the concept page →
The breakthrough
Attention looks back
Bahdanau, Cho and Bengio's 2014 solution was to keep the encoder's state at every source position. For each target word, the decoder scores how relevant each source state is, normalizes the scores with softmax, and takes their weighted average. The resulting context is different at each decoding step. When producing bleue, the model can look toward blue; when producing maison, toward house. Switch the translation diagram above to With attention and step through the French words to see this.
Keep
Preserve one encoder state for every source position.Align
At this decoder step, score those states and apply softmax.Read
Mix the source states by their weights, then use the result to predict the next target word.
Those weights are learned from data and need not correspond to a clean one-to-one translation dictionary. The essential change is direct, step-specific access to the source. This is encoder-decoder attention, often called cross-attention; Chapter 7's self-attention lets positions within a sequence exchange information with one another.
Attention lets a model build each output from a weighted mix of all the inputs, with the weights computed on the fly from how relevant each input is.
Open the concept page →
Neural machine translation trains an encoder and decoder to map a source-language sequence to a target-language sequence.
Open the concept page →
Why it matters
Why it matters
This chapter is the chain of problems behind the Transformer: exact word counts could not generalize, dense word vectors shared evidence, recurrent state extended context, gates made that state more usable, and attention let a decoder retrieve source details rather than trusting one compressed final state.
For a researcher, each step is an example of an architecture changing the path information must travel. For an engineer, the same story explains why model input units, vocabulary design, context length and sequential computation are real system choices rather than cosmetic details.
What came next
To Transformers
Attention had fixed the single-summary bottleneck, but the encoder and decoder were still recurrent. Information within each side still moved through a chain of hidden states, and each step waited for the previous one. The next proposal removed the recurrence and let every position look directly at other positions.
A recurrent network reads left to right, carrying one hidden state. What it knew about animal must survive 6 sequential updates before reaching it — fading a little at each step (shaded). And step 7 can't be computed until step 6 is done, so training can't be parallelized across the sequence.
Concepts in this chapter
Mark each one as you go. Must-know concepts are the core path.
- AttentionAttention lets a model build each output from a weighted mix of all the inputs, with the weights computed on the fly from how relevant each input is.Know wellMust know
- EmbeddingsAn embedding is a learned vector for an item — a word, token, document or image — positioned so that items used in similar ways end up close together.Know wellMust know
- The Fixed-Vector BottleneckEarly encoder-decoder models compressed every detail of the source sequence into one fixed-size vector before decoding.Know wellMust know
- Language ModelingA language model assigns a probability to each possible next text unit given the units before it.Know wellMust know
- LSTMs and GRUsLSTMs and GRUs add learned gates to a recurrent network so it can keep, discard and update information more deliberately.UnderstandMust know
- N-Gram ModelsAn n-gram model predicts the next word by counting what followed the previous n−1 words in a corpus.Know wellMust know
- One-Hot EncodingA one-hot vector represents a vocabulary item with a 1 in its own position and 0 everywhere else.Know wellMust know
- Recurrent Neural NetworksAn RNN reads a sequence one step at a time, updating a hidden state that carries information from earlier steps.Know wellMust know
- Sequence-to-Sequence ModelsA sequence-to-sequence model uses an encoder to read one sequence and a decoder to produce another, possibly of a different length.Know wellMust know
- Text as DataA language model receives a sequence of discrete text units and must map each unit to a vocabulary ID before any neural computation can begin.Know wellMust know
- Word2VecWord2vec trains compact word vectors with simple local-context prediction tasks rather than a full neural language model.UnderstandMust know
- GloVeGloVe learns word vectors from global word co-occurrence statistics, providing another route to distributional geometry.UnderstandShould know
- Neural Language ModelA neural language model learns word vectors and a probability function together, so similar contexts can support one another.UnderstandShould know
- Neural Machine TranslationNeural machine translation trains an encoder and decoder to map a source-language sequence to a target-language sequence.UnderstandShould know
What do I actually need to remember?
- Text must be split into units and assigned vocabulary IDs; the choice of unit changes the problem.
- One-hot vectors preserve identity but make every different word equally unrelated; embeddings can share statistical structure.
- A language model assigns P(next unit | previous units); the chain rule combines those probabilities over a sequence.
- N-grams count exact short contexts; smoothing removes zeros but cannot make an unseen context meaningful.
- Bengio's neural language model, word2vec and GloVe learned dense word vectors by different training routes.
- An RNN carries a hidden state forward and trains through time; long paths hurt gradient flow and force sequential computation.
- LSTM and GRU gates help preserve information, but still process positions in order.
- Early seq2seq models used one fixed-size encoder summary for the whole source — the fixed-vector bottleneck.
- Bahdanau attention lets each decoder step score and mix all encoder positions; self-attention is the next chapter's extension.
You do not need to memorize everything else. This list is the revision sheet.
Key papers
A Neural Probabilistic Language Model
Yoshua Bengio, Réjean Ducharme et al. · 2003 · Journal of Machine Learning Research
Learned word representations and next-word probabilities jointly, so similar words could help the model generalize to word sequences it had never counted.
- Problem
- An n-gram table sees most possible word sequences zero times, and counting alone cannot share evidence between similar words.
- What was new
- A neural probability model that looks up a distributed vector for each context word and learns those vectors with the prediction task.
How to read it: Read the abstract and Figure 1 first: the embedding lookup and the probability model are learned together.
Efficient Estimation of Word Representations in Vector Space
Tomas Mikolov, Kai Chen et al. · 2013 · ICLR 2013 (workshop)
Showed that simple, fast models trained on billions of words produce word vectors whose geometry captures meaning — the idea behind every embedding you use today.
- Problem
- Neural language models learned good word representations but were too slow to train on very large corpora.
- What was new
- Two stripped-down architectures (CBOW and skip-gram) that drop the expensive hidden layer, making it practical to learn embeddings from huge datasets.
How to read it: Read sections 1, 3 and 4. The famous 'king − man + woman ≈ queen' analogy test is in section 4.
Distributed Representations of Words and Phrases and their Compositionality
Tomas Mikolov, Ilya Sutskever et al. · 2013 · NeurIPS 2013
Introduced negative sampling as a faster way to train skip-gram word vectors and explicitly discussed the limits of word-only representations.
- Problem
- Full-vocabulary prediction was expensive, especially for large corpora and vocabularies.
- What was new
- Train a word-context pair against a few sampled non-pairs, alongside subsampling of frequent words and phrase discovery.
GloVe: Global Vectors for Word Representation
Jeffrey Pennington, Richard Socher, Christopher Manning · 2014 · EMNLP 2014
Showed another path to word vectors: fit them to global word co-occurrence statistics rather than only local prediction examples.
- Problem
- Local context prediction does not explicitly use the full corpus-wide co-occurrence table.
- What was new
- Fit vector dot products to log co-occurrence counts so vector relationships reflect probability ratios.
Learning long-term dependencies with gradient descent is difficult
Yoshua Bengio, Patrice Simard, Paolo Frasconi · 1994 · IEEE Transactions on Neural Networks
Showed why gradients vanish or explode when trained across many steps — the core obstacle for deep and recurrent networks.
- Problem
- Recurrent networks failed to learn dependencies spanning long time gaps.
- What was new
- Analysis showing a trade-off between storing information robustly and propagating useful gradients, so gradients shrink exponentially with distance.
- Influenced
- Long Short-Term Memory
Long Short-Term Memory
Sepp Hochreiter, Jürgen Schmidhuber · 1997 · Neural Computation
LSTM added gated memory cells so recurrent networks could keep information over long sequences; it dominated sequence modelling until Transformers.
- Problem
- Plain recurrent networks lose gradient signal over long time lags.
- What was new
- A memory cell with a self-connection of weight 1 (a 'constant error carousel') protected by learned multiplicative gates.
Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation
Kyunghyun Cho, Bart van Merrienboer et al. · 2014 · EMNLP 2014
Proposed a jointly trained RNN encoder and decoder for mapping one sequence to another, with the gated recurrent unit in the architecture.
- Problem
- Translation must map an input phrase to an output phrase of a different length.
- What was new
- Encode a variable-length source into one vector, then decode a variable-length target; use gates to control recurrent memory.
- Built on
- Long Short-Term Memory
Sequence to Sequence Learning with Neural Networks
Ilya Sutskever, Oriol Vinyals, Quoc V. Le · 2014 · NeurIPS 2014
Established the encoder–decoder pattern: read an input sequence into a vector, then generate an output sequence from it. Its central weakness motivated attention.
- Problem
- Standard neural networks need fixed-size inputs and outputs, but translation maps sequences to sequences of different lengths.
- What was new
- A deep LSTM encoder compresses the source sentence into one vector; a second LSTM decodes the translation from it, trained end to end.
How to read it: Notice the trick of reversing the source sentence — a hint that long-range dependencies were the real problem.
Neural Machine Translation by Jointly Learning to Align and Translate
Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio · 2014 · ICLR 2015
Introduced attention in neural networks for language: instead of squeezing a sentence into one vector, the decoder looks back at every input word and decides which ones matter right now.
- Problem
- Encoder–decoder models squeezed the whole source sentence into a single fixed-length vector, and translation quality fell sharply on long sentences.
- What was new
- A learned alignment: at each output step the model scores every encoder state, normalizes the scores with softmax, and uses the weighted average as context.
- Influenced
- Attention Is All You Need
How to read it: Figure 3's alignment heat-maps are the best picture of 'attention' ever drawn — look at them first.
Watch
Andrej Karpathy
The spelled-out intro to language modeling: building makemore
Builds a character-level bigram model from counts, then trains a one-layer neural network that learns the same table by gradient descent.
Covers: Language modeling, count tables, smoothing, negative log-likelihood, and swapping counting for a trained network.
Andrej Karpathy
Building makemore Part 2: MLP
Implements the Bengio et al. 2003 neural language model at character level: an embedding lookup, a hidden layer and a softmax over the next character.
Covers: Learned embeddings, a fixed context window, training splits and why sharing vectors beats exact-count tables.
What came next?
Chapter 7
Recurrent networks read one token at a time, so distant words interact only through a long chain of steps — slow to train and hard to remember across.