BERT: what the pretraining examples actually contain
BERT
Build selected-token labels, distinguish corruption from selection, and audit a synthetic next-sentence task.
bertA prediction target need not be masked
In a BERT training example, a position can be selected for prediction without being replaced by [MASK]. That sounds contradictory until selection and corruption are separated. Selection determines which positions contribute a prediction loss. Corruption determines what the encoder sees at those positions. The original recipe sometimes leaves a selected token unchanged, but still asks the model to predict it.
BERT stands for Bidirectional Encoder Representations from Transformers. Its original pretraining combines masked language modeling with next-sentence prediction, then adapts the resulting representations to downstream tasks. The encoder architecture explains bidirectional computation. Here we examine the actual input and target construction, because an incorrect data generator can silently change the method while leaving the network architecture intact. BERT
RoBERTa subsequently investigates changes to the training recipe, including masking and the next-sentence objective. Reading those comparisons requires looking at input construction as well as which loss was removed. Architecture names alone do not identify a controlled experiment. RoBERTa
Three embedding components and two training tasks
The original input can contain a pair of text spans separated by [SEP], with [CLS] at the beginning. A “sentence” in this construction need not be one grammatical sentence. Token, segment and position embeddings are added:
Segment IDs indicate membership in the first or second span. They are not an attention mask: tokens in the two spans can exchange information through the bidirectional encoder. Padding positions need separate handling. The final [CLS] representation supplies the original next-sentence prediction head, and task-specific heads can use the resulting token or sequence representations during adaptation. BERT, section 3
Let be the selected target positions, the original tokens and the corrupted input. The original recipe selects 15% of positions, then applies three alternatives to a selected position:
These are probabilities of corruption branches, not necessarily disjoint observable outcomes. A random replacement can equal the original token. In a simplified vocabulary of ordinary tokens sampled uniformly, the probability that a selected token ends up unchanged is:
For , that value is 0.11. The explicit-mask probability among all eligible positions is . The first calculation depends on the toy replacement vocabulary; do not carry its numeric value over to BERT’s actual tokenizer or special-token conventions. The 80/10/10 branch rule, by contrast, is stated in the paper. BERT, section 3.1
The selected-token objective compares predictions with the original tokens, including at positions that remained unchanged:
Unselected positions do not contribute directly to this sum, though their representations can affect selected predictions. Replacing the denominator with the full sequence length changes the scale. A sample with no selected positions requires an explicit policy; our helper rejects its loss instead of silently dividing by zero.
The second task classifies whether the second span was taken from the actual continuation or sampled randomly. The original construction uses these two branches equally. Let denote the actual-next branch and its predicted probability:
The label describes a sampling procedure, not a complete semantic judgment. A randomly drawn span can share the topic or even resemble a plausible continuation. Conversely, successive spans can change topic. The paper’s reported benefit from NSP in its own ablation does not prove that every useful encoder requires this exact objective. BERT, section 5.1 RoBERTa, section 4.2
An exact artificial example makes the ambiguity visible. Give each span one of two equally likely topics. Positive pairs always share a topic; random negatives choose the second topic independently. Under equal class priors:
Predicting “next” for a matching topic and “random” otherwise achieves Bayes accuracy 0.75. The irreducible ambiguity is deliberate: one-quarter of all pairs are random negatives with matching topics. This is not BERT’s NSP accuracy, nor a model of real discourse.
Keep original labels beside corrupted inputs
The original NumPy program returns three separate objects: corrupted tokens, original-token labels and a Boolean selection mask. Unselected labels use the local sentinel −1. The loss helper recognizes that sentinel explicitly; it is not assumed to be the default ignore value of any external library.
"""Original corruption and NSP arithmetic; no pretrained BERT execution."""
import json
import math
import numpy as np
def corrupt(tokens, eligible, rng, rate=.15, vocabulary=10):
tokens = np.asarray(tokens)
eligible = np.asarray(eligible)
if tokens.ndim != 1 or tokens.dtype.kind not in 'iu' or eligible.dtype != bool or eligible.shape != tokens.shape:
raise ValueError('Integer token vector and matching boolean eligibility required')
if vocabulary < 2 or not 0 <= rate <= 1 or ((tokens < 0) | (tokens >= vocabulary)).any():
raise ValueError('Invalid vocabulary, rate or token')
# Bernoulli selection is an explicit toy convention, not BERT generator rounding.
selected = eligible & (rng.random(len(tokens)) < rate)
draw = rng.random(len(tokens))
masked = selected & (draw < .8)
random = selected & (draw >= .8) & (draw < .9)
result = tokens.copy()
result[masked] = vocabulary # separate MASK ID, never an ordinary replacement
result[random] = rng.integers(vocabulary, size=int(random.sum()))
labels = np.where(selected, tokens, -1)
return result, labels, selected
def selected_loss(logits, labels):
z, y = np.asarray(logits, float), np.asarray(labels)
if z.ndim != 2 or y.shape != (len(z),) or y.dtype.kind not in 'iu' or not np.isfinite(z).all():
raise ValueError('Finite logits and integer labels required')
keep = y != -1
if not keep.any() or (y[keep] < 0).any() or (y[keep] >= z.shape[1]).any():
raise ValueError('At least one valid selected target required')
v = z[keep];v = v-v.max(axis=1, keepdims=True)
return float(np.mean(np.log(np.exp(v).sum(axis=1))-v[np.arange(len(v)), y[keep]]))
def nsp_distribution():
# Uniform binary topics. Positive pairs match; random negatives can match too.
joint = np.zeros((2, 2, 2)) # A, B, IsNext
for a in range(2):
joint[a, a, 1] += .25
for b in range(2):
joint[a, b, 0] += .125
observed = joint.sum(axis=2)
posterior = joint[:, :, 1]/observed
accuracy = joint.max(axis=2).sum()
loss = 0.
for a, b, label in np.ndindex(joint.shape):
if joint[a,b,label]:
p = posterior[a,b] if label else 1-posterior[a,b]
loss -= joint[a,b,label]*math.log(p)
return joint, posterior, float(accuracy), loss
def demo():
original=np.arange(20)%10
eligible=np.ones(20,dtype=bool);eligible[[0,19]]=False
values, labels, selected=corrupt(original,eligible,np.random.default_rng(23))
_, posterior, accuracy, loss=nsp_distribution()
return dict(original=original.tolist(), corrupted=values.tolist(), labels=labels.tolist(),
selected=int(selected.sum()), selected_unchanged_probability=.1+.1/10,
population_selected_rate=.15, population_mask_rate=.15*.8,
nsp_posterior=posterior.tolist(), nsp_bayes_accuracy=accuracy,
nsp_minimum_loss=loss, nsp_random_negative_same_topic=.5,
scope='Bernoulli toy corruption; two-topic Bayes calculation, no natural-language inference')
if __name__=='__main__':
print(json.dumps(demo(),indent=2))
The teaching generator uses independent Bernoulli selection among eligible positions. It therefore need not select exactly 15% in a short example. The original BERT generator’s rounding and sampling details are not reproduced here. The example marks the first and last positions ineligible to illustrate protecting special positions, while treating their numeric contents as ordinary toy IDs.
selected_loss uses a stable shifted log-sum-exp and averages only selected labels. Changing an unselected row of logits should not change its value. In an actual network, changing an input token can still affect other positions through attention; the test isolates the final loss aggregation, not the full network’s response.
The NSP helper enumerates every topic-pair and label combination rather than sampling. Its total probability is one, matching pairs have posterior two-thirds, Bayes accuracy is 0.75 and minimum expected binary cross-entropy is about 0.477386 nats. A constant equal-prior classifier would have accuracy 0.5 and loss .
Corruption costs time and memory for tokens. The shown loss helper receives all logits, so its input already costs space; computation after selection depends on the selected rows and vocabulary size. These data operations do not include the encoder’s attention or projection cost. No pretrained checkpoint is loaded.
A sampling label is not a semantic truth
The toy’s topic feature is perfectly observed and its data distribution is fully specified. Real next-sentence prediction can exploit surface clues, document differences or formatting artifacts. A high score on the sampling task does not by itself establish discourse understanding. The Bayes calculation explains one possible ambiguity, not the actual source of BERT’s errors.
Likewise, selected-token accuracy can be inflated by unchanged positions or predictable subword fragments. That does not make the original objective meaningless; it means that a diagnostic should report which positions and corruption branches it evaluates. A separate downstream evaluation asks a different question from reconstructing training-time targets.
BERT’s original pretraining-task ablation and RoBERTa’s later input-format comparisons have different experimental setups. RoBERTa considers both the loss and how sequences are assembled. “Removing NSP helps” cannot be universalized without those conditions, just as the earlier paper’s result cannot establish universal necessity. This chapter reproduces neither paper’s benchmark values. BERT RoBERTa
Audit the labels
- Among eligible positions, what fraction is expected to become an explicit mask under the 15% and 80% probabilities?
Answer: , or 12%. Fifteen percent describes selection, not the final frequency of [MASK]. A short random example can differ from this expectation.
- With ten equally sampled ordinary replacement tokens, what fraction of selected positions ends up unchanged?
Answer: . The keep branch contributes 0.1 and a coincidental match in the random branch contributes 0.01. For all eligible positions under independent 15% selection, the expectation is .
- Two logits rows have labels
[-1, 1], and the second row assigns probability 0.8 to class one. What loss does the helper return?
Answer: , approximately 0.223144. The first row is ignored and the denominator is one selected position. Averaging across two rows would incorrectly halve this helper’s intended loss.
- Why can the two-topic NSP oracle not exceed 75% accuracy?
Answer: Matching-topic pairs include all positive examples, with total mass 0.5, and random negatives with mass 0.25. Those negative examples are indistinguishable using topics alone. Predicting positive on every match and negative on every mismatch correctly classifies mass .
Separate architecture, data and objective changes
The BERT paper documents the original two-task recipe and its task adaptation. RoBERTa is useful for seeing how training duration, masking and sequence construction complicate attribution to one objective. To investigate a claim, keep the tokenizer, data access, optimizer budget and evaluation fixed as far as the experiment permits, and state the remaining differences. BERT RoBERTa
A small extension can add a spurious document marker to the synthetic NSP task. Fit a classifier with and without that marker, then change its correlation on a held-out set. The resulting failure would concern the artificial distribution you created; it should not be reported as evidence that a particular released BERT model uses the same shortcut.
Make a prediction, then check
Under the original BERT recipe, how often is a selected position explicitly masked?
Learning objectives
- Build selected-token labels, distinguish corruption from selection, and audit a synthetic next-sentence task.
- Compute expected selection, explicit-mask and unchanged-token rates with their correct denominators.
- Explain why a random-negative sampling label is not a complete semantic judgment.
Prerequisites & connections
Explore related knowledge →References
- BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
Jacob Devlin; Ming-Wei Chang; Kenton Lee; Kristina Toutanova · 2019 - RoBERTa: A Robustly Optimized BERT Pretraining Approach (v1)
Yinhan Liu; Myle Ott; Naman Goyal; Jingfei Du; Mandar Joshi; Danqi Chen; Omer Levy; Mike Lewis; Luke Zettlemoyer; Veselin Stoyanov · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked BERT3.1 and5.1/Table5 plus previously read RoBERTa4.2. Six paired equations and four explained exercises distinguish selected labels,80/10/10 corruption, unchanged random outcomes and NSP sampling labels. Bernoulli toy selection is not the original generator rounding; two-topic Bayes accuracy0.75 is not BERT performance.
- Single AI author checked BERT3.1 and5.1/Table5 plus previously read RoBERTa4.2. Six paired equations and four explained exercises distinguish selected labels,80/10/10 corruption, unchanged random outcomes and NSP sampling labels. Bernoulli toy selection is not the original generator rounding; two-topic Bayes accuracy0.75 is not BERT performance.
- 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.
- Post-freeze English heading corrected to distinguish selected prediction targets from input masking. The previous heading wrongly suggested the label stayed hidden when its unchanged token was visible. Chinese heading and both explanatory paragraphs already stated the correct rule and remain unchanged; all equations, code, sources and figures are identical. Single AI reread of BERT3.1 and the paired section; original candidate retained with exact delta.
Source locations checked:
- BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding · Identical historical Source object preserved; additionally read section3.1 selection/corruption and NSP. Section5.1/Table5 and PDF8 visually checked; qualitative attribution only. No BERT training or benchmark claims.
- RoBERTa: A Robustly Optimized BERT Pretraining Approach (v1) · Read sections2.2-2.3 and4.1-4.2, including input-format/NSP confounds; PDF4 viewed. Architecture held fixed in these ablations; not proof of universal NSP harm.
Related topics