BERT

The paper made the encoder-only Transformer a reusable bidirectional language representation backbone.

Metadata

FieldValue
PaperBERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
AuthorsJacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova
Year2019
VenueNAACL-HLT 2019
arXiv1810.04805
ACL AnthologyN19-1423
Statusfull paper note

Question

Before BERT, many language models were left-to-right or shallowly bidirectional. The question was whether a deep Transformer encoder could learn reusable bidirectional token representations from unlabeled text and then adapt to many supervised NLP tasks.

More concretely, the paper asks whether a single pre-trained encoder can replace many task-specific NLP architectures. The architectural bet is that deep bidirectional self-attention is a better default representation engine than a stack of task-specific feature extractors.

Main Claim

BERT pre-trains a deep bidirectional Transformer encoder with masked language modeling and next-sentence prediction, then fine-tunes the same backbone with small task heads.

Masked language modeling objective:

where is the set of masked token positions.

Next-sentence prediction in the original paper is a binary classification objective:

The combined pre-training loss is:

The claim should be read narrowly: BERT shows that encoder-only Transformer pre-training plus fine-tuning is powerful for language understanding benchmarks. It does not claim that the encoder-only form is the best architecture for generation.

Architecture Contract

ItemContract
Inputtokenized text sequence or text pair
Special tokens[CLS] at the start, [SEP] between or after segments
Token representationtoken embedding + segment embedding + positional embedding
Backbonestacked bidirectional Transformer encoder blocks
Context directionevery non-masked token can attend to left and right context
Sequence outputcontextual vector for each token
Sequence-level output[CLS] vector for classification-style heads

The input embedding for position can be written as:

The encoder maps token embeddings into contextual states:

where:

with sequence length and hidden dimension .

Encoder Block Walkthrough

BERT inherits the Transformer encoder block from Attention Is All You Need, but uses it as a pre-trained representation stack rather than a translation encoder.

One block can be summarized as:

The exact normalization placement follows the original post-norm Transformer style. Later Transformer stacks often use pre-norm variants for more stable scaling.

The key architectural difference from a decoder-only language model is the attention mask:

Model TypeAttention PatternNatural Use
encoder-only Transformerbidirectional attentionrepresentation, classification, extraction
decoder-only Transformercausal attentiongeneration, prompting, next-token prediction
encoder-decoder Transformerbidirectional source encoder + causal target decodersequence-to-sequence transduction

Method

ComponentRole
Transformer encoderbidirectional token mixing
[CLS] tokensequence-level representation
masked language modelingforces contextual token reconstruction
next-sentence predictiontrains a sentence-pair signal in the original setup
fine-tuning headadapts shared backbone to downstream tasks

Pre-training Pipeline

BERT pre-training has three important design choices.

ChoiceMeaningWhy it matters
masked token predictionpredict selected tokens from contextpermits bidirectional conditioning without trivial copying
sentence-pair formattingpack one or two segments with segment embeddingssupports entailment, QA, and sentence-pair tasks
task-agnostic backbonekeep the encoder shared across tasksmakes the paper a pre-trained architecture paper, not only an NLP benchmark paper

The masking recipe is easy to misread. The model does not simply replace every target token with [MASK] at fine-tuning time. A subset of tokens is selected for prediction; selected positions are mostly replaced by [MASK], sometimes left unchanged, and sometimes replaced by a random token. This reduces mismatch between pre-training and fine-tuning because [MASK] is not present in downstream input.

Fine-tuning Routes

The paper’s practical contribution is the simple route from one encoder to many downstream heads.

Task TypeOutput UsedHead
sentence classification[CLS] hidden statelinear classifier
sentence-pair classification[CLS] after packed pair inputlinear classifier
token classificationper-token hidden statestoken-level classifier
extractive question answeringper-token hidden statesstart/end span classifiers

For classification:

For extractive QA:

This is why BERT became a backbone: most task-specific architecture is reduced to a small prediction head.

Pre-training Input Contract

BERT does not receive an arbitrary text string directly. It receives a packed sequence with explicit segment structure:

For a single sentence, segment is empty. The embedding at position combines three lookup tables:

The segment embedding is a small but important interface decision. It tells the same shared encoder whether a token belongs to sentence or sentence without requiring a separate encoder for each side. The [SEP] tokens provide explicit boundaries to the self-attention stack.

The representation contract is therefore:

Input formMain state usedTypical output
one segmenttoken states and [CLS]classification or tagging
two segmentsshared contextual states with segment IDsentailment, matching, pair classification
question plus contextper-token contextual statesstart/end span prediction

This packing convention is part of the architecture. Replacing it with an unmarked concatenation changes the information available to the encoder and the downstream head.

Masked Language Modeling in Detail

Let be the set of selected token positions. In the original recipe, approximately 15 percent of token positions are selected for prediction. For each selected position, the input corruption is sampled from three cases:

CaseApproximate fraction of selected positionsInput shown to encoder
mask80 percent[MASK] token
unchanged10 percentoriginal token
random replacement10 percentrandom vocabulary token

The target remains the original token in all three cases. The objective is:

The unchanged and random-replacement cases reduce the pre-training/fine-tuning mismatch caused by a special [MASK] token that is absent from ordinary downstream inputs. They also mean that the model cannot assume that every selected target position is visibly marked as corrupted.

MLM is not ordinary left-to-right language modeling. The attention graph for an unmasked token can include both left and right context, while the loss is applied only to selected positions. The useful separation is:

BERT learns contextual representations using both directions; it does not define a left-to-right procedure for generating an arbitrary paragraph.

Next Sentence Prediction

For the original next-sentence objective, a pair of segments is labeled as either a true consecutive pair or a randomly sampled pair. The binary loss is:

The total objective is commonly written as:

NSP should be read as a historical task-interface choice, not as a necessary property of every encoder. Later work changed or removed it, used sentence-order alternatives, or trained with larger contiguous spans while retaining the encoder-only backbone. This makes BERT useful as a decomposition point:

When comparing BERT with later encoders, keep those two axes separate.

Representation Flow

For input length and hidden width , the encoder produces:

Each layer mixes information across the entire sequence through self-attention and then applies a token-wise feed-forward transformation. The contextual state at position is not a fixed feature extractor output:

The same token can receive a different representation when the surrounding sentence changes. This context dependence is the reason BERT can support token labeling, span extraction, and sentence-level classification from one backbone.

For masked prediction, a small output transformation maps the selected hidden states to vocabulary logits:

For a downstream classification task, the same encoder state is connected to a task-specific head instead:

The backbone and head therefore have different lifetimes: the pre-training head is discarded or replaced, while the encoder is transferred.

Model Scale as an Architecture Variable

The original paper presents base and large configurations. Their important distinction is not the model name but the scaling axes:

AxisBase-style configurationLarge-style configurationArchitectural effect
encoder depthfewer blocksmore blocksmore sequential representation transformations
hidden widthnarrower stateswider stateslarger token representation and projection matrices
attention headsfewer headsmore headsmore parallel relation subspaces
parameterslowerhighermore capacity and higher pre-training cost

For a Transformer layer, the dominant dense projections scale approximately with width and the attention interaction scales with sequence length:

This explains two boundaries of the original BERT design:

  1. increasing sequence length is expensive because of the attention term;
  2. increasing hidden width is expensive because of the projection and feed-forward terms.

Model size alone is not a complete explanation for transfer quality. Corpus size, tokenization, optimization schedule, sequence-length curriculum, and fine-tuning hyperparameters are part of the effective system.

Architecture Versus Objective

The BERT contribution is often summarized as “MLM plus Transformer,” but the reusable architecture can be decomposed more precisely:

Layer of the systemBERT choiceCan later work change it?
token interfaceWordPiece-style subword tokens and special separatorsyes, with other tokenizers or byte-level units
backbonestacked bidirectional Transformer encoderyes, with different attention or state operators
corruptionselected-token maskingyes, with spans, replaced tokens, or denoising schemes
auxiliary targetnext-sentence classificationyes, remove or replace it
transfer interface[CLS], token states, span headsyes, pool, retrieve, or attach task-specific modules

This decomposition is useful when reading protein, image, or multimodal encoders. A masked objective can be transferred while changing the token unit and backbone; conversely, the encoder can be retained while replacing MLM with another representation objective.

Evidence and Claim Boundaries

The headline benchmark numbers in the paper support the claim that BERT was a strong transfer recipe on the evaluated language-understanding tasks. They do not independently prove each of the following stronger claims:

Strong statementWhat would be needed to support it
bidirectionality alone caused the gaincontrolled objective, data, and parameter comparisons
NSP is necessaryablations across datasets and later training recipes
[CLS] is a universal sentence embeddingretrieval and semantic similarity evaluations, not only classification
pre-training always improves transfertask- and domain-matched baselines with equal compute
BERT is suitable for generationan explicit generation architecture and decoding evaluation

The paper’s most durable evidence is the combination of a shared encoder, simple adaptation heads, and gains across several task families. The exact objective recipe should remain historically important without being treated as immutable.

Ablations and Reading Questions

When reading or reproducing BERT, ask:

  • Does the comparison use the same tokenizer and vocabulary coverage?
  • Are the number of pre-training updates, tokens, and sequence lengths matched?
  • Is the baseline bidirectional, left-to-right, or shallowly contextual?
  • Are MLM and NSP changed together, or is one isolated?
  • Is a result from frozen probing, full fine-tuning, or an intermediate setting?
  • Does the task use [CLS], per-token states, or span logits?
  • Are sentence pairs sampled in a way that makes NSP artificially easy?
  • Does the downstream task exceed the 512-token sequence limit?

Useful ablation axes include:

AblationIsolates
remove NSPvalue of the auxiliary sentence-pair signal
alter mask replacement proportionssensitivity to the pre-training/fine-tuning mismatch
replace token masking with span maskingdependence on local versus contiguous corruption
reduce pre-training data or stepsdata/compute scaling versus architecture
freeze encoder and train a probequality of the representation without task adaptation
compare encoder-only and decoder-only attention maskscontextual representation versus autoregressive prediction

Failure Modes in Practice

  1. Tokenizer mismatch: a downstream domain uses many rare or fragmented subwords, so the model spends capacity on tokenization artifacts.
  2. Mask leakage: preprocessing exposes target information through duplicated text, labels, or unmasked copies.
  3. Sentence-pair shortcut: NSP examples contain topic or document-boundary artifacts that make the auxiliary task easier than discourse understanding.
  4. Pooler overinterpretation: the [CLS] state is treated as a universal embedding without a matching objective or evaluation.
  5. Context truncation: important evidence falls outside the maximum input window, silently changing the task.
  6. Fine-tuning variance: small data or unstable hyperparameters make benchmark gains sensitive to seed and schedule.
  7. Generation mismatch: an encoder checkpoint is used as if it were a causal decoder, even though its attention and training objective do not define that interface.

For a minimal implementation test, verify that changing the right-hand context can change the representation of a token in the left-hand segment. Then verify that a causal attention mask produces a different model contract rather than merely a different tensor shape.

Relation to Later Encoder Families

BERT is an anchor, not the final encoder design:

Later familyWhat it changes relative to BERT
RoBERTa-style trainingdata, batch, schedule, and objective recipe while keeping an encoder backbone
ALBERT-style factorizationparameter sharing and embedding factorization for efficiency
DeBERTadisentangled content/position representations and attention design
Long-context encodersattention pattern or memory interface to reduce the quadratic window limit
protein language encoderstoken unit and corpus, while reusing masked representation learning ideas
vision masked encoderspatch units and reconstruction target, often with an asymmetric decoder

The comparison with MAE is especially instructive. Both hide part of the input, but BERT keeps the full sequence in the encoder and predicts discrete token identities, while MAE removes masked patches from the expensive encoder and reconstructs continuous patch targets with a lightweight decoder.

Reproduction Checklist

  • define tokenizer, vocabulary, special tokens, and maximum sequence length;
  • verify segment IDs and [CLS]/[SEP] placement;
  • implement the selected-token mask with the recorded replacement proportions;
  • ensure MLM loss is computed only at selected positions;
  • record whether NSP is used, removed, or replaced;
  • record depth, width, head count, and normalization placement;
  • separate pre-training output heads from downstream task heads;
  • distinguish frozen probing from full fine-tuning;
  • report token count, update count, batch size, and compute budget;
  • test long-input truncation and sentence-pair formatting;
  • compare against a causal and a non-pretrained baseline where relevant.

Evidence

ClaimEvidence in paperCaveat
Bidirectional encoder pre-training improves NLP tasksGLUE, MultiNLI, SQuAD, and other benchmark gainsobjective and data scale are coupled with architecture
One backbone can support many tasksfine-tuning with small task-specific headstask formatting still matters
Deep bidirectional context is usefulcomparison against prior contextual representationslater work revised NSP and pre-training recipes

Benchmark Card

FieldValue
Main task familylanguage understanding
Input/output unittext or text pair to class label, token label, or answer span
Main benchmarksGLUE, MultiNLI, SQuAD, named entity recognition, and related NLP tasks
Main comparisonprior contextual representation models and task-specific systems
Main metric typesaccuracy, F1, exact match, task-specific benchmark scores
Not directly testedopen-ended generation, tool use, retrieval-augmented reasoning, multimodal modeling

Ablation Reading

The most useful ablations are not just “BERT is better.” They answer which ingredients are carrying the result.

Ablation AxisWhat it testsReading
bidirectional vs left-to-right contextwhether full-context encoder attention matterssupports the encoder-only representation claim
MLM and NSP objectiveswhether each pre-training signal helpslater work weakened the case for NSP as a universal requirement
model sizewhether depth/width improves transfersupports scaling, but data and optimization also change effective capacity
pre-training duration/datawhether representation quality is data-dependentarchitecture should not be isolated from corpus and compute

The main architectural takeaway is the bidirectional encoder stack. The MLM/NSP recipe is important historically, but later encoder models changed the exact objective while keeping the encoder-only backbone idea.

What To Reuse

For this wiki, BERT should be reused as a pattern, not only as a named model.

Reusable PatternWhere it appears later
pre-train a generic encoder, fine-tune small headsNLP classification, retrieval, protein language models
mask parts of the input and reconstruct them[[concepts/learning/masked-modeling
encode pairs with segment/context structuresentence-pair tasks, cross-encoder rerankers
use pooled sequence state for classificationrepresentation evaluation and benchmark probing

Implementation Notes

  • The [CLS] vector is not automatically a semantic sentence embedding unless trained/evaluated for that use.
  • Tokenization affects vocabulary coverage, span boundaries, and downstream error analysis.
  • Fine-tuning is sensitive to learning rate, batch size, warmup, sequence length, and random seed.
  • Long documents require truncation, sliding windows, retrieval, or long-context encoder variants.
  • For retrieval systems, bi-encoder and cross-encoder BERT variants have different latency/accuracy tradeoffs.

Limitations

  • BERT is not an autoregressive generator; it is mainly an encoder representation model.
  • The paper mixes architecture, pre-training objective, data, and fine-tuning recipe.
  • Maximum sequence length and quadratic attention limit long-context use.
  • Later encoder models changed data, objectives, scaling, and training details.
  • NSP should not be treated as mandatory for all encoder pre-training; the later literature changed this recipe.
  • Benchmark gains do not by themselves prove robust out-of-distribution language understanding.

Why It Matters

BERT is the canonical paper for encoder-only Transformers as reusable language representation backbones.

It also explains a recurring pattern in AI architecture papers:

That pattern later appears in vision, speech, protein language modeling, and multimodal representation learning.

Connections