Deep Learning
BERT — How Google Changed Search with Bidirectional Understanding
Understand how BERT revolutionized NLP by processing text bidirectionally for better comprehension.
- Bidirectional context — understand words from both directions
- Pre-training + fine-tuning — powerful transfer learning paradigm
- Search and Q and A — transformed Google Search and beyond
Understanding context is the key to understanding language.
BERT and Encoder Models — Complete Guide
BERT (Bidirectional Encoder Representations from Transformers, Devlin et al., 2018) revolutionized NLP by introducing bidirectional pre-training on large unlabeled text, followed by task-specific fine-tuning. It demonstrated that pre-training + fine-tuning outperforms training from scratch on nearly every NLP benchmark.
BERT Architecture
Reading the Architecture Diagram
BERT stacks identical encoder blocks — twelve in the base model, twenty-four in the large one — and every block applies multi-head self-attention followed by a position-wise feed-forward network, with a residual connection and layer normalization wrapped around both. The property that matters is that attention is fully connected: token five attends to tokens one through n in a single step, so no recurrence and no ordering trick is needed to see both directions at once.
The input is a sum of three embeddings. Token embeddings come from a 30,522-entry WordPiece vocabulary, which splits rare words into subwords so playing becomes play plus ##ing. Position embeddings inject word order, because attention by itself is permutation invariant. Segment embeddings let the model know that one sentence belongs to sequence A and the other to sequence B, which is what next-sentence prediction needs to work. All three are 768-dimensional and added element by element before the result enters the first encoder layer.
The [CLS] token sits at position zero and its final hidden state serves as a pooled summary of the whole input. Classification heads read that vector, while token-level heads ignore it and read the per-position states instead. BERT-base ends at about 110 million parameters and BERT-large at about 340 million, and the difference comes from width and depth rather than any change in the input handling described above.
Pre-training Objectives
Why the 80/10/10 Split Exists
If every masked position were replaced with [MASK], the model could learn a shortcut: spot the blank slot and predict whichever word fits best without reading much of the surrounding sentence. Worse, the special mask token never appears during fine-tuning, so the inputs seen in training would differ from the inputs the model sees later in production. BERT therefore masks 15% of tokens but only replaces four fifths of them with [MASK]; one in ten becomes a random vocabulary item and one in ten is left exactly as it was. The random substitution forces the model to check its context instead of trusting what it was handed, and the untouched tokens keep the training distribution close to what a downstream task will provide.
The loss is ordinary cross-entropy, but it is computed only at the positions that were chosen for prediction. Every other position contributes nothing to the gradient, which keeps the effective supervision dense enough to learn from a single sentence while still requiring the model to reconstruct meaning rather than copy it.
from transformers import pipeline
unmasker = pipeline('fill-mask', model='bert-base-uncased')
preds = unmasker("the capital of [MASK] is paris")
for p in preds[:5]:
print(f"{p['token_str']:>10} {p['score']:.4f}")
Next sentence prediction looks similar on the diagram, but it proved far less important. RoBERTa dropped the objective entirely, trained on longer sequences with much larger batches, and still matched or beat the original model on nearly every benchmark, which suggests half the training pairs were built from documents that shared nothing. Later encoders kept the masked prediction recipe and replaced the other pieces: ALBERT shares weights across layers to cut the parameter count, DeBERTa separates content from position in the attention computation, and DistilBERT trains a smaller student to reach roughly the same accuracy at a fraction of the latency.
Fine-tuning BERT
What Actually Changes During Fine-Tuning
A fine-tuning run updates all 110 million parameters, but it does so with a learning rate near 2e-5, roughly a thousand times smaller than the rates used in pre-training. Two safeguards keep that stable. A warmup phase raises the rate linearly over the first tenth of the steps, so the freshly initialised task head is never hit with a full-size update. Training then stops after three to five epochs, because the encoder already understands language structure and further passes simply memorise the few thousand labelled examples, dragging training accuracy up while validation accuracy flattens or falls.
The head you attach is tiny. Sequence classification adds a single linear map from 768 dimensions to the number of labels, so a two-class sentiment model grows by about 1,500 parameters. Token classification applies one map per position, and extractive question answering applies two, one for the start of the answer span and one for the end. That asymmetry is the reason one pre-trained checkpoint can serve tasks as different as sentiment analysis, name tagging and reading comprehension: only the last, task-specific layer changes shape.
BERT for Different Tasks
Fine-Tuning BERT
Common Mistakes & How to Avoid Them
Common Mistakes
Fine-tuning with a pre-training learning rate and destroying the representations in the first few steps
Fix: Use 2e-5 to 5e-5 with 10% warmup and gradient clipping at 1.0; the encoder only needs a gentle nudge toward the new labels
Feeding single sentences without the token_type_ids BERT expects, so segment embeddings are always zero
Fix: Pass both sequences to the tokenizer and let it build attention masks and segment ids, then verify the shapes before training
Training for twenty epochs on a small labelled set and watching test accuracy fall while training accuracy climbs
Fix: Stop at three to five epochs, keep a held-out validation split, and pick the checkpoint with the best validation score
Key Takeaways
What to Learn Next
-> GPT Architecture Compare with autoregressive models.
-> Transformers Master the underlying architecture.
-> NLP Fundamentals Learn natural language processing basics.
-> Transfer Learning Apply pre-trained models to new tasks.
-> Pre-training Language Models Understand how models learn from text.
-> Tokenization for LLMs Learn how text is converted to tokens.