Contextual Embeddings and the Masked-LM Objective
Hide a token and ask a bidirectional encoder to put it back: the objective's optimum is the posterior of the hidden token given its corrupted context, with a closed form under BERT's 80/10/10 corruption; its conditionals belong to no joint distribution; and the vectors it learns give each occurrence its own point, which reads what the neighbors determine and nothing more
Overview & Motivation
In the shared filings, the word kestrel occurs times. Fifty-seven of them name a company, “Kestrel Turbine Services”, and sixty-one name its product, “the Kestrel turbine”. The word2vec topic gives kestrel one vector for all , so no classifier reading that vector can tell the company from the turbine: whatever it answers, it answers for every occurrence, and it is right about half the time. An encoder that reads the sentence gives each occurrence its own vector. A linear probe on those vectors types all correctly in cross-validation.
Such vectors are contextual embeddings, and BERT (Devlin and colleagues 2019) made them standard by a simple training signal: hide some tokens and ask a bidirectional encoder to put them back. This topic is about what that signal converges to and what the vectors it produces can and cannot do. We develop it in order:
- One vector per type sees a mixture. A word with two senses has a PMI that is the log of a mixture of its senses’ PMIs, and a probe on any static vector is capped at the commoner sense’s share.
- The masked-LM optimum has a closed form. The risk is entropy plus divergence, so the best predictor is the posterior of the hidden token given the corrupted sentence. Under BERT’s corruption, that posterior is the context’s prediction at a
[MASK], shrunk toward the visible token elsewhere, and the selection rate drops out. - BERT is not a joint language model. With one mask per sequence the objective is pseudo-likelihood. Brook’s lemma says the conditionals of a joint determine it, and a four-cycle test that every joint passes shows that the trained encoder’s conditionals come from no joint at all.
- The geometry of the vectors. Occurrences of one word spread apart once context enters, in a cloud that is not isotropic, and we measure how much of the cloud a single static vector could carry.
- What probes see. Against a language whose exact posteriors we can compute, a linear probe on the encoder’s vectors comes within of the Bayes accuracy for a word’s sense, far above the static cap.
Then the finance case. On the filings, context separates a company from its product and good news from bad (“costs rose” against “revenue rose”), where static vectors cannot. It does not recover whether strong is a positive word, because the filings barely write that into their sentences.
One vector per type
A static embedding is a function of the token. A contextual one is a function of the sentence.
Definition 1 (Static and contextual embeddings).
Write a sentence as over a vocabulary of tokens. A static embedding is a map of the token alone. A contextual embedding is a map of the sentence and the position. The input layer of an encoder, with a token table and a position table , is static at any fixed position .
To see what a static vector loses, we need a language whose senses we know. Ours is a hidden Markov model with two regimes of four hidden states. Each state emits three tokens of its own, and the heaviest state of each regime also emits one shared token, , with probability . So has two senses, one per regime, with shares and . A sense is a hidden state, and what follows an occurrence depends on the occurrence only through its state. Because the model is a known distribution, forward–backward (Rabiner 1989) gives every conditional and every sense posterior exactly.
Proposition 1 (A static vector sees the mixture).
Let a word have senses with shares , and let a context depend on an occurrence of only through its sense, . Then
and hence .
Proof.
By total probability over the senses, . Dividing by and writing gives the identity. For the bounds, because the shares sum to , and the sum is at least each of its terms .
∎The word2vec topic proved that skip-gram with negative sampling fits shifted PMI (its Theorem 1). So at its unconstrained optimum, the row of a polyseme that it factorizes is this log-mixture, shifted. Where one sense dominates a context, the row follows that sense, up to . It is never both senses at once. On the HMM the identity holds to , and the two senses’ PMIs with the next token differ by up to nats. Arora and colleagues (2018) read trained static vectors as superpositions of sense vectors, which is the same picture in the embedding space.
Corollary 1 (The static cap).
Any classifier that reads only a static embedding, , labels the senses of the occurrences of with accuracy at most .
Proof.
Every occurrence of has the same vector , so the classifier gives every occurrence the same label , and its accuracy on them is .
∎On the HMM the cap is . A probe on the encoder’s token table attains it exactly, and a probe on its second layer reaches , where the exact Bayes accuracy is .
Word2vec’s other architecture, CBOW (Mikolov and colleagues 2013), predicts a word from the average of its neighbors’ input vectors. It is already a masked predictor with one hidden token. What it lacks is an encoder: its representation of the context is an average of static vectors, with no positions and no attention.
The masked-LM objective
Definition 2 (The corruption channel and the masked-LM loss).
Each position of is selected independently with probability ; write for the set of selected positions. A selected position is replaced by the symbol [MASK] with probability , by a token drawn uniformly from the with probability (possibly itself), and kept with probability . Unselected positions are kept. The result is the corrupted sentence . The masked-LM loss of a predictor is the mean over selected positions of . Write for what a selected position shows given its token : , and for a token .
BERT uses and , and selects a fixed of the positions of each sequence rather than each one independently. The independent version is what Theorem 2 needs (Theorem 1’s proof uses no independence), and we come back to the difference in the caveats. The loss counts only the selected positions, so the encoder is trained only where something may have happened; at the other it is free.
Theorem 1 (The masked-LM loss is a proper scoring rule).
At a selected position , let . For every predictor ,
so the risk is minimized exactly when , almost surely in .
Proof.
Condition on . The conditional risk is , the cross-entropy of relative to . Adding and subtracting splits it into . The KL term is nonnegative and vanishes only at (Gibbs’ inequality). The entropy term does not involve , so taking the expectation over gives the identity, and the KL term is minimized pointwise.
∎This is the decomposition and the strict propriety of the log score from the perplexity topic (its Proposition 1 and Corollary 1), applied to the distribution of the hidden token given the corrupted sentence. formalML’s KL-divergence topic proves both pieces (its Propositions 1 and 2). What makes the theorem useful is that the target can be written down.
Theorem 2 (The optimum under the corruption channel).
Let be what the rest of the corrupted sentence predicts for position . Then the minimizer of Theorem 1 is
In particular:
(i) at a [MASK], ;
(ii) at a visible token , , so the visible token keeps ;
(iii) the selection rate does not appear;
(iv) if and then , and if then .
Proof.
Whether position is selected, and the draws that corrupt it, are independent of and of every other position’s selection and draws. So , which gives . Given and , the symbol shown at has law , so
Bayes’ theorem in gives the formula. The rate entered only through the event , on which we conditioned, which is (iii). For (i), for every and cancels. For (ii), . For (iv), at with the numerator is and the denominator , while at the channel is for every and cancels.
∎Read (ii) and (iv) together. The random replacements are what keep a contextual prediction alive at visible positions. Without them (), every visible token is the original, so the best predictor copies it, and nothing forces the encoder to represent the context there. With them, the visible token is a strong hint, worth a factor of about , but only a hint. The size of the vocabulary matters a great deal: for the filings below, and , so the visible token keeps nearly all the mass unless the context finds it implausible. formalStatistics’ conditional-probability topic proves Bayes’ theorem (its Theorem 4), the only tool the proof uses.
On the HMM, the notebook checks the formula against brute-force enumeration of a length- joint, with the selection of made explicit and the channel applied to the other positions: they agree to at and at .
The encoder. We build the encoder from the pre-LN block of the transformer-block topic (its Definition 1) with the causal mask removed, so every position attends to every other. To that block we add three things from BERT: a learned position table (Definition 1 of the positional-encodings topic), input and output embeddings tied into one table , and a final LayerNorm before the logits . There are two blocks. The HMM encoder has and is trained for Adam steps on fresh corrupted sequences of length . Its gradient is written by hand and checked against central differences.
On selected positions of held-out sequences, the exact posterior has a cross-entropy of nats and the encoder . Those score one sampled token per position, so their gap of is only an estimate. Computed directly, distribution against distribution, the mean KL is , under of the -nat entropy. The KL is at a [MASK], at a random token, and at a kept one. We can also read Theorem 2 (ii) off the encoder itself. At a kept token, it puts on the token on average, and the formula applied to its own [MASK] guess predicts . That guess alone puts only on the same token.
Pseudo-likelihood and the missing joint
A masked LM predicts each token from the rest, which is a different thing from assigning probabilities to sentences. The first question is what the objective estimates.
Theorem 3 (One mask is pseudo-likelihood).
Mask one position , chosen uniformly from , and corrupt nothing else. Then the masked-LM risk of is
with the pseudo-likelihood. If a family contains the true conditionals at , then maximizes , and it is the unique maximizer when the conditionals identify .
Proof.
Averaging over gives , which is the first claim. For each , conditioning on and applying Theorem 1 with nothing corrupted gives , with equality exactly when almost surely. Summing over , the lower bound is attained at . Any other maximizer has the true conditionals and so, under identifiability, equals .
∎Besag (1975) introduced the pseudo-likelihood for spatial data, where a joint’s normalizing constant is intractable and its conditionals are not. Theorem 3 is the population statement. That the maximizer of a finite sample’s pseudo-likelihood converges to is a separate question, which we check rather than prove. On an open Ising chain of spins with field and coupling , the expected log pseudo-likelihood has zero gradient at the truth to rounding. The estimate from exact samples is off by , and from samples by . Against formalStatistics’ maximum-likelihood topic, whose Theorem 3 gives the MLE’s consistency and whose Theorem 5 gives its asymptotic efficiency, pseudo-likelihood gives up efficiency to get conditionals that need no normalizing constant. That trade is known, and we do not measure it here. BERT’s objective, with many masks and the 80/10/10 channel, is not exactly a pseudo-likelihood: its targets read the rest of the sentence through the channel.
Can the conditionals be turned back into a joint?
Theorem 4 (Brook's lemma).
Let be a positive distribution on sequences of length . For any two sequences and ,
so the full conditionals of determine up to normalization.
Proof.
Let , so that and , and telescope: . The sequences and agree everywhere except position , where they hold and . Dividing both by the marginal probability of their shared coordinates turns their ratio into . Positivity makes every term defined.
∎Brook (1964) proved it, and Besag (1974) made it the foundation for specifying a model through its conditionals. The notebook rebuilds the HMM’s joint over all sequences of length from its four conditionals alone, to . The lemma has a consequence that we can test on any family of conditionals, including a trained network’s.
Corollary 2 (The four-cycle test).
Fix two positions and everything else. Write for a conditional of position given , and for one of position given . For values and , let
If the are the conditionals of a positive joint, then . So anywhere proves that no joint has them as its conditionals.
Proof.
Under a joint , the first bracket is , the change in log-probability along the path . The second bracket is the change along , which is the same quantity.
∎Arnold and Press (1989) prove the converse for two variables: conditionals come from some joint exactly when their ratio factors. We need only the direction proved above.
Over random choices of a sequence, an adjacent pair of positions, and the two likeliest values at each, the median of is:
- for the HMM’s own conditionals, which is rounding;
- for the trained encoder, with a maximum of .
So the encoder’s conditionals belong to no joint distribution, and BERT is not a language model in the generative sense. Generating text from it by Gibbs-style resampling (Wang and Cho 2019) runs a Markov chain whose stationary distribution has no stated relation to the conditionals. formalStatistics’ MCMC topic shows that a Gibbs sampler needs conditionals from one joint (its Theorem 2). Scoring sentences by their pseudo-log-likelihood (Salazar and colleagues 2020) is a useful heuristic for the same reason it is not a likelihood. Hennigen and Kim (2023) and Young and colleagues (2022) measure the incompatibility in large masked LMs.
There is a subtler point. Even the population optimum of Theorem 2 fails the test slightly, with a median of and a maximum of . At a [MASK], the optimum predicts the clean token from a context it reads through the channel, where any other visible token might be a substitute. Those targets, one per position, are not the conditionals of a single joint. So the incompatibility is not only a training failure: the objective’s own optimum, under BERT’s corruption, does not define one.
The geometry of contextual vectors
What does the cloud of one word’s occurrences look like, layer by layer? Ethayarajh (2019) gave three measures.
Definition 3 (Self-similarity, the anisotropy baseline, and MEV).
Let the occurrences of a word have vectors at some layer, the rows of its occurrence matrix . The self-similarity of is the mean of over . The anisotropy baseline is the mean cosine between the vectors of uniformly drawn tokens of any words. Self-similarity minus the baseline is the adjusted self-similarity. The maximum explainable variance is , with the singular values of .
An isotropic cloud has baseline . A baseline near means that every vector points the same way, so a high self-similarity says little until the baseline is subtracted.
Proposition 2 (The best static summary).
Let have rank and nonzero singular values .
(i) The constant minimizing is the mean of the rows.
(ii) , the largest share of the energy of the cloud that one direction carries.
(iii) , with equality on the right exactly when all occurrences are collinear.
Proof.
For (i), the gradient of in is , which vanishes only at the mean, and the function is strictly convex. For (ii), , whose maximum over unit is , the top eigenvalue of , while . For (iii), is the largest of positive numbers that sum to , so it is at least their mean and at most their sum, with equality in the latter exactly when .
∎By Eckart–Young, is the share of the cloud that the best rank- approximation misses. Ethayarajh reads MEV as an upper bound on how well a single static vector could stand in for a word’s contextual ones. formalML’s PCA topic proves the optimal projection for centered data (its Theorem 2), and (ii) is its uncentered, one-direction analogue, through the origin instead of the mean.
| layer | HMM : self-similarity | MEV | baseline | adjusted | kestrel: self-similarity | MEV | baseline | adjusted |
|---|---|---|---|---|---|---|---|---|
Layer of the HMM encoder is not static, because positions vary across occurrences. In the filings we read every token at one position, so the layer- vectors of kestrel are a single point. Context lowers the adjusted self-similarity at both layers, most at layer . The baseline rises from layer to layer in both encoders, as Ethayarajh found for BERT, ELMo, and GPT-2, but it is not monotone: the filing encoder’s top layer has no shared cone, with a mean cosine of . That is not isotropy, for which a mean cosine near zero is necessary but not sufficient. The MEV of uniformly drawn token vectors at that layer is , against for a truly isotropic cloud in dimensions. Gao and colleagues (2019) explain the cone through tied embeddings, which push the vectors of rare tokens along a common direction. That is an account, not a theorem, and two blocks are too few to test it.
Probing
A probe is a simple classifier trained on frozen vectors to read off a property. Ours is a logistic regression with a ridge penalty, as formalML’s representation-learning topic defines a linear probe (its Definition 9.1), on standardized vectors, with a strength fixed before the final runs and never tuned on a test split. The HMM lets us compare it with two references we can compute: Corollary 1’s static cap, and the exact Bayes accuracy .
| layer | probe | shuffled control |
|---|---|---|
| static cap | — | |
| exact Bayes | — |
The probe is trained on sequences and tested on others ( occurrences of ). The shuffled control trains and scores the same probe on permuted senses. A probe that found structure in noise would beat the cap there, and it does not. Hewitt and Liang (2019) design controls of this kind for probes of real models, and Tenney and colleagues (2019) probe BERT layer by layer. One layer of attention already reads off almost all the sense information the context contains.
A probe shows that information is linearly decodable, which is not the same as showing that the model uses it. Suppose we read each token of the filings from document-internal windows, at whichever window position lies nearest its center. Then the context-free layer types kestrel as company or product with five-fold accuracy , through the position table alone. Product mentions close a document, so all of them land at positions to of the last window. Reading every token at the center of its own window removes the cue, and that is how every finance number below is measured.
The encoder, interactively
The laboratory has two figures.
Figure A puts Theorem 2 in front of you. Pick a token of an HMM sentence and choose what it shows: [MASK], itself, or a substitute. The bars are the exact posterior and the encoder’s prediction, with their divergence. On the four filing windows of the case study below, clicking a word shows the encoder’s five best guesses with that word masked. Beside them, the readout compares the encoder’s probability of the visible word with what Theorem 2 predicts from its own guess. A third view plots the four-cycle gap for the three families of conditionals.
Figure B is the geometry. Choose the HMM word or kestrel and a layer, and see the occurrences on their own two principal axes, colored by sense, beside the measures of Definition 3, the probes, and the finance results.
At a [MASK] both bars are the context’s prediction. Shown its own token, the posterior shrinks toward it by Theorem 2 (ii), but keeps mass on the alternatives, because one selected position in ten shows a random token. Over the test set the encoder’s mean KL to the exact posterior is 0.032 nats, against an entropy of 1.874. The highlighted tokens are the polyseme w, once in each sense.
Shading is the exact sense posterior: faint points are occurrences whose context leaves the sense uncertain. Layer 0 is E[x] + P at the occurrence’s position, so it varies only with position and the probe sits at chance; one block of attention separates the senses almost to the Bayes accuracy.
Finance case study: a company or its product, and the news a word reports
Where this goes next
- Fine-tuning. A pretrained encoder is usually adapted by training a linear head on its vectors, as the probes here do, and by updating the encoder itself. The fine-tuning topic asks how small an update can be, through low-rank adaptation.
- Named entities. Typing kestrel as company or product is entity typing done one token at a time. The named-entity-recognition topic labels whole spans, with a sequence model over these vectors.
- Dense retrieval. formalRAG’s dual-encoder topic takes a pretrained encoder as given, pools its vectors, and trains it contrastively; its hypersphere topic meets the anisotropic cone measured here.
- Learned sparse retrieval. SPLADE turns the masked-LM head into term weights, of the logits, which is formalRAG’s late-interaction topic.
Honest caveats
Implementation
The companion notebook (notebookPath) imports contextual_embeddings_masked_lm.py, which owns every number on this page. That module imports the transformer-block topic’s module for the pre-LN block, LayerNorm, and attention with their backward passes, and through it the neural-language-models topic’s Adam constants and the shared finance corpus. It imports the word2vec topic’s module for its skip-gram vectors and polarity probe, and through it the distributional-semantics topic’s corpus and vocabulary. It trains two encoders from scratch in NumPy with hand-written gradients and runs a harness of assertion-based tests in about forty seconds on a laptop CPU. The tests cover:
- Proposition 1 exactly on the HMM, and Corollary 1 against the token table’s probe.
- Theorem 1’s identity on random distributions and on the trained encoder.
- Theorem 2 against brute-force enumeration at two selection rates, with its limiting cases, and the encoder’s shrinkage at kept tokens.
- Theorem 3’s population gradient and the pseudo-likelihood estimates on the Ising chain.
- Theorem 4 against the enumerated joint, and Corollary 2 on three families of conditionals.
- Proposition 2 on random matrices and on both encoders.
- The probes and their controls, the position leak, and the finance tables, including the sample-size check on the evaluative verbs and the encoder’s shortfall at visible words.
- The encoder’s gradient against central differences, the selected-rows loss against the full forward pass, and the faster MLP backward pass against the transformer-block topic’s.
The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.
References & Further Reading
- paper BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding — Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova (2019) NAACL-HLT 2019. The masked-LM objective and its 80/10/10 corruption, Definition 2
- paper Deep Contextualized Word Representations — Matthew E. Peters, Mark Neumann, Mohit Iyyer, Matt Gardner, Christopher Clark, Kenton Lee, and Luke Zettlemoyer (2018) NAACL-HLT 2018. Contextual word vectors (ELMo), Definition 1
- paper Efficient Estimation of Word Representations in Vector Space — Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean (2013) CBOW, a single-mask predictor over averaged static vectors
- paper RoBERTa: A Robustly Optimized BERT Pretraining Approach — Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov (2019) Dynamic masking; the masked-LM objective without next-sentence prediction
- paper Extracting and Composing Robust Features with Denoising Autoencoders — Pascal Vincent, Hugo Larochelle, Yoshua Bengio, and Pierre-Antoine Manzagol (2008) ICML 2008. Corrupt the input, reconstruct the clean one: the objective's ancestor
- paper Spatial Interaction and the Statistical Analysis of Lattice Systems — Julian Besag (1974) Journal of the Royal Statistical Society, Series B 36. Specifying a joint through its conditionals, beside Theorem 4
- paper Statistical Analysis of Non-Lattice Data — Julian Besag (1975) The Statistician 24. Pseudo-likelihood, Theorem 3
- paper On the Distinction between the Conditional Probability and the Joint Probability Approaches in the Specification of Nearest-Neighbour Systems — D. Brook (1964) Biometrika 51. Brook's lemma, Theorem 4
- paper Compatible Conditional Distributions — Barry C. Arnold and S. James Press (1989) Journal of the American Statistical Association 84. When conditionals come from a joint: the converse of Corollary 2
- paper BERT has a Mouth, and It Must Speak: BERT as a Markov Random Field Language Model — Alex Wang and Kyunghyun Cho (2019) Workshop on Methods for Optimizing and Evaluating Neural Language Generation. Generating from BERT by Gibbs-style sampling
- paper Masked Language Model Scoring — Julian Salazar, Davis Liang, Toan Q. Nguyen, and Katrin Kirchhoff (2020) ACL 2020. Pseudo-log-likelihood scores
- paper Deriving Language Models from Masked Language Models — Lucas Torroba Hennigen and Yoon Kim (2023) ACL 2023. The incompatibility of masked-LM conditionals, measured
- paper Inconsistencies in Masked Language Models — Tom Young, Yunan Chen, and Yang You (2022) Inconsistent conditionals in large masked LMs, measured
- paper How Contextual are Contextualized Word Representations? Comparing the Geometry of BERT, ELMo, and GPT-2 Embeddings — Kawin Ethayarajh (2019) EMNLP-IJCNLP 2019. Self-similarity, the anisotropy baseline, and maximum explainable variance, Definition 3
- paper Representation Degeneration Problem in Training Natural Language Generation Models — Jun Gao, Di He, Xu Tan, Tao Qin, Liwei Wang, and Tie-Yan Liu (2019) ICLR 2019. An account of the anisotropic cone through tied embeddings
- paper Designing and Interpreting Probes with Control Tasks — John Hewitt and Percy Liang (2019) EMNLP-IJCNLP 2019. Controls for probes
- paper BERT Rediscovers the Classical NLP Pipeline — Ian Tenney, Dipanjan Das, and Ellie Pavlick (2019) ACL 2019. Layerwise probing of BERT
- paper Linear Algebraic Structure of Word Senses, with Applications to Polysemy — Sanjeev Arora, Yuanzhi Li, Yingyu Liang, Tengyu Ma, and Andrej Risteski (2018) Transactions of the ACL 6. A static vector as a superposition of senses, beside Proposition 1
- paper A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition — Lawrence R. Rabiner (1989) Proceedings of the IEEE 77. The forward–backward algorithm behind every exact posterior here