AI Wiki中文/EN

Masked language modeling: what remains visible changes the score

掩码语言建模

Compute conditional and whole-word scores on a small joint distribution and test candidate rescoring.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A visible word fragment can make the guess easier

Suppose an artificial word contains two token pieces. Hide the first piece but leave the second visible. Now hide both pieces. The questions are different: the first prediction can use information from its partner, while the second cannot. A lower loss under the first setup may reflect that extra clue rather than a better model.

Masked language modeling trains predictions at selected positions after corrupting an input. The original BERT recipe distinguishes selected targets from the subset actually replaced with [MASK]. This chapter focuses on the conditional probabilities and their use in sequence scoring. Read the encoder architecture for how both sides of a gap can influence its representation. BERT

Salazar and colleagues use masked models to score text by masking each position separately and adding the log probability assigned to its original token. They call the result pseudo-log-likelihood, or PLL. This score can rank existing candidates without being an ordinary normalized sentence likelihood. Masked Language Model Scoring

Compatible conditional scores need not form the original joint; masking and normalization units also change pseudo-perplexity.
Compatible conditional scores need not form the original joint; masking and normalization units also change pseudo-perplexity.

Training masks and scoring masks need not match

Let MM be selected positions and x~\widetilde x the corrupted version of xx. One explicit mean-loss convention for MLM is:

LMLM=Ex,M,x~[−1∣M∣∑i∈Mlog⁡qθ(xi∣x~)]. \mathcal L_{\mathrm{MLM}}=\mathbb E_{x,M,\widetilde x} \left[-\frac1{|M|}\sum_{i\in M}\log q_\theta(x_i\mid\widetilde x)\right].

The expectation includes both target selection and input corruption; its definition needs a policy for an empty selected set. Multiple selected positions may be predicted from the same corrupted input. That generally differs from giving each prediction every other original token. The original BERT recipe includes random replacements and unchanged selected positions as well as explicit masks. BERT, section 3.1

In single-position PLL scoring, each position gets its own masked input. Write x∖ix_{\setminus i} for the other visible token positions, with the hidden position represented by a mask in the actual model input:

PLL⁡(x)=∑i=1nlog⁡qθ(xi∣x∖i). \operatorname{PLL}(x)=\sum_{i=1}^{n}\log q_\theta(x_i\mid x_{\setminus i}).

The mask does not mean physically deleting the token and shifting the remaining positions. If several pieces belong to one word, scoring them separately leaves the other pieces visible. Whole-word masking changes that conditioning information. Masked Language Model Scoring, PLL definition and section 2

To calculate the difference exactly, define four artificial two-piece words. Their first and second pieces are bits A,BA,B, with joint probability table:

P=(0.450.050.100.40),PA=(0.5,0.5),PB=(0.55,0.45). P=\begin{pmatrix}0.45&0.05\\0.10&0.40\end{pmatrix}, \qquad P_A=(0.5,0.5),\quad P_B=(0.55,0.45).

All values are positive and sum to one. Use the true conditionals as an oracle, avoiding any uncertainty from model fitting. Masking only the first piece gives P(A∣B)P(A\mid B); masking only the second gives P(B∣A)P(B\mid A). Their product is:

exp⁡(PLL⁡(a,b))=P(a∣b)P(b∣a)=P(a,b)2PA(a)PB(b). \exp(\operatorname{PLL}(a,b))=P(a\mid b)P(b\mid a) =\frac{P(a,b)^2}{P_A(a)P_B(b)}.

For word 00, the conditionals are 9/119/11 and 0.90.9, so the product is 81/11081/110, approximately 0.736364. Its true joint probability is only 0.45. This is not an inconsistency in the conditionals: both came from the same valid joint. Multiplying overlapping conditionals simply does not apply the ordered chain rule.

Summing the four products gives about 1.494949. Dividing by that sum creates a normalized table, but it does not in general recover the original joint or preserve its conditionals:

P~(a,b)=exp⁡(PLL⁡(a,b))∑a′,b′exp⁡(PLL⁡(a′,b′))≠P(a,b)in this example. \widetilde P(a,b)=\frac{\exp(\operatorname{PLL}(a,b))}{\sum_{a',b'}\exp(\operatorname{PLL}(a',b'))} \ne P(a,b)\quad\text{in this example}.

For instance, the normalized probability of 00 becomes about 0.492568, rather than 0.45. When AA and BB are independent, the product instead equals their joint; the tests include that special case. A counterexample to automatic normalization should not be overstated as a claim that equality is impossible.

If both pieces are hidden and two prediction heads act independently, they use the marginals PA,PBP_A,P_B. Their summed log score is the log of the independent marginal product, not the log of the original correlated joint. An autoregressive reconstruction could condition the second target piece on the first and express that dependence, but it would be another scoring setup.

Pseudo-perplexity is an exponential of a normalized negative PLL. For corpus token count NN:

PPPL⁡=exp⁡ ⁣(−1N∑xPLL⁡(x)). \operatorname{PPPL}=\exp\!\left(-\frac1N\sum_x\operatorname{PLL}(x)\right).

The unit matters. The scoring paper discusses vocabulary and normalization constraints when comparing values. In this toy, every word contains two pieces, so changing the denominator from piece count to word count squares PPPL. That numerical change does not reflect a change in predictions. Masked Language Model Scoring, section 2.3

An exact oracle, then a candidate reranker

The original NumPy program computes single-piece conditionals, PLL, independent whole-word-mask scores and true joint probabilities from the same table. It also combines a base candidate log score with weighted PLL. This is a transparent scoring example, not a call to BERT or a natural-language fluency test.

"""Exact synthetic two-piece word scoring: single-piece versus whole-word masks."""
import json
import numpy as np


def scores(joint):
    p=np.asarray(joint,float)
    if p.ndim!=2 or min(p.shape)<2 or not np.isfinite(p).all() or (p<=0).any() or not np.isclose(p.sum(),1):
        raise ValueError('Positive normalized joint table required')
    rows=p.sum(axis=1,keepdims=True);columns=p.sum(axis=0,keepdims=True)
    # Mask piece1 while showing piece2, then mask piece2 while showing piece1.
    first=p/columns;second=p/rows
    pll=np.log(first)+np.log(second)
    # Hide both pieces, predict each independently from its marginal.
    whole=np.log(rows)+np.log(columns)
    return dict(conditional_first=first,conditional_second=second,pll=pll,whole=whole,
                true_log_joint=np.log(p),normalized_pll=np.exp(pll)/np.exp(pll).sum())


def rescore(base_log_scores,pll,weight):
    base=np.asarray(base_log_scores,float);pll=np.asarray(pll,float)
    if base.shape!=pll.shape or base.ndim!=1 or not np.isfinite(base).all() or not np.isfinite(pll).all() or not np.isfinite(weight) or weight<0:
        raise ValueError('Matching finite candidate vectors and nonnegative weight required')
    mixed=base+weight*pll
    return int(np.argmax(mixed)),mixed


def demo():
    p=np.array([[.45,.05],[.1,.4]])
    s=scores(p)
    pll=s['pll'].ravel()
    base=np.log([.1,.7,.1,.1])
    winner,mixed=rescore(base,pll,1.)
    # Pseudo-perplexity uses two pieces, not one synthetic word.
    expected_pll=float(np.sum(p*s['pll']))
    expected_whole=float(np.sum(p*s['whole']))
    return dict(joint=p.tolist(),pll=s['pll'].tolist(),whole_mask_scores=s['whole'].tolist(),
                pseudo_mass=float(np.exp(s['pll']).sum()),normalized_pll=s['normalized_pll'].tolist(),
                token_pseudo_perplexity=float(np.exp(-expected_pll/2)),
                word_pseudo_perplexity=float(np.exp(-expected_pll)),
                whole_mask_token_pseudo_perplexity=float(np.exp(-expected_whole/2)),
                before_winner=int(np.argmax(base)),after_winner=winner,mixed_scores=mixed.tolist(),
                scope='Four artificial words, two pieces each; exact conditional oracle, not BERT scores or a fluency benchmark')


if __name__=='__main__':
    print(json.dumps(demo(),indent=2))

Averaging under the true word distribution gives piece-normalized PPPL about 1.514745 and word-normalized PPPL about 2.294451. Independently predicting both hidden pieces gives piece-normalized pseudo-perplexity about 1.994998. The single-piece score benefits from visible partner information. These numbers should not be read as a comparison between two trained language models.

For candidate order 00,01,10,11, the base probabilities are 0.1,0.7,0.1,0.1, initially favoring 01. Adding PLL with weight one selects 00 instead. The mixed scores are ranking quantities; the program does not label them normalized probabilities. A weight should be selected on development data for a real application, then evaluated separately.

On a table with VAVBV_A V_B entries, these exact calculations take O(VAVB)O(V_A V_B) time and space. A neural PLL calculation instead needs a distinct masked view for each scored position. Those views can be batched, but batching does not remove the work or memory requirement. The paper also studies learning a separate approximation to the total score; that is an additional model, not the same computation becoming free. Masked Language Model Scoring, section 2.2

A reranker can only choose what it receives

If the correct answer is absent from the candidate list, PLL rescoring cannot produce it. A candidate generator and a reranker solve separate problems. Improving ranking accuracy among a fixed list does not prove improved unconstrained generation.

Our oracle starts from compatible conditionals of a known joint. Arbitrary learned conditional heads need not satisfy that compatibility. The example makes the narrower point that even compatibility does not make their overlapping product a normalized joint. It does not prove that masked models cannot be used within any generative algorithm.

The artificial two-piece words also omit surrounding context, morphology and tokenization ambiguity. Whole-word masking in real data requires a reliable mapping from words to token positions. Changing that mapping changes which clues remain visible. Comparisons should keep the mask policy, token vocabulary, corpus and normalization unit explicit rather than treating all “masked perplexity” numbers as one metric.

Keep the probability events separate

  1. For artificial word 00, why is the single-piece conditional product greater than its true joint probability?

Answer: Each prediction receives the other piece. The product is (9/11)×0.9=81/110(9/11)\times0.9=81/110, while the joint is 0.45. These are different events and factorizations; the ordered joint would use one marginal and one appropriate conditional.

  1. Does normalizing the four exponentiated PLL values recover the original table?

Answer: No. The sum is about 1.494949 and the normalized 00 entry becomes about 0.492568, not 0.45. The program compares every entry, so this is a direct finite counterexample rather than an appeal to terminology.

  1. If every artificial word has two pieces, why is word-normalized PPPL the square of piece-normalized PPPL?

Answer: The total PLL stays fixed, but the denominator is halved. The negative average doubles before exponentiation, so the result is squared. It is a unit change, not an improvement or degradation of the model.

  1. Can giving PLL a larger weight recover a missing correct candidate?

Answer: No. The ranking function selects an index in the supplied list. Changing its weight can change which existing item wins, but cannot create an absent item. Candidate coverage must be measured separately.

A useful score need not be a sentence probability

BERT supplies a way to train contextual token predictions. The scoring paper investigates applying those predictions to candidate ranking and pseudo-perplexity. The usefulness of a score for a particular decision is an empirical question, distinct from whether it forms a normalized joint distribution. Neither the synthetic table nor a paper’s application result settles all uses of masked models. BERT Masked Language Model Scoring

For a small extension, vary the correlation in the table while holding the marginals fixed. Track the gap between single-piece and whole-word-mask scores, then test how reranking changes with the base candidate distribution. Include independent pieces as a control. This isolates how visible evidence and candidate coverage affect the score before introducing a pretrained model.

Make a prediction, then check

What does a normalized exponential of PLL necessarily recover?

Choose one answer

Learning objectives

  • Compute conditional and whole-word scores on a small joint distribution and test candidate rescoring.
  • Construct a compatible-conditional counterexample whose normalized PLL changes the original joint.
  • Explain why tokenization units and candidate coverage limit a pseudo-perplexity or reranking claim.

Prerequisites & connections

Explore related knowledge →

References

  1. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
    Jacob Devlin; Ming-Wei Chang; Kenton Lee; Kristina Toutanova · 2019
  2. Masked Language Model Scoring
    Julian Salazar; Davis Liang; Toan Q. Nguyen; Katrin Kirchhoff · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked BERT corruption definition and ACL2020 MLM scoring PLL/sections2.1-2.3. Six paired equations and four explained exercises; compatible two-piece conditional oracle, overlapping-product mass148/99, changed joint after normalization, PPPL units and candidate reranking. Independent-control table and invalid inputs checked; no BERT model execution or fluency benchmark.

  • Single AI author checked BERT corruption definition and ACL2020 MLM scoring PLL/sections2.1-2.3. Six paired equations and four explained exercises; compatible two-piece conditional oracle, overlapping-product mass148/99, changed joint after normalization, PPPL units and candidate reranking. Independent-control table and invalid inputs checked; no BERT model execution or fluency benchmark.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and42 responsive cases passed; fourteen final Chinese-mobile/English-desktop screenshots actually inspected. Initial English mobile-heading clipping and corrections preserved. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.