20 / 28 · Pretrained Language Models
BERT and masked language modeling
Separate selected positions, corruption and MLM loss, trace contextual states, count a specified encoder and execute an independent head-only diagnostic without pretrained assets.
Transformer Architecture · Transformer for machine translation · Tokenization
On this page 7
In carry [MASK] folded, the words on both sides may help recover an equipment name. A next-token model can use only the allowed prefix for its next prediction. A bidirectional encoder can use both sides, but training it to copy a visible token at its own position would provide a shortcut. BERT changes the training input and asks the encoder to recover selected original tokens.
Give the encoder a prediction problem#
The Transformer encoder calculates one state per input position using bidirectional attention over real tokens. It needs an objective to determine which distinctions those states should retain. Architecture alone does not create useful representations.
BERT’s masked language modeling objective starts from an original sequence and a selected set of prediction positions . A corruption procedure produces . The encoder reads that corrupted sequence and a vocabulary head predicts the original token at each selected position:
This expression assumes a nonempty selected set and an equal weight for every selected position. A batch can instead pool its selected positions; empty cases need an explicit policy. The original labels are kept separately before corruption. Replacing a token in the input must not overwrite the target that the model is meant to recover.
The state for a selected position may use left and right context. It sees the corrupted version of every selected position, not the unavailable original tokens by a special side channel. A large capacity model can still exploit artifacts or memorize training examples; hiding tokens creates a task, not a guarantee that its solution transfers to every downstream use.
Selection, corruption and the loss mask#
The original paper selects roughly 15% of token positions for prediction. Among selected positions, its described replacement mixture uses a mask token for 80%, a random token for 10%, and the unchanged original for 10%. Selection and replacement are different decisions. An unchanged selected position still contributes a target to the loss.
For an idealized eligible position selected with probability , multiply the conditional replacement probabilities to obtain:
| Event | Probability over eligible positions |
|---|---|
| Selected, mask-replacement branch | 3/25 |
| Selected, random-replacement branch | 3/200 |
| Selected, unchanged branch | 3/200 |
| Not selected | 17/20 |
The probabilities sum to one. This is exact arithmetic for the stated idealized selection probability, not a claim that every finite implementation selects independent Bernoulli positions. The pinned original data generator selects a rounded, capped count from eligible candidates, excludes special boundary tokens and optionally groups WordPieces. Those details can change finite-sequence selection frequencies.
Random replacement can equal the original token. It can also coincide with a special token if that token belongs to the sampler’s vocabulary. Consequently the visible presence of [MASK], or an observed difference between original and corrupted IDs, does not reconstruct the selection mask reliably. Preserve the selected positions explicitly.
A deterministic replacement trace makes the branch probabilities inspectable without pretending to be a random draw. Take twenty already-selected positions and supplied quantiles for . The intervals below 0.8, from 0.8 to below 0.9, and from 0.9 onward give sixteen mask, two random and two unchanged actions. These twenty positions are already selected; they are not twenty tokens from which the 15% selection rule has been applied.
The loss denominator is equally important. Suppose a sequence has six real positions, only positions one and four are selected, and their correct-token probabilities are and . The mean selected-token loss is
Dividing the same numerator by six gives 0.3276854761, one third as large, without improving either prediction. Padding positions and unselected real positions have different meanings, but neither belongs in this selected-token denominator. Loss values are comparable only when masking and reduction conventions are comparable.
Input markers do different jobs#
The original model combines token, learned absolute position and token-type embeddings, followed by normalization and dropout. For a position , before those final operations, write
The type index identifies an input segment. It does not label a grammatical category or guarantee a semantic relationship. The special [CLS] position supplies a state used by a sequence-level head; [SEP] marks boundaries. These marker tokens do not replace the numerical token-type IDs, position IDs or attention mask.
Padding keys must be excluded from attention, while real tokens may attend in both directions. The selected-position loss mask is separate from this attention mask. Hiding an entire selected position from all communication would define another objective from replacing its input token and allowing the resulting state to read context.
WordPiece tokenization determines the prediction units. One word may occupy several positions; predicting one subword can leave other pieces visible. Whole-word selection changes which groups are corrupted, while each output position can still have its own vocabulary prediction. A tokenizer and its vocabulary must match a pretrained checkpoint; equal vector widths do not make different token-ID assignments compatible.
The original BERT training also used next-sentence prediction: a binary head distinguished a real continuation segment from a randomly chosen segment under the data construction. That target describes the source of a pair, not logical implication or factual agreement. The input format can be useful for pair tasks, but the original binary objective should not be relabeled as a general semantic-similarity test.
Count an explicitly specified small architecture#
BERT uses a bidirectional Transformer encoder with per-position prediction heads rather than an autoregressive decoder with a causal triangle. The pinned original implementation uses post-normalized residuals and GELU in the feed-forward transformation. Its MLM head adds a width-preserving nonlinear transform and normalization before the vocabulary projection, with output weights tied to the token embedding table.
We can count an independently chosen miniature configuration without downloading a model. Set width four, inner FFN width eight, two encoder blocks, two attention heads, a vocabulary of nine IDs, six position rows and two token-type rows. Include all linear biases and affine LayerNorms. Include the original-style MLM transform, a pooled [CLS] transform and a two-class pair head.
For width and inner width , the encoder-block count is . The specified block therefore has 172 parameters. The complete hypothetical count is:
| Component | Calculation | Parameters |
|---|---|---|
| Token table | 9 × 4 | 36 |
| Position table | 6 × 4 | 24 |
| Token-type table | 2 × 4 | 8 |
| Embedding normalization | 2 × 4 | 8 |
| Two encoder blocks | 2 × 172 | 344 |
| MLM transform and normalization | 4 × 4 + 4 + 2 × 4 | 28 |
| Tied vocabulary output bias | 9 | 9 |
| Pooled sequence transform | 4 × 4 + 4 | 20 |
| Binary pair head | 2 × 4 + 2 | 10 |
| Total | Sum of these rows | 487 |
Tying the vocabulary matrix means its weights are counted in the token table once, while its output-only bias remains separate. Removing the pair head or pooling transform changes the count. Optimizer states, activations and gradients require memory but do not add model parameters. This table is arithmetic for a new configuration, not a reconstruction of a published checkpoint size or a claim that a 487-parameter model was pretrained.
A fixed mask token can produce contextual states#
The token lookup for [MASK] is fixed, but its final hidden state can change with the other input positions. This is the distinction between the static lookup table and a contextual representation. The same applies to an ordinary unmasked token: its contextual state is an output of the encoder’s entire computation, not simply its embedding row renamed.
Construct a minimal diagnostic with one query (1, 0), two keys (0, 1) and (1, 0), and left value (0.2, 0.2). Only the right value changes. Attention uses the usual division by the square root of key width two. The weights on left and right are approximately 0.3302384507 and 0.6697615493.
| Case | Supplied right value | Resulting two-coordinate state | Target token |
|---|---|---|---|
| A | (1, 0) | (0.735809, 0.066048) | lamp |
| B | (0.8, 0) | (0.601857, 0.066048) | lamp |
| C | (0, 1) | (0.066048, 0.735809) | tripod |
| D | (0, 0.8) | (0.066048, 0.601857) | tripod |
These values and targets are newly specified mathematical inputs. They are not embeddings extracted from the opening phrase or another sentence. They isolate one operation that an encoder can use to make the selected position depend on right context. The attention parameters remain fixed throughout the following fit; no BERT weights, corpus or tokenizer are loaded.
The paired changes also illustrate a limit of attention-only inspection. All four cases have identical attention weights but different states, since the values differ. A contextual representation requires examining the whole computation, not equating a softmax row with the final meaning of a token.
Fit a diagnostic head and separate its claim#
Attach a linear softmax head to those four fixed two-coordinate states. Its output vocabulary is exactly lamp, tripod, bright, folded, carry, storage, in that order. This six-item diagnostic vocabulary is separate from the nine-ID hypothetical architecture count above. The head contains twelve weights and six biases, all initialized to zero.
Use mean cross-entropy for the supplied targets plus an L2 penalty on weights only:
At zero initialization every vocabulary item has probability one sixth, so the objective is . Six hundred simultaneous full-batch gradient steps of size 0.3 reduce it to 0.1780554451; the value after 300 steps is 0.1872423748. The saved probabilities of the four supplied targets are approximately 0.941782, 0.902599, 0.941782 and 0.902599.
All eighteen initial and final analytic head-gradient coordinates are checked by finite differences. The stored output includes the exact inputs, features, labels, parameters and intermediate losses. Four other vocabulary items receive probability but are never positive targets in this tiny fit, so this experiment cannot assess recognition of those items.
This is head-only optimization on constructed states, without BERT’s full MLM transform or encoder training. It demonstrates how a selected-position state can drive vocabulary prediction. A real pretrained MLM head has learned parameters and a much broader training distribution; its token suggestions still need evaluation for the intended task. A likely completion does not by itself establish factual truth, suitability or a calibrated probability for another domain.
Multiple masked positions create another distinction. The loss sums predictions conditioned on the same corrupted input. It does not directly supply the left-to-right sequence factorization used by an autoregressive generator. One cannot multiply arbitrary bidirectional token scores and call the result the same sequence likelihood without defining an additional scoring procedure. That matters when comparing perplexity-like quantities across objectives.
What changed#
The encoder now has a training signal that can require both sides of a selected position. Corruption changes the visible input while the original labels remain separate. A vocabulary head reads contextual states, and a loss mask chooses which predictions matter. Pretraining can then supply parameters to downstream token or sequence tasks, whose objectives and evaluation remain separate.
Limitations#
Mask recovery can reward local statistical shortcuts and memorization. Tokenization, corruption choices, available context and domain affect its difficulty. The original input length is bounded by its learned position table; truncation can remove required evidence. Neither [CLS] nor an average of token states automatically provides a validated sentence-similarity space.
The constructed head fit contains four training cases and no held-out evaluation. It does not establish language understanding, transfer quality, pretrained-model behavior or an advantage over another objective. Its purpose is to expose the contextual path, loss selection and optimization arithmetic with saved reproducible outputs.
What to remember#
Keep original labels before corruption. Selection, replacement, attention masking and loss masking are separate. Unchanged selected tokens still contribute to MLM loss. Contextual states differ from lookup embeddings. Parameter tying changes counting, not vocabulary compatibility. The new four-case head fit is a diagnostic, not a pretrained BERT evaluation.
Notebook#
- The standard-library executable saves the idealized branch probabilities, deterministic twenty-selected-position trace, selected-loss denominator and 487-parameter arithmetic.
- It separately computes all four contextual states and executes the eighteen-parameter head fit, recording parameters, losses, probabilities and finite-difference checks. It downloads no tokenizer, weights, text corpus or external notebook.
Next#
A masked encoder predicts selected tokens using both sides. A GPT-style causal model instead trains each next-token distribution from its prefix, giving a direct autoregressive generation rule. The change is an information-flow and objective decision, not merely a different name for the same head.
References#
- Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT, 2019. Sections 3–3.1: input structure, MLM corruption and the original next-sentence objective. No source sentence, figure, corpus or benchmark table is reused.
- The Google AI Language Team Authors and BERT contributors. Original BERT implementation, revision
eedf571.modeling.py: embedding composition, post-normalized encoder and pooling;create_pretraining_data.py: selected-position and corruption contracts;run_pretraining.py: tied MLM output and weighted selected-token loss. These files identify Apache-2.0 for their code; the implementation is referenced for contracts, not copied into the independent calculation, and no license is inferred for separate corpora or weights.