advanced representations 45 min read

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 118118 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 118118, 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 118118 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. What probes see. Against a language whose exact posteriors we can compute, a linear probe on the encoder’s vectors comes within 0.0080.008 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 x=(x1,…,xn)x = (x_1, \dots, x_n) over a vocabulary of VV tokens. A static embedding is a map xi↦e(xi)∈Rdx_i \mapsto e(x_i) \in \mathbb{R}^d of the token alone. A contextual embedding is a map (x,i)↦hi(x1,…,xn)∈Rd(x, i) \mapsto h_i(x_1, \dots, x_n) \in \mathbb{R}^d of the sentence and the position. The input layer of an encoder, E[xi]+PiE[x_i] + P_i with a token table EE and a position table PP, is static at any fixed position ii.

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, ww, with probability 0.40.4. So ww has two senses, one per regime, with shares 0.4910.491 and 0.5090.509. 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 ww have senses s1,…,sKs_1, \dots, s_K with shares πk=P(sk∣w)\pi_k = P(s_k \mid w), and let a context cc depend on an occurrence of ww only through its sense, P(c∣sk,w)=P(c∣sk)P(c \mid s_k, w) = P(c \mid s_k). Then

PMI⁡(w,c)=log⁡∑kπkexp⁡PMI⁡(sk,c),\operatorname{PMI}(w, c) = \log \sum_{k} \pi_k \exp \operatorname{PMI}(s_k, c),

and hence max⁡k(log⁡πk+PMI⁡(sk,c))≤PMI⁡(w,c)≤max⁡kPMI⁡(sk,c)\max_k \bigl(\log \pi_k + \operatorname{PMI}(s_k, c)\bigr) \le \operatorname{PMI}(w, c) \le \max_k \operatorname{PMI}(s_k, c).

Proof.

By total probability over the senses, P(c∣w)=∑kP(sk∣w)P(c∣sk,w)=∑kπkP(c∣sk)P(c \mid w) = \sum_k P(s_k \mid w) P(c \mid s_k, w) = \sum_k \pi_k P(c \mid s_k). Dividing by P(c)P(c) and writing P(c∣sk)/P(c)=exp⁡PMI⁡(sk,c)P(c \mid s_k)/P(c) = \exp \operatorname{PMI}(s_k, c) gives the identity. For the bounds, ∑kπkeak≤(∑kπk)max⁡keak=max⁡keak\sum_k \pi_k e^{a_k} \le \bigl(\sum_k \pi_k\bigr) \max_k e^{a_k} = \max_k e^{a_k} because the shares sum to 11, and the sum is at least each of its terms πkeak\pi_k e^{a_k}.

∎

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 log⁡πk\log \pi_k. It is never both senses at once. On the HMM the identity holds to 10−1210^{-12}, and the two senses’ PMIs with the next token differ by up to 3.6543.654 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, g∘eg \circ e, labels the senses of the occurrences of ww with accuracy at most max⁡kπk\max_k \pi_k.

Proof.

Every occurrence of ww has the same vector e(w)e(w), so the classifier gives every occurrence the same label ℓ\ell, and its accuracy on them is P(sense=ℓ∣w)=πℓ≤max⁡kπkP(\text{sense} = \ell \mid w) = \pi_\ell \le \max_k \pi_k.

∎

On the HMM the cap is 0.5090.509. A probe on the encoder’s token table attains it exactly, and a probe on its second layer reaches 0.9620.962, where the exact Bayes accuracy is 0.9700.970.

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 xx is selected independently with probability ρ\rho; write MM for the set of selected positions. A selected position is replaced by the symbol [MASK] with probability mm, by a token drawn uniformly from the VV with probability rr (possibly itself), and kept with probability κ=1−m−r\kappa = 1 - m - r. Unselected positions are kept. The result is the corrupted sentence x~\tilde x. The masked-LM loss of a predictor qq is the mean over selected positions of −log⁡q(xi∣x~)-\log q(x_i \mid \tilde x). Write S(s∣y)S(s \mid y) for what a selected position shows given its token yy: S([MASK]∣y)=mS(\texttt{[MASK]} \mid y) = m, and S(v∣y)=κ 1[v=y]+r/VS(v \mid y) = \kappa\, \mathbb{1}[v = y] + r/V for a token vv.

BERT uses ρ=0.15\rho = 0.15 and (m,r,κ)=(0.8,0.1,0.1)(m, r, \kappa) = (0.8, 0.1, 0.1), and selects a fixed 15%15\% 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 85%85\% it is free.

Theorem 1 (The masked-LM loss is a proper scoring rule).

At a selected position ii, let Pi(⋅∣x~)=P(xi=⋅∣x~,i∈M)P_i(\cdot \mid \tilde x) = P(x_i = \cdot \mid \tilde x, i \in M). For every predictor qq,

E[−log⁡q(xi∣x~)∣i∈M]=E H(Pi(⋅∣x~))+E KL⁡(Pi(⋅∣x~) ∥ q(⋅∣x~)),\mathbb{E}\bigl[-\log q(x_i \mid \tilde x) \bigm| i \in M\bigr] = \mathbb{E}\, H\bigl(P_i(\cdot \mid \tilde x)\bigr) + \mathbb{E}\, \operatorname{KL}\bigl(P_i(\cdot \mid \tilde x) \,\big\|\, q(\cdot \mid \tilde x)\bigr),

so the risk is minimized exactly when q=Piq = P_i, almost surely in x~\tilde x.

Proof.

Condition on x~\tilde x. The conditional risk is −∑yPi(y∣x~)log⁡q(y∣x~)-\sum_y P_i(y \mid \tilde x) \log q(y \mid \tilde x), the cross-entropy of qq relative to PiP_i. Adding and subtracting ∑yPilog⁡Pi\sum_y P_i \log P_i splits it into H(Pi)+KL⁡(Pi ∥ q)H(P_i) + \operatorname{KL}(P_i \,\|\, q). The KL term is nonnegative and vanishes only at q=Piq = P_i (Gibbs’ inequality). The entropy term does not involve qq, so taking the expectation over x~\tilde x 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 PiP_i can be written down.

Theorem 2 (The optimum under the corruption channel).

Let p(y)=P(xi=y∣x~−i)p(y) = P(x_i = y \mid \tilde x_{-i}) be what the rest of the corrupted sentence predicts for position ii. Then the minimizer of Theorem 1 is

q(y)=p(y) S(x~i∣y)∑y′p(y′) S(x~i∣y′).q(y) = \frac{p(y)\, S(\tilde x_i \mid y)}{\sum_{y'} p(y')\, S(\tilde x_i \mid y')}.

In particular:

(i) at a [MASK], q=pq = p;

(ii) at a visible token vv, q(y)=p(y)(κ 1[y=v]+r/V)/(κ p(v)+r/V)q(y) = p(y)\bigl(\kappa\,\mathbb{1}[y = v] + r/V\bigr)/\bigl(\kappa\, p(v) + r/V\bigr), so the visible token keeps q(v)=p(v)(κ+r/V)/(κ p(v)+r/V)q(v) = p(v)(\kappa + r/V)/(\kappa\, p(v) + r/V);

(iii) the selection rate ρ\rho does not appear;

(iv) if r=0r = 0 and κ>0\kappa > 0 then q(v)=1q(v) = 1, and if κ=0\kappa = 0 then q=pq = p.

Proof.

Whether position ii is selected, and the draws that corrupt it, are independent of xx and of every other position’s selection and draws. So P(i∈M∣x,x~−i)=ρP(i \in M \mid x, \tilde x_{-i}) = \rho, which gives P(xi=y∣x~−i,i∈M)=p(y)P(x_i = y \mid \tilde x_{-i}, i \in M) = p(y). Given i∈Mi \in M and xx, the symbol shown at ii has law S(⋅∣xi)S(\cdot \mid x_i), so

P(xi=y, x~i=s∣x~−i, i∈M)=p(y) S(s∣y).P(x_i = y,\ \tilde x_i = s \mid \tilde x_{-i},\ i \in M) = p(y)\, S(s \mid y).

Bayes’ theorem in xix_i gives the formula. The rate ρ\rho entered only through the event i∈Mi \in M, on which we conditioned, which is (iii). For (i), S([MASK]∣y)=mS(\texttt{[MASK]} \mid y) = m for every yy and cancels. For (ii), ∑y′p(y′)(κ 1[y′=v]+r/V)=κ p(v)+r/V\sum_{y'} p(y')(\kappa\, \mathbb{1}[y' = v] + r/V) = \kappa\, p(v) + r/V. For (iv), at r=0r = 0 with κ>0\kappa > 0 the numerator is p(y)κ 1[y=v]p(y)\kappa\, \mathbb{1}[y = v] and the denominator κ p(v)\kappa\, p(v), while at κ=0\kappa = 0 the channel is r/Vr/V for every yy and cancels.

∎

Read (ii) and (iv) together. The random replacements are what keep a contextual prediction alive at visible positions. Without them (r=0r = 0), 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 κV/r\kappa V/r, but only a hint. The size of the vocabulary matters a great deal: for the filings below, V=879V = 879 and r/V≈1.1×10−4r/V \approx 1.1 \times 10^{-4}, 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-33 joint, with the selection of ii made explicit and the channel applied to the other positions: they agree to 10−1210^{-12} at ρ=0.15\rho = 0.15 and at ρ=0.4\rho = 0.4.

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 EE, and a final LayerNorm before the logits LN⁡(xL)E⊤/d+b\operatorname{LN}(x_L) E^\top/\sqrt{d} + b. There are two blocks. The HMM encoder has d=32d = 32 and is trained for 30003000 Adam steps on fresh corrupted sequences of length 2424. Its gradient is written by hand and checked against central differences.

On 14391439 selected positions of held-out sequences, the exact posterior has a cross-entropy of 1.8951.895 nats and the encoder 1.9171.917. Those score one sampled token per position, so their gap of 0.0220.022 is only an estimate. Computed directly, distribution against distribution, the mean KL is 0.0320.032, under 2%2\% of the 1.8741.874-nat entropy. The KL is 0.0210.021 at a [MASK], 0.0980.098 at a random token, and 0.0400.040 at a kept one. We can also read Theorem 2 (ii) off the encoder itself. At a kept token, it puts 0.7470.747 on the token on average, and the formula applied to its own [MASK] guess predicts 0.7610.761. That guess alone puts only 0.1760.176 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 II, chosen uniformly from {1,…,n}\{1, \dots, n\}, and corrupt nothing else. Then the masked-LM risk of qq is

−1n E∑i=1nlog⁡q(xi∣x−i)=−1n Elog⁡PL⁡q(x),-\frac1n\, \mathbb{E} \sum_{i=1}^{n} \log q(x_i \mid x_{-i}) = -\frac1n\, \mathbb{E} \log \operatorname{PL}_q(x),

with PL⁡q(x)=∏iq(xi∣x−i)\operatorname{PL}_q(x) = \prod_i q(x_i \mid x_{-i}) the pseudo-likelihood. If a family {qθ}\{q_\theta\} contains the true conditionals at θ∗\theta^\ast, then θ∗\theta^\ast maximizes Elog⁡PL⁡θ\mathbb{E} \log \operatorname{PL}_\theta, and it is the unique maximizer when the conditionals identify θ\theta.

Proof.

Averaging over II gives EIEx[−log⁡q(xI∣x−I)]=1n∑iE[−log⁡q(xi∣x−i)]\mathbb{E}_I \mathbb{E}_x[-\log q(x_I \mid x_{-I})] = \frac1n \sum_i \mathbb{E}[-\log q(x_i \mid x_{-i})], which is the first claim. For each ii, conditioning on x−ix_{-i} and applying Theorem 1 with nothing corrupted gives E[−log⁡qθ(xi∣x−i)]≥E[−log⁡p(xi∣x−i)]\mathbb{E}[-\log q_\theta(x_i \mid x_{-i})] \ge \mathbb{E}[-\log p(x_i \mid x_{-i})], with equality exactly when qθ(⋅∣x−i)=p(⋅∣x−i)q_\theta(\cdot \mid x_{-i}) = p(\cdot \mid x_{-i}) almost surely. Summing over ii, the lower bound is attained at θ∗\theta^\ast. Any other maximizer has the true conditionals and so, under identifiability, equals θ∗\theta^\ast.

∎

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 θ∗\theta^\ast is a separate question, which we check rather than prove. On an open Ising chain of 1010 spins with field 0.20.2 and coupling 0.50.5, the expected log pseudo-likelihood has zero gradient at the truth to rounding. The estimate from 200200 exact samples is off by 0.0110.011, and from 2000020000 samples by 0.0040.004. 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 pp be a positive distribution on sequences of length nn. For any two sequences xx and yy,

p(x)p(y)=∏i=1np(xi∣x<i, y>i)p(yi∣x<i, y>i),\frac{p(x)}{p(y)} = \prod_{i=1}^{n} \frac{p(x_i \mid x_{\lt i},\, y_{\gt i})}{p(y_i \mid x_{\lt i},\, y_{\gt i})},

so the full conditionals of pp determine pp up to normalization.

Proof.

Let z(i)=(x1,…,xi,yi+1,…,yn)z^{(i)} = (x_1, \dots, x_i, y_{i+1}, \dots, y_n), so that z(0)=yz^{(0)} = y and z(n)=xz^{(n)} = x, and telescope: p(x)/p(y)=∏ip(z(i))/p(z(i−1))p(x)/p(y) = \prod_i p(z^{(i)})/p(z^{(i-1)}). The sequences z(i)z^{(i)} and z(i−1)z^{(i-1)} agree everywhere except position ii, where they hold xix_i and yiy_i. Dividing both by the marginal probability of their shared coordinates (x<i,y>i)(x_{\lt i}, y_{\gt i}) turns their ratio into p(xi∣x<i,y>i)/p(yi∣x<i,y>i)p(x_i \mid x_{\lt i}, y_{\gt i})/p(y_i \mid x_{\lt i}, y_{\gt i}). 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 254=39062525^4 = 390625 sequences of length 44 from its four conditionals alone, to 10−1510^{-15}. 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 i≠ji \ne j and everything else. Write qi(a∣b)q_i(a \mid b) for a conditional of position ii given xj=bx_j = b, and qj(b∣a)q_j(b \mid a) for one of position jj given xi=ax_i = a. For values a,a′a, a' and b,b′b, b', let

δ=[log⁡qi(a∣b)qi(a′∣b)+log⁡qj(b∣a′)qj(b′∣a′)]−[log⁡qj(b∣a)qj(b′∣a)+log⁡qi(a∣b′)qi(a′∣b′)].\delta = \Bigl[\log \tfrac{q_i(a \mid b)}{q_i(a' \mid b)} + \log \tfrac{q_j(b \mid a')}{q_j(b' \mid a')}\Bigr] - \Bigl[\log \tfrac{q_j(b \mid a)}{q_j(b' \mid a)} + \log \tfrac{q_i(a \mid b')}{q_i(a' \mid b')}\Bigr].

If the qq are the conditionals of a positive joint, then δ=0\delta = 0. So δ≠0\delta \ne 0 anywhere proves that no joint has them as its conditionals.

Proof.

Under a joint pp, the first bracket is log⁡p(a,b)p(a′,b)+log⁡p(a′,b)p(a′,b′)=log⁡p(a,b)p(a′,b′)\log \frac{p(a, b)}{p(a', b)} + \log \frac{p(a', b)}{p(a', b')} = \log \frac{p(a, b)}{p(a', b')}, the change in log-probability along the path (a,b)→(a′,b)→(a′,b′)(a, b) \to (a', b) \to (a', b'). The second bracket is the change along (a,b)→(a,b′)→(a′,b′)(a, b) \to (a, b') \to (a', b'), 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 200200 random choices of a sequence, an adjacent pair of positions, and the two likeliest values at each, the median of ∣δ∣\lvert\delta\rvert is:

  • 2.2×10−162.2 \times 10^{-16} for the HMM’s own conditionals, which is rounding;
  • 0.1300.130 for the trained encoder, with a maximum of 1.6231.623.

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 3.55×10−43.55 \times 10^{-4} and a maximum of 0.9150.915. 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 ww have vectors h1,…,hkh_1, \dots, h_k at some layer, the rows of its occurrence matrix H∈Rk×dH \in \mathbb{R}^{k \times d}. The self-similarity of ww is the mean of cos⁡(hj,hl)\cos(h_j, h_l) over j≠lj \ne l. 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 MEV⁡(w)=σ12/∑iσi2\operatorname{MEV}(w) = \sigma_1^2 / \sum_i \sigma_i^2, with σi\sigma_i the singular values of HH.

An isotropic cloud has baseline 00. A baseline near 11 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 H∈Rk×dH \in \mathbb{R}^{k \times d} have rank r≥1r \ge 1 and nonzero singular values σ1≥⋯≥σr\sigma_1 \ge \dots \ge \sigma_r.

(i) The constant cc minimizing ∑j∥hj−c∥2\sum_j \lVert h_j - c \rVert^2 is the mean of the rows.

(ii) MEV⁡(w)=max⁡∥u∥=1∑j⟨hj,u⟩2/∑j∥hj∥2\operatorname{MEV}(w) = \max_{\lVert u \rVert = 1} \sum_j \langle h_j, u \rangle^2 \big/ \sum_j \lVert h_j \rVert^2, the largest share of the energy of the cloud that one direction carries.

(iii) 1/r≤MEV⁡(w)≤11/r \le \operatorname{MEV}(w) \le 1, with equality on the right exactly when all occurrences are collinear.

Proof.

For (i), the gradient of ∑j∥hj−c∥2\sum_j \lVert h_j - c \rVert^2 in cc is −2∑j(hj−c)-2\sum_j (h_j - c), which vanishes only at the mean, and the function is strictly convex. For (ii), ∑j⟨hj,u⟩2=∥Hu∥2\sum_j \langle h_j, u \rangle^2 = \lVert H u \rVert^2, whose maximum over unit uu is σ12\sigma_1^2, the top eigenvalue of H⊤HH^\top H, while ∑j∥hj∥2=∥H∥F2=∑iσi2\sum_j \lVert h_j \rVert^2 = \lVert H \rVert_F^2 = \sum_i \sigma_i^2. For (iii), σ12\sigma_1^2 is the largest of rr positive numbers that sum to ∥H∥F2\lVert H \rVert_F^2, so it is at least their mean and at most their sum, with equality in the latter exactly when r=1r = 1.

∎

By Eckart–Young, 1−MEV⁡1 - \operatorname{MEV} is the share of the cloud that the best rank-11 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.

layerHMM ww: self-similarityMEVbaselineadjustedkestrel: self-similarityMEVbaselineadjusted
000.7630.7630.7630.7630.0680.0680.6950.6951.0001.0001.0001.0000.1820.1820.8180.818
110.6200.6200.6380.6380.1520.1520.4670.4670.8620.8620.8680.8680.3200.3200.5420.542
220.6760.6760.6910.6910.2030.2030.4730.4730.8460.8460.8620.8620.0480.0480.7980.798

Layer 00 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-00 vectors of kestrel are a single point. Context lowers the adjusted self-similarity at both layers, most at layer 11. The baseline rises from layer 00 to layer 11 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 0.0480.048. That is not isotropy, for which a mean cosine near zero is necessary but not sufficient. The MEV of 10001000 uniformly drawn token vectors at that layer is 0.0930.093, against 1/641/64 for a truly isotropic cloud in 6464 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 Emax⁡kP(sense k∣x)\mathbb{E} \max_k P(\text{sense } k \mid x).

layerprobeshuffled control
000.5010.5010.5040.504
110.9630.9630.4990.499
220.9620.9620.5050.505
static cap0.5090.509—
exact Bayes0.9700.970—

The probe is trained on 15001500 sequences and tested on 15001500 others (66636663 occurrences of ww). 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 00 types kestrel as company or product with five-fold accuracy 0.9070.907, through the position table alone. Product mentions close a document, so all 6161 of them land at positions 2222 to 2424 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.

A · Fill in the blank — the optimum of Theorem 2, the encoder, and the four-cycle test
00.10.20.3wa1a2a3a4a5a6a7a8a9a10a11a12b1b2b3b4b5b6b7b8b9b10b11b12position 4 (true token w) shows [MASK]token (true token in bold color)
exact Bayes posterior (Theorem 2)trained encoder
KL(exact ‖ encoder)
0.016
exact q(true token)
0.217
encoder q(true token)
0.209
P(sense A | sentence)
0.999

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.

B · One word, many vectors — occurrence clouds by layer, and what probes read from them
layer 1
top two principal axes
sense A (regime a)sense B (regime b)
self-similarity
0.620
anisotropy baseline
0.152
adjusted self-similarity
0.467
MEV (its baseline)
0.638 (0.373)
sense probe
0.963
static cap
0.509
exact Bayes accuracy
0.970

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, log⁡(1+ReLU⁡)\log(1 + \operatorname{ReLU}) 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 2121 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