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

ELECTRA

ELECTRA (Clark, Luong, Le and Manning, ICLR 2020) replaces masked language modelling with replaced-token detection. A small generator, trained as a masked LM, fills masked positions with plausible tokens, and the main model, a discriminator, classifies every token as original or replaced. Because the discriminator learns from all positions rather than 15%, ELECTRA reached BERT-level accuracy with a fraction of the compute; the discriminator is what gets fine-tuned. This page covers the generator–discriminator setup, losses, sizes and efficiency. In the exercises you implement ELECTRA's corruption and loss, then pre-train small encoders with masked LM or replaced-token detection and fine-tune them on two downstream tasks. Both beat training from scratch, and each wins the task closest to its own objective: masked LM 0.831 against 0.544 on token recovery, replaced-token detection 0.891 against 0.605 on corruption detection.

Level 0: Foundation

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

Spot the fake word

BERT practises by filling in blanks, but only 15% of words are blanks, so most of each sentence teaches it nothing. ELECTRA plays a different game. A small helper model swaps some words for plausible fakes (“the pilot cooked the engine”), and the main model checks every word: real or fake? Every word now gives a lesson, so it learns faster for the same compute. The demo shows bidirectional attention, which the detector uses to judge each word in context.

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

Compute-efficient pre-training lets smaller teams build strong domain encoders (for example on aerospace or maintenance text) with modest hardware.

📝 Quick check (Level 0)
0/3 answered
  1. 1. ELECTRA's main model predicts for each token…
  2. 2. The replacements come from…
  3. 3. ELECTRA learns from…

Level 1: Beginner

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

By hand

  • Generator:
    • a small masked LM;
    • mask 15% of tokens and sample replacements from its predictions;
    • a sample equal to the original counts as original. If the generator reproduces the original 40% of the time, 0.15 × 0.6 = 9% of tokens are labelled replaced.
  • Discriminator: an encoder predicting, for every position, whether the token was replaced (binary cross-entropy).
  • Loss:
    • L = L_MLM(generator) + λ · L_disc, with λ = 50;
    • gradients do not flow from the discriminator through the sampling into the generator. It is not a GAN.
  • Signal: the discriminator gets a loss from 100% of positions against 15% for MLM, 6.7 times more per sequence.
  • Sizes:
    • generators of 1/4–1/2 the discriminator’s width worked best (192 for 768);
    • too strong a generator makes the task too hard early on;
    • a quarter-width generator adds only about 1/16 to compute.
  • After pre-training, discard the generator and fine-tune the discriminator like BERT.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Ratio of loss positions, RTD to MLM (15%):
  2. 2. Weight λ of the discriminator loss:
  3. 3. Is ELECTRA a GAN?

Level 2: Intermediate

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

ELECTRA in code

Exercise 1.

  • Corrupting [3, 1, 4, 1, 5] with generator samples at masked positions gave labels [0, 0, 1, 0, 1]: a sampled 3 at the first masked position matched the original and counts as original.
  • The total loss with λ = 50 matched its formula.

Practice.

  • Hugging Face ElectraForPreTraining is the discriminator (per-token logits); ElectraForSequenceClassification is used for fine-tuning.
  • Tie the generator’s and discriminator’s token embeddings, as in the paper.
  • ELECTRA-small (14 M parameters) trained on one GPU for 4 days beat GPT on GLUE, and ELECTRA-large matched RoBERTa with about a quarter of its compute.
gen_logits = generator(masked_ids).logits                       # small MLM
sampled = torch.distributions.Categorical(logits=gen_logits).sample()
corrupt = torch.where(mask, sampled, ids); labels = (corrupt != ids).float()
disc_logits = discriminator(corrupt).logits                     # one logit per token
loss = mlm_loss + 50 * F.binary_cross_entropy_with_logits(disc_logits, labels)
🐍 Exercise 1: replaced-token detection
Implement ELECTRA's corruption with labels, its combined loss and the signal fraction.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The model fine-tuned after pre-training is…
  2. 2. ELECTRA ties…
  3. 3. ELECTRA-small was trained on…

Level 3: Advanced

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

Theory

Why replaced-token detection is efficient.

  • MLM’s loss covers only masked positions, so most computation produces no gradient signal.
  • RTD makes every position a binary prediction with a meaningful label, so each forward pass trains the model at all positions.
  • It also avoids the [MASK] token mismatch between pre-training and fine-tuning: the discriminator always sees real-looking tokens.

The generator’s role.

  • Random replacements are easy to spot (they rarely fit the context), so the discriminator would learn shallow cues.
  • A small MLM generator proposes plausible replacements, making detection require understanding.
  • If the generator is too strong, replacements become indistinguishable early in training and the discriminator struggles.

Objective alignment.

  • Different pre-training tasks favour different downstream skills.
  • Exercise 2 uses random replacements (no generator) and shows each objective transferring best to the task most like itself, while both beat no pre-training.
  • ELECTRA’s paper found its discriminator better than MLM on GLUE overall at equal compute.
📝 Quick check (Level 3)
0/3 answered
  1. 1. RTD avoids the mismatch caused by…
  2. 2. Random replacements are…
  3. 3. A too-strong generator…

Level 4: Expert

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

Does the pre-training objective shape what transfers?

History.

  • K. Clark, M.-T. Luong, Q. Le and C. Manning, “ELECTRA: pre-training text encoders as discriminators rather than generators” (ICLR 2020).
  • Its replaced-token detection idea was reused in DeBERTa-v3 (E12-9).

Exercise 2.

  • Pre-training: one-layer encoders (d = 32) pre-trained for 300 steps on mirrored sequences (E12-4), with masked LM or replaced-token detection. Replacements are random tokens instead of a learned generator, for simplicity.
  • Downstream A, token recovery: predict masked tokens from only 64 labelled sequences.
  • Downstream B, corruption detection: decide whether a sequence is an intact mirror or has one corrupted token, from 512 labelled sequences, with a noisy-OR head.
  • Fine-tuning: 200 steps.
starting point token recovery (64 labelled) corruption detection (512 labelled)
no pre-training 0.165 0.472
masked LM 0.831 0.605
replaced-token detection 0.544 0.891
  • Both pre-trainings beat training from scratch on both tasks. From scratch, neither task is learned with these few labels; chance is 0.125 and 0.5.
  • Each objective transfers best to the task resembling itself: masked LM to recovering tokens, replaced-token detection to spotting corruption.
  • The comparison is about alignment, not ELECTRA’s efficiency claim, which concerns compute at scale and a learned generator. It shows why choosing a pre-training objective close to the target use matters.
🐍 Exercise 2 (research): does the pre-training objective shape what transfers?
Pre-train with masked LM or replaced-token detection and fine-tune on token recovery and corruption detection.

ELECTRA in AI, robotics and aerospace

  • Domain encoders on a budget: ELECTRA-style pre-training on in-domain text gets strong encoders with modest compute.
  • Anomaly detection in text and logs: a replaced-token detector is naturally an “is this token unusual here?” model, useful for spotting odd entries in structured logs.
  • Objective choice: pick pre-training tasks resembling the downstream use (detection, recovery, generation).

References

  1. K. Clark, M.-T. Luong, Q. V. Le, C. D. Manning (2020). “ELECTRA: pre-training text encoders as discriminators rather than generators.” Proc. ICLR.
  2. P. He, J. Gao, W. Chen (2023). “DeBERTaV3: improving DeBERTa using ELECTRA-style pre-training with gradient-disentangled embedding sharing.” Proc. ICLR.