BERT: Bidirectional Encoder Representations
BERT (Bidirectional Encoder Representations from Transformers), introduced by Devlin et al. at Google in 2018, is a pre-trained language model that learns deep bidirectional representations from unlabeled text by jointly conditioning on both left and right context in every layer. It matters because it established the dominant "pre-train then fine-tune" paradigm that underpins nearly every state-of-the-art NLP system in production today. The counterintuitive fact: BERT is never trained to predict the next word — instead it learns language by randomly masking tokens and predicting them from surrounding context, a seemingly simple objective that produces richer representations than any directional language model before it.
Before BERT, language models read text in only one direction — left-to-right or right-to-left — which means every word representation is "blind" to the words that come after it. BERT's breakthrough is making every layer of the Transformer encoder attend to the entire sequence simultaneously, so the representation of the word "bank" in "river bank" is shaped by both "river" (to the left) and whatever comes after (to the right) at every depth of the network. This bidirectionality is achieved not by architecture wizardry but by a training objective called Masked Language Modeling: randomly hide 15% of tokens and ask the model to reconstruct them from full context. The "aha moment" is realising that a single pre-trained BERT checkpoint can be fine-tuned with just one extra linear layer to achieve state-of-the-art performance on tasks as different as question answering, sentiment analysis, and named entity recognition.
How It Works
Input Representation
BERT takes a token sequence and constructs its input embedding by summing three learned embedding tables:
Explanation: The final embedding for position i is the sum of a token embedding, a segment embedding (sentence A vs. B), and a positional embedding — all three are learned jointly during pre-training.
- : token embedding matrix, = vocabulary size (30,522 for BERT-base), = 768
- : two embeddings distinguishing sentence A from sentence B in paired-sentence tasks
- : learned absolute positional embeddings (not sinusoidal as in the original Transformer)
Scaled Dot-Product Self-Attention
Within each of BERT's 12 (base) or 24 (large) Transformer encoder layers, the scaled dot-product attention mechanism computes:
Explanation: Each query vector attends to all key vectors, the dot-product scores are scaled to prevent vanishing gradients in the softmax, and the resulting weights form a convex combination of value vectors.
- , , — projections of the same input
- where is the number of heads (12 for BERT-base)
- The scaling prevents dot products from growing large in magnitude as dimension increases
Multi-Head Attention
BERT runs attention heads in parallel, then concatenates and projects:
Explanation: Running multiple heads lets the model simultaneously attend to different types of relationships — syntactic, semantic, coreference — at different subspace positions.
- Each
- : output projection matrix
- For BERT-base: , , ; for BERT-large: ,
Masked Language Modeling Objective
The MLM loss is a standard cross-entropy over only the masked positions:
Explanation: The model is penalised only on the masked tokens; non-masked positions contribute no gradient signal, which is why BERT sees bidirectional context without "cheating" by looking at the token it must predict.
- : the set of masked token indices (≈15% of tokens per sequence)
- : the corrupted input (masked tokens replaced with `[MASK]`, a random token, or left unchanged per the 80/10/10 rule)
- : softmax over the full vocabulary from the final hidden state at position
Next Sentence Prediction Objective
BERT's second pre-training task is a binary classification on the `[CLS]` token:
Explanation: The model learns whether sentence B naturally follows sentence A in the original document, forcing the [CLS] embedding to capture inter-sentence coherence — though later work showed NSP adds marginal benefit compared to MLM alone.
- : label, 1 if the pair is consecutive, 0 if sentence B is a random negative
- : sigmoid applied to a single linear projection of the `[CLS]` final hidden state
---
PyTorch Fine-Tuning Skeleton
```python from transformers import BertTokenizer, BertForSequenceClassification import torch tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") model = BertForSequenceClassification.from_pretrained( "bert-base-uncased", num_labels=2)
# Tokenise a batch enc = tokenizer( ["The river bank was flooded.", "I deposited cash at the bank."], padding=True, truncation=True, max_length=128, return_tensors="pt" )
# Forward pass — the [CLS] hidden state is pooled + projected internally outputs = model(**enc, labels=torch.tensor([0, 1])) loss, logits = outputs.loss, outputs.logits loss.backward() # only the task head + BERT weights fine-tune together ``` The `[CLS]` token at position 0 accumulates a sentence-level representation through all 12 layers of self-attention; the classification head is simply a linear layer applied to that vector. ---
Jacob Devlin was a research scientist at Google AI Language when he led the team that published BERT in October 2018, building directly on the Transformer architecture of Vaswani et al. His key insight was that making the pre-training objective bidirectional — rather than the left-to-right approach used by OpenAI's GPT — could be achieved cleanly through masked token prediction, yielding dramatically stronger representations without architectural changes. A surprising fact: the original BERT paper was posted to arXiv just two months before it swept the GLUE benchmark leaderboard by large margins, and Devlin has said the team was initially uncertain whether the approach would outperform ELMo and GPT by such a wide margin.
Ashish Vaswani was a senior researcher at Google Brain when he co-authored "Attention Is All You Need" (2017), the paper that introduced the Transformer architecture upon which BERT is directly built — BERT uses the Transformer's encoder stack unchanged except for learned positional embeddings. His contribution to this topic is foundational: without the parallelisable, fully-attentive encoder block, the bidirectional pre-training that defines BERT would be computationally intractable at scale. Vaswani later co-founded Adept AI, and he has noted that the team originally expected the Transformer to be most valuable for machine translation, not as a general-purpose representation learning engine.
Intuition
Imagine you are doing a crossword puzzle where you must fill in a blank word given all the clues — clues from letters to the left and letters to the right of the blank, clues from intersecting words above and below. You are not forced to read only left-to-right; you use the full two-dimensional context of the grid. That is exactly what BERT does for every masked word in a sentence. Contrast this with how a child might be taught to read: "sound it out left to right." That child, upon encountering "I went to the river ___" has to predict "bank" before seeing the next sentence about depositing money. BERT instead sees both sentences simultaneously and can use "depositing money" in the next sentence to inform its representation of "bank" in the current one — something no left-to-right language model can do. The pre-training / fine-tuning split has a vivid analogy too: think of BERT's pre-training as a student spending years reading every Wikipedia article and every book, building rich background knowledge. Fine-tuning is then a one-week crash course for a specific exam — the student needs very few labelled examples because their background knowledge is already so deep. The single linear layer added on top of BERT for classification is that crash course: just enough to redirect pre-existing knowledge toward a new task. Finally, the `[CLS]` token is a designated "notepad" that the model learns to write a sentence-level summary onto across 12 layers of bidirectional attention — by the time you read off the `[CLS]` hidden state, it has aggregated information from every other token in both sentences.