Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

BERT

BERT (Devlin, Chang, Lee and Toutanova, 2019) pre-trains a Transformer encoder on unlabelled text by masked language modelling: 15% of tokens are hidden and predicted from both left and right context. A next-sentence prediction objective is added, and the model is then fine-tuned with one small output layer per task. It set new records on GLUE, SQuAD and many other benchmarks and made pre-train-then-fine-tune the standard recipe in NLP. This page covers the masking scheme, input format, model sizes, fine-tuning and what later work changed. In the exercises you implement BERT's 80/10/10 masking and sentence-pair inputs and count BERT-base's 109,482,240 parameters. You then vary the masking rate for a small encoder: 40% learns fastest (0.857 after 200 steps, near the 0.869 ceiling), ahead of 15% (0.782), 80% (0.671) and 5% (0.424).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Fill in the blanks

BERT learns language by doing millions of fill-in-the-blank exercises: “The pilot [MASK] the engine before take-off.” To guess the hidden word it must use words on both sides. After this practice on billions of words, it is fine-tuned briefly for a specific job, such as answering questions or classifying reports, with only a small labelled set. The demo shows attention patterns: BERT sees in both directions, unlike a left-to-right model.

Transformer lab
Computed pairs: 136 of 256 for 16 tokens. Sparse patterns grow linearly with length instead of quadratically.
Why engineers care

Pre-trained encoders let teams build accurate text classifiers and search tools for maintenance logs, incident reports and manuals from a few hundred labelled examples.

📝 Quick check (Level 0)
0/3 answered
  1. 1. BERT is pre-trained by…
  2. 2. BERT reads context…
  3. 3. After pre-training, BERT is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Architecture: a Transformer encoder.
    • BERT-base: 12 layers, d = 768, 12 heads, 110 M parameters (109,482,240 by exact count with the pooler);
    • BERT-large: 24 layers, d = 1024, 16 heads, 340 M.
  • Input:
    • format [CLS] A [SEP] B [SEP] with WordPiece tokens (about 30,000 types);
    • the embedding is the sum of token, learned position (up to 512) and segment (A or B) embeddings;
    • for a 2-token A and 1-token B the segment ids are 0, 0, 0, 0, 1, 1.
  • Masked LM:
    • choose 15% of tokens: replace 80% of them by [MASK], 10% by a random token, and keep 10%;
    • predict the originals;
    • for 512 tokens, about 61 [MASK]s, 8 random and 8 kept.
  • Next-sentence prediction: classify from the [CLS] output whether B followed A (50%) or is random.
  • Pre-training:
    • BooksCorpus and English Wikipedia (3.3 B words);
    • 1 M steps of 256 sequences, reported as 256 × 512 tokens per batch, about 131 B tokens or 40 epochs (most steps actually used length 128).
  • Fine-tuning:
    • add a linear layer on [CLS] for classification, or on each token for tagging and span prediction;
    • train everything for 2–4 epochs with a small learning rate.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Share of tokens chosen for prediction:
  2. 2. Of chosen tokens, replaced by [MASK]:
  3. 3. BERT-base layers:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

BERT in code

Exercise 1.

  • The masking function chose 15% of tokens and replaced 80% / 10% / 10% of them as specified (within 2%).
  • Sentence-pair inputs and segment ids were correct.
  • The parameter count gave 109,482,240 for BERT-base and 335,141,888 for BERT-large.

Practice.

  • Hugging Face: BertForMaskedLM, BertForSequenceClassification and DataCollatorForLanguageModeling(mlm_probability=0.15), which applies the 80/10/10 rule.
  • Fine-tuning recipe: learning rate 2–5 × 10⁻⁵, batch 16–32, 2–4 epochs, warmup and linear decay. Results vary with the random seed on small datasets, so try several.
  • Why 80/10/10: [MASK] never appears at fine-tuning time. Random and unchanged tokens force the model to keep useful representations for every token.
from transformers import BertTokenizerFast, BertForSequenceClassification
tok = BertTokenizerFast.from_pretrained("bert-base-uncased")
model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=3)
batch = tok(["hydraulic leak on gear", "nominal flight"], padding=True, return_tensors="pt")
loss = model(**batch, labels=torch.tensor([2, 0])).loss
🐍 Exercise 1: BERT inputs and size
Implement 80/10/10 masking, sentence-pair inputs with segment ids, and BERT's parameter count.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Typical BERT fine-tuning learning rate:
  2. 2. Why not always use [MASK]?
  3. 3. Classification uses the output at…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why masking enables bidirectionality. A left-to-right language model cannot see the right context, or it would see the answer. Masking hides the targets instead, so every layer can attend in both directions without leaking. The price is that only the masked 15% of positions give a training signal per pass.

The masking rate is a trade-off.

  • More masks give more prediction targets per sequence, but less visible context for each.
  • Too few masks waste computation; too many make the task ill-posed.
  • Wettig et al. (2023) found 40% better than 15% for BERT-large-sized models. Exercise 2 finds the same inverted U at toy scale.

What later work changed.

  • RoBERTa (E12-5) dropped next-sentence prediction, trained longer on more data and used dynamic masking.
  • SpanBERT masked contiguous spans. ELECTRA (E12-8) learns from all tokens.
  • DeBERTa (E12-9) disentangled content and position.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Masking allows bidirectional attention without…
  2. 2. Who found 40% masking can beat 15%?
  3. 3. RoBERTa dropped…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much should we mask?

History.

  • J. Devlin, M.-W. Chang, K. Lee and K. Toutanova introduced BERT (NAACL 2019). BERT-large raised GLUE to 80.5 and SQuAD v1.1 F1 to 93.2.
  • It built on ELMo’s contextual embeddings (2018) and GPT’s Transformer pre-training (2018).
  • A. Wettig, T. Gao, Z. Zhong and D. Chen asked “Should you mask 15% in masked language modeling?” (EACL 2023).

Exercise 2.

  • Data: sequences of 16 tokens (vocabulary 8) made of a random half followed by its mirror image, so every token can be recovered from its partner.
  • Model: a one-layer bidirectional encoder (d = 32), trained for 200 steps with masked-token prediction at rates 5%, 15%, 40% and 80%, 2 seeds.
  • Evaluation: accuracy on masked tokens at the standard 15% rate. The best possible is 0.869, because the partner is itself masked 15% of the time.
masking rate accuracy after 200 steps (2 seeds) mean
5% 0.417, 0.431 0.424
15% 0.808, 0.756 0.782
40% 0.870, 0.843 0.857
80% 0.674, 0.668 0.671
The code runs seed 0 only, to stay fast in the browser; the second value and the means include seed 1 from a native run.
  • An inverted U, peaking above BERT’s 15%. At 40% the model nearly reaches the 0.869 ceiling in 200 steps.
  • 5% gives too few prediction targets, so learning is slow.
  • 80% hides most partners, so the targets often cannot be inferred.
  • The best rate depends on the data and model: with more training every rate reached the ceiling (all about 0.87 at 400 steps). The comparison is about efficiency, as in Wettig et al.
🐍 Exercise 2 (research): how much should we mask?
Train a small masked language model at masking rates from 5% to 80% and compare learning speed.

BERT in AI, robotics and aerospace

  • Maintenance and safety text: BERT-style encoders classify defect reports, extract components and fault types, and power semantic search over manuals.
  • Domain adaptation: continued masked-LM pre-training on in-domain text (aviation, space operations) before fine-tuning improves accuracy.
  • Deployment: distilled or small encoders (E12-7) run on edge hardware for offline text analysis.

References

  1. J. Devlin, M.-W. Chang, K. Lee, K. Toutanova (2019). “BERT: pre-training of deep bidirectional Transformers for language understanding.” Proc. NAACL.
  2. A. Wettig, T. Gao, Z. Zhong, D. Chen (2023). “Should you mask 15% in masked language modeling?” Proc. EACL.
  3. M. Peters et al. (2018). “Deep contextualized word representations.” Proc. NAACL.