Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.The same word, different meanings
“The river bank flooded” and “the bank approved the loan” use the same word in two senses. A static word vector has to average them. Contextual models like ELMo and BERT read the whole sentence and give “bank” a different vector in each, close to “shore” in one and to “lender” in the other. They do this by letting each word look at all the other words around it. The demo shows static word vectors; contextual models build on them.
Technical words are often ambiguous: “bus” (data bus or vehicle), “pitch” (attitude or blade setting), “stall” (aerodynamic or engine). Contextual embeddings let search and classification systems tell them apart.
- 1. A static embedding gives 'bank'…
- 2. A contextual embedding depends on…
- 3. BERT reads context…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Polysemy: a static vector for an ambiguous word is roughly a frequency-weighted average of its senses, so it lies between them.
- ELMo: two-layer forward and backward LSTM language models; a token’s representation is γ Σ_j s_j h_j over the layers, with softmax weights s_j learned per task. Lower layers carry more syntax, higher layers more semantics.
- BERT: a Transformer encoder (12 or 24 layers) pretrained with:
- masked-language modelling: choose 15% of tokens and predict them; of those, 80% become [MASK], 10% a random token, 10% unchanged;
- next-sentence prediction (later shown to be unnecessary by RoBERTa).
- Self-attention: each output is a weighted average of all positions’ value vectors, with weights softmax(QKᵀ/√d). It is the learned context mixer; a 512-token input has 262,144 attention weights per head.
- Using them: fine-tune the whole model on a task, or extract features (for example the last-layer or averaged hidden states) and train a probe.
- 1. Tokens BERT masks in a 512-token input (15%):
- 2. ELMo combines layers with…
- 3. Attention weights per head for 512 tokens:
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Contextual embeddings in code
Exercise 1.
- Implement single-head self-attention; changing another token changes a token’s output.
- Create BERT-style masked-LM inputs and targets.
Practice.
- Hugging Face
AutoModelreturns hidden states for every layer (output_hidden_states=True). - For feature extraction, try the mean of the last 4 layers; for most tasks, fine-tuning beats frozen features.
- Pick a domain model when available (SciBERT, BioBERT, or continued pretraining on your corpus).
- Align word-level labels with subword tokens, and use the same tokenizer as the model.
from transformers import AutoTokenizer, AutoModel
tok = AutoTokenizer.from_pretrained("bert-base-uncased"); bert = AutoModel.from_pretrained("bert-base-uncased")
batch = tok(["the river bank flooded", "the bank approved the loan"], return_tensors="pt", padding=True)
h = bert(**batch).last_hidden_state # (2, seq, 768): one vector per token in context
i = [ids.index(tok.convert_tokens_to_ids("bank")) for ids in batch["input_ids"].tolist()]
print(torch.cosine_similarity(h[0, i[0]], h[1, i[1]], dim=0)) # well below 1- 1. To get hidden states of every layer:
- 2. For most tasks, better than frozen features is…
- 3. A scientific-domain BERT:
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Why context resolves senses. The sense of an ambiguous token is a function of its context, so any representation that includes context features can separate senses with a simple classifier. A static vector is the same for all occurrences, so no classifier on it alone can beat predicting the most frequent sense.
Masked-LM as denoising. Predicting masked tokens from both sides forces the encoder to represent each position using the whole sentence. Unlike a left-to-right LM, BERT cannot generate text naturally, but its representations are bidirectional, which suits understanding tasks.
What layers encode. Probing studies (Tenney and colleagues, 2019) found that BERT layers roughly follow the classical pipeline: part of speech in lower layers, then parsing, entities, semantic roles and coreference higher up. Contextual embeddings are also anisotropic: vectors occupy a narrow cone, so raw cosine similarities are high overall and must be compared relatively.
- 1. A static vector alone can at best predict…
- 2. Masked-LM training is a form of…
- 3. Lower BERT layers encode more…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How much context does it take to tell word senses apart?
History.
- M. Peters et al., “Deep contextualized word representations” (NAACL 2018), ELMo.
- J. Devlin, M.-W. Chang, K. Lee and K. Toutanova, “BERT: pre-training of deep bidirectional transformers for language understanding” (NAACL 2019).
- I. Tenney, D. Das and E. Pavlick, “BERT rediscovers the classical NLP pipeline” (ACL 2019).
Exercise 2.
- Corpus: 3000 sentences of 8 words on one of 4 topics (topic words with probability 0.5, otherwise general words). 10 ambiguous words each belong to two topics, with a different sense in each; about 2090 ambiguous tokens.
- Representations of an ambiguous token:
- its static PPMI + SVD vector (20 dimensions);
- a minimal contextual representation: the static vector concatenated with the mean of the neighbours’ static vectors within ±1, ±3 or the whole sentence.
- Probe: for each ambiguous word, a linear (ridge) probe trained on half of its occurrences and tested on the other half.
- Caveat: the context mixing is fixed averaging, not learned attention; it shows the principle, not BERT’s quality.
| representation | sense accuracy |
|---|---|
| static vector | 0.559 |
| + context, ±1 word | 0.847 |
| + context, ±3 words | 0.950 |
| + context, whole sentence | 0.984 |
- Static vectors cannot disambiguate: 0.56 is roughly the majority sense.
- Context resolves senses, and more context helps: one neighbour per side gives 0.85, the whole sentence 0.98.
- Learned mixing does better still: self-attention can weight informative neighbours (topic words) above uninformative ones (general words), which plain averaging cannot.
- Seeds: seeds 1 and 2 gave static 0.540/0.555 and whole-sentence 0.993/0.991.
Contextual embeddings in AI, robotics and aerospace
- Technical search: distinguishing senses of terms like “stall”, “pitch” or “bus” in documentation search.
- Classification: fine-tuned BERT-style encoders for routing reports and extracting entities.
- Design lesson: meaning depends on context; represent each occurrence, not just each word type.
References
- M. E. Peters et al. (2018). “Deep contextualized word representations.” Proc. NAACL.
- J. Devlin, M.-W. Chang, K. Lee and K. Toutanova (2019). “BERT: pre-training of deep bidirectional transformers for language understanding.” Proc. NAACL.
- I. Tenney, D. Das and E. Pavlick (2019). “BERT rediscovers the classical NLP pipeline.” Proc. ACL.
- K. Ethayarajh (2019). “How contextual are contextualized word representations?” Proc. EMNLP.