Skip to content

Smaller, faster, sharper encoders: ALBERT, ELECTRA, DeBERTa and DistilBERT

Four ways to get more from an encoder. ALBERT shares parameters, ELECTRA learns from every token, DeBERTa separates content from position, DistilBERT copies a bigger teacher. Run two of them frozen in CodeSplash.

Advanced ~15 min8 steps

What runs in CodeSplash

You will be able to

  • Count how ALBERT's factorized embedding cuts parameters, and say what it doesn't cut
  • Explain replaced-token detection and why it uses every position
  • Describe DeBERTa's disentangled attention
  • Write the temperature-scaled distillation loss behind DistilBERT

Read first

01

ALBERT: fewer parameters, same compute

Read

ALBERT shrinks BERT two ways. Cross-layer sharingCross-layer parameter sharingReusing one set of weights in several layers (as ALBERT does): fewer weights to store, but every layer still runs. reuses one set of Transformer weights in every layer. A factorized embedding maps each token to a small vector first, then projects it up to the hidden size.

With 30,000 tokens, a hidden size of 768 and a small size of 128, the reference program counts 23,040,000 embedding weights directly, against 3,938,304 factorized, 17.1% of the original.

Sharing saves memory for weights, not computation: every layer still runs, so prediction is no faster.

02

ELECTRA: learn from every token

Read

BERT learns only from the masked 15%. ELECTRA uses replaced-token detectionReplaced-token detectionELECTRA's pretraining task: a small generator swaps some tokens, and the model labels every token as original or replaced.: a small generator fills the masked positions with plausible substitutes, and the main model, the discriminator, says for every token whether it is original or replaced.

Every position now gives a training signal, so ELECTRA reaches BERT's quality with much less compute. In the reference program, a discriminator scoring three tokens has binary cross-entropy 0.312. The generator is thrown away after pretraining.

03

DeBERTa: content and position, separately

Read

BERT adds a position vector to each token vector and attends on the sum. Disentangled attentionDisentangled attentionDeBERTa's attention: content and relative position are separate vectors, each pair of them scored separately and added. keeps the two apart and scores a query–key pair as content-to-content plus content-to-relative-position plus relative-position-to-content:

sij=qic⋅kjc+qic⋅kδ(i,j)r+qδ(j,i)r⋅kjcs_{ij} = q^{c}_i \cdot k^{c}_j + q^{c}_i \cdot k^{r}_{\delta(i,j)} + q^{r}_{\delta(j,i)} \cdot k^{c}_j

The reference program's three terms add up to 0.29. DeBERTa models fine-tuned on entailment are popular zero-shot classifiers: "does this text entail This text is about sport?"

04

DistilBERT: a student copies a teacher

Read

DistillationKnowledge distillationTraining a new model (the student) to copy another model's predictions, usually so a small model can stand in for a big one. trains a small student to match a large teacher's softened output distribution. Both softmaxes divide their logits by a temperature T, and the loss is the KL divergence, scaled by T² so its gradients keep their size:

LKD=T2 KL ⁣(softmax(zt/T) ∥ softmax(zs/T))\mathcal{L}_{\mathrm{KD}} = T^{2}\,\mathrm{KL}\!\left(\mathrm{softmax}(z_t/T)\,\middle\|\,\mathrm{softmax}(z_s/T)\right)

With T = 2, the reference program's loss is 0.215. DistilBERT keeps about 97% of BERT's benchmark score with 40% fewer parameters; how much faster it runs depends on your hardware.

DExplorable · Distillation: soft targets at a temperature

What does a student learn from a teacher's probabilities that it can't learn from the label alone?

1.0

Dividing logits by T before the softmax spreads probability onto the wrong classes.

0.50

Loss = α·cross-entropy with the label + (1 − α)·T²·KL to the soft targets.

200

Gradient steps on the student's logits for this one example.

1.0

Step size on the student's logits.

cat0.898dog0.064fox0.031car0.003truck0.003
  • Teacher's soft targets at T
  • Student after training (T = 1)
Soft-target entropy (bits)
0.932
Student: P(dog) / P(car)
18.60
KL at T after training
0.0489
Soft-target gradient with T²
0.6785
Soft-target gradient without T²
0.6785
  • Puzzle: At T = 4 or higher, make the student match the soft targets to within 0.001 nats of KL.
  • Puzzle: Find a temperature where the soft targets carry more than 1.5 bits.
At T = 1.0 the teacher's soft targets carry 0.93 bits. After 200 steps the student thinks “dog” is 18.6 times as likely as “car” (the teacher: 66.7 times). The student ranks the wrong classes as the teacher does: that ranking is what distillation passes on.

At T = 1.0 the teacher's soft targets carry 0.93 bits. After 200 steps the student thinks “dog” is 18.6 times as likely as “car” (the teacher: 66.7 times). The student ranks the wrong classes as the teacher does: that ranking is what distillation passes on.

05

Which ones run here

Read

In Text encoder, Encoder offers DistilBERT base and ELECTRA-small beside MiniLM, E5 and RoBERTa, each frozen, fine-tuned or with LoRA. ELECTRA-small, for example, predicts star ratings with cross-validated RMSE 1.34 on a small review set. ALBERT is explained here only.

DeBERTa's entailment route isn't built. Zero-shot text labels takes the embedding route instead: it compares each text with a label sentence by cosine similarity.

Zero-shot text labelsRecorded · Python and R agreeRecorded 2026-11-21 · 25 values compared
R

61 texts into 3 labels; most common finance (34%); accuracy 100% against theme.

Texts
61
Labels
3
Mean margin
0.2229
Accuracy
100.0%
Macro F1
1

Plots

Texts per labelWhich words or phrases appear most in a text column, overall or by group?
View data
TextsLabel
20sport
20cooking
21finance
Margin between the best and the second-best labelHow is one numeric variable distributed?
View data
Margin
0.1220
0.1145
0.1360
0.1915
0.2859
0.1832
0.1199
0.2201
0.1541
0.1751
0.0527
0.2158
0.2230
0.1561
0.1873
0.0087
0.2549
0.1449
0.2370
0.0558
0.2842
0.3200
0.2824
0.2003
0.3854
0.3380
0.3283
0.2248
0.3520
0.2702
0.2749
0.2520
0.1756
0.2778
0.3419
0.3104
0.2773
0.2662
0.2431
0.3681
0.2081
0.2676
0.1135
0.2104
0.2483
0.2883
0.1367
0.1742
0.3109
0.2776
0.2029
0.2837
0.1654
0.2936
0.1464
0.2009
0.2805
0.2096
0.2340
0.2634

First 60 of 61 rows.

Zero-shot labels against themeHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?
View data
themeZero-shot label
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
sportsport
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
cookingcooking
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance
financefinance

First 60 of 61 rows.

Assumptions

  • Label wording — Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result.
  • English text — all-MiniLM-L6-v2 was trained mostly on English text.
  • No training on your labels — No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.

Labels

LabelTextsShare of textsMean similarity (labeled texts)KnownPrecisionRecallF1
sport200.32790.209620111
cooking200.32790.279320111
finance210.34430.250121111

Each label is embedded as “This text is about {label}.” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.

Labeled texts

RowTextLabelSimilarityMargin to the next labelKnown label
1The striker scored a late goal and the team won the match at homesport0.17280.1220sport
2Fans cheered as the goalkeeper saved a penalty in the final minutesport0.14810.1145sport
3The coach praised the defence after a clean sheet in the league matchsport0.22320.1360sport
4A thrilling match ended level after the striker hit the post twicesport0.23250.1915sport
5The team trained hard before the cup final against their rivalssport0.32050.2859sport
6Injury kept the captain out of the match but the team still wonsport0.20950.1832sport
7The referee awarded a penalty and the striker scored the winning goalsport0.15830.1199sport
8Supporters filled the stadium to watch the league leaders playsport0.16030.2201sport
9The young winger crossed the ball and the striker headed it homesport0.21430.1541sport
10After the final whistle the coach thanked the fans for their supportsport0.22870.1751sport
11The goalkeeper made three saves to keep the team in the cupsport0.14910.0527sport
12League rivals met in a tense match that ended with a late goalsport0.22350.2158sport
13The team celebrated the title with their fans in the stadiumsport0.20240.2230sport
14A penalty miss cost the team the match against the league leaderssport0.22130.1561sport
15The coach changed the formation and the team pressed highersport0.31360.1873sport
16The striker signed a new contract after a season of goalssport0.07870.0087sport
17Rain made the pitch heavy but the team kept passing the ballsport0.26170.2549sport
18The captain lifted the cup as fans sang in the stadiumsport0.17400.1449sport
19Training focused on set pieces before the derby matchsport0.30780.2370sport
20The defence held firm and the goalkeeper kept another clean sheetsport0.19250.0558sport
21Chop the onions and garlic then fry them gently in olive oilcooking0.23880.2842cooking
22Add the tomatoes and simmer the sauce for twenty minutescooking0.29320.3200cooking
23Season the soup with salt and pepper before serving it hotcooking0.31720.2824cooking
24Knead the dough until smooth and let it rise in a warm placecooking0.18700.2003cooking
25Roast the vegetables with olive oil garlic and fresh herbscooking0.34060.3854cooking
26Stir the sauce often so the garlic and onions do not burncooking0.30310.3380cooking
27Bake the bread until the crust is golden and sounds hollowcooking0.31170.3283cooking
28Whisk the eggs with sugar then fold in the flour gentlycooking0.19010.2248cooking
29Simmer the beans with tomatoes onions and a pinch of saltcooking0.30260.3520cooking
30Serve the pasta with the tomato sauce and fresh basilcooking0.30150.2702cooking
31Fry the fish in butter and finish it with lemon and herbscooking0.29040.2749cooking
32Let the dough rest before you roll it out and bake itcooking0.23830.2520cooking
33Add stock to the pan and simmer the rice until tendercooking0.29370.1756cooking
34Grate the cheese over the pasta and bake until bubblingcooking0.29150.2778cooking
35Toast the spices in a dry pan before adding the onionscooking0.28150.3419cooking
36Slice the bread and serve it warm with butter and soupcooking0.34230.3104cooking
37Marinate the chicken with garlic lemon and olive oil overnightcooking0.23040.2773cooking
38Taste the sauce and add salt pepper or a little sugarcooking0.25890.2662cooking
39Bake the cake for forty minutes and let it cool on a rackcooking0.25580.2431cooking
40Roast the chicken with garlic herbs and lemon until goldencooking0.31730.3681cooking

First 40 of 61 rows.

  • 1 of 62 rows were left out because a value was missing.
  • Labels are probabilities from a softmax of similarity ÷ 0.05; the predicted label is the most similar one (ties go to the label listed first).
The exact R script · R R version 4.5.1 (2025-06-13)
# Zero-shot text labels (sentence embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.zero_shot_text 1.0.0 · spec 52703ebb414de8c7
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_minilm_embed (all-MiniLM-L6-v2 in base R) and cs_zero_shot* (twins of codesplash.text.search)

# %% Data (rows with a text; known labels may be missing)
TEXT <- "text"
TRUTH <- "theme"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c("text", "theme")))
n_input <- nrow(df)
keep_rows <- which(!is.na(df[[TEXT]]))
df <- df[keep_rows, , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
rows <- as.integer(keep_rows)  # 1-based input rows
texts <- as.character(df[[TEXT]])
n <- length(texts)
truth <- as.character(df[[TRUTH]])
seen <- unique(truth[!is.na(truth)])
truth_levels <- intersect(c("cooking", "finance", "sport"), seen)  # stored level order

# %% Labels
LABELS <- cs_search_split_labels("sport, cooking, finance")
if (!length(LABELS) && length(truth_levels)) LABELS <- truth_levels
if (length(LABELS) < 2) {
  cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "at least two labels separated by commas",
           value = if (length(LABELS)) paste(LABELS, collapse = ", ") else "(empty)")
}
if (anyDuplicated(LABELS)) cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "distinct labels", value = paste(LABELS, collapse = ", "))
TEMPLATE <- "This text is about {label}."
if (!grepl("{label}", TEMPLATE, fixed = TRUE)) cs_error("CS_E_INVALID_OPTION", option = "Label sentence", allowed = "a sentence containing {label}", value = TEMPLATE)
MIN_SIM <- NULL
TEMPERATURE <- 0.05
L <- length(LABELS)

# %% Embeddings and similarities
EMBEDDER <- "minilm"  # "minilm": all-MiniLM-L6-v2, the only embedder today
if (!cs_minilm_available()) cs_error("CS_WEIGHTS_MISSING", model = "all-MiniLM-L6-v2 (download it from Discover → Topics in text → Pretrained embeddings)")
model <- cs_minilm_load()
E_text <- cs_minilm_embed(texts, model)  # n x 384, unit rows
E_label <- cs_minilm_embed(cs_zero_shot_prompts(LABELS, TEMPLATE), model)
sim <- cs_search_cosine(E_text, E_label)  # texts x labels
z <- cs_zero_shot(sim, TEMPERATURE)
assigned <- if (is.null(MIN_SIM)) rep(TRUE, n) else z$best >= MIN_SIM
pred <- ifelse(assigned, LABELS[z$pred], NA_character_)
n_unassigned <- sum(!assigned)

# %% Agreement with the known labels
ev <- NULL
n_not_in <- 0L
if (!is.null(truth)) {
  keep <- which(!is.na(truth) & truth %in% LABELS)
  n_not_in <- sum(!is.na(truth) & !(truth %in% LABELS))
  if (n_not_in > 0) warnings <- c(warnings, sprintf("%d known label(s) are not among the labels and are left out of the agreement figures.", n_not_in))
  if (length(keep)) {
    ev <- cs_zero_shot_classification(truth[keep], pred[keep], LABELS)
  } else {
    warnings <- c(warnings, "No text has a known label that is one of the labels, so agreement can't be computed.")
  }
}

# %% Result
counts <- vapply(LABELS, function(l) sum(!is.na(pred) & pred == l), numeric(1), USE.NAMES = FALSE)
names(counts) <- LABELS
mean_sim <- lapply(LABELS, function(l) { m <- !is.na(pred) & pred == l; if (any(m)) mean(z$best[m]) else NA })
names(mean_sim) <- LABELS
never <- LABELS[counts == 0]
if (length(never)) warnings <- c(warnings, sprintf("No text was given %s.", paste(never, collapse = ", ")))
if (n_unassigned > 0) warnings <- c(warnings, sprintf("%d text(s) have no label above the minimum similarity %s.", n_unassigned, format(MIN_SIM, digits = 6)))
values <- list(
  n_docs = n, n_labels = L, embedder = "all-MiniLM-L6-v2", labels_text = paste(LABELS, collapse = ", "),
  mean_best = mean(z$best), mean_margin = mean(z$margin),
  n_unassigned = n_unassigned, coverage = 1 - n_unassigned / n,
  n_evaluated = if (!is.null(ev)) ev$n else if (!is.null(truth)) 0L else NA,
  n_not_in_labels = if (!is.null(truth)) n_not_in else NA,
  accuracy = if (!is.null(ev)) ev$accuracy else NA, macro_f1 = if (!is.null(ev)) ev$macro_f1 else NA,
  balanced_accuracy = if (!is.null(ev)) ev$balanced_accuracy else NA
)
for (l in LABELS) {
  values[[sprintf("n[%s]", l)]] <- counts[[l]]
  values[[sprintf("share[%s]", l)]] <- counts[[l]] / n
  values[[sprintf("mean_similarity[%s]", l)]] <- mean_sim[[l]]
}
if (!is.null(ev)) for (r in ev$rows) values[[sprintf("f1[%s]", r$label)]] <- r$f1
label_cols <- list(list(key = "label", label = "Label", type = "string"), list(key = "texts", label = "Texts", type = "integer"),
                   list(key = "share", label = "Share of texts", type = "number"), list(key = "similarity", label = "Mean similarity (labeled texts)", type = "number"))
label_rows <- lapply(LABELS, function(l) list(label = l, texts = counts[[l]], share = counts[[l]] / n, similarity = mean_sim[[l]]))
if (!is.null(ev)) {
  label_cols <- c(label_cols, list(list(key = "support", label = "Known", type = "integer"), list(key = "precision", label = "Precision", type = "number"),
                                   list(key = "recall", label = "Recall", type = "number"), list(key = "f1", label = "F1", type = "number")))
  for (j in seq_along(label_rows)) {
    r <- ev$rows[[j]]
    label_rows[[j]] <- c(label_rows[[j]], list(support = r$support, precision = r$precision, recall = r$recall, f1 = r$f1))
  }
}
SHOW <- min(n, 100L)
pred_cols <- list(list(key = "row", label = "Row", type = "integer"), list(key = "text", label = "Text", type = "string"),
                  list(key = "label", label = "Label", type = "string"), list(key = "similarity", label = "Similarity", type = "number"),
                  list(key = "margin", label = "Margin to the next label", type = "number"))
if (!is.null(truth)) pred_cols <- c(pred_cols, list(list(key = "known", label = "Known label", type = "string")))
pred_rows <- lapply(seq_len(SHOW), function(i) {
  r <- list(row = rows[i], text = cs_search_snippet(texts[i]), label = pred[i], similarity = z$best[i], margin = z$margin[i])
  if (!is.null(truth)) r$known <- truth[i]
  r
})
tables <- list(
  list(key = "labels", title = "Labels", columns = label_cols, rows = label_rows,
       note = sprintf("Each label is embedded as “%s” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.", TEMPLATE)),
  list(key = "texts", title = "Labeled texts", columns = pred_cols, rows = pred_rows,
       note = if (SHOW == n) NULL else sprintf("The first %d of %d texts.", SHOW, n))
)
charts <- list(
  cs_chart("labels", "ngram-bars", "Texts per label",
           list(term = cs_col("Label", LABELS, kind = "categorical"), count = cs_col("Texts", unname(counts))), controls = list(top = min(L, 50L))),
  cs_chart("margins", "histogram", "Margin between the best and the second-best label", list(x = cs_col("Margin", z$margin)))
)
if (!is.null(ev)) {
  keep <- which(!is.na(truth) & truth %in% LABELS)
  levels_pred <- c(LABELS, if (any(is.na(pred[keep]))) "(no label)")
  charts[[length(charts) + 1]] <- cs_chart("confusion", "confusion-matrix", sprintf("Zero-shot labels against %s", TRUTH),
    list(actual = cs_col(TRUTH, truth[keep], kind = "categorical", levels = LABELS),
         predicted = cs_col("Zero-shot label", ifelse(is.na(pred[keep]), "(no label)", pred[keep]), kind = "categorical", levels = levels_pred)))
}
statistics <- list(list(key = "n_docs", label = "Texts", value = n), list(key = "n_labels", label = "Labels", value = L),
                   list(key = "mean_margin", label = "Mean margin", value = values$mean_margin))
if (!is.null(ev)) statistics <- c(statistics, list(list(key = "accuracy", label = "Accuracy", value = values$accuracy, format = "percent"),
                                                  list(key = "macro_f1", label = "Macro F1", value = values$macro_f1)))
assumptions <- list(
  list(key = "wording", label = "Label wording", status = "info",
       detail = "Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result."),
  list(key = "language", label = "English text", status = "info", detail = "all-MiniLM-L6-v2 was trained mostly on English text."),
  list(key = "not_trained", label = "No training on your labels", status = "info",
       detail = "No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.")
)
top <- LABELS[which.max(counts)]
summary <- paste0(sprintf("%d texts into %d labels; most common %s (%s)", n, L, top, sprintf("%.0f%%", 100 * counts[[top]] / n)),
                  if (!is.null(ev)) sprintf("; accuracy %.0f%% against %s.", 100 * values$accuracy, TRUTH) else ".")
cs_publish(list(
  method = "describe.zero_shot_text",
  methodVersion = "1.0.0",
  title = "Zero-shot text labels",
  engine = cs_engine_info("nanoparquet", "stringi"),
  n = n,
  summary = summary,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Labels are probabilities from a softmax of similarity ÷ %s; the predicted label is the most similar one (ties go to the label listed first).", format(TEMPERATURE, digits = 6))),
  charts = charts,
  values = values
))
Python

61 texts into 3 labels; most common finance (34%); accuracy 100% against theme.

Texts
61
Labels
3
Mean margin
0.2229
Accuracy
100.0%
Macro F1
1

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Label wording — Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result.
  • English text — all-MiniLM-L6-v2 was trained mostly on English text.
  • No training on your labels — No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better.

Labels

LabelTextsShare of textsMean similarity (labeled texts)KnownPrecisionRecallF1
sport200.32790.209620111
cooking200.32790.279320111
finance210.34430.250121111

Each label is embedded as “This text is about {label}.” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings.

Labeled texts

RowTextLabelSimilarityMargin to the next labelKnown label
1The striker scored a late goal and the team won the match at homesport0.17280.1220sport
2Fans cheered as the goalkeeper saved a penalty in the final minutesport0.14810.1145sport
3The coach praised the defence after a clean sheet in the league matchsport0.22320.1360sport
4A thrilling match ended level after the striker hit the post twicesport0.23250.1915sport
5The team trained hard before the cup final against their rivalssport0.32050.2859sport
6Injury kept the captain out of the match but the team still wonsport0.20950.1832sport
7The referee awarded a penalty and the striker scored the winning goalsport0.15830.1199sport
8Supporters filled the stadium to watch the league leaders playsport0.16030.2201sport
9The young winger crossed the ball and the striker headed it homesport0.21430.1541sport
10After the final whistle the coach thanked the fans for their supportsport0.22870.1751sport
11The goalkeeper made three saves to keep the team in the cupsport0.14910.0527sport
12League rivals met in a tense match that ended with a late goalsport0.22350.2158sport
13The team celebrated the title with their fans in the stadiumsport0.20240.2230sport
14A penalty miss cost the team the match against the league leaderssport0.22130.1561sport
15The coach changed the formation and the team pressed highersport0.31360.1873sport
16The striker signed a new contract after a season of goalssport0.07870.0087sport
17Rain made the pitch heavy but the team kept passing the ballsport0.26170.2549sport
18The captain lifted the cup as fans sang in the stadiumsport0.17400.1449sport
19Training focused on set pieces before the derby matchsport0.30780.2370sport
20The defence held firm and the goalkeeper kept another clean sheetsport0.19250.0558sport
21Chop the onions and garlic then fry them gently in olive oilcooking0.23880.2842cooking
22Add the tomatoes and simmer the sauce for twenty minutescooking0.29320.3200cooking
23Season the soup with salt and pepper before serving it hotcooking0.31720.2824cooking
24Knead the dough until smooth and let it rise in a warm placecooking0.18700.2003cooking
25Roast the vegetables with olive oil garlic and fresh herbscooking0.34060.3854cooking
26Stir the sauce often so the garlic and onions do not burncooking0.30310.3380cooking
27Bake the bread until the crust is golden and sounds hollowcooking0.31170.3283cooking
28Whisk the eggs with sugar then fold in the flour gentlycooking0.19010.2248cooking
29Simmer the beans with tomatoes onions and a pinch of saltcooking0.30260.3520cooking
30Serve the pasta with the tomato sauce and fresh basilcooking0.30150.2702cooking
31Fry the fish in butter and finish it with lemon and herbscooking0.29040.2749cooking
32Let the dough rest before you roll it out and bake itcooking0.23830.2520cooking
33Add stock to the pan and simmer the rice until tendercooking0.29370.1756cooking
34Grate the cheese over the pasta and bake until bubblingcooking0.29150.2778cooking
35Toast the spices in a dry pan before adding the onionscooking0.28150.3419cooking
36Slice the bread and serve it warm with butter and soupcooking0.34230.3104cooking
37Marinate the chicken with garlic lemon and olive oil overnightcooking0.23040.2773cooking
38Taste the sauce and add salt pepper or a little sugarcooking0.25890.2662cooking
39Bake the cake for forty minutes and let it cool on a rackcooking0.25580.2431cooking
40Roast the chicken with garlic herbs and lemon until goldencooking0.31730.3681cooking

First 40 of 61 rows.

  • 1 of 62 rows were left out because a value was missing.
  • Labels are probabilities from a softmax of similarity ÷ 0.05; the predicted label is the most similar one (ties go to the label listed first).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Zero-shot text labels (sentence embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.zero_shot_text 1.0.0 · spec 52703ebb414de8c7
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.text import minilm  # all-MiniLM-L6-v2 in numpy (twin: codesplashr cs_minilm_embed)
from codesplash.text import search as zs  # labels, cosine, first-maximum labels, metrics (twin: cs_zero_shot*)

# %% Data (rows with a text; known labels may be missing)
TEXT = "text"
TRUTH = "theme"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=["text", "theme"])
n_input = len(df)
df = df[df[TEXT].notna()]
warnings = []
if n_input - len(df):
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
rows = (df.index.to_numpy() + 1).astype(np.int64)  # 1-based input rows
texts = df[TEXT].astype(str).tolist()
n = len(texts)
truth = [None if pd.isna(v) else str(v) for v in df[TRUTH].tolist()]
truth_levels = [lv for lv in ["cooking", "finance", "sport"] if lv in set(t for t in truth if t is not None)]  # stored level order

# %% Labels
LABELS = zs.split_labels("sport, cooking, finance")
if not LABELS and truth_levels:
    LABELS = list(truth_levels)
if len(LABELS) < 2:
    cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="at least two labels separated by commas", value=", ".join(LABELS) or "(empty)")
if len(set(LABELS)) < len(LABELS):
    cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="distinct labels", value=", ".join(LABELS))
TEMPLATE = "This text is about {label}."
if zs.LABEL_SLOT not in TEMPLATE:
    cs.cs_error("CS_E_INVALID_OPTION", option="Label sentence", allowed="a sentence containing {label}", value=TEMPLATE)
MIN_SIM = None
TEMPERATURE = 0.05
L = len(LABELS)

# %% Embeddings and similarities
EMBEDDER = "minilm"  # "minilm": all-MiniLM-L6-v2, the only embedder today
if not minilm.available():
    cs.cs_error("CS_WEIGHTS_MISSING", model=f"{minilm.NAME} (download it from Discover → Topics in text → Pretrained embeddings)")
model = minilm.Model()
E_text = minilm.embed(texts, model)  # n × 384, unit rows
E_label = minilm.embed(zs.label_prompts(LABELS, TEMPLATE), model)
sim = zs.cosine(E_text, E_label)  # texts × labels
z = zs.zero_shot(sim, TEMPERATURE)
assigned = np.ones(n, dtype=bool) if MIN_SIM is None else z["best"] >= MIN_SIM
pred = [LABELS[int(j)] if ok else None for j, ok in zip(z["pred"], assigned)]
n_unassigned = int(np.sum(~assigned))

# %% Agreement with the known labels
ev = None
n_not_in = 0
if truth is not None:
    keep = [i for i, t in enumerate(truth) if t is not None and t in LABELS]
    n_not_in = sum(1 for t in truth if t is not None and t not in LABELS)
    if n_not_in:
        warnings.append(f"{n_not_in} known label(s) are not among the labels and are left out of the agreement figures.")
    if keep:
        ev = zs.classification([truth[i] for i in keep], [pred[i] for i in keep], LABELS)
    else:
        warnings.append("No text has a known label that is one of the labels, so agreement can't be computed.")

# %% Result
counts = {lab: sum(1 for p in pred if p == lab) for lab in LABELS}
mean_sim = {}
for j, lab in enumerate(LABELS):
    m = np.array([p == lab for p in pred])
    mean_sim[lab] = float(z["best"][m].mean()) if m.any() else None
never = [lab for lab in LABELS if counts[lab] == 0]
if never:
    warnings.append(f"No text was given {', '.join(never)}.")
if n_unassigned:
    warnings.append(f"{n_unassigned} text(s) have no label above the minimum similarity {MIN_SIM:g}.")
values = {
    "n_docs": n, "n_labels": L, "embedder": minilm.NAME, "labels_text": ", ".join(LABELS),
    "mean_best": float(np.mean(z["best"])), "mean_margin": float(np.mean(z["margin"])),
    "n_unassigned": n_unassigned, "coverage": 1.0 - n_unassigned / n,
    "n_evaluated": ev["n"] if ev else (0 if truth is not None else None),
    "n_not_in_labels": n_not_in if truth is not None else None,
    "accuracy": ev["accuracy"] if ev else None, "macro_f1": ev["macro_f1"] if ev else None,
    "balanced_accuracy": ev["balanced_accuracy"] if ev else None,
}
for lab in LABELS:
    values[f"n[{lab}]"] = counts[lab]
    values[f"share[{lab}]"] = counts[lab] / n
    values[f"mean_similarity[{lab}]"] = mean_sim[lab]
if ev:
    for r in ev["rows"]:
        values[f"f1[{r['label']}]"] = r["f1"]
label_cols = [{"key": "label", "label": "Label", "type": "string"}, {"key": "texts", "label": "Texts", "type": "integer"},
              {"key": "share", "label": "Share of texts", "type": "number"}, {"key": "similarity", "label": "Mean similarity (labeled texts)", "type": "number"}]
label_rows = [{"label": lab, "texts": counts[lab], "share": counts[lab] / n, "similarity": mean_sim[lab]} for lab in LABELS]
if ev:
    label_cols += [{"key": "support", "label": "Known", "type": "integer"}, {"key": "precision", "label": "Precision", "type": "number"},
                   {"key": "recall", "label": "Recall", "type": "number"}, {"key": "f1", "label": "F1", "type": "number"}]
    for row, r in zip(label_rows, ev["rows"]):
        row.update({"support": r["support"], "precision": r["precision"], "recall": r["recall"], "f1": r["f1"]})
SHOW = min(n, 100)
pred_cols = [{"key": "row", "label": "Row", "type": "integer"}, {"key": "text", "label": "Text", "type": "string"},
             {"key": "label", "label": "Label", "type": "string"}, {"key": "similarity", "label": "Similarity", "type": "number"},
             {"key": "margin", "label": "Margin to the next label", "type": "number"}]
if truth is not None:
    pred_cols.append({"key": "known", "label": "Known label", "type": "string"})
pred_rows = []
for i in range(SHOW):
    r = {"row": int(rows[i]), "text": zs.snippet(texts[i]), "label": pred[i], "similarity": float(z["best"][i]), "margin": float(z["margin"][i])}
    if truth is not None:
        r["known"] = truth[i]
    pred_rows.append(r)
tables = [
    {"key": "labels", "title": "Labels", "columns": label_cols, "rows": label_rows,
     "note": f"Each label is embedded as “{TEMPLATE}” with the label filled in; similarity is the cosine of all-MiniLM-L6-v2 sentence embeddings."},
    {"key": "texts", "title": "Labeled texts", "columns": pred_cols, "rows": pred_rows,
     "note": None if SHOW == n else f"The first {SHOW} of {n} texts."},
]
charts = [
    cs.chart("labels", "ngram-bars", "Texts per label", {
        "term": cs.col("Label", LABELS, kind="categorical"), "count": cs.col("Texts", [counts[lab] for lab in LABELS])}, controls={"top": min(L, 50)}),
    cs.chart("margins", "histogram", "Margin between the best and the second-best label", {"x": cs.col("Margin", z["margin"])}),
]
if ev:
    keep = [i for i, t in enumerate(truth) if t is not None and t in LABELS]
    levels_pred = LABELS + (["(no label)"] if any(pred[i] is None for i in keep) else [])
    charts.append(cs.chart("confusion", "confusion-matrix", f"Zero-shot labels against {TRUTH}", {
        "actual": cs.col(TRUTH, [truth[i] for i in keep], kind="categorical", levels=LABELS),
        "predicted": cs.col("Zero-shot label", [pred[i] if pred[i] is not None else "(no label)" for i in keep], kind="categorical", levels=levels_pred)}))
statistics = [{"key": "n_docs", "label": "Texts", "value": n}, {"key": "n_labels", "label": "Labels", "value": L},
              {"key": "mean_margin", "label": "Mean margin", "value": values["mean_margin"]}]
if ev:
    statistics += [{"key": "accuracy", "label": "Accuracy", "value": values["accuracy"], "format": "percent"},
                   {"key": "macro_f1", "label": "Macro F1", "value": values["macro_f1"]}]
assumptions = [
    {"key": "wording", "label": "Label wording", "status": "info",
     "detail": "Labels are matched by meaning, so their wording matters; compare a few wordings or label sentences before relying on the result."},
    {"key": "language", "label": "English text", "status": "info", "detail": "all-MiniLM-L6-v2 was trained mostly on English text."},
    {"key": "not_trained", "label": "No training on your labels", "status": "info",
     "detail": "No labeled examples from your data were used; with enough labeled rows, a model trained in ML Studio usually does better."},
]
top = max(LABELS, key=lambda lab: (counts[lab], -LABELS.index(lab)))
summary = f"{n} texts into {L} labels; most common {top} ({counts[top] / n:.0%})" + (f"; accuracy {values['accuracy']:.0%} against {TRUTH}." if ev else ".")
cs.publish({
    "method": "describe.zero_shot_text",
    "methodVersion": "1.0.0",
    "title": "Zero-shot text labels",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Labels are probabilities from a softmax of similarity ÷ {TEMPERATURE:g}; the predicted label is the most similar one (ties go to the label listed first)."],
    "charts": charts,
    "values": values,
})
06

Where it stands in CodeSplash

Read
EntryIn CodeSplash
ALBERT (LNG012)Explained here
ELECTRA (LNG013)Partly runs in CodeSplash: Encoder: ELECTRA-small, frozen, fine-tuned or with LoRA; replaced-token-detection pretraining isn't run here
DeBERTa (LNG015)Partly runs in CodeSplash: Zero-shot text labels uses the embedding route; the entailment route isn't built
DistilBERT (LNG016)Runs in CodeSplash: Encoder: DistilBERT base in Text encoder, frozen, fine-tuned or with LoRA
07

Check: efficient encoders

Checkpoint

Check yourself

ALBERT shares one set of layer weights across all 12 layers. What does that save?

Show the answer

Answer: a

The same weights are applied 12 times. Fewer parameters to store, the same number of operations to run.

Check yourself

Why does a factorized embedding (vocabulary × 128, then 128 × hidden) cut parameters so much?

Show the answer

Answer: b

V × H becomes V × E + E × H. With V large and E much smaller than H, the first term shrinks by about H/E.

Check yourself

Why does ELECTRA learn more per sentence than BERT?

Show the answer

Answer: b

BERT's loss covers the masked share; replaced-token detection turns every position into a training example.

Check yourself

What happens to ELECTRA's generator after pretraining?

Show the answer

Answer: b

The generator only supplies plausible replacements during pretraining. The discriminator's encoder is what downstream tasks use.

Check yourself

What does DeBERTa's attention score add, compared with BERT's?

Show the answer

Answer: b

Keeping content and relative position as separate vectors lets attention weigh "what" and "how far" independently.

Check yourself

A DeBERTa entailment model labels texts zero-shot with the template "This text is about {label}." What should you check before trusting it?

Show the answer

Answer: b

Zero-shot results depend on label wording and the template. Pilot them against known labels (accuracy, macro-F1, κ) like any labeler.

Check yourself

Why is the distillation loss multiplied by T²?

Show the answer

Answer: b

Softened distributions have smaller gradients; the T² factor restores their scale relative to any hard-label loss.

Check yourself

A paper reports DistilBERT is 60% faster than BERT. What should you expect on your own machine?

Show the answer

Answer: b

Fewer layers mean fewer operations, but real speed depends on where time goes on your hardware. Measure before planning on a number.

08

Recap

Recap
  • ALBERT: shared layers and a factorized embedding cut weights, not compute.
  • ELECTRA: a discriminator learns from every token by spotting replacements.
  • DeBERTa: attention scores content and relative position separately; entailment models do zero-shot labels.
  • DistilBERT: a student matches the teacher's softened outputs, loss scaled by T².
  • DistilBERT and ELECTRA-small run in Text encoder, frozen, fine-tuned or with LoRA; zero-shot labels use embeddings.

Concepts in this lesson