After this chapter you will be able to
measure what a static vector for an ambiguous word holds, and how it depends on the corpus;
explain how a language model gives each word a vector computed from its sentence;
build a character-level word vector by hand with convolution and max pooling;
read the layer mixture of ELMo and say what tagging and sense disambiguation use;
state what layer normalisation does and why transformers use it.
This chapter builds on Chapter 9, whose single vector per word this chapter replaces.
Part II built word vectors and Part III built models that use them, and both rest on an assumption that was never stated out loud. Every word gets one vector, decided before any sentence exists. Chapter 9 already showed the damage, since the bank of a river and the bank that holds money collapse into one point and that point is correct for neither sense. It can be measured, so we measure it.
Take a toy space on three axes for money, river and generic, then give the two senses the vectors a contextual model would produce.
A static embedding must pick one vector, and trained on a corpus carrying both senses equally it lands on their average, . Now ask all three for nearest neighbours.
| query | nearest neighbours |
|---|---|
| money sense | loan , deposit , vault |
| river sense | water , flood , erosion |
| static average | loan , flood , water , deposit |
The two sense vectors give clean, single-topic lists, while the average gives a list that mixes both and commits to neither. Measure the geometry directly. The static average sits at cosine from each sense, which sounds close until you notice the two senses are only from each other. The static vector is therefore equally wrong in two directions and right in neither.
The average is not a fixed compromise either, because it moves with whatever mixture the training corpus happened to contain.
| share of money sense | cosine to money | cosine to river |
|---|---|---|
| 50% | 0.7591 | 0.7591 |
| 70% | 0.9293 | 0.5068 |
| 90% | 0.9942 | 0.2577 |
| 99% | 1.0000 | 0.1623 |
At per cent the vector is almost entirely the money sense and the river sense has been erased. Figure 16.1 shows the whole curve.
This is what a static embedding holds. It does not represent a word. It represents that word’s frequency-weighted mixture in one particular corpus. Chapter 9 made the same point with apple, and here it is as arithmetic.
The repair is short. Do not look the vector up. Compute it, from the sentence the word is actually in. ELMo (Peters et al. 2018) was the model that made this practical, and its name is the method, Embeddings from Language Models.
Three pieces make it up, and each has a job. The input is character-based, so the bottom layer builds each word’s initial representation from its characters through a convolution. ELMo therefore has no vocabulary to fall off, and a word it has never seen still gets a sensible vector, the FastText argument of Chapter 9 applied at the input layer.
Above that sits a bidirectional language model (biLM), where two multi-layer LSTMs run over the sentence, one forward and one backward, the forward one predicting the next token and the backward one the previous. Both are ordinary language models in the sense of Chapter 10, trained by maximum likelihood on plain text. The third piece is the layer-wise combination, and it is the part worth dwelling on.
The character layer is the one piece of this architecture with no counterpart earlier in the book, so we build it by hand. It turns a spelling into a vector with a one-dimensional convolution, in four steps, and the example word is banks.
Pad the word with a start mark ^ and an end mark
$, so that the edges of a word are visible to the filters,
and look every character up in a small embedding table. The table here
has size two so that every product can be checked by hand. A trained one
is learned along with the rest of the model, and the values below are
chosen only to differ.
| character | ^ |
b | a | n | k | s | $ |
|---|---|---|---|---|---|---|---|
| dimension 1 | |||||||
| dimension 2 |
The word is now a sequence of seven vectors, and a convolution looks at several neighbours at a time. A filter is a small window of weights slid along the word.
A filter of width holds one row of weights for each of the characters it covers, plus a bias. Placed over a window, it multiplies each weight by the matching embedding entry, adds everything up and adds the bias. The result goes through a ReLU, which replaces a negative score with zero. Four filters will do, two covering two characters and two covering three.
| filter | row 1 | row 2 | row 3 | bias |
|---|---|---|---|---|
| A | ||||
| B | ||||
| C | ||||
| D |
Take filter A over the window nk, whose embeddings are and :
Sliding each filter along the padded word gives one score per window, six windows for the width two filters and five for the width three ones.
| window | ^b |
ba | an | nk | ks | s$ |
|
|---|---|---|---|---|---|---|---|
| A | score | ||||||
| ReLU | 0.0000 | 0.0000 | 0.1000 | 0.8900 | 0.0000 | 0.0000 | |
| B | score | ||||||
| ReLU | 0.0000 | 1.0000 | 0.5100 | 0.0000 | 0.6600 | 0.1700 |
| window | ^ba |
ban | ank | nks | ks$ |
|
|---|---|---|---|---|---|---|
| C | score | |||||
| ReLU | 0.0000 | 0.0000 | 1.5100 | 0.0000 | 0.0900 | |
| D | score | |||||
| ReLU | 0.1900 | 0.8100 | 0.0000 | 0.8200 | 0.0000 |
Each filter has learned to respond to some pattern of letters. Filter A is strongest on nk, filter B on ba and filter C on ank, and in a trained model such patterns are prefixes, suffixes and stems.
Keep the strongest window of each filter and forget where it was.
| filter | strongest window | value |
|---|---|---|
| A | nk | 0.8900 |
| B | ba | 1.0000 |
| C | ank | 1.5100 |
| D | nks | 0.8200 |
The vector for banks is therefore . Seven positions went in and four numbers came out, and that would be four numbers for a word of any length, because pooling collapses the positions. A word of fifteen characters gets a vector the same size as a word of three, which is what lets the next layer treat every word alike.
Run the same four filters over some other words and measure how far each pooled vector lies from that of banks.
| word | pooled vector | distance | A | B | C | D | |
| to banks | strongest window | ||||||
| bank | 0.010 | nk | ba | ank | ban | ||
| banks | 0.000 | nk | ba | ank | nks | ||
| banking | 0.014 | nk | in | ank | ban | ||
| banker | 0.390 | nk | ba | ank | ker | ||
| zebra | 1.250 | eb | br | bra | ebr | ||
All four bank words win filters A and C on the same windows, nk and ank, so most of the reason their vectors sit close together is shared spelling. The differences are small. Banking wins B on in at against , and banker wins D on ker at against about . Zebra shares no winning window with any of them, and its vector lies away.
Two properties follow from the table. Every string receives a vector, including a spelling the model has never met, so there is no vocabulary to fall off. And words that share pieces of spelling receive vectors that share values, so the model generalises from banks to banking without being told that they are related.
ELMo does this at scale. By its authors’ account the character layer applies filters, passes the pooled result through two highway layers (shortcut layers with a gate) and projects it down to numbers (Peters et al. 2018). Every weight in it, the character table and the filters alike, is learned together with the language model. The result is the vector the first LSTM layer reads, and it is context-free, since bank receives the same vector in every sentence. The context comes from the layers above.
A biLM with layers gives representations for each token, being the character layer plus one per LSTM layer, and ELMo does not pick one but combines them all:
where the are softmax-normalised weights and is a single scaling factor. The detail that matters is which parameters are learned downstream, and the answer is only the and , with the biLM itself frozen. This is a handful of numbers per task, so ELMo was cheap enough to adopt everywhere within months. The weights are readable, because different tasks learn different profiles.
| task | , characters | , lower | , upper |
|---|---|---|---|
| part-of-speech tagging | 0.1369 | 0.6782 | 0.1848 |
| word sense disambiguation | 0.1071 | 0.1766 | 0.7162 |
| no preference | 0.3333 | 0.3333 | 0.3333 |
Tagging leans on the lower layer while sense disambiguation leans on the upper one. The ELMo paper is remembered for this finding: lower layers carry more syntax and upper layers more meaning. Which one a task wants is something you read off the learned weights and not decide in advance. It is also the clearest evidence that depth in these models does something structured and does not merely add capacity.
Deep stacks need their activations kept in range, and this is the place to introduce the tool, because everything after it uses it. Layer normalisation rescales each vector to zero mean and unit variance, then applies a learned scale and shift:
where and are the mean and standard deviation of itself. The contrast with batch normalisation is the point. Batch norm computes its statistics across the batch, so its behaviour depends on what else is in the batch and on the batch size, whereas layer norm computes them within a single example. That makes layer norm independent of batch composition, which matters when examples have different lengths, and it also behaves identically at training and inference time. Sequence models need that property, so layer norm is universal in transformers and batch norm is not.
ELMo established a pattern that outlived the architecture. Train a large model once on plain text using a self-supervised objective that needs no labels, then adapt it to each task with a small amount of labelled data.
The economics are the argument, since pretraining is expensive and happens once while adaptation is cheap and happens many times. For ELMo the adaptation was minimal, being just the weights of Equation (16.1) and one scalar, and later models fine-tune more without changing the shape of the bargain. Everything in Parts IV and V is a variation on it.
ELMo improved the state of the art on six tasks at once, and that breadth is unusual: question answering, textual entailment, sentiment analysis, named entity recognition, coreference resolution and semantic role labelling. One architecture change, six benchmarks and no task-specific engineering, which is what convinced the field more than any single number did. The mechanism behind it is the one this chapter opened with. A word’s representation now depends on its sentence, so bank in “the river bank” and bank in “the savings bank” are different vectors rather than one blurred average.
ELMo proved the principle and inherited a limitation. Its two LSTMs are the recurrent networks of Chapter 13, with Chapter 12’s two burdens intact, so they process one token at a time and carry everything through a fixed-size state.
There is a subtler point too, which is that the forward and backward models are independent and only combined at the end. No layer of ELMo ever sees left and right context at once, and what it sees instead is two one-sided summaries stitched together. Chapter 17 removes the recurrence, and Chapter 19 uses attention to build a model that reads both directions in every layer at once.
Run it.
code/worked_examples/contextual.pyproduces the tables in this chapter.--bankmeasures what averaging two senses costs and how it shifts with the corpus mixture,--charsreproduces the character convolution of Section 16.2.2 step by step,--elmoprints the three task profiles, and--maskpreviews the masking budget of Chapter 19.
Summary
A static embedding gives a word one vector, which for an ambiguous word is a frequency-weighted average of its senses, equally far from both and close to neither, and which moves with the training corpus. ELMo computes the vector from the sentence instead. It builds a word’s first vector from characters with convolutions, runs a forward and a backward LSTM language model over the sentence, and combines the layers with learned weights, so the same word gets different vectors in different sentences. Tagging weights the lower layers and sense disambiguation the upper ones. Layer normalisation keeps activations in range without depending on the batch. Pretraining once and adapting cheaply improved six tasks at once, and the idea outgrew its recurrent machine.
Key terms
static embedding. a single vector per word type, fixed before any sentence is seen.
contextual embedding. a vector for a word computed from the sentence it occurs in.
ELMo. a contextual embedding built from a forward and a backward LSTM language model over characters.
character convolution. a set of filters slid over a word’s characters, max-pooled into one vector.
layer normalisation. rescaling each vector to zero mean and unit variance, then applying a learned scale and shift.
Peters et al. (2018) is the ELMo paper, and its analysis of what each
layer holds is the part worth reading closely. Ba et al. (2016)
introduce layer normalisation. Jurafsky and Martin (2025) cover
contextual representations alongside the static ones, so the contrast is
easy to follow. Any of these models is three lines with
transformers, where AutoTokenizer and
AutoModel will fetch a pretrained checkpoint and hand you
the per-token vectors this chapter describes.
16.1 Measure the averaging. Using the two bank vectors of this chapter, compute the cosine of their average against each sense, and the cosine of the senses against each other. Explain why the first two numbers being equal is a problem rather than a reassurance.
16.2 Shift the corpus. Recompute the mixture table for shares of , and per cent. At what share does the cosine to the minority sense fall below ? State what that implies for a downstream task that needs the minority sense.
16.3 Read the layer weights. A task learns under Equation (16.1). What kind of task is it likely to be, and why? Now design a task you would expect to produce the opposite profile, and say what you would check to confirm it.
16.4 Layer norm against batch norm. Write out Equation (16.2) for a vector of five numbers and compute the result. Then explain, in two sentences, why batch normalisation would give a different answer for the same vector depending on the rest of the batch, and why that is fatal for variable-length sequences.
16.5 Characters at the input. ELMo builds word vectors from characters. Name two kinds of word this helps with, and one kind of word where it actively misleads. Chapter 9 discussed the same trade for FastText.
Build and measure
16.6 Run the filters yourself. Pad the word bank with the two marks and compute the four scores of filter C by hand, using the tables of Section 16.2.2. Which window is strongest, and how does the pooled value compare with the one for banks? Then say what would have to change in the filter for banker and banking to land far apart.
16.7 The stitching problem. ELMo’s forward and backward models are trained independently and combined only at the output. Construct a sentence whose correct reading requires left and right context simultaneously, and explain why a stitched pair of one-sided models can miss it.
16.8 Watch a word change. Load a
pretrained encoder with AutoTokenizer and
AutoModel, embed the two bank sentences of this
chapter, and measure the cosine between the two bank vectors
and between two occurrences of a word that is not ambiguous. Report
both. Before you run it, write down which layer you are taking the
vectors from and why, because the answer changes with depth and a number
without that detail cannot be compared with anyone else’s.
16.9 Why not one more layer? The layer weights are learned per task. Say what it would mean if a task learned equal weights, and what you would conclude about the task and about the model.
In practice
16.10 Which layer? A team wants vectors for named entity recognition and for word sense disambiguation from the same pretrained language model. Say which layers you would try for each, and how you would decide without guessing.
16.11 A rare sense. A corpus is per cent news and per cent cooking, and the word stock has both senses. Use Figure 16.1 to say what a static vector for stock contains, and what a contextual model would do instead.
16.12 Frozen or fine-tuned? A team has a hundred labelled examples. Argue whether to learn only the layer weights and or to fine-tune the whole language model, and name one risk of each.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
contextual.pyWhat one vector per word costs
Averaging two senses into one vector, and the layer weights ELMo learns instead.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.