AI Logic

Architectures

ELECTRA

Updated:

ELECTRA pre-training. Left: the overall flow (part of the original sentence is masked with [MASK], the generator picks words to fill them in, and the discriminator decides at every position whether the word is original or replaced). Right: the difference from BERT (computing the loss only at the masked 15% versus at every position), the loss formula, and how the generator and discriminator are connected

Background and Overview

ELECTRA (Efficiently Learning an Encoder that Classifies Token Replacements Accurately) is a language model pre-trained on the task of predicting, at every position, which input words have been replaced by other words. It was proposed by Clark et al. at Stanford University and Google Brain in 2020 and presented at ICLR 2020.

The masked language model of BERT masks 15% of the input and predicts the original words. With this approach, only the masked 15% of positions in each sentence provide a learning signal, and the remaining 85% contribute nothing. As a result, good performance required a large amount of compute.

ELECTRA changes the task to replaced token detection.

  • A small masked language model (the generator) fills the masked positions with plausible words to corrupt the sentence.
  • The main model (the discriminator) predicts, for every position, whether the word is the original or a replacement.

Because it learns from every position, it learns far better representations than BERT at the same compute. The main results of the paper are:

  • ELECTRA-Small (14M parameters), trained for 4 days on a single GPU, scores 79.9 on the GLUE dev set. It beats BERT-Small (75.1) trained with the same compute by nearly 5 points, and also beats GPT (78.8), which used about 30× more compute
  • ELECTRA-Large matches RoBERTa and XLNet with less than 1/4 of their compute, and outperforms them with comparable compute
  • F1 of 91.4 on the SQuAD 2.0 test set (single model)

Architecture

ELECTRA trains two networks jointly: a generator and a discriminator. Both are Transformer encoders, like BERT. The left side of the figure at the top of the article shows the pre-training flow, and the right side shows how it differs from BERT.

  • Generator: A small masked language model. It outputs word probabilities at the masked positions and picks one word according to those probabilities (sampling).
  • Discriminator: This is the ELECTRA model itself. It applies a sigmoid output layer to the output at each position and outputs the probability that the word at that position is the original.

After pre-training, the generator is thrown away, and only the discriminator is fine-tuned on downstream tasks. The discriminator's architecture and most settings are the same as BERT's.

The three sizes in the paper are:

ModelLayersHidden sizeHeadsEmbedding sizeGenerator sizeParameters
ELECTRA-Small1225641281/4 of the discriminator14M
ELECTRA-Base12768127681/3 of the discriminator110M
ELECTRA-Large2410241610241/4 of the discriminator335M

Generator size indicates the fraction of the discriminator's hidden size, feed-forward intermediate size, and number of heads used by the generator.

The generator and discriminator share token and positional embeddings. The discriminator can update only the embeddings of words that appear in the input or are sampled by the generator, whereas the generator computes a softmax over the whole vocabulary and can therefore update every word's embedding. Sharing embeddings lets the generator's training benefit the discriminator's embeddings as well.

Training: Replaced Token Detection

ELECTRA pre-training proceeds as follows for a sentence x=[x1,…,xn]\boldsymbol{x} = [x_1, \dots, x_n].

  1. Randomly select kk positions (typically 15% of the total, k=⌈0.15n⌉k = \lceil 0.15 n \rceil). Call the set of selected positions m\boldsymbol{m}.
  2. Replace the words at the selected positions with [MASK] to obtain xmasked\boldsymbol{x}^{\mathrm{masked}}.
  3. The generator outputs word probabilities pGp_G at each masked position and samples a word x^i\hat{x}_i from them.
  4. Replace the masked positions with x^i\hat{x}_i to form the corrupted sentence xcorrupt\boldsymbol{x}^{\mathrm{corrupt}}.
  5. The discriminator predicts, for every position in xcorrupt\boldsymbol{x}^{\mathrm{corrupt}}, whether the word matches the original sentence.
  6. The generator loss and the discriminator loss are summed, and both networks are updated together.

The probability that the generator outputs word xtx_t at masked position tt is given below, using the token embedding ee and the generator output hGh_G.

pG(xt∣x)=exp⁡(e(xt)⊤hG(x)t)∑x′exp⁡(e(x′)⊤hG(x)t)p_G(x_t \mid \boldsymbol{x}) = \frac{\exp\left(e(x_t)^\top h_G(\boldsymbol{x})_t\right)}{\sum_{x'} \exp\left(e(x')^\top h_G(\boldsymbol{x})_t\right)}

The probability that the discriminator judges the word at position tt to be "original" is:

D(x,t)=sigmoid(w⊤hD(x)t)D(\boldsymbol{x}, t) = \mathrm{sigmoid}\left(w^\top h_D(\boldsymbol{x})_t\right)

The generator loss is the standard masked language modeling loss of predicting the original words at the masked positions.

LMLM=E(∑i∈m−log⁡pG(xi∣xmasked))\mathcal{L}_{\mathrm{MLM}} = \mathbb{E}\left(\sum_{i \in \boldsymbol{m}} -\log p_G(x_i \mid \boldsymbol{x}^{\mathrm{masked}})\right)

The discriminator loss is the binary cross-entropy over all positions.

LDisc=E(∑t=1n−1(xtcorrupt=xt)log⁡D(xcorrupt,t)−1(xtcorrupt≠xt)log⁡(1−D(xcorrupt,t)))\mathcal{L}_{\mathrm{Disc}} = \mathbb{E}\left(\sum_{t=1}^{n} -\mathbb{1}(x^{\mathrm{corrupt}}_t = x_t) \log D(\boldsymbol{x}^{\mathrm{corrupt}}, t) - \mathbb{1}(x^{\mathrm{corrupt}}_t \neq x_t) \log\left(1 - D(\boldsymbol{x}^{\mathrm{corrupt}}, t)\right)\right)

The combined loss is minimized over a large text corpus X\mathcal{X}.

min⁡θG,θD∑x∈XLMLM(x,θG)+λLDisc(x,θD)\min_{\theta_G, \theta_D} \sum_{\boldsymbol{x} \in \mathcal{X}} \mathcal{L}_{\mathrm{MLM}}(\boldsymbol{x}, \theta_G) + \lambda \mathcal{L}_{\mathrm{Disc}}(\boldsymbol{x}, \theta_D)

The paper uses λ=50\lambda = 50. Because the discriminator loss is binary classification, it tends to be much smaller than the generator loss, which is classification over a 30,000-word vocabulary, so a large weight balances the two.

Positions where the generator happens to pick the original word are treated as "original," not "replaced." In the figure's example, the generator put the same word "chef" back into the masked "chef" position, so the correct label at that position is "original." The paper reports that this treatment slightly improves downstream results.

The pre-training settings in the paper are as follows (nearly the same as BERT).

ItemSmallBaseLarge
DataWikipedia and BooksCorpus (3.3B tokens)Same as SmallSame data as XLNet (33B tokens)
Mask ratio15%15%25%
Batch size1282562,048
Steps1M766K400K (1.75M for the longer-trained model)
Learning rate5×10−45 \times 10^{-4}2×10−42 \times 10^{-4}2×10−42 \times 10^{-4}

The optimizer is Adam (β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−6\epsilon = 10^{-6}) with weight decay 0.01, a warmup over the first 10,000 steps, and linear decay afterward. Dropout is 0.1. Following RoBERTa, masks are re-sampled for every input, and next sentence prediction is not used. The mask ratio for Large was raised to 25% because at 15% the generator was so accurate that very few words were actually replaced.

Why It Is Efficient

ELECTRA's efficiency comes mainly from two sources.

  • It learns from every position: A masked language model learns only from the masked 15% of positions, but ELECTRA's discriminator decides "original or replaced" at every position, so each sentence yields more learning signal.
  • No [MASK] mismatch: BERT sees the [MASK] symbol during pre-training but never during fine-tuning. ELECTRA's discriminator receives natural sentences in which words have been replaced with plausible ones, so this mismatch does not exist.

To measure how much each factor contributes, the paper compares tasks intermediate between BERT and ELECTRA (see the table in the Experimental Results section). Computing the discriminator loss only at the masked 15% of positions drops the GLUE score to about BERT's level. On the other hand, a masked language model that merely inserts generator words instead of [MASK] is only slightly better than BERT. The paper concludes that most of the improvement comes from learning from every position, and that resolving the [MASK] mismatch contributes only a little.

It can be likened to a spot-the-error quiz. BERT's task is fill-in-the-blank, "fill in the 15% of blanks in a sentence," and the rest of the sentence is only read. ELECTRA's task is spot-the-error, "find the plausible mistakes hidden in the sentence," which requires asking "is this correct?" for every word. Even when reading the same sentence, more thinking means more learning.

There is also a reason to keep the generator small. In the paper's experiments, the best results came when the generator was 1/4 to 1/2 the size of the discriminator. The paper speculates that a generator that is too strong produces replacements so natural that the discriminator's task becomes too hard to learn well. A small generator also keeps the per-step compute down.

The generator–discriminator setup resembles a GAN, but ELECTRA is not trained adversarially. The generator does not try to fool the discriminator; it is trained as an ordinary masked language model, and the discriminator loss is not backpropagated into the generator (because the sampling step that picks words is not differentiable). The paper also tried training the generator adversarially with reinforcement learning, but the generator's masked language modeling accuracy fell from 65% to 58%, the diversity of sampled words was lost, and results got worse.

Experimental Results

Small models (GLUE dev set; training compute is pre-training FLOPs)

ModelTraining computeParametersTraining time and hardwareGLUE
ELMo3.3×10183.3 \times 10^{18}96M14 days on 3 GTX 1080 GPUs71.2
GPT4.0×10194.0 \times 10^{19}117M25 days on 8 P6000 GPUs78.8
BERT-Small1.4×10181.4 \times 10^{18}14M4 days on 1 V100 GPU75.1
BERT-Base6.4×10196.4 \times 10^{19}110M4 days on 16 TPU v3 chips82.2
ELECTRA-Small1.4×10181.4 \times 10^{18}14M4 days on 1 V100 GPU79.9
ELECTRA-Small (25% trained)3.6×10173.6 \times 10^{17}14M1 day on 1 V100 GPU77.7
ELECTRA-Base6.4×10196.4 \times 10^{19}110M4 days on 16 TPU v3 chips85.1

BERT-Small and ELECTRA-Small use the same settings and the same compute. ELECTRA-Base also outperforms BERT-Large (84.0).

Large models (GLUE dev set; compute relative to ELECTRA-400K = 1)

ModelTraining computeCoLASST-2MRPCSTS-BQQPMNLIQNLIRTEAvg.
BERT0.2760.693.288.090.091.386.692.370.484.0
RoBERTa (100K steps)0.9066.195.691.492.292.089.394.082.787.9
RoBERTa (500K steps)4.568.096.490.992.192.290.294.786.688.9
XLNet5.469.097.090.892.292.390.894.985.989.1
BERT (paper's reimplementation)167.095.989.191.291.589.693.579.587.2
ELECTRA (400K steps)169.396.090.692.192.490.594.586.889.0
ELECTRA (1.75M steps)4.469.196.990.892.692.490.995.088.089.5

ELECTRA (400K steps) matches RoBERTa (500K steps) and XLNet with less than 1/4 of their compute, and ELECTRA (1.75M steps), trained with comparable compute, outperforms them. On the GLUE test set (leaderboard), it also scores 89.4, beating RoBERTa's 88.1.

SQuAD (single model; EM / F1)

ModelTraining computeSQuAD 1.1 (dev)SQuAD 2.0 (dev)SQuAD 2.0 (test)
BERT-Base0.0980.8 / 88.5——
ELECTRA-Base0.0984.5 / 90.880.5 / 83.3—
RoBERTa (500K steps)4.588.9 / 94.686.5 / 89.486.8 / 89.8
ALBERT4489.3 / 94.887.4 / 90.288.1 / 90.9
ELECTRA (400K steps)188.7 / 94.286.9 / 89.6—
ELECTRA (1.75M steps)4.489.7 / 94.988.0 / 90.688.7 / 91.4

ELECTRA is especially strong on SQuAD 2.0. The paper suggests this may be because distinguishing unanswerable questions resembles its pre-training task of distinguishing plausible fakes.

What contributes (Base size, GLUE dev set)

Pre-training taskDescriptionGLUE
ELECTRADetect replacements at every position85.0
All-Tokens MLMReplace with generator words and predict the original word at every position84.3
Replace MLMInsert generator words instead of [MASK] and predict the original words at the masked positions82.4
ELECTRA 15%Compute the discriminator loss only at the masked 15% of positions82.4
BERTStandard masked language model82.2

Weight sharing between generator and discriminator (same size, 500K steps): 83.6 with no sharing, 84.3 with shared token embeddings, and 84.4 with all weights shared. Sharing all weights gives only a small gain while forcing the generator to be the same size as the discriminator, a significant drawback, so ELECTRA shares only the embeddings.

Practical Considerations

Keep the following points in mind when using ELECTRA.

  • Fine-tune the discriminator: Released models come in two kinds, generator and discriminator. Use the discriminator for downstream tasks. The generator is a small masked language model useful only for filling in blanks.
  • Not for fill-in-the-blank (masked language modeling): The discriminator is trained to predict "original or replaced," so it cannot predict the word at a [MASK] position the way BERT can.
  • Keep the generator small: When pre-training yourself, make the generator 1/4 to 1/2 the size of the discriminator. An overly large generator makes the discriminator's training harder and lowers results.
  • The smaller the model, the bigger the gain: In the paper, the gap over BERT grows as the model gets smaller. ELECTRA is especially suited to limited compute budgets.
  • Fine-tuning settings: For Base, the paper searches learning rates from 3×10−53 \times 10^{-5} to 1.5×10−41.5 \times 10^{-4} along with layer-wise learning rate decay (smaller learning rates for layers closer to the input). The same settings as BERT are not necessarily optimal.

ELECTRA's efficiency concerns pre-training compute. Inference speed is the same as a BERT of the same size. For faster inference, choose a small model such as DistilBERT or ELECTRA-Small. Also, because the generator runs alongside, the per-step compute is higher than for a BERT of the same size.

Comparison with Other Models

Comparing BERT and its improved variants from the same perspective gives the following.

ModelPre-training taskPositions that provide the learning signalAim of the improvementUse on downstream tasks
BERTMasked language model + next sentence predictionMasked 15%(Baseline)Fine-tune the whole model
RoBERTaMasked language modelMasked 15%Training recipe and data volumeSame as above
ALBERTMasked language model + sentence order predictionMasked positionsFewer parametersSame as above
DistilBERTImitating a teacher + masked language modelMasked positions (plus imitating the teacher's outputs)Faster inferenceSame as above
ELECTRAReplaced token detectionAll positionsPre-training compute efficiencyFine-tune the discriminator

Guidelines for choosing:

  • Pre-training from scratch with limited compute: ELECTRA is a good fit. Even ELECTRA-Small, trained for a few days on a single GPU, beats GPT.
  • Improving classification or question answering accuracy with a pre-trained model: At the same size, ELECTRA can be expected to match or beat BERT and RoBERTa. It is especially strong on tasks that require deciding whether an answer exists, such as SQuAD 2.0.
  • Fill-in-the-blank or text generation: ELECTRA's discriminator is not suitable. Use BERT or RoBERTa for fill-in-the-blank, and a decoder model such as GPT-2 for generation.

PyTorch example

Show code
python
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, ElectraForPreTraining, ElectraForSequenceClassification

"""
1. Replaced token detection loss, written to follow the paper's equations
2. Finding replaced words with a pre-trained ELECTRA discriminator
3. Fine-tuning the discriminator for sentence classification
"""

def electra_loss(gen_logits, disc_logits, input_ids, masked_ids, mask_pos, lam=50.0):
  """
  gen_logits:  [B, n, vocab size]  Generator output (given the masked sentence masked_ids)
  disc_logits: Function that calls the discriminator. Takes the corrupted sentence and returns [B, n] scores
  input_ids:   [B, n]  Original sentence
  mask_pos:    [B, n]  True at masked positions
  """
  # Generator loss L_MLM: predict the original words at the masked positions
  loss_mlm = F.cross_entropy(gen_logits[mask_pos], input_ids[mask_pos])
  # Fill the masked positions with words sampled from the generator's probabilities (sampling is not differentiated)
  with torch.no_grad():
    sampled = torch.distributions.Categorical(logits=gen_logits[mask_pos]).sample()
  corrupt = input_ids.clone()
  corrupt[mask_pos] = sampled
  # Positions where the original word was sampled are "original" (label 0); different words are "replaced" (label 1)
  is_replaced = (corrupt != input_ids).float()
  # Discriminator loss L_Disc: binary cross-entropy at every position
  # (In the paper, D is the probability of "original"; here, as in Hugging Face, the score is the probability of "replaced")
  loss_disc = F.binary_cross_entropy_with_logits(disc_logits(corrupt), is_replaced)
  return loss_mlm + lam * loss_disc

# Shape check only (in practice, the generator and discriminator are Transformer encoders that share embeddings)
B, n, V = 2, 10, 30522
input_ids = torch.randint(1000, V, (B, n))
mask_pos = torch.rand(B, n) < 0.15
mask_pos[:, 0] = True                              # Mask at least one position
masked_ids = input_ids.masked_fill(mask_pos, 103)  # 103 = [MASK]
gen_logits = torch.randn(B, n, V, requires_grad=True)
disc_head = torch.nn.Embedding(V, 1)               # Tiny stand-in for the discriminator (for shape checking)
loss = electra_loss(gen_logits, lambda ids: disc_head(ids).squeeze(-1), input_ids, masked_ids, mask_pos)
loss.backward()
print(loss.item())

# --- Finding replaced words with the pre-trained discriminator ---
name = "google/electra-small-discriminator"        # Use the discriminator for fine-tuning
tokenizer = AutoTokenizer.from_pretrained(name)
disc = ElectraForPreTraining.from_pretrained(name)
disc.eval()
inputs = tokenizer("The chef ate the meal.", return_tensors="pt")   # The original sentence is "The chef cooked the meal."
with torch.no_grad():
  scores = disc(**inputs).logits[0]               # Per-position scores. Greater than 0 means "replaced"
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
print([(t, round(float(s), 2)) for t, s in zip(tokens, scores)])

# --- Fine-tuning the discriminator for sentence classification ---
clf = ElectraForSequenceClassification.from_pretrained(name, num_labels=2)
optimizer = torch.optim.AdamW(clf.parameters(), lr=1e-4)   # The paper reports a larger learning rate works better for Small
batch = tokenizer(["I loved this movie.", "The plot was boring."], padding=True, return_tensors="pt")
labels = torch.tensor([1, 0])
clf.train()                                        # Enable dropout
out = clf(**batch, labels=labels)
out.loss.backward()
optimizer.step()
optimizer.zero_grad()
clf.eval()

FAQ

Q. What is the difference between ELECTRA and BERT?
A.

The architecture is nearly the same; the pre-training task differs. BERT is trained as a masked language model that predicts the masked 15% of words, while ELECTRA is trained to detect, at every position, the words replaced by a small generator. Because it learns from every position, ELECTRA gives better results at the same compute (GLUE 82.2 → 85.1 at Base size in the paper).

Q. Is ELECTRA the same as a GAN?
A.

The form, with a generator and a discriminator, is similar, but training differs. ELECTRA's generator does not try to fool the discriminator; it is trained as an ordinary masked language model. Since the word-sampling step is not differentiable, the discriminator loss is not passed to the generator. Also, if the generator picks the original word, that position is treated as "real."

Q. Can ELECTRA fill in blanks?
A.

Not with the main discriminator. The discriminator only predicts whether each word is "original or replaced" and has no output layer for predicting the original word. The generator trained alongside it during pre-training is a small masked language model and can fill in blanks, but its accuracy is not high. For fill-in-the-blank, use BERT or RoBERTa.

References

  1. Clark, K., Luong, M.-T., Le, Q. V., & Manning, C. D. (2020). ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators. ICLR 2020. arXiv:2003.10555.
  2. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. arXiv:1810.04805.
  3. Google Research. ELECTRA (official implementation and pre-trained models).
  4. Hugging Face. Transformers documentation: ELECTRA.