Monday , November 30 2026
BERT explained: bidirectional encoder, masked language modelling, fine-tuning for classification with Hugging Face, BERT variants and BERT vs LLMs.

BERT Explained: Pre-training, Fine-tuning and Hugging Face Code

Updated: 29 November 2026Level: IntermediateReading time: about 10 minutesHugging Face Transformers

BERT (Bidirectional Encoder Representations from Transformers), released by Google in 2018, changed NLP by pre-training a transformer encoder on huge text and then fine-tuning it for tasks such as classification, NER and question answering.

What You Will Learn

  • Encoder-only vs decoder-only transformers
  • Pre-training: masked language modelling
  • Fine-tuning for classification
  • Use BERT with Hugging Face
  • BERT variants and when to choose BERT vs an LLM

Prerequisites

Transformer Architecture, Word Embeddings.

What Makes BERT Different

BERT GPT-style LLMs
Architecture Encoder only Decoder only
Reads text Both directions at once Left to right
Pre-training task Fill in masked words Predict the next word
Best at Understanding: classify, extract, search Generating text, chat, reasoning
Typical size 110M–340M parameters Billions of parameters

Pre-training

  • Masked language modelling (MLM): 15% of tokens are hidden and the model predicts them from context on both sides.
  • Next-sentence prediction (original BERT): does sentence B follow sentence A? Later variants such as RoBERTa dropped it.
  • Input uses WordPiece tokens with special tokens [CLS] at the start and [SEP] between sentences.
Masked-word prediction (not run here – downloads the model)
from transformers import pipeline
fill = pipeline("fill-mask", model="bert-base-uncased")
for r in fill("Ludhiana is a city in [MASK].")[:3]:
    print(r["token_str"], round(r["score"], 3))

Explanation: BERT scores possible words for the [MASK] position using context on both sides. This is exactly the task it was pre-trained on.

Fine-tune for Classification

Hugging Face Trainer (not run here – needs a GPU; argument names change between versions)
from datasets import load_dataset
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
                          TrainingArguments, Trainer)
name = "distilbert-base-uncased"
ds = load_dataset("imdb")
tok = AutoTokenizer.from_pretrained(name)
ds = ds.map(lambda b: tok(b["text"], truncation=True, max_length=256), batched=True)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
args = TrainingArguments("out", per_device_train_batch_size=16, num_train_epochs=1,
                         learning_rate=2e-5, eval_strategy="epoch")
trainer = Trainer(model=model, args=args, processing_class=tok,
                  train_dataset=ds["train"].shuffle(seed=0).select(range(5000)),
                  eval_dataset=ds["test"].shuffle(seed=0).select(range(2000)))
trainer.train()

Explanation: A classification head is added on top of the [CLS] representation and the whole model is fine-tuned with a small learning rate (2e-5 to 5e-5) for 1–3 epochs. Even on a 5,000-review subset this usually beats TF-IDF models clearly – compare with the sentiment analysis tutorial. Older transformers versions use evaluation_strategy and tokenizer= instead.

BERT Family

Model Why use it
DistilBERT 40% smaller, ~60% faster, keeps most accuracy
RoBERTa Better pre-training, stronger results
ALBERT Parameter sharing, very small
DeBERTa Top accuracy on many benchmarks
XLM-R, MuRIL, IndicBERT Multilingual and Indian languages
Sentence-BERT Sentence embeddings for search
ModernBERT Recent encoder with longer context and faster inference

BERT or an LLM?

  • Choose a BERT-style encoder for high-volume classification, NER, search and on-device use – fast, cheap and accurate after fine-tuning.
  • Choose an LLM for generation, few-shot tasks with no training data, or complex reasoning – see LLM Fundamentals.

Series

NLP series: NLP Intro · Tokenizer · Stop Words · Stemming · Lemmatization · Bag of Words & TF-IDF · Word Embeddings · Sentiment Analysis · NER · Topic Modeling · BERT · Spam Project

Interview Questions

Q: What does bidirectional mean in BERT?
Each token’s representation uses context from both its left and right.

Q: What is masked language modelling?
Randomly hiding tokens and training the model to predict them.

Q: How do you use BERT for classification?
Add a classifier on the [CLS] output and fine-tune the whole model on labelled data.

Practice Exercises

  1. Run the fill-mask example with three sentences about your city.
  2. Fine-tune DistilBERT on 2,000 reviews in Google Colab and compare with TF-IDF + logistic regression.

Summary

BERT is a bidirectional transformer encoder pre-trained with masked language modelling and fine-tuned for understanding tasks. Its variants remain the efficient choice for classification, NER and search.

Next: Hugging Face · LLM Fundamentals

About Machine Learning

Check Also

Sentiment Analysis in Python: ML Model and Transformers

Sentiment analysis in Python with a tested TF-IDF and logistic regression model, why small datasets fail, word coefficients and pre-trained Hugging Face models.