🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

BERT and Encoder Models — Complete Guide

Deep LearningTransformers🟢 Free Lesson

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

BERT Architecture (Encoder-Only Transformer)Input Tokens[CLS]Thecatsat[MASK]on[SEP]Token + Position + SegmentEmbeddings (d=768)TransformerEncoder × 12Layer 1 → Layer 2 → ... → Layer 12Each: MHA + FFN + LayerNormOutputh₁...hₙ768-dim eachFine-tuning Tasks[CLS] → FCClassificationSentiment, NLIhᵢ → FCToken-levelNER, POShᵢ → start/endSpan ExtractSQuAD QABERT Model VariantsBERT-base:12 layers, 768 hidden, 12 heads, 110M paramsBERT-large:24 layers, 1024 hidden, 16 heads, 340M paramsImprovements:RoBERTa (better training), ALBERT (parameter sharing), DeBERTa (disentangled attention, SOTA)Efficient:DistilBERT (97% accuracy, 60% faster), TinyBERT (7.5M params, distillation)

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

BERT Pre-training ObjectivesTask 1: Masked Language Modeling (MLM)Input: "The [MASK] sat on the [MASK]"Target: "The cat sat on the mat"• Randomly mask 15% of tokens (not all — must prevent shortcut learning)• Of masked: 80% replaced with [MASK], 10% random, 10% unchanged (reduces pre-train/fine-tune mismatch)• Loss: Cross-entropy over vocabulary at masked positions only — forces bidirectional understandingTask 2: Next Sentence Prediction (NSP)Positive: "[CLS] The cat sat [SEP] It was happy [SEP]" → IsNextNegative: "[CLS] The cat sat [SEP] The sky blue [SEP]" → NotNext• 50% positive (actual consecutive sentences), 50% negative (random pair)• Binary classification on [CLS] token output• Note: RoBERTa showed NSP is not helpful — replaced with sentence ordering instead

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.

python
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

BERT Fine-tuning ProcessPre-trained BERT12-24 layers110-340M paramsLearned: syntax, semantics, world knowledge→Add Task HeadClassification: FCNER: FC per tokenQA: start/end FC~0.1-1M new params→Fine-tuneALL params updatedSmall LR: 2e-5 to 5e-53-5 epochsHours on single GPU→Fine-tunedModelTask-specificBERT + headReady for inferenceKey insight: Pre-training learns general representations → Fine-tuning adapts to specific task. This transfer learning paradigm achieved SOTA on 11 NLP benchmarks simultaneously.

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.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement