The Illustrated ModernELECTRA: a new pre-training recipe for BERT-like models that classify and embed
TL;DR
This post introduces ModernELECTRA, a pre-training recipe for compact encoders, and the first two models trained with it: EdgeCoder-31M for English and EdgeCoder-Multilingual-61M for 46 languages. Each model was trained on about one trillion tokens and reads up to 8192 tokens. The recipe keeps replaced-token detection, the objective of ELECTRA and DeBERTaV3, and adds one small task that makes the same model usable as a backbone for embeddings.
It first explains the method step by step, with illustrations, and then reports the training data, the results and the usage of the models. Example code is at the end of this post.
Figure 1: boundary-window reconstruction. For every token, the model predicts it from the two hidden states at the borders of a window around it.
Replaced-Token Detection
Most encoders, from BERT to ModernBERT, are trained with masked language modelling: a fraction of the tokens is hidden, and the model reconstructs them. ELECTRA and DeBERTaV3 use a different objective, replaced-token detection (RTD).
The generator replaces tokens. Training starts from an ordinary sentence. A small auxiliary model, the generator, selects some of the tokens and replaces them with tokens that are plausible in the same position. In the example below, "cooked" becomes "ate" and "meal" becomes "dish". The result is still a well-formed sentence, but it is no longer the original one.
Figure 2: the generator replaces some tokens with plausible alternatives.
The encoder classifies every token. The encoder, which is the model being trained, receives only the corrupted sentence. It maps every token to a hidden state, and from each state it predicts whether the token is original or replaced.
Figure 3: replaced-token detection is a binary decision for every token.
This is an efficient training signal. Every token contributes to the loss, not only the masked fraction, and the replacements are close to the original tokens, so the model has to learn fine distinctions in meaning. This is why RTD encoders are the strongest classifiers for their size.
Why RTD Encoders Are Weak Embedding Backbones
The same encoders are known to be weak backbones for embedding models: after the same retrieval fine-tuning, DeBERTaV3-base reaches about half the BEIR score of BERT-base, although it is the better classifier. The reason lies in the objective.
The decision "original or replaced" is one bit per token. To make it, a state has to encode whether its token fits the context, and the objective requires nothing beyond that. It does not ask the final layer to retain the identity of the token at a position or the identities of the tokens around it, so this information can be discarded.
A sentence embedding is usually the average of the final states. If each state retains little more than one bit, the average carries little information about the content of the sentence.
Figure 4: the information that RTD allows a state to discard is the information a pooled embedding needs.
In practice this has meant a choice between an RTD model for classification and a masked-language model for embeddings. ModernELECTRA is designed to remove this choice for compact encoders.
Boundary-Window Reconstruction
ModernELECTRA keeps RTD unchanged as the main objective and adds one auxiliary task, boundary-window reconstruction, which gives the final states a reason to retain their context.
A single window. For a target token, a window of 3 to 12 tokens that contains it is sampled. Only two hidden states are used: the state at the left border of the window and the state at the right border. They are interpolated into one vector, with a larger weight for the border that is closer to the target, and the original token at the target position is predicted from this vector alone.
Two properties of the task are important. The state of the target token is not an input of the reconstruction, so the prediction cannot be read from it. The prediction target is the original token ("cooked"), not the replacement ("ate") that the encoder received.
Figure 5: reconstruction of one token from the two states at the borders of its window.
All tokens at once. During training, the task is applied to every token of the sequence, each with its own randomly sampled window. Every token is therefore a target for some pair of borders, and every state serves as a border for several of its neighbours.
Figure 6: every token is a target, and every token is a boundary.
Effect on the states. A state can be used as a border for any token up to about ten positions to its left or right. It can contribute to the reconstruction only if it carries information about the tokens in this neighbourhood. The final states therefore encode local context in addition to the RTD decision, and their average describes the content of the sentence. This is the information a pooled embedding requires.
Figure 7: states that carry their neighbours produce an informative pooled embedding.
Combined Objective and Training Schedule
Loss weight. The two losses are added, and the window loss is multiplied by a weight of 0.003, so RTD remains the dominant signal. The weight controls a real trade-off: a larger weight improves MTEB and lowers GLUE, and a smaller weight does the opposite. The window task adds one small feed-forward block during training and nothing at inference, so the trained encoder is an ordinary DeBERTa-style model.
Figure 8: the weight of the window loss balances classification against embedding quality.
Generator temperature. The generator is trained first and then frozen. Replacements are sampled from it at a temperature that decreases from 1.5 to about 0.9 during training. Early replacements are more random and easier to detect; later replacements are more plausible, so the task becomes harder as the encoder improves.
Length curriculum. Most of the training is performed on sequences of 512 tokens (about 90% of the training tokens for the English model), followed by shorter phases on long documents at 2048 and 8192 tokens. This keeps most of the compute in the inexpensive short-context phase.
Figure 9: the generator temperature decreases and the sequence length increases over the course of training.
Training Data
Both models were trained on corpora built with the same pipeline.
English corpus. About 1.0T tokens from fourteen sources: web text (FineWeb-Edu), news (CC-News), educational and technical PDFs (FinePDFs-Edu), Wikipedia, books (Project Gutenberg), legal text (Pile of Law), source code (StarCoderData, SciCode), mathematics (Open-Web-Math, AutoMathText), scientific papers (peS2o, arXiv in LaTeX source, PubMed Central Open Access) and Stack Exchange.
Multilingual corpus. About 1.1T tokens in 46 languages and 10 scripts. It contains the whole English corpus as its English part and adds FineWeb-2 web pages for 45 other languages and FinePDFs documents. The languages are English, the official languages of the European Union and their neighbours, with particular attention to Slavic languages, and the largest global markets. The non-English budget is split by temperature sampling, so smaller languages get a larger share than their raw size would give them.
Length stages. Documents are routed by length into three disjoint stages, for sequences of 512, 2048 and 8192 tokens. Web text dominates the first stage (79% of its tokens in English), and the last stage is made mostly of sources with naturally long documents: legal text, full papers, PDFs and books.
Architecture
Both models are DeBERTa-v3-style encoders with disentangled relative attention and a factorized embedding table. They load in transformers as ordinary DeBERTa-v2 checkpoints.
| EdgeCoder-31M | EdgeCoder-Multilingual-61M | |
|---|---|---|
| Layers | 8 | 16 |
| Parameters | 31.0M (14.2M without embeddings) | 61.0M |
| Languages | English | 46 |
| Maximum length | 8192 tokens | 8192 tokens |
Training follows the schedule described above: the generator first, then the short-context phase, then the long-context phases. Each model takes about 210k optimizer steps, with about 5M real tokens in every step.
Results
Natural Language Understanding (NLU)
English: on GLUE, EdgeCoder-31M reaches 86.0. Encoders of the same size reach 83.5 (Ettin-Enc-32m) and 84.6 (MiniLM-L12), and BERT-base, with 3.5 times more parameters, reaches 84.7. The largest gains are on CoLA and RTE.
Multilingual: EdgeCoder-Multilingual-61M reaches 85.1 on GLUE, ahead of mmBERT-small (84.7), which is 2.3 times larger.
| Model | Params | CoLA | SST-2 | MRPC | STS-B | QQP | MNLI | QNLI | RTE | Avg |
|---|---|---|---|---|---|---|---|---|---|---|
| English encoders, up to 35M parameters | ||||||||||
| BERT-small | 28.8M | 44.8 | 90.1 | 83.1 | 87.6 | 90.1 | 79.2 | 88.2 | 69.3 | 79.0 |
| MiniLM-L12 | 33.4M | 59.1 | 93.3 | 91.2 | 89.2 | 91.5 | 85.6 | 91.9 | 74.7 | 84.6 |
| Ettin-Enc-32m | 31.9M | 57.4 | 92.0 | 89.7 | 89.5 | 91.0 | 83.4 | 90.7 | 74.7 | 83.5 |
| EdgeCoder-31M | 31.0M | 64.9 | 92.2 | 91.8 | 90.2 | 91.1 | 84.5 | 90.3 | 82.7 | 86.0 |
| Larger English encoders (reference) | ||||||||||
| DistilBERT | 66.4M | 56.9 | 92.2 | 86.8 | 87.4 | 90.8 | 82.7 | 89.5 | 66.1 | 81.5 |
| Ettin-Enc-68m | 68.1M | 64.8 | 94.4 | 92.2 | 91.1 | 91.9 | 87.0 | 92.9 | 83.8 | 87.2 |
| BERT-base | 109.5M | 59.0 | 93.1 | 89.5 | 89.4 | 91.4 | 85.4 | 91.6 | 78.2 | 84.7 |
| ModernBERT-base | 149.0M | 65.1 | 96.0 | 92.2 | 91.8 | 92.1 | 89.1 | 93.9 | 87.4 | 88.4 |
| Multilingual encoders | ||||||||||
| mDistilBERT | 134.7M | 34.7 | 89.4 | 90.5 | 87.5 | 86.6 | 79.0 | 87.5 | 73.3 | 77.5 |
| Multilingual MiniLM | 117.7M | 25.4 | 91.6 | 91.3 | 88.6 | 87.7 | 82.1 | 89.7 | 75.8 | 78.3 |
| mmBERT-small | 140.5M | 61.8 | 93.1 | 91.6 | 90.3 | 88.6 | 85.8 | 91.9 | 81.9 | 84.7 |
| EdgeCoder-Multilingual-61M | 61.0M | 58.3 | 91.4 | 92.1 | 90.2 | 91.5 | 84.8 | 91.2 | 81.6 | 85.1 |
Table 1: GLUE dev. Our rows are single runs, best of a hyperparameter sweep. Baseline rows are taken from the cited papers: English baselines from Ettin, multilingual baselines from mmBERT.
Cross-lingual Transfer
On XTREME, models are fine-tuned on English and evaluated on the other languages. On the 26 XTREME languages that EdgeCoder-Multilingual-61M was pre-trained on, it averages 67.8, ahead of Multilingual MiniLM (67.3) and behind mmBERT-small (70.0), with about half their parameters.
| Model | Params | XNLI | PAWS-X | XCOPA | XQuAD | MLQA | TyDiQA | WikiANN | UDPOS | Avg |
|---|---|---|---|---|---|---|---|---|---|---|
| mDistilBERT | 134.7M | 60.8 | 79.6 | 53.5 | 50.1 | 45.5 | 40.3 | 59.7 | 72.5 | 57.7 |
| Multilingual MiniLM | 117.7M | 71.1 | 83.2 | 58.8 | 67.2 | 61.1 | 58.5 | 58.9 | 79.4 | 67.3 |
| mmBERT-small | 140.5M | 73.8 | 85.4 | 62.8 | 73.0 | 66.2 | 66.8 | 59.4 | 72.4 | 70.0 |
| EdgeCoder-Multilingual-61M | 61.0M | 71.5 | 83.5 | 59.1 | 69.4 | 62.0 | 62.0 | 57.4 | 77.9 | 67.8 |
Table 2: XTREME, zero-shot transfer from English, on the 26 languages covered by our pre-training corpus.
Per-language results for every task are given in the appendix of the paper.
Embeddings
Each backbone is fine-tuned once into a sentence embedding model on 1M MS MARCO triplets (one epoch, mean pooling, contrastive loss) and then evaluated. The scores describe the backbone after this fine-tuning, not the released checkpoint used as is.
MTEB English v2 (41 tasks): EdgeCoder-31M scores 51.1, level with the masked-language models of its size (50.9 to 51.3). The collapse that RTD models usually show on embedding tasks does not happen.
| Model | Params | Class. | Clust. | PairCl. | Rerank. | Retr. | STS | Summ. | Mean (Type) | Mean (Task) |
|---|---|---|---|---|---|---|---|---|---|---|
| English encoders, up to 35M parameters | ||||||||||
| BERT-small | 28.8M | 64.7 | 39.6 | 79.4 | 41.7 | 38.1 | 73.0 | 21.6 | 51.1 | 54.0 |
| MiniLM-L12 | 33.4M | 64.9 | 37.8 | 79.8 | 43.5 | 38.4 | 73.2 | 21.4 | 51.3 | 53.9 |
| Ettin-Enc-32m | 31.9M | 64.2 | 39.6 | 77.1 | 42.6 | 39.7 | 73.2 | 19.9 | 50.9 | 54.2 |
| EdgeCoder-31M | 31.0M | 65.3 | 39.7 | 78.0 | 42.3 | 38.6 | 73.1 | 20.9 | 51.1 | 54.2 |
| Larger English encoders (reference) | ||||||||||
| Ettin-Enc-68m | 68.1M | 66.6 | 40.1 | 79.3 | 43.3 | 43.1 | 74.2 | 21.7 | 52.6 | 56.1 |
| BERT-base | 109.5M | 67.2 | 40.4 | 80.5 | 43.1 | 41.2 | 74.8 | 23.1 | 52.9 | 56.0 |
| ModernBERT-base | 149.0M | 67.5 | 41.3 | 80.4 | 44.7 | 43.9 | 75.3 | 25.2 | 54.0 | 57.1 |
| Multilingual encoders | ||||||||||
| Multilingual MiniLM | 117.7M | 59.3 | 36.9 | 77.3 | 42.4 | 35.0 | 71.9 | 19.3 | 48.9 | – |
| mDistilBERT | 134.7M | 59.0 | 38.3 | 75.9 | 42.7 | 38.4 | 72.4 | 19.4 | 49.4 | – |
| mmBERT-small | 140.5M | 62.1 | 40.8 | 78.9 | 44.1 | 40.7 | 74.1 | 23.6 | 52.1 | – |
| EdgeCoder-Multilingual-61M | 61.0M | 63.8 | 38.6 | 76.8 | 43.0 | 37.9 | 72.1 | 20.6 | 50.4 | 53.3 |
Table 3: MTEB English v2, main metric of each task in percent, per category. Baseline rows are taken from the Ettin and mmBERT papers; Mean (Task) is not reported by mmBERT.
Limitations
The GLUE and XTREME results are single runs with one seed, so differences below about one point should not be over-interpreted. Languages outside the 46 of the pre-training corpus are not supported. We did not run a controlled ablation without the window task, because at a trillion tokens per run it was outside our budget.
Efficiency Improvements
DeBERTa's attention adds two position terms to the usual scores, so standard fused attention kernels cannot be used, and the reference implementation stores several n×n matrices per head. At 8192 tokens that does not fit in memory.
FlashDeBERTa is our open-source implementation of this attention as fused GPU kernels that never store an n×n matrix. On DeBERTa-v3-base at 4096 tokens the forward pass is about 10 times faster and uses 93% less memory than the reference implementation, and at 8192 tokens the reference runs out of memory on the same GPU. Training steps at 2048 tokens are 9.8 times faster. It loads existing DeBERTa-v2 and v3 checkpoints without changes, and it is what made long-context pre-training of these models practical.
Figure 10: FlashDeBERTa against the reference DeBERTa attention.
Usage Examples
The checkpoints have no masked-language-model head, so they are meant for feature extraction and fine-tuning, not for fill-mask.
import torch
from transformers import AutoTokenizer, AutoModel
model_id = "knowledgator/EdgeCoder-31M" # or knowledgator/EdgeCoder-Multilingual-61M
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModel.from_pretrained(model_id)
texts = ["EdgeCoder is a compact text encoder.", "It reads up to 8192 tokens."]
inputs = tokenizer(texts, padding=True, return_tensors="pt")
with torch.no_grad():
hidden = model(**inputs).last_hidden_state # (batch, seq_len, 384)
mask = inputs["attention_mask"].unsqueeze(-1)
embeddings = (hidden * mask).sum(1) / mask.sum(1) # mean pooling
print(embeddings.shape)
For long inputs, load the same checkpoint with FlashDeBERTa (pip install flashdeberta -U):
import torch
from transformers import AutoTokenizer
from flashdeberta import FlashDebertaV2Model
tokenizer = AutoTokenizer.from_pretrained("knowledgator/EdgeCoder-31M")
model = FlashDebertaV2Model.from_pretrained("knowledgator/EdgeCoder-31M").to("cuda")
inputs = tokenizer(long_text, truncation=True, max_length=8192, return_tensors="pt").to("cuda")
with torch.no_grad():
outputs = model(**inputs)
Fine-tuning Examples
Click to see how to fine-tune EdgeCoder into a text classifier with Transformers
import numpy as np
import evaluate
from datasets import load_dataset
from transformers import (AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding,
Trainer, TrainingArguments)
model_id = "knowledgator/EdgeCoder-31M"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(model_id, num_labels=2)
dataset = load_dataset("nyu-mll/glue", "sst2")
dataset = dataset.map(lambda x: tokenizer(x["sentence"], truncation=True, max_length=512), batched=True)
accuracy = evaluate.load("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
return accuracy.compute(predictions=np.argmax(logits, axis=-1), references=labels)
args = TrainingArguments(
output_dir="edgecoder-31m-sst2",
learning_rate=5e-5,
per_device_train_batch_size=32,
per_device_eval_batch_size=64,
num_train_epochs=3,
weight_decay=0.01,
warmup_ratio=0.06,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="accuracy",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=dataset["train"],
eval_dataset=dataset["validation"],
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
Click to see how to fine-tune EdgeCoder into a dense embedding model with Sentence Transformers
from datasets import load_dataset
from sentence_transformers import (SentenceTransformer, SentenceTransformerTrainer,
SentenceTransformerTrainingArguments)
from sentence_transformers.evaluation import TripletEvaluator
from sentence_transformers.losses import MultipleNegativesRankingLoss
from sentence_transformers.training_args import BatchSamplers
model = SentenceTransformer("knowledgator/EdgeCoder-31M") # mean pooling is added automatically
dataset = load_dataset(
"sentence-transformers/msmarco-co-condenser-margin-mse-sym-mnrl-mean-v1",
"triplet-hard",
split="train",
).select(range(1_000_000))
dataset = dataset.train_test_split(test_size=1_000, seed=12)
train_dataset, eval_dataset = dataset["train"], dataset["test"]
loss = MultipleNegativesRankingLoss(model)
args = SentenceTransformerTrainingArguments(
output_dir="edgecoder-31m-msmarco",
num_train_epochs=1,
per_device_train_batch_size=128,
learning_rate=5e-4, # the value we used for this model in the paper
warmup_ratio=0.05,
bf16=True,
batch_sampler=BatchSamplers.NO_DUPLICATES,
eval_strategy="steps",
eval_steps=1000,
save_strategy="steps",
save_steps=1000,
logging_steps=100,
)
evaluator = TripletEvaluator(
anchors=eval_dataset["query"],
positives=eval_dataset["positive"],
negatives=eval_dataset["negative"],
name="msmarco-dev",
)
trainer = SentenceTransformerTrainer(
model=model,
args=args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
loss=loss,
evaluator=evaluator,
)
trainer.train()
model.save_pretrained("edgecoder-31m-msmarco/final")
Using EdgeCoder as a Backbone for GLiNER and GLiClass
The EdgeCoder checkpoints are ordinary DeBERTa-v2 models, so they work as the encoder in frameworks that are built on top of a DeBERTa backbone. In GLiNER and GLiClass this is a change of one name in the configuration. The examples below start a new model from the EdgeCoder backbone, so the model has to be trained before it can be used.
GLiNER: set the encoder in the model section of the training config and run the training script from the GLiNER repository.
# configs/config.yaml
model:
model_name: knowledgator/EdgeCoder-31M # or knowledgator/EdgeCoder-Multilingual-61M
python train.py --config configs/config.yaml
GLiClass: pass the encoder name to the training script from the GLiClass repository.
python train.py --encoder_model_name knowledgator/EdgeCoder-31M
Long inputs: both frameworks can run the DeBERTa encoder with FlashDeBERTa. Install it with pip install flashdeberta -U and set the environment variable before loading the model.
export USE_FLASHDEBERTA=1
Model Family and Links
Models:
- EdgeCoder-31M: English, 8 layers, 31M parameters
- EdgeCoder-Multilingual-61M: 46 languages, 16 layers, 61M parameters
Resources:
- Paper: arXiv:2611.31495
- FlashDeBERTa: github.com/Knowledgator/FlashDeBERTa









