◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

BERT and Encoder Models

BERT is a Transformer encoder pretrained by filling in hidden words, so every token's vector draws on context from both sides. Fine-tuned with a small extra layer, it became the standard tool for classification, search and extraction, and encoders still beat chatbots on cost for many of those jobs.

Level
●●●●● Intermediate
Reading
11 min
To learn it well
1 hour to read, an afternoon to fine-tune a model
↗ Plan a path here

Read first

The Transformer

This leads to

Sentence Embeddings
The full path from zero — 28 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Recurrent Neural Networks
  18. Backpropagation
  19. Activation Functions
  20. Vanishing and Exploding Gradients
  21. Normalization Layers: BatchNorm and LayerNorm
  22. LSTMs and GRUs
  23. Residual Connections
  24. Sequence-to-Sequence Models
  25. Attention
  26. Self-Attention and Multi-Head Attention
  27. Positional Encodings
  28. The Transformer
  29. BERT and Encoder Models

Read them roughly in this order. See it on the concept map →

Why it matters

In October 2018 a team at Google released BERT (Bidirectional Encoder Representations from Transformers). Overnight it set new records on eleven language-understanding benchmarks, from sentiment analysis to question answering, and it did so with one recipe: pretrain a The Transformer encoder on a few billion words of ordinary text, then fine-tune it on each task with a tiny extra layer and a few thousand labelled examples. A year later Google said BERT was helping to rank about one in ten English search queries in the US.

BERT made Transfer Learning the default in language processing, the way ImageNet-pretrained networks already were in vision. It is still everywhere, often unnoticed: spam filters, content moderation, document classification, named-entity extraction, and above all search. The embedding models behind Embeddings and Semantic Search and Retrieval-Augmented Generation, and the "rerankers" that sort search results, are mostly BERT-style encoders.

Chat models can do many of these tasks too, but an encoder with 100 million parameters can classify thousands of documents per second on a single GPU or even a CPU, for a tiny fraction of the cost of calling a large GPT-style model. Knowing when to reach for one is a practical skill.

The intuition

Take the sentence "She went to the bank to deposit her cheque." To understand "bank" you need "deposit" and "cheque", which come after it. A left-to-right language model like GPT, reading word by word, has to decide what "bank" means before it sees them.

BERT reads the whole sentence at once. Its Self-Attention and Multi-Head Attention has no causal mask, so every word's vector is built from context on both sides. That's the "bidirectional" in its name.

But how do you train a model that sees everything? You can't ask it to predict the next word: it can already see it. BERT's answer is a fill-in-the-blanks game, like a cloze test at school. Hide some words, show the model the rest, and ask it to guess the hidden ones:

The cat sat on the [MASK].

To fill the blank well, the model must understand grammar ("the" is followed by a noun), meaning (cats sit on things) and world knowledge (floors, mats, sofas). Play this game on billions of words and the model's internal vectors become a rich description of what every word means in its context.

BERT reads the whole sentence with unmasked self-attention and predicts the hidden word. The bars are the real top-5 predictions of bert-base-uncased for "The cat sat on the [MASK]."

Key idea BERT = a Transformer encoder trained to fill in masked words using context from both sides. Its output vectors are contextual embeddings: the same word gets a different vector in each sentence. Add a small layer on top and fine-tune to solve almost any understanding task.

How it works

Architecture

BERT is the encoder half of the original The Transformer: a stack of blocks with multi-head self-attention and feed-forward layers, but no causal mask and no decoder. It came in two sizes:

Model Blocks Width dd Heads Parameters
BERT-base 12 768 12 110 million
BERT-large 24 1,024 16 340 million

Inputs are cut into WordPiece tokens from a vocabulary of 30,522, up to 512 tokens long. Two special tokens frame them: [CLS] at the very start, whose output vector is used as a summary of the whole input, and [SEP] at the end of each segment. Each input vector is the sum of three learned embeddings: the token, its position (learned, up to 512) and its segment (A or B, for tasks with two texts, such as question and passage).

Pretraining task 1: masked language modelling

Masked language modelling (MLM) picks 15% of the token positions in each training sequence at random. Of those:

  • 80% are replaced with the special token [MASK],
  • 10% are replaced with a random token,
  • 10% are left unchanged.

The model must predict the original token at every chosen position, and the loss, ordinary cross-entropy over the 30,522-token vocabulary (Loss Functions), is computed only at those positions.

Why the odd 80/10/10 split? If chosen positions were always [MASK], the model would learn that only [MASK] positions need careful thought, but [MASK] never appears when you later use the model on real text. Sometimes showing a random or the real token forces it to build a good representation for every token, because it can't tell which ones will be tested.

Pretraining task 2: next sentence prediction

The original BERT also trained on next sentence prediction (NSP): given two segments joined as [CLS] A [SEP] B [SEP], predict from the [CLS] vector whether B really followed A in the text or was a random sentence. The idea was to teach relationships between sentences. Later work (RoBERTa, 2019) found NSP didn't help and dropped it, so most modern encoders use MLM alone.

Pretraining data and cost

BERT was pretrained on BooksCorpus (about 800 million words) and English Wikipedia (about 2.5 billion words). BERT-large took four days on 16 Cloud TPUs. That is modest by today's standards, when LLM pretraining uses trillions of tokens.

Fine-tuning

After pretraining, the MLM output layer is thrown away. For each task you add a small, freshly initialised layer, a fine-tuning head, and train the whole network, encoder included, on labelled examples for a few epochs with a small learning rate (the BERT paper recommends 2e-5 to 5e-5).

Two common fine-tuning set-ups. For whole-sentence tasks a linear layer reads the [CLS] vector. For token-level tasks such as named-entity recognition, the same small layer is applied to every token's vector.

  • Sentence classification (sentiment, topic, spam, "does sentence B follow from sentence A?"): a linear layer on the [CLS] output vector, softmax over the classes.
  • Token classification (named entities, parts of speech): a linear layer on each token's output vector.
  • Extractive question answering (SQuAD): feed [CLS] question [SEP] passage [SEP] and train two vectors that score each passage token as the start or end of the answer span.

With BERT-large, the paper's GLUE benchmark score (an average over nine understanding tasks) jumped to 80.5, 7.7 points above the previous best. Fine-tuning a pretrained encoder beat years of task-specific architectures.

Contextual embeddings

Older Word Embeddings such as word2vec give "bank" one fixed vector. BERT's output vector for "bank" depends on the sentence it's in: river banks and money banks land in different places. These contextual embeddings are what make encoders good at search. Average or pool the token vectors, train with a contrastive objective, and you get Sentence Embeddings, where similar meanings land close together.

Encoders versus decoders

Encoder (BERT) Decoder (GPT)
Attention bidirectional causal (left to right)
Training task fill in masked tokens predict the next token
Natural output one vector per token the next token
Good at classification, extraction, embeddings, ranking generation, chat, open-ended tasks
Typical size in use 20 million to 400 million parameters 1 billion to hundreds of billions

Encoders can't easily generate text, because they were never trained to produce a sequence left to right. Decoders can do classification by being prompted ("Is this review positive or negative?"), but they are much larger and slower for it. That's the trade-off.

In code

BERT's masking recipe in a few lines of PyTorch. The label -100 tells PyTorch's cross-entropy to ignore a position:

import torch

def mask_tokens(ids, mask_id, vocab_size, p=0.15):
    """BERT's masking recipe. Returns (inputs, labels); label -100 = not scored."""
    labels = ids.clone()
    chosen = torch.rand(ids.shape) < p                    # pick 15% of positions
    labels[~chosen] = -100                                # only chosen ones count in the loss
    inputs = ids.clone()
    r = torch.rand(ids.shape)
    inputs[chosen & (r < 0.8)] = mask_id                  # 80% -> [MASK]
    rand = chosen & (r >= 0.8) & (r < 0.9)                # 10% -> random token
    inputs[rand] = torch.randint(vocab_size, ids.shape)[rand]
    return inputs, labels                                 # last 10% left unchanged

torch.manual_seed(4)
ids = torch.arange(1000, 1020)                            # 20 pretend token ids
inputs, labels = mask_tokens(ids, mask_id=103, vocab_size=30522)
print(inputs.tolist()); print(labels.tolist())

# [1000, 1001, 103, 1003, 1004, 103, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 103]
# [-100, -100, 1002, -100, 1004, 1005, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 1019]

Four positions were chosen. Three became [MASK] (id 103 in BERT's vocabulary), and position 4 (token 1004) was left unchanged but must still be predicted: the 10% case.

Using a real pretrained BERT with Hugging Face transformers (The Hugging Face Ecosystem; the first run downloads about 440 MB):

from transformers import pipeline

fill = pipeline("fill-mask", model="bert-base-uncased")
for r in fill("The cat sat on the [MASK].")[:5]:
    print(round(r["score"], 3), r["token_str"])
print(fill("Paris is the [MASK] of France.")[0]["token_str"])

# 0.314 floor
# 0.119 bed
# 0.107 couch
# 0.06 sofa
# 0.055 ground
# capital

And fine-tuning it as a sentiment classifier, with a toy dataset of six sentences so it runs on a laptop CPU in about a minute:

import torch
torch.manual_seed(0)
from transformers import AutoTokenizer, AutoModelForSequenceClassification

name = "bert-base-uncased"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)  # new head on [CLS]

texts = ["I loved this film", "What a wonderful day", "Absolutely brilliant acting",
         "This was a waste of time", "Terrible, boring plot", "I hated every minute"]
labels = torch.tensor([1, 1, 1, 0, 0, 0])                 # 1 = positive, 0 = negative
batch = tok(texts, padding=True, return_tensors="pt")

opt = torch.optim.AdamW(model.parameters(), lr=2e-5)
model.train()
for epoch in range(10):                                   # fine-tune the whole network
    out = model(**batch, labels=labels)                   # cross-entropy on the [CLS] head
    out.loss.backward(); opt.step(); opt.zero_grad()
    print(epoch, round(out.loss.item(), 3))

model.eval()
test = tok(["An amazing, moving story", "Dull and far too long"], padding=True, return_tensors="pt")
with torch.no_grad():
    print(model(**test).logits.softmax(-1).round(decimals=2))

# 0 0.692
# 1 0.616
# ...
# 9 0.248
# tensor([[0.3900, 0.6100],      <- new positive review: 61% positive
#         [0.6900, 0.3100]])     <- new negative review: 69% negative

With only six examples the model is already leaning the right way on sentences it has never seen. With a real dataset of a few thousand examples, BERT-base typically reaches strong accuracy on sentiment in a few minutes on a GPU. (Output from transformers 5.24 on CPU; your numbers will differ slightly.)

Common pitfalls

  • Using raw BERT vectors for similarity. Averaging the output vectors of a plain pretrained BERT gives poor sentence embeddings, often worse than older methods. Use a model trained for the purpose (Sentence Embeddings, e.g. Sentence-BERT).
  • Exceeding 512 tokens. Original BERT models silently truncate or fail on longer inputs. Split documents into chunks, or use a long-context encoder such as ModernBERT (8,192 tokens).
  • Learning rate too high. Fine-tuning with rates like 1e-3 destroys the pretrained knowledge within a few steps (catastrophic forgetting, see Fine-Tuning). Stay in the 1e-5 to 5e-5 range.
  • Cased versus uncased. bert-base-uncased lowercases everything, losing the difference between "US" and "us". Use a cased model where capitals matter, as in named-entity recognition.
  • Expecting generation. An encoder won't write coherent paragraphs. Use a decoder for that.

Watch out Tiny fine-tuning datasets give unstable results: different random seeds can swing accuracy by several points. Always evaluate on a held-out set (Training, Validation and Test Sets) and, for small data, average over a few runs.

Where it leads

BERT spawned a family of improved encoders:

  • RoBERTa (Meta, 2019): same architecture, but trained longer on about 160 GB of text, with bigger batches, freshly sampled masks and no NSP. Clearly better, showing BERT had been undertrained.
  • DistilBERT (Hugging Face, 2019): a 40% smaller student trained to imitate BERT (Knowledge Distillation and Small Models), about 60% faster while keeping about 97% of its benchmark performance.
  • ELECTRA (2020): instead of predicting masked tokens, detect which tokens were swapped by a small generator, which learns from every position and is more compute-efficient.
  • DeBERTa (Microsoft, 2020): separates content and position in attention; strong on benchmarks.
  • ModernBERT (2024): an encoder rebuilt with the LLaMA-era toolkit (RoPE, longer 8,192-token context, trained on about 2 trillion tokens).

Encoders lead directly to Sentence Embeddings, Embeddings and Semantic Search, Vector Databases and the retrieval step of Retrieval-Augmented Generation. The same masked-prediction idea reappears in vision as masked autoencoders and in Self-Supervised Learning generally. The decoder branch of the family tree is GPT and Decoder-Only Models.

A bit of history

In early 2018 two papers showed that pretrained language models could transfer: ELMo (Peters et al., Allen Institute), which produced contextual word vectors from bidirectional LSTMs, and ULMFiT (Howard and Ruder), which fine-tuned an LSTM language model. In June 2018 OpenAI's GPT did the same with a Transformer decoder. In October 2018 Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova at Google released BERT, combining the Transformer with bidirectional masked-word training, and swept the benchmarks. The paper became one of the most cited in all of computer science. The masked-word idea itself is old: the "cloze test" was proposed by the reading researcher Wilson Taylor in 1953. From 2020 onwards the spotlight moved to ever larger decoder models, but encoders remain the workhorses of search and classification.

Try it

  1. Run the fill-mask pipeline on "The doctor said that [MASK] would arrive soon." and "The nurse said that [MASK] would arrive soon." Compare the probabilities of "he" and "she". What does this tell you about what BERT learned from its training data? (See Bias and Fairness.)
  2. Call mask_tokens on 10,000 ids and check that about 15% get a label, and of those about 80% became 103.
  3. Replace bert-base-uncased with distilbert-base-uncased in the fine-tuning example. Is it faster? Are the predictions similar?

Hint for 2: (labels != -100).float().mean() and (inputs[labels != -100] == 103).float().mean().

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In "She went to the bank to deposit her cheque", why can BERT interpret "bank" better than a left-to-right model reading word by word?

  2. Why does BERT replace only 80% of the chosen positions with [MASK], leaving 10% random and 10% unchanged?

  3. Your company needs to classify 10 million support tickets by topic, cheaply and fast. What does the chapter suggest?

  4. You fine-tune BERT with a learning rate of 1e-3 and accuracy collapses within a few steps. What went wrong?

  5. You average the output vectors of plain pretrained BERT to find similar sentences, and results are poor. Why?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

The Illustrated BERT, ELMo, and co.

Jay Alammar · Beginner · Free

A picture-led walk through BERT's pretraining tasks and how it is fine-tuned for downstream jobs.

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.

Book

Speech and Language Processing

Dan Jurafsky & James H. Martin · Intermediate · Free

The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/bert.md