Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova
We introduce a new language representation model called BERT, which stands for Bidirectional Encoder Representations from Transformers. Unlike recent language representation models (Peters et al., 2018a; Radford et al., 2018), BERT is designed to pretrain deep bidirectional representations from unlabeled text by jointly conditioning on both left and right context in all layers. As a result, the pre-trained BERT model can be fine-tuned with just one additional output layer to create state-of-the-art models for a wide range of tasks, such as question answering and language inference, without substantial task-specific architecture modifications. BERT is conceptually simple and empirically powerful. It obtains new state-of-the-art results on eleven natural language processing tasks, including pushing the GLUE score to 80.5% (7.7% point absolute improvement), MultiNLI accuracy to 86.7% (4.6% absolute improvement), SQuAD v1.1 question answering Test F1 to 93.2 (1.5 point absolute improvement) and SQuAD v2.0 Test F1 to 83.1 (5.1 point absolute improvement).
We introduce a new language representation model called BERT, which stands for Bidirectional Encoder Representations fro...
The abstract introduces BERT, a foundational breakthrough in natural language processing (NLP). Think of it as unveiling a powerful universal tool that can learn to understand language from vast amounts of text, then be quickly adapted to solve many different language tasks. The key innovation isn't in the raw architecture (transformers already existed), but in how BERT learns language representations and what it learns them from.
Let me unpack what makes BERT different from its predecessors (like ELMo and GPT):
Previous approaches (unidirectional):
BERT's approach (bidirectional):
Mathematical intuition: If we denote a sequence of words as , previous models computed a representation for word using only (and possibly ). BERT computes it using the full context .
BERT operates in two phases:
Pre-training phase (on unlabeled data):
Fine-tuning phase (on task-specific data):
This is powerful because it separates the expensive learning of general language patterns from the cheaper adaptation to specific problems.
The abstract claims BERT achieves state-of-the-art results on eleven NLP tasks. Let me interpret what these metrics mean:
| Benchmark | Task Type | Metric | BERT's Result | Improvement |
|---|---|---|---|---|
| GLUE | Language understanding (9 diverse tasks combined) | Accuracy (%) | 80.5% | +7.7 percentage points |
| MultiNLI | Natural Language Inference (does sentence A entail B?) | Accuracy (%) | 86.7% | +4.6 percentage points |
| SQuAD v1.1 | Question Answering (extracting answer spans) | F₁ score | 93.2 | +1.5 points |
| SQuAD v2.0 | Question Answering (with unanswerable questions) | F₁ score | 83.1 | +5.1 points |
What do these metrics mean?
Accuracy: Simply the percentage of correct predictions. If BERT scores 80.5% on GLUE, it gets 80.5 out of every 100 predictions correct (on average across the nine GLUE tasks).
F₁ score: A weighted average of precision and recall, defined as:
where:
F₁ is useful when you care about both false positives and false negatives.
These aren't marginal improvements:
Here's the logical flow:
Massive unlabeled text corpus
↓
[Pre-training: BERT learns bidirectional representations]
↓
Pre-trained BERT model (with general language knowledge)
↓
[Add one output layer + fine-tune on task-specific labeled data]
↓
Task-specific model (question answering, sentiment analysis, etc.)
↓
State-of-the-art performance on diverse NLP tasks
Why is this "conceptually simple"? Because the core idea—pre-train on unlabeled data, then fine-tune on specific tasks—is straightforward. No complex task-specific engineering needed.
Why is this "empirically powerful"? Because the results speak for themselves across 11 different NLP tasks.
| Term | Meaning |
|---|---|
| Bidirectional | Using context from both left and right (before and after) |
| Encoder | Neural network that converts input text into representations (as opposed to "decoder" which generates text) |
| Representations | Dense numerical vectors that capture meaning—learned during pre-training |
| Pre-training | Training on large unlabeled data to learn general patterns |
| Fine-tuning | Adapting a pre-trained model to a specific task with labeled data |
| Transfer learning | Leveraging knowledge learned on one task to improve performance on another |
Before BERT:
After BERT:
This abstract is announcing a shift in how the entire NLP field approaches language understanding.
Language model pre-training has been shown to be effective for improving many natural language processing tasks (Dai and...
This introduction section accomplishes something crucial: it identifies a fundamental limitation in how language models were being pre-trained before BERT, and explains why this limitation matters. The authors argue that previous approaches were "unidirectional" (only looking left-to-right), which prevented them from fully understanding context. BERT's innovation is to use a "bidirectional" approach that can look in both directions simultaneously.
Think of it like reading: if you're trying to understand an ambiguous word, looking only at words that came before it is limiting. You also need to see what comes after it to fully grasp the meaning. Previous models were artificially restricted to the "looking before" approach. BERT removes this restriction.
The section opens by noting that language model pre-training is effective. This means:
The section identifies two types of tasks where pre-training helps:
Sentence-level tasks: Predict relationships between sentences
Token-level tasks: Make predictions about individual words
The section explains there are two strategies for using pre-trained language models:
Think of this like extracting features:
Mathematical intuition: If represents features from the pre-trained model and are the task-specific parameters, the final prediction might look like:
where is the task-specific architecture and are task-specific inputs.
This is simpler:
Mathematical intuition: Starting from pre-trained parameters , we optimize:
where is initialized to rather than randomly. This is "fine-tuning" because we're adjusting the pre-trained weights (not just using them frozen).
Both strategies use the same pre-training objective: learning from unidirectional language models.
Here's the key problem the authors identify:
Unidirectional language models can only condition on one direction of context.
Let's make this concrete. A traditional language model predicts the next word given all previous words. Mathematically, for a sequence of words , a left-to-right model computes:
$ P(w_i | w_1, w_2, \ldots, w_{i-1}) $This means: "predict word using only words 1 through ".
In OpenAI GPT's Transformer architecture, this is enforced at the attention mechanism level. The self-attention mechanism (which we can think of as a learned weighted average) is masked so that word can only attend to (look at) words .
Why is this a problem?
Consider this sentence:
"The bank executive was not a man, she was a woman."
If you want to understand what "bank" means here, looking only at "The" isn't enough. You need to see the word "executive" that follows it. A left-to-right model can't do this during pre-training.
For token-level tasks like question answering, this is especially harmful:
A unidirectional model trained left-to-right would struggle because during its pre-training, it never got to use rightward context.
Instead of predicting the next word, BERT uses a Masked Language Model (MLM) objective, inspired by the Cloze task from psychology.
The Cloze task concept: "The capital of France is ____"
The idea is simple: hide a word and predict it from context.
How BERT implements this:
Mathematically, for a sequence where we've masked token :
where is the learned representation of position (which is computed using attention over all positions, not just previous ones).
The crucial difference: During pre-training, token can now see both:
This makes the learned representations bidirectional.
Why does this work? The model can't "cheat" by just copying the adjacent words. It must actually understand the semantic relationships across the entire sentence to predict a masked word accurately. This forces it to build representations that incorporate information from both directions.
Beyond MLM, BERT uses an additional pre-training task:
Next Sentence Prediction (NSP):
This is a binary classification task that forces the model to understand how sentences relate to each other.
The authors summarize their contributions:
| Aspect | Previous Approaches | BERT |
|---|---|---|
| Pre-training objective | Left-to-right language modeling | Masked Language Model (bidirectional) |
| Context direction | Only previous tokens | Both previous and following tokens |
| Task adaptation | Feature-based OR fine-tuning | Fine-tuning (with minimal task-specific changes) |
| Architecture changes needed | Task-specific networks needed | Single output layer needed |
The fundamental insight: By forcing the model to predict masked words using surrounding context in both directions, you create representations that inherently understand bidirectional context. These representations then transfer better to downstream tasks.
Learning widely applicable representations of words has been an active area of research for decades, including non-neura...
This section is a literature review that traces the history of learning word and sentence representations from unlabeled data. It's crucial context for understanding why BERT is novel. The authors are essentially saying: "Here's what people have done before BERT, and here's why those approaches had limitations."
The key narrative arc is:
This limitation is exactly what BERT will solve.
For decades, researchers have worked on the fundamental problem: How do we represent words as vectors so that similar words have similar vectors?
The section mentions three main traditions:
When we talk about a word embedding, we mean a function that maps each word to a vector:
where is the embedding dimension (typically 50-300). For example, the word "cat" might map to a vector like .
Why does this help? Through mathematics (specifically through certain loss functions), we can train these vectors so that:
The section mentions two main objectives for learning word embeddings:
Left-to-right language modeling: Predict the next word given all previous words
Word2Vec discriminative objective (Mikolov et al., 2013): Predict whether a word appears in the correct context (left and right)
Once we have word embeddings, the natural next question is: How do we represent entire sentences or paragraphs?
The section cites several approaches that scale the idea of unsupervised pre-training from words to larger units:
These approaches use different objectives:
Next sentence prediction: Given sentence A, predict sentence B (the actual next sentence) from among multiple candidates
Left-to-right generation: Given an encoded sentence representation, generate the next sentence word-by-word
Denoising autoencoder objectives: Corrupt a sentence (add noise) and train the model to reconstruct the original
ELMo (Embeddings from Language Models) introduced a key idea: context-sensitive representations.
Rather than having one embedding per word (e.g., "bank" always has the same vector), ELMo produces different embeddings for the same word depending on context.
How it works:
Train two language models in parallel:
For each word position , extract the hidden representations from both models
Concatenate them: The representation of word is
where denotes concatenation.
Why this is clever: You get information from both directions (left and right context) for each word.
Here's the key phrase to understand:
"Similar to ELMo, their model is feature-based and not deeply bidirectional."
What does "not deeply bidirectional" mean?
Think of it this way:
Why does depth matter mathematically?
In transformer architectures, each layer builds representations by computing:
With ELMo's shallow concatenation:
With BERT's deep bidirectionality:
The final sentence is a subtle hint toward BERT's innovation:
"Fedus et al. (2018) shows that the cloze task can be used to improve the robustness of text generation models."
What's the cloze task? It's inspired by the classical reading comprehension task where you fill in blanks:
"The capital of France is ______."
Mathematically, the objective is: Given a sentence with some tokens removed (masked), predict the original tokens.
This is elegant because:
This is exactly what BERT will use! The masked language model (MLM) objective mentioned in the introduction is a direct application of the cloze task.
| Approach | Directional? | Bidirectional? | Deep? | Status |
|---|---|---|---|---|
| Left-to-right LM | Left only | No | Can be deep | Simple but limited |
| Word2Vec | Both | Yes (implicitly) | No | Only word-level |
| ELMo | Both | Shallow | No (two separate models) | State-of-the-art before BERT |
| BERT | Both | Yes | Yes | Solves the problem |
The authors are positioning their work as the natural evolution: take the best idea (bidirectionality + contextual representations) and apply it properly (deeply, in a single unified model) using the cloze task as the objective.
As with the feature-based approaches, the first works in this direction only pre-trained word embedding parameters from ...
This section discusses how researchers have been using pre-training and fine-tuning as a strategy for building better language models. Think of it like learning: if you first learn general skills (pre-training), you need to learn fewer specific skills to master a particular task (fine-tuning).
The key question this section answers is: "What approaches have been tried before BERT to pre-train language models, and why are they not quite good enough?"
The section begins by referencing the very earliest work:
"the first works in this direction only pre-trained word embedding parameters from unlabeled text"
What this means mathematically:
Early approaches learned vectors for each word in the vocabulary. Here:
The limitation: these embeddings are static — the same word always gets the same vector, regardless of context.
The section then moves to more sophisticated methods:
"sentence or document encoders which produce contextual token representations have been pre-trained from unlabeled text and fine-tuned for a supervised downstream task"
What this means:
Instead of fixed word vectors, these models output different representations for the same word depending on context. Mathematically:
Where:
Key advantage: The model learns with few additional parameters by reusing the pre-trained encoder.
The section identifies the objectives used in pre-training:
Let me unpack these:
In left-to-right language modeling, the model predicts the next word given all previous words:
The loss function (called the language modeling loss) is:
Where:
Intuition: The model learns general patterns about language by trying to predict what comes next—a challenging task that requires understanding grammar, semantics, and world knowledge.
Auto-encoder objectives involve corrupting the input and learning to reconstruct it:
This is a squared error loss where the model must reconstruct each token.
After pre-training on unlabeled data, these models are fine-tuned on specific downstream tasks:
Where:
Key insight: Because the model already understands language from pre-training, it needs relatively few labeled examples and parameters to adapt to new tasks.
The section highlights a crucial limitation:
"OpenAI GPT (Radford et al., 2018) achieved previously state-of-the-art results... Left-to-right language modeling and auto-encoder objectives have been used"
The problem: All these existing approaches use unidirectional context:
Mathematically, in a left-to-right Transformer layer with self-attention:
Notice the subscript constraint: token only attends to tokens through (past and current), not to (future).
Why is this bad? For many NLP tasks—especially token-level tasks like question answering—you need context from both directions to understand what a word means.
| Approach | Context Type | Advantage | Limitation |
|---|---|---|---|
| Word embeddings (pre-BERT) | None | Simple, fast | No context-sensitivity |
| ELMo, Peters et al. | Left-to-right + Right-to-left concatenated | Some bidirectionality | Shallow concatenation, not deeply bidirectional |
| OpenAI GPT | Left-to-right only | Few parameters to learn | Unidirectional—misses future context |
| BERT (coming up) | Bidirectional | Deep, true bidirectionality | (overcomes all above limitations) |
This section establishes the historical context for why BERT was needed:
This sets up the motivation for the technical innovation that BERT introduces.
There has also been work showing effective transfer from supervised tasks with large datasets, such as natural language ...
Before diving into BERT's novel approach, the authors are establishing context about what was already working in the field. This section serves as important background showing that:
This context is crucial because it helps justify BERT's design philosophy: if transfer learning works well in supervised settings, why not try to harness it through unsupervised pre-training (which BERT does)? The section essentially says: "Transfer learning is powerful—now imagine if we could do it without requiring massive labeled datasets."
The section begins by noting that researchers have shown effective transfer from supervised tasks with large datasets:
What does "transfer from supervised tasks" mean?
When we have a large labeled dataset for Task A, we can:
Mathematically, this is about learning a representation function with parameters on the source task such that the learned representations are useful for target tasks.
### 2. The Computer Vision Precedent The authors strengthen their argument by citing computer vision, which has already validated this principle: > "Computer vision research has also demonstrated the importance of transfer learning from large pre-trained models, where an effective recipe is to fine-tune models pre-trained with ImageNet" **What's ImageNet?** - A massive dataset of ~14 million labeled images across 1,000 object categories - Models pre-trained on ImageNet have learned to recognize visual features (edges, textures, shapes, objects) **The transfer learning recipe in computer vision:** 1. Train a deep neural network on ImageNet (source task: image classification) 2. Remove the final classification layer 3. Add a new classification head for your target task 4. Fine-tune all or some of the parameters on your smaller labeled dataset This works because low-level visual features learned on ImageNet (like edge detection) are useful for nearly any vision task. --- ## Why This Matters for BERT This section is setting up a crucial insight: **If transfer learning works so well with supervised pre-training (ImageNet, NLI, machine translation), couldn't it work even better with unsupervised pre-training?** Here's the conceptual progression: | Approach | Pre-training Data | Training Signal | Challenge | |----------|-------------------|-----------------|-----------| | **Supervised Transfer** (ImageNet, NLI) | Large labeled dataset | Explicit labels (expensive to create) | Still requires a large labeled dataset for pre-training | | **BERT's Unsupervised Transfer** | Unlabeled text (freely available!) | Masked language modeling + next sentence prediction | Can we learn useful representations *without* labels? | The key insight: BERT will use **unsupervised pre-training objectives** (as introduced in Section 2.2) to achieve what supervised transfer learning achieved—but at a much larger scale, since unlabeled text is essentially unlimited. --- ## Mathematical Perspective on Transfer Learning While this section doesn't present equations, the underlying mathematics is important: **Transfer learning fundamentally exploits the assumption that:** f_{\text{target}} \approx g_{\theta_{\text{source}}} \text{circ} h_{\text{new}}Where:
The intuition: Features learned on large source tasks encode general knowledge that's broadly useful. We "reuse" these features () and only train new task-specific layers ().
Notice what BERT will improve upon in the next sections:
Section 2.3 establishes that transfer learning is a proven, powerful technique. By understanding this baseline, we can appreciate BERT's achievement: it shows that unsupervised bidirectional pre-training can outperform supervised transfer approaches, even on tasks that previously benefited from supervised pre-training like ImageNet.
This is why BERT's results are so impressive—the paper is essentially saying: "We learned better representations without any labels than previous approaches could achieve with massive labeled datasets."
We introduce BERT and its detailed implementation in this section. There are two steps in our framework: pre-training an...
This section is the architectural heart of the BERT paper. It describes how BERT actually works—the structural blueprint that makes the bidirectional pretraining possible. After the previous sections reviewed existing approaches (which were mostly unidirectional or pseudo-bidirectional), this section introduces BERT's key innovation: a truly bidirectional Transformer architecture.
The importance here is understanding that BERT doesn't invent entirely new mathematics—it cleverly combines existing components (the Transformer architecture) in a new way to solve the unidirectionality problem.
BERT operates in two distinct phases:
Key insight: The same basic architecture serves both phases. This is elegant because it means you don't need task-specific architectures—the same model structure works for question answering, classification, sequence labeling, etc.
The paper emphasizes:
"A distinctive feature of BERT is its unified architecture across different tasks."
What does this mean? Compare to prior work:
Traditional pipelines: Different tasks required different model architectures. A classification task might use one network structure, while question-answering used another.
BERT's approach: Almost the same architecture handles everything. You add one small task-specific output layer, but the core representation learning is identical.
This is powerful because:
The paper states: "BERT's model architecture is a multi-layer bidirectional Transformer encoder based on the original implementation described in Vaswani et al. (2017)."
A Transformer encoder is a stack of identical layers, where each layer processes an entire sequence in parallel using self-attention. Let me break down the architecture:
The paper defines three key dimensions:
Think of it like a deep neural network where:
The paper reports results on two configurations:
Parameter count intuition: With hidden dimensions and layers, even just the main weight matrices consume millions of parameters. Multiply this across attention heads, feedforward networks, and embeddings, and you get 110M parameters.
This is the innovation that distinguishes BERT from prior work like GPT:
"Critically, however, the BERT Transformer uses bidirectional self-attention, while the GPT Transformer uses constrained self-attention where every token can only attend to context to its left."
In a Transformer, self-attention computes how much each token should "look at" every other token. The attention mechanism is:
Where:
The key difference:
GPT (Constrained/Causal Attention):
BERT (Bidirectional Attention):
With bidirectional attention:
Analogy: Imagine reading with context:
[Figure 1 shows this visually]: The model uses special tokens:
[CLS] = A special token prepended to the start of every input
[SEP] = A separator token between segments
Example for a question-answering task:
[CLS] What is BERT? [SEP] BERT is a language model... [SEP]
The model processes this entire sequence through all layers, and the [CLS] token's output vector (after all 24 or 12 layers) serves as the representation for the entire sequence.
Connecting back to the abstract: BERT is "designed to pretrain deep bidirectional representations from unlabeled text by jointly conditioning on both left and right context in all layers."
"In all layers" is crucial:
ELMo (mentioned in section 2.1): Creates bidirectional representations by concatenating separate left-to-right and right-to-left models
BERT: Uses the same attention mechanism that can attend bidirectionally at every layer
| Concept | Meaning |
|---|---|
| Pre-training | Learning from unlabeled data with unsupervised objectives |
| Fine-tuning | Adapting pre-trained weights to labeled downstream tasks |
| Bidirectional | Each token's representation uses information from all other tokens |
| Unified architecture | Same structure for all tasks; minimal task-specific modifications |
| (layers) | Depth of the network; more layers = more expressive but slower |
| (hidden size) | Width of representations; more dimensions = more capacity |
| (attention heads) | Number of parallel attention mechanisms; enables multi-perspective processing |
| Self-attention | Computing relevance between all pairs of positions in a sequence |
| [CLS] and [SEP] | Special tokens that structure the input and provide anchor points |
Because of this architecture:
This is why BERT achieved state-of-the-art on 11 NLP benchmarks—the architecture is fundamentally well-suited to understanding language from both directions.
To make BERT handle a variety of down-stream tasks, our input representation is able to unambiguously represent both a s...
Before we get into the mathematical details, let's understand what this section is solving. In previous sections, we learned that BERT uses a unified architecture that handles many different NLP tasks without major modifications. But there's a critical problem: different tasks have different input structures:
This section explains how BERT cleverly encodes both cases into a single, unified input format. The key insight is that the model needs to understand not just what the tokens are, but also:
Let's break down how BERT constructs its inputs.
The paper uses WordPiece embeddings with a vocabulary of 30,000 tokens. This is important because:
Each unique piece/word gets mapped to a token embedding — a vector in where is the hidden size (768 for BERT_BASE).
Key notation:
The paper introduces two special tokens that serve critical functions:
This is mathematically elegant. Denote:
Then is used directly for classification tasks. For example, to classify sentiment, you'd apply a simple linear layer to :
where is a learned weight matrix and is a bias term.
Here's where the engineering elegance appears. BERT handles both cases in a single format:
Example (sentiment analysis):
Example (question answering):
Why this matters: With this unified format, the same Transformer architecture processes both single and paired inputs. The model learns to understand the [SEP] boundary without explicit instructions.
This is the core mathematical insight of this section. For each token in the input sequence, BERT constructs its input representation by summing three different embeddings:
Let's break down each component:
Why this matters: For single-sentence inputs, all tokens get . For paired inputs, the model learns that tokens after [SEP] have a different segment embedding, helping it understand sentence boundaries.
For BERT, the position embeddings are learned, meaning they're parameters optimized during pre-training.
Once we construct for each token, the full input to BERT is a sequence of vectors:
where is the length of the input and each .
These vectors then flow through the Transformer encoder (the layers we defined earlier).
Dimensionality note: The input is a matrix of shape where:
After passing through all Transformer layers, we get output hidden states. The paper denotes:
Use directly:
Use for each token. For example, in named entity recognition, each is classified independently.
You might wonder: Why not concatenate them instead of summing?
| Approach | Dimension | Trade-off |
|---|---|---|
| Sum | Embeddings must be same dimension; more parameter-efficient | |
| Concatenate | Scales embedding dimension; increases computation |
BERT chooses summation because:
The assumption is that the model can learn to disentangle these three information sources even though they're summed together.
Recall from Section 3 that BERT has two stages:
This input representation is identical in both stages. The pre-trained embeddings (token, segment, position) are transferred directly to the fine-tuning phase, which is part of why BERT is so effective — the representations learned during pre-training on massive unlabeled data benefit all downstream tasks.
| Component | Dimension | Fixed? | Purpose |
|---|---|---|---|
| Token Embedding | No (learned) | Semantic content of token | |
| Segment Embedding | No (learned) | Which sentence (A or B) | |
| Position Embedding | No (learned) | Location in sequence | |
| Final Input | No | Combined representation |
Imagine building a person's identity from three types of information:
By summing these, you get a rich representation that blends all three types of information. The Transformer then uses attention to understand relationships between all tokens, benefiting from this enhanced input representation.
BERT elegantly solves the problem of unified input representation by:
This simple yet powerful approach enables the same architecture to handle diverse NLP tasks, which is central to BERT's success.
Unlike Peters et al. (2018a) and Radford et al. (2018), we do not use traditional left-to-right or right-to-left languag...
This section tackles a fundamental problem: How do we train a deep neural network to understand language by looking at context from both directions simultaneously?
Why does this matter? Previous models like GPT only looked left-to-right (each word only sees words before it), which is limiting. BERT wants bidirectional understanding, but there's a critical problem with doing this naively—which this section solves with an elegant trick called Masked Language Modeling (MLM).
Let me explain the paradox the authors identify:
A bidirectional model would allow each word to "see itself" through the network's layers. Here's why this is catastrophic:
In a standard language model, we compute the probability of a token given its context:
where is the -th word in the sequence.
If you allowed the model to use context in both directions in a normal language model setup, the model could trivially "cheat" by directly attending to the actual token it's supposed to predict. With multi-layered attention, word could indirectly see itself through other tokens, making the task meaningless.
Think of it this way: If you're asked "Fill in the blank: The capital of France is ____" and you can read the entire sentence including the answer, the task becomes trivial.
Instead of asking "predict the next word," BERT asks: "Some words are hidden (masked). Can you predict what they are based on the surrounding context?"
The procedure is:
Let's denote:
For each masked position , the model processes the modified input and produces a hidden vector (recall from Section 3 that is the hidden size: for BERT or for BERT).
This hidden vector is passed through an output softmax over the vocabulary:
where:
The loss for each masked position is cross-entropy loss:
where is the original token that was masked. The total MLM loss is the average over all masked positions:
After pre-training, the model has never seen actual [MASK] tokens during inference—because real sentences don't contain them! During fine-tuning on real tasks, the input format changes completely. This creates a distribution shift:
This mismatch could hurt performance because the model's representations were learned with a somewhat artificial input format.
To mitigate this, the authors use a stochastic replacement scheme. When they select the -th token for masking (probability 15%), they don't always replace it with [MASK]. Instead:
When token position is chosen for prediction, replace it with:
Let me break down why each case matters:
| Case | Probability | Purpose | Effect |
|---|---|---|---|
| [MASK] | 80% | Standard masking—most common case | Model learns from typical masked examples |
| Random token | 10% | Makes the task harder; forces deep understanding | Model must learn that a random token is "wrong" |
| Unchanged | 10% | Bridges pre-training and fine-tuning | Model sees real tokens during pre-training, adjusts to fine-tuning format |
The key insight: By only 10% of the time using the actual token, the model still learns it should predict, but 90% of the time it must work with artificial input. This gradually conditions the model to not simply copy inputs.
More formally, let denote the token after replacement (the token actually shown to the model). The model then learns:
where the expectation is over both:
This ensures the model learns robust representations that work with partial, noisy, or real input.
| Aspect | Standard LM | MLM |
|---|---|---|
| Directionality | Left-to-right only | Bidirectional |
| Context available | Only previous tokens | Both previous and future tokens |
| Model power | More limited | More powerful (but no cheating) |
| Information per example | Prediction at one position | Prediction at 15 positions (more efficient training) |
This approach is related to denoising autoencoders (Vincent et al., 2008), but with a key difference:
This is more efficient because:
BERT's masked language modeling works like this:
The result: A pre-trained model with deep bidirectional representations that understand language from both directions, without the architectural limitations of previous approaches. This is powerful because real language understanding requires both left and right context—understanding a word requires knowing what comes before and after it.
Many important downstream tasks such as Question Answering (QA) and Natural Language Inference (NLI) are based on unders...
The paper has just introduced the Masked Language Model (MLM) task, which teaches BERT to understand individual words in context. But here's the problem: many real-world NLP tasks require understanding the relationship between two sentences, not just predicting individual masked words.
Think about:
The MLM task alone doesn't capture these sentence-level relationships. This section introduces a second pre-training task called Next Sentence Prediction (NSP) to fill that gap. The key insight: BERT learns better when it's trained on both word-level and sentence-level understanding simultaneously.
NSP is a binary classification task. For each training example, the model receives:
The model must predict: Is B actually the next sentence that follows A in the corpus, or is B a random sentence from somewhere else?
More formally, let's define:
When constructing pre-training examples:
In other words, exactly half the time the model sees genuine consecutive sentences, and half the time it sees random pairs. This balanced distribution forces the model to actually learn the task rather than just memorizing one class.
Recall from the earlier section that is the final hidden vector corresponding to the special [CLS] token. Mathematically:
where:
The NSP prediction works like this:
where:
Why the [CLS] token? It's a special pooling mechanism. The [CLS] token is forced (through the training objective) to aggregate information about the entire sequence. Unlike taking a simple average of all tokens, allowing the Transformer to learn what information to aggregate via the [CLS] representation is more powerful.
Standard language modeling only trains left-to-right or right-to-left prediction:
This captures intra-sentence structure, but not inter-sentence relationships. Consider:
Sentence A: "The dog sat in the park."
Sentence B (IsNext): "It was a beautiful day."
Sentence B' (NotNext): "Quantum computing is fascinating."
A language model can't distinguish between these because it doesn't directly model whether one sentence logically follows another.
NSP requires the model to learn:
These are exactly the skills needed for QA and NLI tasks.
The NSP loss is standard binary cross-entropy:
where:
Recall that MLM from the previous section has its own loss . During pre-training, BERT is trained on both tasks simultaneously:
This joint training (called multi-task learning) means gradients from both tasks backpropagate through the same parameters. The model learns representations that are useful for both masked word prediction and sentence relationship understanding.
The paper acknowledges that similar ideas appeared in:
However, there are key differences:
| Aspect | Prior Work | BERT |
|---|---|---|
| What transfers | Only learned sentence embeddings | All parameters of the full model |
| Transfer mechanism | Extract sentence embeddings; use in downstream tasks | Initialize entire model; fine-tune all parameters |
| Flexibility | Limited to tasks that use sentence embeddings | Applicable to any task by swapping output layer |
BERT's approach is more powerful because the entire pre-trained representation (all layers with all hidden dimensions and all attention heads) can be adapted to downstream tasks, not just a fixed embedding.
BERT pre-trains on:
Total: ~3.3 billion words (in order of magnitude)
This is crucial for NSP to work effectively:
Document-level corpus (what BERT uses):
Sentence 1: "The economy grew last quarter."
Sentence 2: "Unemployment dropped to historic lows." ← These are actually consecutive
Sentence 3: "Consumer confidence surged."
Shuffled sentence-level corpus (like Billion Word Benchmark):
Sentence 1: "The economy grew last quarter."
Sentence 2: "Unemployment dropped to historic lows." ← These might not be consecutive!
Sentence 3: "Penguins live in Antarctica."
If you use a shuffled corpus, the NSP task becomes meaningless—you can't tell if a sentence should follow another because they were never in context together originally.
By using documents, BERT can:
The genius of this approach is its simplicity—NSP requires no additional annotation, just access to a document corpus. Yet it provides a powerful learning signal for capturing sentence relationships essential to QA and NLI tasks.
Fine-tuning is straightforward since the self-attention mechanism in the Transformer allows BERT to model many downstrea...
At this point in the paper, BERT has been pre-trained on massive amounts of unlabeled text using the Masked LM and Next Sentence Prediction tasks described in Section 3.1. Think of pre-training as learning general language understanding. Now the question becomes: how do we actually use this pre-trained model for specific tasks?
This section explains that the answer is surprisingly simple and elegant. Rather than building completely new architectures for each task, BERT's design (specifically its self-attention mechanism) is flexible enough to handle many different downstream tasks with minimal modification. We just need to adapt the inputs and outputs while reusing the pre-trained parameters—this process is called fine-tuning.
Before BERT, a common approach for handling sentence pairs (like a question and a passage) followed this pattern:
This required designing specialized architectures for each type of task. BERT's innovation is much more elegant:
Instead of encoding sentences separately and then combining them, BERT encodes them together as a single concatenated sequence, with the self-attention mechanism naturally handling the cross-talk between sentences.
Recall from the previous sections that BERT is a Transformer, which uses self-attention. Self-attention computes relationships between all positions in the input sequence simultaneously. When you concatenate two sentences together in the input:
The self-attention mechanism automatically learns to:
This happens in a single pass through the network, without needing a separate architecture specifically designed for sentence pairs.
The fine-tuning process follows a straightforward three-step pattern:
The genius of BERT's design is its flexibility. Different downstream tasks have different structures, but they can all be mapped to BERT's input format:
| Downstream Task | Sentence A | Sentence B | Purpose |
|---|---|---|---|
| Paraphrasing | Sentence 1 | Sentence 2 | Determine if two sentences mean the same thing |
| Entailment (NLI) | Premise | Hypothesis | Determine if premise logically implies hypothesis |
| Question Answering | Question | Passage | Find answer span in passage |
| Text Classification | Text | (none) | Classify single text into categories |
| Sequence Tagging | Text | (none) | Label each token in the sequence |
Notice that some tasks use both inputs, some use only one. BERT handles this by treating single-text tasks as having a "degenerate" (empty) Sentence B.
BERT produces two types of outputs, depending on what you're trying to predict. Recall from Section 3 that:
For classification tasks (entailment, sentiment analysis, paraphrasing):
For token-level tasks (sequence tagging, question answering):
Here's the crucial part: you don't train just the output layer. Instead, you:
This is called "end-to-end" fine-tuning because gradients flow backward through the entire network. The loss from your specific task is backpropagated all the way down to the embedding layers and even the self-attention weights.
Mathematically, if is the loss for your specific task, the update rule is:
\theta \leftarrow \theta - \eta \nabla_\theta \mathcal{L}_{\text{task}}(\theta)
This is a practical but important point. The section notes that all results in the paper can be replicated in:
Why is this so fast? Consider the computational burden:
Additionally:
One final conceptual point: BERT's use of self-attention creates a single unified architecture that handles diverse tasks. This is more elegant than task-specific approaches because:
The concatenation of sentence pairs and the self-attention mechanism work together to create this unified framework—no additional cross-attention modules needed.
| Concept | Explanation |
|---|---|
| Task mapping | Convert your downstream task inputs into BERT's format (Sentence A, optional Sentence B) |
| Output selection | Use [CLS] for classification; use for token-level tasks |
| Fine-tuning | Add a small task-specific layer, then train all parameters end-to-end with task-specific labeled data |
| Computational cost | Very cheap compared to pre-training (hours not weeks) |
| Why it works | Self-attention creates bidirectional cross-attention naturally, unifying different task structures |
The General Language Understanding Evaluation (GLUE) benchmark (Wang et al., 2018a) is a collection of diverse natural l...
After pre-training BERT on massive unlabeled text (using the masked language modeling and next sentence prediction tasks from Section 3), the researchers need to evaluate how well it performs on real-world NLP tasks. This section describes how they fine-tune and evaluate BERT on GLUE (General Language Understanding Evaluation), which is a benchmark containing multiple diverse NLP tasks.
The key insight here is simple: BERT's pre-trained representations are flexible enough to work across many different task types with minimal modifications. We only need to add a small classification layer on top and adjust it for each specific task.
From Section 3, recall that BERT processes input sequences and produces hidden representations at each layer. For GLUE classification tasks, the crucial representation is:
What this means:
Why use [CLS]? During pre-training, BERT learned to accumulate relevant information about the entire sequence into this single token's representation. It's like having the model compress the whole input into one vector.
To actually make predictions, BERT adds a very simple classification layer. The only new parameters introduced during fine-tuning are:
What this means:
Geometric interpretation: We're taking the -dimensional vector and projecting it into a -dimensional space using the matrix . This is a standard linear transformation.
The final prediction is made using:
Let me break this down step by step:
Step 1: Matrix multiplication
Step 2: Softmax normalization The softmax function converts these raw scores into a probability distribution:
where is the vector of logits.
What this does:
Step 3: Natural logarithm Taking the gives us the log-probability, which is standard for computing cross-entropy loss during training.
During fine-tuning, BERT minimizes the cross-entropy loss:
where is the one-hot encoded true label (for a single example).
Interpretation: Cross-entropy loss penalizes incorrect predictions heavily — if the true class has probability near 0, the of that near-0 value is a large negative number, making the loss large.
The authors used several practical choices for fine-tuning:
For context: smaller batch sizes are often used for fine-tuning because pre-trained models can learn task-specific adaptations quickly.
The authors selected the best learning rate from a set of candidate values:
What this means:
A notable practical detail: BERT-LARGE sometimes suffered from instability on small datasets (where the number of training examples is limited). The solution:
This is a pragmatic approach to a real problem in deep learning: when datasets are small, the high capacity of large models can cause high variance in performance.
According to the paper:
What "average accuracy improvement" means:
BERT-BASE vs OpenAI GPT:
This result is theoretically important: it validates the claim from the abstract that bidirectional pre-training is more powerful than directional pre-training.
MNLI (Multi-Genre Natural Language Inference):
Official GLUE Leaderboard Score:
For context: GLUE scores typically range from 0–100, with 100 being perfect. An improvement from 72.8 to 80.5 is substantial and indicates BERT captures linguistic phenomena that GPT missed.
This section demonstrates that:
Simplicity of fine-tuning: Only one new layer () needs to be added — the entire pre-trained model remains frozen (in principle, though in practice parameters are updated).
Generality: The same architecture works across diverse task types (text classification, sentence pair classification, sequence tagging via slight variants).
Efficiency: Fine-tuning takes only 1 hour on specialized hardware (Cloud TPU) or a few hours on a GPU — cheap compared to pre-training.
Empirical validation: The results confirm that bidirectional pre-training (BERT's innovation) works better than the alternatives that existed at the time.
This is a compelling case study showing that good pre-training on large unlabeled data is a powerful approach to NLP — you can achieve state-of-the-art performance on diverse downstream tasks without task-specific architecture engineering.
The Stanford Question Answering Dataset (SQuAD v1.1) is a collection of 100k crowdsourced question/answer pairs (Rajpurk...
This section explains how BERT tackles question answering—specifically, the task of finding where an answer appears in a passage. Unlike classification tasks (like GLUE), where you predict a category, SQuAD requires the model to identify the exact location of the answer within text. The elegance here is that BERT solves this without fundamentally changing its architecture; it just adds two small vectors and uses them to score candidate answer spans.
What is SQuAD v1.1?
Why is this different from GLUE?
Following the fine-tuning approach from Section 3.2, BERT treats the question-passage pair as a single concatenated sequence:
Input representation:
This is conceptually similar to how BERT handles "sentence pairs" in entailment tasks, just with a different semantic interpretation.
During fine-tuning, BERT adds only two learnable vectors:
These are small additions—contrast this with classification tasks in Section 4.1, which introduced a weight matrix . Here we're just adding two vectors, making the fine-tuning very efficient.
For each word position in the passage, BERT produces a hidden representation (the transformer output at that position).
The probability that position is the start of the answer is:
Breaking this down:
Numerator: is an exponential
Denominator:
Intuition: Words that have hidden representations most similar (in dot product) to the learned start vector get higher probability of being the answer start.
The paper states "the analogous formula is used for the end of the answer span," meaning:
Same structure, but using the end vector instead of .
Once we have these individual probabilities, we need to score complete answer spans (sequences from position to position ).
The score of a span from position to is:
Why add these two terms?
Constraint: The model only considers valid spans where (the end comes after or at the start).
Prediction: The model selects — the span with the highest score.
The model is trained by minimizing a loss based on the correct answer span positions.
Specifically:
The training objective is:
What this means:
Why this objective makes sense:
These are modest hyperparameter choices—fine-tuning is indeed "relatively inexpensive" as mentioned in Section 3.2.
[Table 2 shows SQuAD v1.1 results]
The key takeaways:
Strong single-model performance: BERT's single model outperforms the previous best ensemble system in terms of F1 score
Ensemble performance: The BERT ensemble (7 systems with different random seeds and checkpoints) achieves +1.5 F1 above the previous best
Robustness: Even without additional TriviaQA fine-tuning data, BERT loses only 0.1-0.4 F1, still beating all existing systems
This exemplifies BERT's key insight: a powerful pre-trained model needs only minimal task-specific additions to achieve state-of-the-art performance on diverse tasks.
Excellent! This decomposition reveals the structure of cross-entropy loss:
When the correct position is , the loss is:
The first term (log-sum-exp) is a normalizer that applies to all positions equally. During training:
Why dot product scoring?
The dot product measures alignment or similarity between the learned start vector and the contextual token representation. Vectors aligned in the same direction have high dot products.
Temperature scaling analogy:
The softmax can be thought of as temperature-controlled decision-making. If we used with different values:
Asymptotic behavior:
BERT's approach for question answering:
This simple bilinear scoring scheme—combined with BERT's strong contextual representations—achieved state-of-the-art results, outperforming hand-crafted features and more complex architectures.
The equation is the softmax function applied to dot-product similarity scores. It transforms:
Show how softmax derivatives enable gradient flow for learning


Calculate one softmax probability




Show how softmax probability for one position varies with its score, while others stay fixed



Visualize log-probability (used in cross-entropy loss)



Simplify the log-probability formula to understand its structure


The SQuAD 2.0 task extends the SQuAD 1.1 problem definition by allowing for the possibility that no short answer exists ...
This section addresses a real-world challenge that wasn't present in the original SQuAD dataset. In SQuAD v1.1, every question has an answer somewhere in the provided passage. But in real life, that's unrealistic—sometimes people ask questions about documents that simply don't contain the answer.
SQuAD v2.0 makes the task harder by including passages where no valid answer exists. The section explains how BERT elegantly extends its question-answering approach to handle this scenario. Rather than completely redesigning the model, the authors use a clever trick: they treat "no answer exists" as a special type of answer.
The key insight is this: represent the absence of an answer using the [CLS] token.
Recall from earlier sections that the [CLS] token is a special token prepended to every input sequence—it's designed to capture aggregate information about the entire input. The authors repurpose this token to represent "the model's best guess that no answer exists in this passage."
Here's the logic:
Let me walk through the scoring equations step by step.
From Section 4.2, you'll remember:
The score of token being the answer start is computed via dot product: . This is a similarity measure—higher scores mean the token representation aligns better with what the model learned to recognize as an answer start.
For the v2.0 extension, define the null answer score:
Here:
Intuition: This score represents how confident the model is that there's no answer. Higher values mean the model thinks "no answer" is more likely.
Next, define the best non-null span score:
Breaking this down:
Intuition: This finds the single best answer span in the passage.
Now comes the prediction mechanism. We have two competing hypotheses:
We predict a non-null answer (i.e., we claim an answer exists) when:
Where:
Why the threshold? In binary classification problems, you often need a margin to account for uncertainty. The threshold acts as a "buffer"—we only commit to a non-null answer if it's clearly better than the null answer by at least points.
Think of this geometrically:
The authors fine-tune using:
These hyperparameters are relatively modest—fine-tuning for SQuAD is computationally inexpensive compared to pre-training.
From Table 3, BERT achieves a +5.1 F1 improvement over the previous best system on SQuAD v2.0. This is substantial—remember that:
The elegance of this solution lies in its simplicity and alignment with BERT's architecture:
This demonstrates how thoughtful architectural choices in pre-training (like the [CLS] token) can be repurposed elegantly for downstream tasks.
The Situations With Adversarial Generations (SWAG) dataset contains 113k sentence-pair completion examples that evaluate...
This section demonstrates how BERT handles a multiple-choice sentence completion task. Unlike the previous tasks (GLUE, SQuAD), where BERT needed to either classify entire texts or find answer spans within passages, SWAG requires BERT to rank four possible continuations and pick the most plausible one.
The key insight: BERT's pre-trained representations are flexible enough to handle this completely different task type with minimal architectural modifications—just a scoring mechanism and a softmax normalization.
SWAG (Situations With Adversarial Generations) is a commonsense reasoning benchmark with:
Example: Given "I walk into the kitchen and...", you might choose between:
Option 1 or 2 are plausible; options 3 and 4 violate commonsense knowledge.
For each of the 4 possible completions, BERT creates a separate input sequence:
Where:
This is exactly the same format described in Section 3 for sentence-pair inputs. You create 4 separate sequences, each one pairing the context with a different continuation candidate.
After passing each of the 4 sequences through BERT, you extract the hidden representation corresponding to the [CLS] token:
Where:
This [CLS] token representation serves as the aggregate summary of the entire input sequence—it has been trained during pre-training to capture the essence of the whole text.
This is where SWAG-specific fine-tuning comes in. BERT introduces a learnable scoring vector (the only task-specific parameters):
This is a vector of parameters, randomly initialized before fine-tuning.
For each of the 4 choices, you compute a scalar score by taking the dot product between this vector and the [CLS] representation:
Where:
Intuition: The vector learns what kinds of representations (in the -dimensional space) correspond to "good continuations." When it aligns well with a choice's [CLS] representation, the dot product is large.
The four raw scores are converted into probabilities using the softmax function:
Where:
Intuition: Softmax converts raw scores into a probability distribution. If one choice has a much higher score than others, its probability will be close to 1; if scores are similar, probabilities are more evenly distributed.
The fine-tuning hyperparameters are:
During training, the cross-entropy loss is minimized:
Where is the predicted probability of the correct choice. The model learns to make this probability as high as possible.
The table shows:
| Model | Accuracy |
|---|---|
| 88.3% | |
| ESIM+ELMo (previous baseline) | 61.2% |
| OpenAI GPT | 79.9% |
Key improvements:
This is a massive jump, showing that BERT's bidirectional pre-training gives it substantially better commonsense reasoning abilities than unidirectional models like GPT.
Notice what BERT did not do for SWAG compared to other tasks:
This demonstrates a core theme of the BERT paper: the power of good pre-training allows minimal task-specific adaptation. Whether you need classification (GLUE), span prediction (SQuAD), or ranking (SWAG), the underlying BERT representations are rich enough to solve all of them with just a thin layer of task-specific parameters on top.
We demonstrate the importance of the deep bidirectionality of BERT by evaluating two pre-training objectives using exact...
This section is a crucial ablation study—a systematic analysis that removes components from BERT one at a time to understand what makes the model work so well. The paper's central claim is that BERT's success comes from being bidirectional (looking at both left and right context simultaneously), unlike previous models like GPT that only looked left-to-right. This section proves that claim by showing what happens when you remove bidirectionality.
Think of it like testing a recipe: if you remove the baking soda from a cake and it flops, you've proven baking soda matters. Here, the researchers are removing key ingredients from BERT to prove that bidirectional training is essential.
The section compares three configurations of the same base architecture:
In the context of neural language models:
This is a fundamental difference in what information is available to the hidden state representation (from the previous section) when making decisions.
Here's a subtle but important point: the LTR model was also constrained to be left-to-right during fine-tuning, not just pre-training. The text explains why:
"The left-only constraint was also applied at fine-tuning, because removing it introduced a pre-train/fine-tune mismatch that degraded downstream performance."
What does this mean mathematically?
When you pre-train a model with constraint (in this case: only left context available), the hidden states learned during pre-training are optimized under that constraint. If you then remove the constraint at fine-tuning (allowing right context), you have a distribution shift: the model's representations are now being used in a way they were never trained for.
In information-theoretic terms, if is the distribution learned during pre-training and is what you'd want at fine-tuning, the KL divergence becomes large, hurting performance.
Looking at [Table 5] in the paper, we can analyze what each comparison tells us:
Finding: Removing NSP hurts performance on some tasks (QNLI, MNLI, SQuAD 1.1)
Finding: The LTR model performs significantly worse on all tasks, with particularly large drops on MRPC and SQuAD
This is the critical finding that validates BERT's bidirectional approach.
The paper gives intuitive reasoning for SQuAD specifically:
"For SQuAD it is intuitively clear that a LTR model will perform poorly at token predictions, since the token-level hidden states have no right-side context."
Let me make this mathematically precise. Recall from Section 4.2 that the answer span is predicted by computing:
where is a learned start vector and is the hidden representation of token .
With bidirectional attention:
With left-to-right attention:
For example, in the question "Where was Albert Einstein born?", when the LTR model processes the token "born", it hasn't seen the answer "Germany" yet that comes later in the passage. So its representation of "born" lacks crucial disambiguating information.
The researchers tried strengthening the LTR model by adding a BiLSTM (Bidirectional LSTM) on top:
"In order to make a good faith attempt at strengthening the LTR system, we added a randomly initialized BiLSTM on top."
Why did this help but not solve the problem?
A BiLSTM can look both directions, so mathematically it does provide bidirectional context. However:
The BiLSTM operates on frozen pre-trained representations: It's stacked on top of LTR hidden states that were never optimized to work bidirectionally. The underlying representations are still incomplete.
Limited expressiveness at one layer: The BiLSTM is a single additional layer trying to recover information the lower layers never had access to during pre-training
Fine-tuning budget: The pre-trained lower layers aren't re-trained during fine-tuning (standard practice to preserve pre-trained knowledge), so they can't learn to encode bidirectional information
Results:
The paper addresses an alternative approach used by ELMo:
"It would also be possible to train separate LTR and RTL models and represent each token as the concatenation of the two models, as ELMo does."
ELMo's approach mathematically:
where denotes concatenation and comes from a separate Right-To-Left model.
Why is this worse than BERT's deep bidirectionality?
The paper gives three reasons, with the first and third being most fundamental:
Computational cost: Training two separate models costs as much as one bidirectional model
Task misalignment: For QA tasks, the RTL model reads the question backward, which breaks the logical flow
Limited representational power: Early layers can't see bidirectional context
This is the deepest insight: bidirectionality in every layer is fundamentally more powerful than combining two unidirectional models, because joint optimization with bidirectional attention at every layer can learn more efficient representations than post-hoc combination.
| Model | Key Finding |
|---|---|
| BERT (full) | Baseline—best performance |
| No NSP | NSP helps but isn't critical |
| LTR & No NSP | Bidirectionality is critical—large performance drops across all tasks |
The section's central claim is experimentally validated: BERT's effectiveness comes primarily from its bidirectional pre-training objective, not just from training on larger data or better hyperparameters.
In this section, we explore the effect of model size on fine-tuning task accuracy. We trained a number of BERT models wi...
This section investigates a fundamental question: Does bigger always mean better? Specifically, the authors want to demonstrate that BERT's performance improves when you make the model larger—more layers, more hidden units, more attention heads. This might seem obvious, but the surprising finding is that this scaling benefit applies even to tiny downstream tasks (with only a few thousand training examples), not just large-scale tasks. This is important because it challenges conventional wisdom and suggests that pre-training is extraordinarily powerful.
The authors created multiple BERT variants with different architectural dimensions:
Key intuition: These three parameters control model capacity. More layers allow deeper reasoning, larger hidden sizes allow richer representations, and more attention heads allow the model to focus on different aspects simultaneously.
They then measured performance on GLUE tasks (a benchmark suite) and tracked the masked language modeling perplexity (a measure of pre-training quality) on held-out data.
In machine learning, capacity roughly refers to the number of parameters (learnable weights) and their flexibility to fit diverse patterns. For transformers, the total number of parameters is approximately:
Where:
Example from the paper:
Perplexity is a standard measure in language modeling. If the model assigns probability to the -th token in a held-out test set, the perplexity is:
Where:
Interpretation: Lower perplexity = better predictions. A perplexity of 10 means the model's predictions are as good as if it were guessing among 10 equally likely options (on average).
The authors note that scaling model size has long been known to help on large-scale tasks like machine translation. Why?
Table 6 shows results on selected GLUE tasks. The key observation:
This holds even for MRPC (only 3,600 labeled examples), which is:
Why is this surprising?
Typically, when you apply a large model to a small dataset, you risk overfitting: the model memorizes the training data rather than learning general patterns. The conventional machine learning wisdom suggests:
With 340M parameters and only 3,600 examples, the first term should be huge! Yet this doesn't happen.
The authors propose a hypothesis (at the end of the section):
"When the model is fine-tuned directly on the downstream tasks and uses only a very small number of randomly initialized additional parameters, the task-specific models can benefit from the larger, more expressive pre-trained representations even when downstream task data is very small."
Let me unpack this mathematically:
During fine-tuning, the model has two types of parameters:
For classification tasks like MRPC, the added layer is typically:
Where:
The key insight: We're only training and on the small downstream dataset. The pre-trained representation was learned on billions of tokens and is highly expressive.
Think of it this way:
Pre-training extracts general knowledge: Larger models can capture more nuanced patterns about language (syntax, semantics, commonsense)
Fine-tuning requires minimal new learning: We only need to learn a linear projection from this pre-trained space to the task labels
Effective model complexity on downstream task: While the total model has 340M parameters, the effective complexity of what we're learning is much lower:
This is why larger pre-trained models help even on small tasks—they provide richer input representations to a simple downstream classifier.
The authors note some historical context:
| System | Encoder Parameters | Architecture |
|---|---|---|
| Vaswani et al. (2017) transformer | 100M | |
| Al-Rfou et al. (2018) transformer | 235M | |
| BERT | 110M | — |
| BERT | 340M | — |
The BERT model (340M parameters) is substantially larger than anything explored before in the literature for NLP. Showing that it yields consistent improvements across tasks of vastly different scales is genuinely novel.
Larger models aren't just about "more parameters"—it's also about deeper networks:
Where denotes function composition and is the number of layers.
Each layer can:
With more layers, the model can:
| Aspect | Traditional ML | BERT Pre-training |
|---|---|---|
| Scaling hypothesis | Bigger models overfit on small data | Bigger models improve all tasks |
| Mechanism | Train all parameters on small data | Train only small output layer on small data |
| Effective complexity | total parameters | output layer size |
| Data requirement | Must match model size | Can be much smaller than model size |
The core insight: Pre-training with self-supervised learning fundamentally changes the scaling laws. Instead of the traditional trade-off between model capacity and dataset size, you can have a large capacity model learning from a small supervised dataset because the pre-trained weights provide the inductive bias.
All of the BERT results presented so far have used the fine-tuning approach, where a simple classification layer is adde...
So far, the paper has shown that BERT works amazingly well when you take the pre-trained model and fine-tune it—meaning you add a simple classification layer on top and train all the parameters (both the pre-trained ones and the new ones) together on your downstream task.
But here's a question: Is fine-tuning the only way to use BERT? And more importantly, is it always the best approach?
This section answers "no" on both counts. The authors introduce an alternative called the feature-based approach, which extracts representations (embeddings) from the pre-trained BERT model without updating any of BERT's parameters. They then use these fixed representations as input to a much simpler, task-specific model.
Why would you want to do this instead of fine-tuning? Two main reasons:
Architectural Flexibility: Not all tasks fit naturally into a Transformer encoder architecture. Some tasks need custom architectures (like sequence labeling tasks), so you'd want to use BERT's representations but add your own specialized model on top.
Computational Efficiency: Pre-computing BERT's representations once for your entire training dataset is expensive, but you only do it once. Then you can experiment with many cheap models on top without repeatedly running the expensive pre-trained model.
To compare these approaches, the authors use the CoNLL-2003 Named Entity Recognition task. Let me explain what this is:
Named Entity Recognition (NER) is a sequence labeling task where you take a sentence like:
"John Smith works at Google in California."
And you label each token (word) with a tag indicating what type of entity it is:
John[PERSON] Smith[PERSON] works O at O Google[ORG] in O California[LOCATION]
Where:
[PERSON] = person name[ORG] = organization name[LOCATION] = location nameO = "outside" (not a named entity)The authors use BERT with a case-preserving WordPiece tokenizer. This is important because:
One technical challenge arises: BERT breaks words into subword tokens, but NER annotates whole words. How do you assign an entity label to a word that was broken into multiple subword pieces?
Solution: Use the representation of the first sub-token as the feature for that word's classification. This is a practical choice—the first sub-token "sees" the most context about the original word since it includes the word's beginning.
This is what was used in previous sections (5.1, 5.2):
Mathematically, if denotes the hidden states at layer (where is the sequence length and 768 is the hidden dimension), then the classification layer computes:
\text{logits} = H^{(L)} W_{\text{tag}} + b_{\text{tag}}
where and are learned parameters, and is the final layer.
### Approach 2: Feature-based (No Fine-tuning) This is the new approach being evaluated: 1. **Freeze BERT completely** — don't update any of its parameters 2. **Extract representations** from one or more layers of the pre-trained model 3. Use these fixed representations as input to a task-specific model: a **2-layer BiLSTM** with 768-dimensional hidden states 4. Only train the BiLSTM and classification layer The key difference: The BiLSTM uses the BERT representations as input but learns its own parameters. BERT acts as a **feature extractor**, not as a learnable component. ### Mathematical Comparison **Fine-tuning**: \hat{y}_i = \text{softmax}(H_i^{(L)} W_{\text{tag}} + b_{\text{tag}})where all parameters in BERT plus and are jointly optimized.
Feature-based:
where the semicolon denotes concatenation, and are the selected layers (frozen). Then:
Only , , and the BiLSTM weights are trained.
--- ## The Key Finding: Which Layers Matter? Look at Table 7 (the results table). The crucial experiment is testing which BERT layers to extract features from. **The winner**: Concatenate the token representations from the **top four hidden layers**. Why the top four? There are a few possible reasons: 1. **Task-specific information accumulates**: As BERT processes information through its layers, later layers capture increasingly fine-grained, task-relevant features 2. **Complementarity**: Different layers capture different aspects of information (syntax, semantics, task-specific knowledge), so combining them is better than using just one 3. **Redundancy reduction**: Using only the final layer might lose some useful information from earlier layers --- ## The Performance Trade-off The results show: - **Fine-tuning approach**: Achieves the best performance (highest F1 score) - **Feature-based approach (top 4 layers concatenated)**: Achieves performance that is **only 0.3 F1 points worse** This is a crucial finding because: \text{Performance gap} = |F1_{\text{fine-tune}} - F1_{\text{feature-based}}| = 0.3 \text{ F1}This 0.3 F1 difference is negligible in practical terms, especially considering the massive computational savings of the feature-based approach.
This section demonstrates an important principle: BERT's representations are powerful enough to be useful in multiple ways.
The paper's main contribution was showing that fine-tuning works spectacularly well. But this section shows:
| Aspect | Fine-tuning | Feature-based |
|---|---|---|
| BERT parameters | Updated jointly | Frozen (fixed) |
| Additional model | Simple classification layer | 2-layer BiLSTM + classification |
| Computational cost | High (backprop through BERT) | Lower (one BERT pass, train cheap BiLSTM) |
| Performance | Slightly better (baseline) | 0.3 F1 worse—essentially equivalent |
| Flexibility | Less (must fit Transformer architecture) | More (task-specific model on top) |
The authors' conclusion: BERT is effective for both approaches, giving practitioners a choice based on their constraints and requirements.
Recent empirical improvements due to transfer learning with language models have demonstrated that rich, unsupervised pr...
This conclusion serves as the capstone of the BERT paper. The authors are making a final argument about why their work matters. Essentially, they're saying: "We've shown that you can take a general pre-trained model and successfully apply it to many different NLP tasks—without needing task-specific architectures." This is a significant departure from previous approaches.
Think of it like building a universal translator: rather than training separate translation systems for each language pair, you train one powerful model that can handle many tasks at once.
The section opens by acknowledging that transfer learning has been increasingly important in NLP.
What is transfer learning? It's the practice of training a model on one large task (the "source" task), then adapting it to solve different, smaller tasks (the "target" tasks). The mathematical intuition:
Why does this work? Lower-resource tasks (tasks with limited labeled data) benefit because the pre-trained representations already capture rich linguistic patterns, rather than having to learn these patterns from scratch with little data.
Notice the phrase "rich, unsupervised pre-training." Let's unpack this:
Unsupervised: The pre-training data requires no human labels. The model learns from raw text alone. This is computationally efficient because text is abundant and free.
Rich: The representations learned are expressive and capture multiple levels of linguistic information (word meanings, syntax, semantics, etc.)
Mathematically, unsupervised learning typically optimizes an objective like masked language modeling (which you saw in earlier sections). Instead of predicting labels given inputs (supervised), the model predicts hidden parts of the input itself.
This is the crucial distinction the paper emphasizes:
Unidirectional models (previous approaches like GPT):
Bidirectional models (BERT):
Why does bidirectionality matter?
The paper essentially argues that bidirectional context is strictly more informative. If we denote the representation of token as :
versus
The bidirectional version has access to all context, so it can potentially learn richer representations. Section 5.1 showed empirically that LTR (left-to-right) models significantly underperform bidirectional ones.
The authors frame their contribution as a generalization:
This is important because it takes an existing insight (transfer learning is useful) and shows it's even more powerful when combined with bidirectional architecture.
The conclusion emphasizes that the same pre-trained BERT model successfully handles "a broad set of NLP tasks":
Rather than designing task-specific architectures (which requires domain expertise and engineering effort), you can:
This is a major practical advance: one model → many tasks, rather than many models → many tasks.
While the conclusion doesn't present explicit equations, it's invoking a conceptual framework:
Pre-training objective (earlier sections):
where is masked language modeling loss and is next sentence prediction loss.
Fine-tuning (for downstream task):
where is the number of classes and comes from a simple classifier applied to the pre-trained representations.
The key insight: (pre-trained parameters) are initialized from the first objective, then adapted slightly for the second—and because of the rich bidirectional context, this works remarkably well even with little downstream data.
The conclusion crystallizes the paper's central message: Bidirectional pre-training + transfer learning = a versatile framework for NLP. This isn't just an incremental improvement over prior work (GPT, ELMo)—it's a more general principle that works better and applies to more tasks.
We provide examples of the pre-training tasks in the following. Masked LM and the Masking Procedure: Assuming the unlabe...
This section reveals the mechanism that makes BERT work so effectively. While the abstract and introduction emphasize that BERT is "bidirectional," this section shows how the model actually learns to be bidirectional during pre-training. Rather than diving into architecture details, the authors illustrate the two key pre-training objectives—Masked Language Modeling (MLM) and Next Sentence Prediction (NSP)—with concrete examples.
This is crucial because pre-training is what gives BERT its power. The paper showed in Section 5.2 that larger pre-trained models achieve massive improvements even on tiny downstream tasks. This section explains what the model learns during that pre-training phase.
Traditional language models predict the next word given all previous words (left-to-right). BERT does something different: it randomly hides words and forces the model to predict them using context from both directions. This creates a truly bidirectional learning signal.
When BERT identifies a word to mask, it applies one of three procedures:
Strategy 1: Replace with [MASK] token (80% of the time)
The model must predict the hidden word "hairy" using:
Strategy 2: Replace with random word (10% of the time)
The model must predict "hairy" while seeing a nonsensical word "apple" in its place. This forces the model to:
Strategy 3: Keep word unchanged (10% of the time)
The model must predict "hairy" while seeing the correct answer. This prevents the model from relying solely on copying the input token.
The critical insight is why the authors use this mixed strategy rather than always replacing with [MASK]:
"the Transformer encoder does not know which words it will be asked to predict or which have been replaced by random words, so it is forced to keep a distributional contextual representation of every input token."
Mathematical intuition: If the model could reliably distinguish between [MASK] tokens and regular tokens, it could adopt a two-mode strategy:
By mixing strategies, the model cannot distinguish cases at the input level. It must assume: "Any token might need to be predicted, so I should maintain rich contextual information for everything." This forces genuine bidirectionality across the entire sequence.
You might worry: "Doesn't replacing 15% of tokens with random words hurt learning?"
The authors address this with a calculation. Let's denote:
This low rate means the noise doesn't significantly corrupt the training signal. The model can learn language patterns from the 98.5% of tokens that are either correct or marked with [MASK].
While MLM teaches word-level bidirectional understanding, NSP teaches sentence-level understanding. The model must predict whether two input sentences actually follow each other in the original text.
Example 1 (IsNext):
Label: IsNext
Example 2 (NotNext):
\text{[CLS] the man [MASK] to the store [SEP] penguin [MASK] are flight ##less birds [SEP]}Label: NotNext
The input structure uses special tokens:
The model outputs a binary classification ( or ) based on the final representation of the token.
MLM + NSP create complementary learning signals:
| Task | What it teaches | Level of understanding |
|---|---|---|
| MLM | Semantic/syntactic meaning of individual words | Token-level |
| NSP | Relationships between sentences, coherence, discourse structure | Sentence-level |
Together, they provide multi-scale understanding of language.
The figure contrasts three approaches:
BERT (Bidirectional Transformer)
OpenAI GPT (Left-to-Right Transformer)
ELMo (Concatenation of BiLSTMs)
The figure illustrates why BERT's approach is fundamentally different:
This allows BERT's representations to be more deeply integrated with bidirectional context, which empirically translates to better performance across downstream tasks.
The pre-training tasks (MLM + NSP) are deliberately designed to force the Transformer encoder to learn:
These learned representations can then be fine-tuned on downstream tasks with minimal additional parameters (as shown in Sections 5.2 and 5.3), which is why BERT works so well even on tiny datasets like MRPC (3,600 examples).
The masking procedure is particularly elegant: by preventing the model from knowing which tokens are masked at inference time, the authors ensure the encoder maintains rich contextual representations for every position, enabling the bidirectional conditioning that makes BERT powerful.
To generate each training input sequence, we sample two spans of text from the corpus, which we refer to as "sentences" ...
Before BERT can be fine-tuned on specific NLP tasks, it must be pre-trained on a massive, unlabeled text corpus. This section describes exactly how that pre-training happens—the data construction, hyperparameters, optimization details, and computational setup. Understanding this is crucial because:
Let's break this down into three manageable parts: (1) Data construction, (2) Optimization/training details, and (3) Computational strategy.
The section starts with the foundational unit: how a single training example is created.
"We sample two spans of text from the corpus, which we refer to as 'sentences'"
Here's what happens:
Step 1: Sample two text spans
This is important because it helps the model learn to distinguish between different input sequences (useful for tasks like question-answering where you need to identify which part is the question vs. the answer).
Step 2: Create the label for Next Sentence Prediction (NSP)
This 50-50 split creates a binary classification task. The model must learn to predict whether two sentences are consecutive in the original text—a task that encourages the model to understand discourse structure and coherence.
Why 512? This is an architectural choice tied to the Transformer's positional embeddings. The model is designed to handle sequences up to 512 tokens (BERT's maximum sequence length). Longer texts are chunked or truncated.
After the two sentences are combined:
This means: for a 512-token sequence, approximately tokens are selected for masking.
For each masked token, the procedure (explained in Appendix A.1) applies:
[MASK] tokenWhy this is clever: The model never knows which words will be predicted, so it must maintain a rich contextual representation of every token—not just the masked ones. The random replacements and unchanged tokens (which account for 10% + 10% = 20% of masked positions, or ~3% overall) prevent the model from just "pattern-matching" to the [MASK] token.
| Parameter | Value | Interpretation |
|---|---|---|
| Batch size | 256 sequences | |
| Tokens per sequence | 512 | Maximum sequence length |
| Tokens per batch | Total gradient computation size | |
| Training steps | 1,000,000 | Total iterations |
| Approximate epochs | 40 | Over 3.3 billion word corpus |
What are "epochs"? An epoch is one complete pass through the entire training data. With ~40 epochs, each token in the corpus is seen approximately 40 times during training.
The model uses the Adam optimizer (Kingma & Ba, 2014) with specific hyperparameters:
What do these mean?
Learning Rate Schedule:
The learning rate doesn't stay constant. Instead, it follows this schedule:
Why warmup? Starting with a very small learning rate allows the model to adapt gradually. The random initialization of weights could cause wild gradient estimates, so warmup prevents erratic behavior early on.
Why decay? As training progresses, you want finer and finer adjustments. The linear decay schedule gradually reduces the step size, allowing convergence to a good minimum.
The model uses GELU (Gaussian Error Linear Unit) instead of the standard ReLU:
where is the cumulative distribution function (CDF) of the standard normal distribution. Intuitively, GELU is a smooth, probabilistic variant of ReLU that empirically works better for language models.
where:
where is the number of masked tokens in the batch.
where is batch size, is the true label, and is the predicted probability.
Key insight: These two objectives are jointly optimized. The model learns to predict missing words and understand discourse structure at the same time. This multi-task learning helps the model develop richer representations.
BERT:
BERT:
(The larger model requires 4× the computational resources but takes the same time because it's trained on a 4× larger setup.)
Here's where the section gets clever—they mention:
"We pre-train the model with sequence length of 128 for 90% of the steps. Then, we train the rest 10% of the steps of sequence of 512"
Why does this matter mathematically?
Computational cost of a Transformer scales quadratically with sequence length due to the self-attention mechanism:
where are matrices ( = sequence length, = hidden dimension). Computing requires operations (matrix multiplication of with ).
So the computational cost ratio is:
The scheduling strategy:
This achieves ~ speedup in wall-clock time (approximately) compared to training all 1M steps with . The model spends most of its computational budget on shorter, faster updates, then "fine-tunes" its understanding of long-range dependencies.
Here's how the pieces fit together:
| Phase | What Happens | Why |
|---|---|---|
| Data Construction | Sample text pairs, create labels (IsNext/NotNext), apply 15% masking | Enables NSP and MLM objectives |
| Optimization | Adam with warmup/decay schedule, 1M steps over 3.3B words | Standard best practices for deep learning |
| Multi-task Loss | MLM + NSP losses combined | Both objectives improve downstream performance |
| Computational Optimization | 90% short sequences (128 tokens), 10% long sequences (512 tokens) | Massive speedup via quadratic scaling of attention |
This pre-training procedure is what enables BERT to then be fine-tuned (as described in Section 5) on downstream tasks with just a classification layer added on top. The pre-trained representations already capture rich linguistic knowledge from this self-supervised learning process.
For fine-tuning, most model hyperparameters are the same as in pre-training, with the exception of the batch size, learn...
The most comparable existing pre-training method to BERT is OpenAI GPT, which trains a left-to-right Transformer LM on a...
The illustration of fine-tuning BERT on different tasks can be seen in Figure 4. Our task-specific models are formed by ...
Figure 5 presents MNLI Dev accuracy after fine-tuning from a checkpoint that has been pre-trained for $k$ steps. This al...
In Section 3.1, we mention that BERT uses a mixed strategy for masking the target tokens when pre-training with the mask...