Skip to content

Language models, retrieval, prompting, and language adaptation · Contextual and sentence encoders · LNG013 · Training method

ELECTRA

Pretrains a text encoder by detecting tokens replaced by a small generator. Learning from many token positions increases training-signal density relative to predicting only a masked subset.

Partly runs in CodeSplash Component demo, not a trained model CodeSplash's own run

In CodeSplash

A CodeSplash method covers part of this entry; some options or variants aren't built yet.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Partly runs in CodeSplash
Code example
Component demo, not a trained model
Who ran it
CodeSplash's own run
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Pretrains a text encoder by detecting tokens replaced by a small generator. Learning from many token positions increases training-signal density relative to predicting only a masked subset. The discriminator becomes the transferable representation model.

Question / objective

Can token-replacement detection supply a denser pretraining signal than masked prediction alone?

Architecture / computational structure

A generator proposes replacements and a discriminator predicts whether each token is original. Learned generator/discriminator weights are separate; generator size and masking/replacement settings are hyperparameters.

Assumptions

Replacement artifacts can make discrimination easier than understanding.

Formula / computational definition

LD=−∑i[rilog⁡Dθ(x~,i)+(1−ri)log⁡(1−Dθ(x~,i))].\mathcal L_D=-\sum_i\left[r_i\log D_\theta(\widetilde x,i)+(1-r_i)\log(1-D_\theta(\widetilde x,i))\right].

A generator proposes replacements; a discriminator D_t minimizes -sum_t[y_t log D_t+(1-y_t)log(1-D_t)], where y_t marks whether the observed token is original. The generator usually has its own masked-token loss.

Parameters and notation

Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Generator/discriminator capacity ratio, replacement rate, loss weights, sampling temperature, and tokenization.

Fitting, fine-tuning, and adaptation

Pretrain the discriminator through replaced-token detection alongside generator training; for downstream tasks retain the discriminator and add a task head. Freeze, progressively unfreeze, or use compatible adapters. Validate leakage-free replacement construction and downstream calibration rather than using discriminator loss as perplexity.

How to use and calibrate

Compare downstream transfer per pretraining compute and inspect shortcut sensitivity, not merely replacement-detection accuracy. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.

Example application

Initialize a token classifier when pretraining compute is limited.

Interpretation / pitfalls

Watch out

A generator that is too weak or too strong changes the task; unlike standard GANs, the sampled text is not normally trained by propagating discriminator gradients through discrete samples. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.

Python and R code examples

Full implementation route: Transformers supports ELECTRA architectures. Reproducing pretraining requires a coupled corruption/generation pipeline; R can orchestrate it through reticulate or implement both losses natively.

Example scope: ELECTRA replaced-token binary cross-entropy; labels here mean original=1.

Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.

Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — ELECTRA replaced-token binary cross-entropy; labels here mean original=1.

Shared setup for this chapter
import math

def softmax(xs):
    m = max(xs)
    es = [math.exp(x-m) for x in xs]
    return [e/sum(es) for e in es]

def dot(a, b):
    return sum(x*y for x, y in zip(a, b))

def matvec(matrix, vector):
    return [dot(row, vector) for row in matrix]

def meanvec(rows):
    return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]

def sigmoid(x):
    return 1/(1+math.exp(-x))

def nll(probabilities):
    return -sum(math.log(p) for p in probabilities)
original = [1, 0, 1]
p_original = [0.8, 0.3, 0.7]
loss = -sum(y * math.log(p) + (1-y) * math.log(1-p) for y, p in zip(original, p_original)) / 3
print(loss)
R

Component demo, not a trained model — ELECTRA replaced-token binary cross-entropy; labels here mean original=1.

Shared setup for this chapter
softmax <- function(x) {
  shifted <- exp(x-max(x))
  shifted/sum(shifted)
}
original <- c(1,0,1); p_original <- c(0.8,0.3,0.7)
loss <- -mean(original*log(p_original) + (1-original)*log(1-p_original))
print(loss)

Sources

From the CodeSplash reference, entry LNG013.