Contents The Transformer Era Code Course home

Chapter 16Contextual Embeddings

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.

One vector is not enough

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.

What the average costs

Take a toy space on three axes for money, river and generic, then give the two senses the vectors a contextual model would produce.

bankmoney=(0.90,0.05,0.20),bankriver=(0.05,0.90,0.20).\text{bank}_{\text{money}} = (0.90,\, 0.05,\, 0.20), \qquad \text{bank}_{\text{river}} = (0.05,\, 0.90,\, 0.20).

A static embedding must pick one vector, and trained on a corpus carrying both senses equally it lands on their average, (0.475,0.475,0.200)(0.475, 0.475, 0.200). Now ask all three for nearest neighbours.

query nearest neighbours
money sense loan +0.999+0.999, deposit +0.998+0.998, vault +0.994+0.994
river sense water +0.998+0.998, flood +0.995+0.995, erosion +0.991+0.991
static average loan +0.741+0.741, flood +0.729+0.729, water +0.729+0.729, deposit +0.728+0.728

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 0.75910.7591 from each sense, which sounds close until you notice the two senses are only 0.15250.1525 from each other. The static vector is therefore equally wrong in two directions and right in neither.

It gets worse, or better, with the corpus

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 9090 per cent the vector is almost entirely the money sense and the river sense has been erased. Figure 16.1 shows the whole curve.

Figure 16.1. A static vector for bank follows the mixture of the training corpus. At an even split it is equally far from both senses. At 9090 per cent money the river sense has fallen to a cosine of 0.25770.2577.

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.

Embeddings from a language model

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.

The architecture

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.

Characters in, worked

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.

Step 1, characters.

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 −0.50-0.50 +0.10+0.10 +0.80+0.80 +0.60+0.60 −0.70-0.70 −0.40-0.40 +0.20+0.20
dimension 2 +0.20+0.20 +0.90+0.90 +0.10+0.10 −0.60-0.60 +0.60+0.60 −0.80-0.80 −0.50-0.50

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.

Step 2, filters.

A filter of width ww holds one row of weights for each of the ww 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 (+0.9,+0.2)(+0.9, +0.2) (−0.3,+0.6)(-0.3, +0.6) −0.10-0.10
B (−0.4,+0.5)(-0.4, +0.5) (+0.8,−0.5)(+0.8, -0.5) +0.00+0.00
C (+0.5,+0.3)(+0.5, +0.3) (+0.2,−0.6)(+0.2, -0.6) (−0.7,+0.1)(-0.7, +0.1) +0.05+0.05
D (+0.1,−0.2)(+0.1, -0.2) (+0.6,+0.4)(+0.6, +0.4) (−0.2,−0.8)(-0.2, -0.8) +0.10+0.10

Take filter A over the window nk, whose embeddings are (+0.6,−0.6)(+0.6, -0.6) and (−0.7,+0.6)(-0.7, +0.6):

0.9(0.6)+0.2(−0.6)+(−0.3)(−0.7)+0.6(0.6)−0.10=0.8900.0.9(0.6) + 0.2(-0.6) + (-0.3)(-0.7) + 0.6(0.6) - 0.10 \;=\; 0.8900 .

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 +0.0000+0.0000 −0.0100-0.0100 +0.1000+0.1000 +0.8900+0.8900 −0.9700-0.9700 −0.9800-0.9800
ReLU 0.0000 0.0000 0.1000 0.8900 0.0000 0.0000
B score −0.0700-0.0700 +1.0000+1.0000 +0.5100+0.5100 −1.4000-1.4000 +0.6600+0.6600 +0.1700+0.1700
ReLU 0.0000 1.0000 0.5100 0.0000 0.6600 0.1700
window ^ba ban ank nks ks$
C score −1.2100-1.2100 −0.0100-0.0100 +1.5100+1.5100 −0.1300-0.1300 +0.0900+0.0900
ReLU 0.0000 0.0000 1.5100 0.0000 0.0900
D score +0.1900+0.1900 +0.8100+0.8100 −0.0600-0.0600 +0.8200+0.8200 −0.2900-0.2900
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.

Step 3, pooling.

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.

Step 4, what the vector knows.

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.89,1.00,1.51,0.81)(0.89, 1.00, 1.51, 0.81) 0.010 nk ba ank ban
banks (0.89,1.00,1.51,0.82)(0.89, 1.00, 1.51, 0.82) 0.000 nk ba ank nks
banking (0.89,1.01,1.51,0.81)(0.89, 1.01, 1.51, 0.81) 0.014 nk in ank ban
banker (0.89,1.00,1.51,1.21)(0.89, 1.00, 1.51, 1.21) 0.390 nk ba ank ker
zebra (1.12,0.86,0.36,1.23)(1.12, 0.86, 0.36, 1.23) 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 1.011.01 against 1.001.00, and banker wins D on ker at 1.211.21 against about 0.80.8. Zebra shares no winning window with any of them, and its vector lies 1.251.25 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 20482048 filters, passes the pooled result through two highway layers (shortcut layers with a gate) and projects it down to 512512 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.

The layer mix

A biLM with LL layers gives L+1L+1 representations for each token, being the character layer plus one per LSTM layer, and ELMo does not pick one but combines them all:

ELMok=γ∑j=0LsjRk,j,(16.1)\begin{equation} \text{ELMo}_k \;=\; \gamma \sum_{j=0}^{L} s_j\,R_{k,j}, \label{eq:elmo} \quad\text{(16.1)} \end{equation}

where the sjs_j are softmax-normalised weights and γ\gamma is a single scaling factor. The detail that matters is which parameters are learned downstream, and the answer is only the sjs_j and γ\gamma, 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 s0s_0, characters s1s_1, lower s2s_2, 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.

Figure 16.2. The learned layer weights of Equation (16.1) for three settings. Tagging puts most weight on the lower layer and sense disambiguation on the upper one. The third group is the untrained baseline of equal weights.

One more piece of machinery

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:

LayerNorm⁡(x)=γ⋅x−μσ+β,(16.2)\begin{equation} \operatorname{LayerNorm}(x) \;=\; \gamma \cdot \frac{x - \mu}{\sigma} \;+\; \beta , \label{eq:layernorm} \quad\text{(16.2)} \end{equation}

where μ\mu and σ\sigma are the mean and standard deviation of xx 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.

One static vector for bank splitting into two contextual vectors near money and river words
A static embedding gives a word one vector however it is used, blending its meanings. A contextual model gives each use its own vector, close to the words that fit that sense.
Softmax layer weights for three tasks: part of speech, word sense and no preference
Different layers of a language model carry different information. ELMo lets each task learn its own mix, with syntax tasks favouring lower layers and meaning tasks favouring higher ones.

Pretrain once, adapt cheaply

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 L+1L+1 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.

What it bought, measurably

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.

The idea outgrows its machine

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.py produces the tables in this chapter. --bank measures what averaging two senses costs and how it shifts with the corpus mixture, --chars reproduces the character convolution of Section 16.2.2 step by step, --elmo prints the three task profiles, and --mask previews the masking budget of Chapter 19.

Run it

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.

Further reading.

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.

Practice problems

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 6060, 8080 and 9595 per cent. At what share does the cosine to the minority sense fall below 0.40.4? State what that implies for a downstream task that needs the minority sense.

16.3 Read the layer weights. A task learns s=(0.05,0.15,0.80)s = (0.05, 0.15, 0.80) 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 sjs_j 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 9999 per cent news and 11 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 sjs_j and γ\gamma or to fine-tune the whole language model, and name one risk of each.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.