GenAI · Language models

BERT Explained: How It Works and Its Variants

⏱ 15 min read🎯 Beginner friendly🖼 7 diagrams🧪 5 live demos🐍 Python code

BERT is the model that taught computers to really understand a sentence. Google released it in 2018, and even today it quietly powers search, spam filters, chatbots and fraud detection. In this lesson, let us understand BERT step by step, with simple examples, pictures you can watch and code you can run.

In short

  • BERT stands for Bidirectional Encoder Representations from Transformers.
  • It reads the full sentence at once, left side and right side together.
  • It learns by doing fill-in-the-blanks on billions of sentences.
  • It is great at understanding text (classify, search, extract), not at writing long answers like ChatGPT.
  • Smaller and better versions exist: DistilBERT, RoBERTa, DeBERTa, ModernBERT and more.

01The simple idea behind BERT

Remember fill-in-the-blanks questions in school? To fill the blank, you never read only the words before it. You read the whole line, and the words after the blank also give you a clue. That is exactly how BERT learns.

Class 6 · English worksheet Q3. Fill in the blank: Mumbai is the ______ capital of India. clue on the left clue on the right BERT answersfinancial
“Capital” alone could mean money or a city. The words on both sides tell BERT it means “financial capital”.

Older models read only from left to right, like reading with one eye closed. When they reached the word “bank” in “I deposited cash at the bank”, they could only look backwards. BERT looks both ways. Try it:

Demo · Which words can “bank” look at?

When BERT came out, it broke records on 11 language tests, including GLUE and SQuAD (a reading-comprehension test). In 2019, Google started using it to understand search queries better.

02What is inside BERT

BERT is made by stacking the same building block again and again. This block is called a Transformer encoder layer. Words go in at the bottom as numbers; after passing through all the layers, each word comes out as a rich vector that carries its meaning in this sentence.

Output: one meaning vector per token CT1T2T3T4T5 Encoder layer 12self-attention + feed-forward Encoder layer 2self-attention + feed-forward Encoder layer 1self-attention + feed-forward ⋮layers 3 to 11 Embeddings (token + segment + position) [CLS]mycardisblocked[SEP] Input tokens
BERT-Base stacks 12 encoder layers. Every token comes out as a 768-number vector. The [CLS] vector acts as a summary of the whole input.
ModelLayersHidden sizeAttention headsParameters
BERT-Base1276812~110 million
BERT-Large241,02416~340 million

Inside one encoder layer

Each layer does two jobs. First, self-attention: every word “talks” to every other word and collects useful information. Second, a small feed-forward network processes each word on its own. Shortcut (residual) connections and normalisation keep training stable.

Input vectors Multi-head self-attentionwords look at each other Add & Norm Feed-forward networkeach word processed alone Add & Norm Output → next layer shortcut shortcut
Repeat this block 12 times (BERT-Base) or 24 times (BERT-Large).

03How BERT reads your sentence

Before the text goes in, BERT adds a few special tokens:

Then every token gets three embeddings added together: which token it is, which sentence it belongs to (A or B), and its position in the line. Press Build to watch it:

Demo · Building the input vectors
Token + Segment + Position are added number by number. In BERT-Base, each row is a list of 768 numbers.
🏏

Think of a cricket scorecard. Knowing who the player is (token), which team he plays for (segment) and his batting position (position) together tells you much more than his name alone.

WordPiece: breaking big words into pieces

BERT’s dictionary has about 30,000 pieces. A rare word is split into smaller known pieces; pieces that continue a word start with ##. So BERT never gets stuck on an unknown word.

tokenize.py
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
print(tokenizer.tokenize("Tokenization handles unseen words"))
print(tokenizer("I love learning AI")["input_ids"])
['token', '##ization', 'handles', 'unseen', 'words'] [101, 1045, 2293, 4083, 9932, 102] # 101 = [CLS], 102 = [SEP]

04How BERT learns: pre-training

BERT learned from English Wikipedia (about 2.5 billion words) and a collection of books (about 800 million words). Nobody labelled this data. BERT makes its own practice questions, using two games.

Game 1 · Masked Language Modelling (fill in the blanks)

In every sentence, BERT picks 15% of the tokens to predict. But it does not always hide them the same way:

Of the 15% chosen tokens… 80% → replaced with [MASK] 10% 10% my card is [MASK]most of the time my card is applerandom word (10%) my card is blockedkept as it is (10%) BERT must still predict the original word “blocked” in all three cases. This stops it from relying on seeing [MASK].
The 80 / 10 / 10 recipe makes BERT pay attention to every word, not only the masked ones.

Now you play the game. Pick a sentence and see what BERT would guess:

Demo · Fill in the blank
Try sentences 2 and 3: the same word “bank” comes from completely different clues.

Game 2 · Next Sentence Prediction

BERT gets two sentences, A and B. Half the time B really comes after A (IsNext); half the time B is a random sentence (NotNext). BERT must say which. Later research (RoBERTa) found this game does not help much, so many newer models skip it.

Demo · Does sentence B follow A?

05Fine-tuning: teaching BERT your task

Pre-training is costly and is done once by big labs. You simply download that trained BERT and give it a little extra training on your own data. This is called fine-tuning.

🏫 SchoolPre-trainingReads Wikipedia + booksbillions of wordsweeks · big labs BERTgeneral knowledgefree to download 🎯 Coaching (fine-tuning) Fraud SMS classifier Find names & amounts Answer from a policy PDF few thousand examples · minutes–hours
Like a student: school gives general knowledge once, then short coaching prepares you for one specific exam.

For each task, BERT uses a different part of its output:

Demo · Which output is used?

Only the [CLS] vector goes to a small classifier. Example: is this SMS fraud or not?

finetune_classifier.py (outline)
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset

tok = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)

data = load_dataset("csv", data_files={"train": "train.csv", "test": "test.csv"})   # columns: text, label
data = data.map(lambda b: tok(b["text"], truncation=True, padding="max_length", max_length=128), batched=True)

args = TrainingArguments("bert-fraud", num_train_epochs=3, learning_rate=2e-5, per_device_train_batch_size=16)
Trainer(model=model, args=args, train_dataset=data["train"], eval_dataset=data["test"]).train()
Good starting settings: learning rate 2e-5 to 5e-5, 2–4 epochs, batch size 16 or 32, max length 128 (up to 512).

06Try it yourself in Python

You only need two libraries. Run these in Google Colab or Jupyter.

1. Let BERT fill a blank

fill_mask.py
# pip install transformers torch
from transformers import pipeline

fill = pipeline("fill-mask", model="bert-base-uncased")
for p in fill("New Delhi is the capital of [MASK].")[:3]:
    print(p["token_str"], round(p["score"], 3))
india 0.9… (exact scores depend on the model version)

2. Get a meaning vector for each word

embeddings.py
import torch
from transformers import AutoTokenizer, AutoModel

tok = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModel.from_pretrained("bert-base-uncased")

inputs = tok("I love learning AI", return_tensors="pt")
with torch.no_grad():
    out = model(**inputs)

print(out.last_hidden_state.shape)   # one 768-number vector per token
print(out.pooler_output.shape)       # one vector for the whole sentence
torch.Size([1, 6, 768]) torch.Size([1, 768])
Building search or RAG? Plain BERT vectors are not great for comparing sentences. Use a model trained for this, like Sentence-BERT from the sentence-transformers library.

07The BERT family: its variants

After BERT, many teams made improved versions. Each one fixes one weakness: speed, size, accuracy or context length.

2018201920202024 BERT RoBERTatrained longer, better DistilBERTsmaller, faster ALBERTshares weights, light Sentence-BERTfor search & RAG DeBERTasmarter attention ELECTRAefficient training ModernBERT8,192-token context Domain & language versionsFinBERT · BioBERT · mBERT · MuRIL (Indian)
One original model, many specialised children.
ModelMade byWhat is differentUse it when
RoBERTa (2019)Facebook AINo NSP, dynamic masking, trained much longer on ~10× more data (160 GB)You want better accuracy at the same size
DistilBERT (2019)Hugging FaceLearns from BERT (distillation): 6 layers, ~40% smaller, ~60% faster, keeps ~97% of the accuracyYou need speed, CPU or mobile
ALBERT (2019)GoogleShares weights across layers; sentence-order task instead of NSPMemory is limited
Sentence-BERT (2019)UKP LabTrained so similar sentences get similar vectorsSemantic search, clustering, RAG
ELECTRA (2020)Google & StanfordSpots replaced words instead of filling blanks; learns from every tokenYou pre-train on a small budget
DeBERTa (2020)MicrosoftKeeps word meaning and position separate inside attentionYou want top accuracy
ModernBERT (2024)Answer.AI & LightOn8,192-token context, trained on ~2 trillion tokens including codeLong documents, code search

For special domains and Indian languages

08BERT vs GPT: what is the difference?

Both come from the same Transformer family, but they take opposite halves of it.

BERT · Encodersees every word, both sides my card [MASK] today ✓ Understand: “blocked” GPT · Decodersees only previous words my card is next → ? ✓ Write: “blocked”, then more
BERT is the reader. GPT is the writer.
BERTGPT
Transformer partEncoder onlyDecoder only
Reads textBoth directions at onceLeft to right
Training gameFill in hidden wordsPredict the next word
Best atUnderstanding: classify, extract, searchGenerating: chat, write, code
Size66 million – 400 million parametersBillions of parameters
Running costCheap and fast, even on CPUUsually needs GPUs or a paid API
Real-world tip: many companies use both together. A small BERT-style model quickly sorts, routes or searches, and an LLM writes the final reply. This saves a lot of money.

09Where BERT is used, and its limits

Where BERT shines

Limitations to remember

10Quick quiz: check your understanding

1. Which part of the Transformer does BERT use?

2. How many tokens does BERT choose to predict during pre-training?

3. To classify a whole SMS as fraud or not, which output do we use?

4. You need a fast BERT that runs on a normal CPU. Which one?

5. What did RoBERTa change?

11Summary

12References

Created by Ajeetkumar