Vol. 10 · ML & Decision Systems

BERT, Encoders & Non-Generative Models

Taxonomy of transformer architectures: encoder-only, decoder-only, encoder-decoder. How BERT works and why bidirectional is better to understand. BERT family. Fine-tuning patterns. T5 and seq2seq. When a small specialized model beats GPT-4. A practical map for choosing an architecture for a task.

Retrieval answer

Taxonomy of transformer architectures: encoder-only, decoder-only, encoder-decoder. How BERT works and why bidirectional is better to understand. BERT family. Fine-tuning patterns. T5 and seq2seq. When a small specialized model beats GPT-4. A practical map for choosing an architecture for a task. All modern NLP models are built on transformers, but they are designed fundamentally differently.

01

Taxonomy: three families of architectures

3 cards
01TaxonomyThree families of transformers: what each one can do1 visual1 source note

All modern NLP models are built on transformers, but they are designed fundamentally differently. The difference is not in “power” - but in how the model sees the text and what it can do with this knowledge. The choice of architecture is the first and most important engineering choice.

Source-complete noteskey selection principle

key selection principle

  • understand text → encoder-only
  • convert A→B→encoder-decoder
  • generate freely → decoder-only
  • LLM can do all three - but it’s expensive and slow
02TaxonomyUnderstanding vs Generation: Different Tasks1 source note

“Understand” and “generate” are fundamentally different operations, and the architectures are optimized for each. Encoder reads everything at once and builds a deep understanding. Decoder only reads the past and predicts the future.

Source-complete notesoperations and architecture
operations and architecturetext
Understanding (encoder):
  input: complete sentence
  attention: each token sees ALL others
  output: enriched vectors of each token
  → perfect for “what does this word mean here?”

Generation (decoder):
  input: everything that has happened so far
  attention: causal mask - only the past
  output: next token
  → perfect for “what’s coming next?”

Analogy:
  Encoder = editor: reads the entire text,
            understands every word in the context of everything

  Decoder = writer: writes word by word,
            each word knows only the previous ones
03TaxonomyWhat does “not an LLM” mean: small vs large1 source note

"LLM" is an informal term for large decoder-only models. Encoder models are not LLMs not because they are bad, but because they solve other problems. BERT-base (110M parameters) vs GPT-4 (~1T) is not a “small LLM”, it is a different tool.

Source-complete noteswhat unites all transformer models
what unites all transformer modelstext
What everyone has in common:
  ✓ Architecture: self-attention + MLP + residuals
  ✓ Training: gradient descent + backprop
  ✓ Tokenization: BPE or WordPiece
  ✓ Pretraining on a large text corpus

How are they different:
  ↔ attention direction (uni vs bidirectional)
  ↔ pre-training task (MLM vs CLM)
  ↔ size (110M vs 70B+ parameters)
  ↔ specialization (understanding vs generation)

All of them are neural networks, all of them are transformers.
"LLM" = large decoder, nothing more.
02

How BERT works

4 cards
04BERTMLM: Masked Language Modeling - BERT pre-training task1 visual1 source note

BERT is trained on the “recover a masked token” task. 15% of the tokens are randomly masked, and the model learns to predict them from the remaining ones. Because the model sees context from both sides, it is forced to learn to deeply understand the meaning of words.

Visual model · Formula mapConnect the quantities and operations that determine MLM: Masked Language Modeling - BERT pre-training task.
Source-complete notesmasking details (original BERT)

masking details (original BERT)

  • 80% → [MASK] is replaced by a mask
  • 10% → replaced with a random token
  • 10% → remains as is
  • why not 100% masks: the model learns to “expect” regular tokens too
05BERTBidirectional vs Causal Attention1 visual

The main difference between BERT and GPT is the direction of attention. In BERT, each token can “look” at all others, including future ones. In GPT - only for past ones. This makes BERT better at understanding but unable to generate.

Visual model · MatrixRead Bidirectional vs Causal Attention across the dimensions encoded by rows and columns.
06BERT[CLS], [SEP] and the second NSP pretraining object1 source note

[CLS] is a special token at the beginning of each BERT input. After training, its vector aggregates the meaning of the entire sentence. NSP (Next Sentence Prediction) was the second learning object that forced [CLS] to understand the relationships between pairs of sentences.

Source-complete notesinput format and usage
input format and usagesql
Entry format (one sentence):
  [CLS] Cat sitting on the windowsill [SEP]

Entry format (a couple of sentences):
  [CLS] Question [SEP] Answer [SEP]
  [CLS] Text A [SEP] Text B [SEP]

NSP - pre-training task:
  50%: [CLS] The cat is sitting. [SEP] He's watching. →IsNext
  50%: [CLS] The cat is sitting. [SEP] Borscht recipe. →NotNext
  predict: IsNext / NotNext from h[CLS]

Using [CLS] for fine-tuning:
  h_cls = bert_output[0] ← vector [CLS] token
  logits = Linear(h_cls, num_classes)
  → classification of the entire proposal

RoBERTa: NSP removed → quality increased
07BERTWordPiece: BERT tokenization1 source note

BERT uses WordPiece, a variant of BPE. Rare words are broken into parts with the prefix “##”. This allows you to process unfamiliar words through morphemes and keep a dictionary of a reasonable size (~30k tokens).

Source-complete notestokenization examples
tokenization examplestext
# Frequent words - one token:
"cat" → [cat]
"sits" → [sits]

# Rare words are broken:
"neural network" → [neuro, ##network]
"window sill" → [under, ##con, ##nick]
"tokenization" → [token, ##ization]

# Special tokens:
[CLS] → id: 101 ← beginning, aggregation of meaning
[SEP] → id: 102 ← sentence separator
[MASK]→ id: 103 ← mask for MLM
[UNK] → id: 100 ← unknown token

Vocab size BERT: ~30k (vs GPT-4: ~100k)
→ more fractional tokenization, but morphemic
03

BERT family: evolution and variants

4 cards
08FamilyRoBERTa: BERT without NSP and with more data2 source notes

RoBERTa (2019, Meta) - retrained BERT with better hyperparameters. Three key changes: removed NSP (turned out to be useless), increased the batch by 8 times, trained 10x longer on a larger corpus. The result is a significant increase in all benchmarks.

Source-complete noteswhat changed vs BERT · when to choose RoBERTa vs BERT
what changed vs BERTtext
Removed NSP:
  → BERT was trained to predict the “next sentence”
  → it turned out that this does not help downstream tasks
  → instead: pack full offers to 512 tokens

Dynamic Masking:
  → BERT: masks are fixed during preprocessing
  → RoBERTa: new masks every era
  → the model sees each sentence with different masks

Scale:
  BERT: 16GB of text, 40 epochs, batch 256
  RoBERTa: 160GB of text, batch 8192, longer training

Result: +2-5% on GLUE benchmark

when to choose RoBERTa vs BERT

  • RoBERTa → almost always better than BERT
  • roberta-base: 125M → fast
  • roberta-large: 355M → more precisely
09FamilyDeBERTa: disentangled attention1 source note

DeBERTa (2021, Microsoft) - the best encoder-only for English. Key idea: separate the content of the token and its position in attention. Each pair of tokens has two attention scores: content-to-content and position-to-content.

Source-complete notesdisentangled attention and enhanced mask decoder
disentangled attention and enhanced mask decodertext
Normal attention:
  score(i,j) = (H_i + P_i) · (H_j + P_j)ᵀ
  ↑ content and position mixed

DeBERTa disentangled:
  score(i,j) = H_i·H_jᵀ ← content-to-content
             + H_i·P_{i→j}ᵀ ← content-to-position
             + P_{i→j}·H_jᵀ ← position-to-content
  ↑ relative positions instead of absolute ones

Enhanced Mask Decoder (EMD):
  → for MLM: a special layer returns
     absolute positions before prediction
  → better at guessing disguised tokens

DeBERTa-v3: the best encoder for GLUE/SuperGLUE (2021-2023)
10FamilyXLM-R: multilingual encoder1 source note

XLM-RoBERTa (2020, Meta) - RoBERTa trained in 100 languages simultaneously. The only model understands Russian, English, Chinese and 97 other languages. Zero-shot transfer: train on English data, apply on Russian.

Source-complete noteskey properties
key propertiestext
Training:
  2.5TB of text in 100 languages (Common Crawl)
  vocab: 250k tokens (sentencepiece, multilingual BPE)
  → BERT: 30k monolingual. | XLM-R: 250k multilingual

Zero-shot transfer:
  fine-tune on NER (English)
  → apply in Russian/Chinese/Arabic without additional data
  → works because tokens are in different languages
     have similar embeddings if they mean the same thing

Dimensions:
  xlm-roberta-base: 278M parameters
  xlm-roberta-large: 560M parameters

For Russian NLP: standard baseline
11FamilyModernBERT: BERT in 20241 source note

ModernBERT (late 2024, Answer.AI + LightOn) - a complete rethinking of the encoder architecture using everything we learned in 6 years after BERT: RoPE, Flash Attention, SwiGLU, deep learning on 2T tokens. Beats DeBERTa at smaller sizes.

Source-complete noteswhat's new vs classic BERT
what's new vs classic BERTtext
Architectural improvements:
  ✓ RoPE instead of learned positional embeddings
  ✓ Flash Attention 2 → faster + long contexts
  ✓ GeGLU instead of GELU activation
  ✓ Pre-norm (RMSNorm) as in Llama
  ✓ Context up to 8192 tokens (BERT: 512)
  ✓Alternating local+global attention

Data:
  2T tokens (text + code)
  → understands code - unique to encoder

Dimensions:
  modernbert-base: 149M
  modernbert-large: 395M

→ the best choice for new projects (2025)
04

Fine-tuning patterns for Encoder models

4 cards
12Fine-tuningThree main fine-tuning patterns1 visual1 source note

Encoder models are universal “understanders” of text. A specific problem is solved by adding a small “head” on top of frozen or additionally trained weights. Three patterns cover 90% of real text problems.

Visual model · Formula mapConnect the quantities and operations that determine Three main fine-tuning patterns.
Source-complete noteswhich pattern for which task

which pattern for which task

  • intent/tonality → sequence classification
  • NER, entity extraction → token classification
  • reranking, fact checking → sentence-pair
  • embeddings → no head, take h_cls or mean
13Fine-tuningFine-tuning practice: hyperparameters1 source note

Fine-tuning an encoder model requires much less data and calculations than LLM training. 1000 examples are often enough for a good classification. The main danger is catastrophic forgetting when lr is too high.

Source-complete notestypical hyperparameters
typical hyperparameterssql
from transformers import AutoModelForSequenceClassification

model = AutoModelForSequenceClassification.from_pretrained(
  "roberta-base",
  num_labels=5
)

Recommended hyperparameters:
  lr: 2e-5 – 5e-5 ← low! don't break pretrain
  batch_size: 16 – 32
  epochs: 3 – 5 ← retraining quickly
  warmup: 6% steps
  weight_decay: 0.01

Data:
  100+ examples → works
  1000+ examples → good
  10k+ examples → excellent
14Fine-tuningFine-tune encoder vs Prompt LLM: when and what1 source note

It is easier to launch LLM through a prompt, but it is expensive and slow at large volumes. Fine-tuned encoder is smaller, faster, cheaper - and often more accurate for a specific task. The choice depends on the volume of traffic, data availability and latency requirements.

Source-complete notestable
Fine-tuned EncoderLLM (prompting)
Dataneed 100–10k examples0 (zero-shot)
Latency2–20ms200–2000ms
Cost~$0.00001/request~$0.001–0.01/request
Accuracy on taskhigh (specialization)average (overall)
Flexibilityonly one taskany task
Supportneed MLOpsAPI
15Fine-tuningKnowledge Distillation: small = fast1 source note

Distillation is training a small “student” model to copy the behavior of a large “teacher” model. DistilBERT has 66% of BERT parameters, is 60% faster and maintains 97% quality. Ideal for production with strict latency requirements.

Source-complete notesmechanics of distillation
mechanics of distillationtext
Teacher: BERT-large (340M), accurate
Student: DistilBERT (66M), fast

Student Loss = combination of three goals:
① Distillation loss:
  KL(softmax(logits_student / T) ‖ softmax(logits_teacher / T))
  T=temperature→ soft probabilities = “dark knowledge”

② Cosine embedding loss:
  hidden states of student ≈ teacher

③ MLM loss:
  standard training on masked tokens

Popular distilled models:
  DistilBERT: 66M, 60% faster, 97% BERT quality
  TinyBERT: 15M, 9.4× faster, 96% quality
  MobileBERT: 25M, edge deployment
05

Encoder-Decoder: T5, BART and Seq2Seq

3 cards
16Encoder-DecoderSeq2Seq: encoder understands, decoder creates1 visual1 source note

Encoder-decoder is an original transformer architecture from Attention Is All You Need. Encoder reads the entire input (bidirectional), builds its representation; decoder generates output using cross-attention to encoder representations. Ideal for "convert A to B" tasks.

Visual model · Concept treeTrace the hierarchy and branches that make up Seq2Seq: encoder understands, decoder creates.
Source-complete notesproblems where seq2seq is better than decoder-only LLM

problems where seq2seq is better than decoder-only LLM

  • machine translation (fixed languages)
  • summation with length control
  • grammatical correction
  • extracting structure from text
  • requires more memory than encoder-only
17Encoder-DecoderT5: «Text-to-Text Transfer Transformer»1 source note

T5 (2020, Google) - unified frame: ALL tasks are formulated as “text → text”. Translation: “translate English to German: The cat...”. Summarize: “summarize: …”. This allows you to train one model on everything at once.

Source-complete notestext-to-text frame
text-to-text frametext
# All tasks are in the same format:
"translate English to Russian: Hello world"
  → "Hello world"

"summarize: [long text...]"
  → "Summary: ..."

"sst2 sentence: I love this movie"
  → "positive"

"cola sentence: The cat sat"
  → "acceptable"

FLAN-T5 (2022):
  → T5 + instruction tuning on 1000+ tasks
  → follows instructions like LLM, but less
  → flan-t5-large (780M) vs GPT-3 (175B)
  → wins on structured generation
18Encoder-DecoderBART: denoising pretraining1 source note

BART (2020, Meta) - encoder-decoder with pre-training through denoising: the input is deliberately “spoilt” (fragments are removed, sentences are rearranged, spans are masked), the decoder learns to restore the original. Particularly good for summarization.

Source-complete notesdenoising tasks during training
denoising tasks during trainingsql
Original: "The cat sat on the warm windowsill and watched"

Token masking: "The cat [M] was on the [M] windowsill watching"
Token deletion: "The cat was watching on the warm windowsill"
Text infilling: "The cat [M M M] was looking" ← one [M] = many words
Sentence permut: "I looked. The cat was sitting on the windowsill and"
Document rotation: start from the middle

Why does this help summarization:
  → infilling = generating a missing fragment
  → summarization = generation of a “compressed” fragment
  → structurally similar tasks

mBART: multilingual BART, 25 languages, including ru
06

When a small model beats GPT-4

3 cards
19ComparisonTriangle: Latency · Cost · Accuracy1 visual

Choosing a model is always a compromise of three parameters. GPT-4 is the most powerful in terms of accuracy, but the most expensive and slow. Fine-tuned RoBERTa is the fastest and cheapest. The key question is: How complex is your specific problem?

Visual model · Process flowFollow the sequence behind Triangle: Latency · Cost · Accuracy and locate where work or state changes.
Complete view · 4 layers
20ComparisonProblems where encoder-only reliably wins1 source note

There are categories of tasks where specialized encoder models consistently outperform LLM in all three parameters - not only in speed and price, but also in accuracy. These are tasks with a clear structure and a sufficient amount of training data.

Source-complete notestasks with victory encoder
tasks with victory encodertext
① Classification of intents (IntentRouter):
  fine-tuned RoBERTa: 96.5% F1, 3ms
  claude-haiku prompt: 91.2% F1, 280ms
  → 100x faster, more precisely, 80x cheaper

② NER (Entity Extraction):
  fine-tuned BERT/DeBERTa: F1=0.92
  GPT-4 prompting: F1=0.87
  → encoder is more accurate on clearly labeled data

③ Reranking in RAG:
  cross-encoder reranker: NDCG@10=0.74
  embedding cosine: NDCG@10=0.61
  → cross-encoder sees query+doc together

④ Semantic similarity (deduplication):
  bi-encoder (E5): 50k par/sec
  LLM: 10 pairs/sec
  → scale is not possible with LLM

⑤ Content moderation:
  fine-tuned toxicity classifier: 0.5ms/request
  → should be cheaper than the LLM request itself
21ComparisonCascade pipeline: small + large1 visual

The best strategy is not to choose one model, but to build a cascade: fast specialized models filter and route, LLM is called only where the “heavy artillery” is needed. This is exactly how production systems with high traffic work.

Visual model · Formula mapConnect the quantities and operations that determine Cascade pipeline: small + large.
07

Practical architecture selection map

2 cards
22Selection cardDecision tree: task → architecture → model2 visuals

Structured choice. Start with the type of task, take into account the availability of data and latency requirements - get a specific model recommendation.

Architecture chooserChange the job. The recommended model family must change.

Describe the task and constraints; follow the highlighted decision path.

  1. 01 · jobClassification
  2. 02 · constraintFew labels
  3. 03 · familySmall instruction LLM
Recommended starting pointZero-shot or few-shot instruction modelstructured output · evaluate before fine-tuning

This chooser recommends a model family, not a vendor winner. Data availability, output shape and latency determine the useful architecture.
Visual model · Decision treeFollow the conditions that change the choice in Decision tree: task → architecture → model.
Complete view · 8 layers
23Selection cardQuick Reference: models and their niches2 source notes

A cheat sheet for specific models for quick selection at the start of the project.

Source-complete notestable · all available at
ModelSizeBest use
ModernBERT-base149Mclassification, NER, 2025
DeBERTa-v3-base184MNLI, QA, best EN encoder
RoBERTa-base125Mclassification, fast
XLM-RoBERTa-base278Mmultilingual, including RU
E5-large-v2335Membeddings for EN search
multilingual-e5278Mmultilingual embeddings
bge-reranker-v2-m3568Mreranking RAG
FLAN-T5-large780Mstructured generation
DistilBERT66Medge/mobile deployment

all available at

  • huggingface.co/models
  • pip install transformers
  • sentence-transformers for embeddings

No dead end

Keep moving through the map.

Continue in sequence, switch to a related guide, or return to the seven-track learning map.

Discovery graph / next reads

Continue through New Runtime

Open the graph
  1. 01learning trackMl And Decision SystemsOpen the complete learning track.
  2. 02related materialStatistics for Evaluating LLM SystemsContinue with another guide in this learning track.
  3. 03related materialClassical Machine Learning in Plain EnglishContinue with another guide in this learning track.
  4. 04related materialForecasting, Causal Inference & BanditsContinue with another guide in this learning track.
  5. 05related materialAdvanced RAG: Context & EnrichmentContinue with a related New Runtime material.

These links are also published in this page’s JSON twin and as typed edges in DiscoveryGraph v1.

Who read this page?Machine requests, hidden until opened

Loading the privacy-safe route aggregate…

Open the JSON contract