Skip to content

BERT, RoBERTa and XLNet: reading text in both directions

BERT learns by filling in hidden tokens from both sides; RoBERTa showed the recipe mattered as much as the model; XLNet predicted tokens in shuffled orders. Use a pretrained encoder with a linear head in CodeSplash.

Applied ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Describe masked language modeling and why it gives bidirectional context
  • Name what RoBERTa changed in BERT's training recipe
  • Explain XLNet's permutation masks and why they were invented
  • Train a frozen encoder with a linear head and read its cross-validated score

Read first

01

Fill in the blanks

Read

A left-to-right language model can't use the words after a position. BERT trains a TransformerTransformerA stack of blocks, each self-attention then a feed-forward network, with residual connections and layer normalization. encoder with masked language modelingMasked language modelingPretraining by hiding a share of tokens and predicting them from both sides: the objective behind BERT and RoBERTa.: hide about 15% of the tokens and predict them from everything around them, on both sides.

L=−1∣M∣∑i∈Mlog⁡p(xi∣x∖M)\mathcal{L} = -\frac{1}{|M|}\sum_{i \in M}\log p(x_i \mid x_{\setminus M})

The loss averages only over the masked positions M. If a model gives the two hidden tokens probabilities 0.7 and 0.4, the reference program's loss is 0.636. A [CLS] token at the start collects a summary of the sequence for classification.

Self-attention with a padding mask, as an encoder uses it.

DExplorable · Attention: scores, masks and heads

Where does each word look, and what do the scaling and the masks change?

With this mask, how much of each word's attention lands on <pad>?

How sure?
6
2

How many of the positions are <pad>.

Width d

Heads

Mask

Without masks or positions the output rows shuffle the same way.

.51.22.16.11.00.00.27.55.07.10.00.00.02.10.59.28.00.00.26.71.02.01.00.00.09.09.69.13.00.00.42.54.03.01.00.00thecatsaton<pad><pad>thecatsaton<pad><pad>
  • Little weight
  • Most weight
  • Masked: score set to −∞

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

Why not always use [MASK]?

Predict

Predict first

Of the chosen positions, BERT replaces 80% with [MASK], 10% with a random token and leaves 10% unchanged. Why not replace all of them with [MASK]?

To make training fasterBecause [MASK] never appears in real text, so always using it would make training and use differTo hide the answer better
Reveal

Because [MASK] never appears when the model is used on real text. Leaving some chosen tokens unchanged, and corrupting others randomly, keeps the model from relying on the mask symbol to know where to work.

03

RoBERTa: the recipe mattered

Read

RoBERTa kept BERT's architecture and changed the training: far more text, longer training with bigger batches, no next-sentence task, byte-level BPE tokens, and dynamic masking. BERT fixed each sentence's mask once; RoBERTa draws a new mask every time a sentence is seen.

The reference program makes two views of "a small model learns", one with "small" hidden and one with "model" hidden. RoBERTa's gains over BERT showed that comparisons between architectures mean little unless the data and training budget are matched.

04

XLNet: every order at once

Read

Masking predicts the hidden tokens independently of each other, and [MASK] is artificial. XLNet instead trains an autoregressive model over random factorization orders. For one sampled order, each token may only attend to the tokens that come before it in that order, which can be on either side in the sentence.

In the reference program the order is position 2, then 0, then 1. Position 1 may see positions 0 and 2; position 2, first in the order, sees nothing. XLNet briefly beat BERT; better-trained masked encoders such as RoBERTa and DeBERTa superseded it.

Reference · LNG014 · Explained hereXLNetUses permutation-based autoregressive pretraining to learn bidirectional dependencies without inserting ordinary masked-token placeholders.
05

A pretrained encoder with a linear head

Read
Text encoder (MiniLM + linear head)Recorded · Python and R agreeRecorded 2026-11-25 · 420 values compared
R

Text encoder (MiniLM + linear head): cross-validated ROC AUC 0.827 ± 0.083 over 3 folds; ROC AUC on the locked test set 0.944 (n = 12).

CV ROC AUC
0.8266
SD across folds
0.0826
Test ROC AUC
0.9444

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
11160.79370.56140.75000.7460
21160.92060.49230.75000.7460
31160.76560.54210.75000.7500

Feature importance

FeatureImportance
review text__emb_3010.8534
review text__emb_3560.7815
review text__emb_1420.7447
review text__emb_2550.6827
review text__emb_1680.6621
review text__emb_2250.6568
review text__emb_860.6081
review text__emb_930.6065
review text__emb_1750.5842
review text__emb_2700.5752
review text__emb_1370.5685
review text__emb_1650.5658
review text__emb_1440.5626
review text__emb_2320.5352
review text__emb_910.5280
review text__emb_2570.5148
review text__emb_2030.5128
review text__emb_1610.5071
review text__emb_2830.5020
review text__emb_3130.4941
review text__emb_370.4924
review text__emb_3620.4824
review text__emb_2630.4805
review text__emb_1660.4795
review text__emb_2930.4731
review text__emb_2750.4468
review text__emb_2810.4385
review text__emb_1150.4376
review text__emb_3110.4334
review text__emb_1670.4327
The exact R script · R R version 4.5.1 (2025-06-13)
# Text encoder (MiniLM + linear head)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.text_encoder 1.4.0 · spec a0b2893701ca7d8c
# Dataset: txt2_reviews (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data and split plan
TARGET <- "good"
FEATURES <- c("product")
TASK <- "binary"
CLASSES <- c("no", "yes")
POSITIVE <- "yes"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  encoder = "minilm",
  penalty = 0.01,
  max_iter = 100,
  mode = "frozen",
  train_layers = 2,
  epochs = 3,
  learning_rate = 0.0001,
  batch_size = 16,
  lora_rank = 8,
  lora_alpha = 16,
  layer_lr_decay = 1,
  gradual_unfreezing = FALSE,
  slanted_triangular = FALSE,
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  label_smoothing = 0,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
)

# Text this learner embeds itself (frozen all-MiniLM-L6-v2), added as columns once the rows are read.
ENCODE_TEXT <- c("review text")

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/txt2_reviews.parquet", col_select = unique(c(TARGET, FEATURES, ENCODE_TEXT))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.text_encoder/binary_reviews_keep_all/folds.parquet")  # host-written folds: identical in Python and R
# Frozen all-MiniLM-L6-v2 sentence vectors of the text (cs_tenc_add_embedding_columns ↔ codesplash.text.encoder),
# added as `<text>__emb_<i>` columns in every mode, so a saved model embeds new text exactly as in training;
# the design compresses them per fold (0 components keeps all).
encoded_text <- cs_tenc_add_embedding_columns(df, ENCODE_TEXT)
df <- encoded_text$df
EMBED <- encoded_text$embed
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    product = "categorical"
  ),
  levels = list(
    product = c("coffee maker", "headphones", "running shoes")
  ),
  impute = "median",
  scale = "standard",
  indicators = FALSE,
  embed = EMBED,
  embed_pcs = 0L
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.text_encoder/binary_reviews_keep_all/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
  warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL  # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
  yy <- y[rows + 1L]
  ww <- sample_weights(rows)
  if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
  r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
                      seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
  if (fold_id == 0) resampled <<- r$info
  r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)

# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  label_smoothing = 0,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.text_encoder/binary_reviews_keep_all/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
  cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
  .deep_training_set(X, rows, fold_id, repeat_)
}
# A frozen sentence encoder with a linear head. The driver adds the text's all-MiniLM-L6-v2 vectors as
# columns (the same in every mode), the design compresses them per fold (or keeps all with 0 components)
# beside any other features, and an L2-penalized linear model learns on top: ridge for numbers, logistic
# for two classes, multinomial (first class as reference) for more. Intercepts are not penalized.
LAMBDA <- PARAMS$penalty

fit_model <- function(X, y, w) {
  maxit <- as.integer(PARAMS$max_iter)
  if (TASK == "regression") {
    f <- cs_tenc_ridge(X, y, w, LAMBDA)
    return(list(intercept = f$intercept, coef = f$coef, converged = TRUE))
  }
  if (TASK == "binary") return(cs_tenc_logistic_l2(X, y, w, LAMBDA, maxit = maxit))
  cs_tenc_multinomial_l2(X, y, length(CLASSES), w, LAMBDA, maxit = maxit)
}

predict_model <- function(model, X) {
  # Classes whose probability is within 1e-12 of the best (or a probability within 1e-12 of 0.5) are set
  # equal to it, so a tie in exact arithmetic picks the first class in both engines, not rounding noise.
  if (TASK == "multiclass") {
    eta <- sweep(X %*% t(model$coef), 2, model$intercept, "+")
    eta <- eta - apply(eta, 1, max)
    P <- exp(eta)
    P <- P / rowSums(P)
    m <- apply(P, 1, max)
    return(ifelse(P >= m - 1e-12, m, P))
  }
  eta <- model$intercept + as.numeric(X %*% model$coef)
  if (TASK == "regression") return(eta)
  p <- 1 / (1 + exp(-eta))
  ifelse(abs(p - 0.5) <= 1e-12, 0.5, p)
}

feature_importance <- function(model, names) {
  if (!isTRUE(model$converged)) {
    warnings[[length(warnings) + 1L]] <<- "The head did not converge within the iteration limit: raise Maximum iterations or the penalty."
  }
  cs_ml_coef_importance(names, model$coef)
}

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)
  list(list(key = "model", path = path, format = "rds"))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
  fold <- folds[[i]]
  prep <- cs_ml_design_fit(design, rows_of(fold$train))
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
  cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
            predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
  cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")

# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
  if (!is.null(resampled)) {
    warnings <- c(warnings, as.list(resampled$notes))
    notes <- c(notes, list(cs_ml_resample_describe(resampled)))
  }
  if (length(plan$test)) {
    cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
              predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
  }
  importance <- feature_importance(model, names_)
  artifacts[[length(artifacts) + 1L]] <- list(
    key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
  )
  artifacts <- c(artifacts, save_model(model, out))
  cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)

# %% Result
cs_publish(cs_ml_result(
  run,
  title = "Text encoder (MiniLM + linear head)",
  engine = cs_engine_info("codesplashr", "stringi", "nanoparquet"),
  n_features = length(names_),
  n_train = length(plan$train),
  n_test = length(plan$test),
  params = PARAMS,
  features = names_,
  importance = importance,
  artifacts = artifacts,
  warnings = warnings,
  notes = notes
))
Python

Text encoder (MiniLM + linear head): cross-validated ROC AUC 0.827 ± 0.083 over 3 folds; ROC AUC on the locked test set 0.944 (n = 12).

CV ROC AUC
0.8266
SD across folds
0.0826
Test ROC AUC
0.9444

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
11160.79370.56140.75000.7460
21160.92060.49230.75000.7460
31160.76560.54210.75000.7500

Feature importance

FeatureImportance
review text__emb_3010.8534
review text__emb_3560.7815
review text__emb_1420.7447
review text__emb_2550.6827
review text__emb_1680.6621
review text__emb_2250.6568
review text__emb_860.6081
review text__emb_930.6065
review text__emb_1750.5842
review text__emb_2700.5752
review text__emb_1370.5685
review text__emb_1650.5658
review text__emb_1440.5626
review text__emb_2320.5352
review text__emb_910.5280
review text__emb_2570.5148
review text__emb_2030.5128
review text__emb_1610.5071
review text__emb_2830.5020
review text__emb_3130.4941
review text__emb_370.4924
review text__emb_3620.4824
review text__emb_2630.4805
review text__emb_1660.4795
review text__emb_2930.4731
review text__emb_2750.4468
review text__emb_2810.4385
review text__emb_1150.4376
review text__emb_3110.4334
review text__emb_1670.4327
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Text encoder (MiniLM + linear head)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.text_encoder 1.4.0 · spec a0b2893701ca7d8c
# Dataset: txt2_reviews (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import linear as cslin
from codesplash.text import encoder as cstenc  # frozen MiniLM columns + L2 heads (twin: codesplashr cs_tenc_*)

# %% Data and split plan
TARGET = "good"
FEATURES = ["product"]
TASK = "binary"
CLASSES = ["no", "yes"]
POSITIVE = "yes"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "encoder": "minilm",
    "penalty": 0.01,
    "max_iter": 100,
    "mode": "frozen",
    "train_layers": 2,
    "epochs": 3,
    "learning_rate": 0.0001,
    "batch_size": 16,
    "lora_rank": 8,
    "lora_alpha": 16,
    "layer_lr_decay": 1,
    "gradual_unfreezing": False,
    "slanted_triangular": False,
    "optimizer": "default",
    "lr_schedule": "none",
    "warmup_epochs": 0,
    "grad_clip": 0,
    "ema_decay": 0,
    "swa_start": 0,
    "label_smoothing": 0,
    "mixup_alpha": 0,
    "history_every_step": False,
    "profile": "parity",
    "checkpoint_every": None,
}

# Text this learner embeds itself (frozen all-MiniLM-L6-v2), added as columns once the rows are read.
ENCODE_TEXT = ["review text"]

df = pd.read_parquet("tests/parity/fixtures/txt2_reviews.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES + ENCODE_TEXT)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.text_encoder/binary_reviews_keep_all/folds.parquet")  # host-written folds: identical in Python and R
# Frozen all-MiniLM-L6-v2 sentence vectors of the text (codesplash.text.encoder ↔ codesplashr
# cs_tenc_add_embedding_columns), added as `<text>__emb_<i>` columns in every mode, so a saved model
# embeds new text exactly as in training; the design compresses them per fold (0 components keeps all).
from codesplash.text import encoder as cstenc

df, EMBED = cstenc.add_embedding_columns(df, ENCODE_TEXT)
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "product": "categorical",
    },
    levels={
        "product": ["coffee maker", "headphones", "running shoes"],
    },
    impute="median",
    scale="standard",
    indicators=False,
    embed=EMBED,
    embed_pcs=0,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-8142/learn.text_encoder/binary_reviews_keep_all/out-python")
warnings = []


def sample_weights(rows):
    return None if weights is None else weights[rows]


RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
    warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None  # the final model's resampling summary
notes = []


def training_set(X, rows, fold_id, repeat):
    """A fit's design matrix, targets and weights: training rows only, resampled when asked
    (codesplash.ml.resample — the same rows in R, from the shared random stream)."""
    yy, ww = y[rows], sample_weights(rows)
    if RESAMPLE == "none" or TASK == "regression":
        return X, yy, ww
    from codesplash.ml import resample as csres

    X2, y2, w2, info = csres.resample(
        X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
    )
    if fold_id == 0:
        global resampled
        resampled = info
    return X2, y2, w2


# %% Model
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "label_smoothing": 0,
        "mixup_alpha": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/learn.text_encoder/binary_reviews_keep_all/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set


def training_set(X, rows, fold_id, repeat):
    """Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
    the training set as _ml_learn does."""
    deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
    return _deep_training_set(X, rows, fold_id, repeat)


# A frozen sentence encoder with a linear head. The driver adds the text's all-MiniLM-L6-v2 vectors as
# columns (the same in every mode), the design compresses them per fold (or keeps all with 0 components)
# beside any other features, and an L2-penalized linear model learns on top: ridge for numbers, logistic
# for two classes, multinomial (first class as reference) for more. Intercepts are not penalized.
LAMBDA = PARAMS["penalty"]


def fit_model(X, y, w):
    maxit = int(PARAMS["max_iter"])
    if TASK == "regression":
        b0, b = cstenc.ridge(X, y, w, LAMBDA)
        return {"intercept": b0, "coef": b, "converged": True}
    if TASK == "binary":
        b0, b, ok = cstenc.logistic_l2(X, y, w, LAMBDA, maxit=maxit)
        return {"intercept": b0, "coef": b, "converged": ok}
    b0, B, ok = cstenc.multinomial_l2(X, y, len(CLASSES), w, LAMBDA, maxit=maxit)
    return {"intercept": b0, "coef": B, "converged": ok}


def predict_model(model, X):
    # Classes whose probability is within 1e-12 of the best (or a probability within 1e-12 of 0.5) are set
    # equal to it, so a tie in exact arithmetic picks the first class in both engines, not rounding noise.
    if TASK == "multiclass":
        P = cslin.softmax_rows(model["intercept"][None, :] + X @ model["coef"].T)
        m = P.max(axis=1, keepdims=True)
        return np.where(P >= m - 1e-12, m, P)
    eta = model["intercept"] + X @ model["coef"]
    if TASK == "regression":
        return eta
    p = 1.0 / (1.0 + np.exp(-eta))
    return np.where(np.abs(p - 0.5) <= 1e-12, 0.5, p)


def feature_importance(model, names):
    if not model["converged"]:
        warnings.append("The head did not converge within the iteration limit: raise Maximum iterations or the penalty.")
    return cslin.coef_importance(names, model["coef"])


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)
    return [{"key": "model", "path": path, "format": "joblib"}]


def load_model(directory):
    import joblib

    return joblib.load(os.path.join(directory, "model.joblib"))


# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
    prep = design.fit(df.iloc[fold.train])
    model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
    run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
    progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")

# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
    model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
    if resampled is not None:
        from codesplash.ml import resample as csres

        warnings.extend(resampled["notes"])
        notes.append(csres.describe(resampled))
    if len(plan.test):
        run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
    importance = feature_importance(model, names)
    artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
    artifacts.extend(save_model(model, out))
    run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()

# %% Result
cs.publish(
    run.result(
        title="Text encoder (MiniLM + linear head)",
        engine=cs.engine_info("numpy", "pandas", "codesplash", "numpy", "pandas"),
        n_features=len(names),
        n_train=len(plan.train),
        n_test=len(plan.test),
        params=PARAMS,
        features=names,
        importance=importance,
        artifacts=artifacts,
        warnings=warnings,
        notes=notes,
    )
)

Text encoder reads each review with MiniLM, a small BERT-architecture encoder, and fits a penalized logistic regression on the frozen vectors, a linear probeLinear probeA penalized linear or logistic model trained on a frozen encoder's vectors; how well it does shows what the vectors already encode.. Cross-validated ROC AUC is 0.827; the locked test set of 12 reviews gives 0.944. With so few test rows, trust the cross-validated figure more.

Encoder also offers RoBERTa base. BERT-style encoders run in CodeSplash this way, and Training can also fine-tune their top layers or add LoRA; XLNet is explained here only.

06

Where it stands in CodeSplash

Read
EntryIn CodeSplash
BERT (LNG010)Runs in CodeSplash: Text encoder with MiniLM, frozen, fine-tuned or with LoRA
RoBERTa (LNG011)Partly runs in CodeSplash: Encoder: RoBERTa base, frozen, fine-tuned or with LoRA; its pretraining recipe isn't run here
XLNet (LNG014)Explained here
07

Check: the BERT family

Checkpoint

Check yourself

What lets BERT use the words on both sides of a position?

Show the answer

Answer: a

Masked language modeling hides tokens instead of hiding the future, so every position can attend to both sides. ELMo needed two one-way models for that.

Check yourself

In masked language modeling, which positions contribute to the loss?

Show the answer

Answer: b

The loss is the mean negative log-probability of the original tokens at the chosen positions; the rest serve as context.

Check yourself

What is dynamic masking in RoBERTa?

Show the answer

Answer: b

A fixed mask shows the model the same blanks every epoch; a fresh mask turns each pass into new training examples.

Check yourself

RoBERTa beat BERT with the same architecture. What does that teach about comparing models?

Show the answer

Answer: b

An apparent architecture gain may be a training-budget gain. Fair comparisons hold data and compute fixed.

Check yourself

In XLNet, a token is predicted from which other tokens?

Show the answer

Answer: c

Averaging over many orders gives each token context from both sides, without an artificial mask symbol.

Check yourself

Which weakness of masked language modeling was XLNet designed to avoid?

Show the answer

Answer: a

Permutation language modeling stays autoregressive, so predictions condition on each other, and no mask symbol is needed.

08

Recap

Recap
  • BERT predicts hidden tokens from both sides; the loss covers the masked positions only.
  • RoBERTa kept the architecture and improved the recipe: more data, dynamic masks, no next-sentence task.
  • XLNet predicted tokens in sampled orders; it was later superseded.
  • Text encoder runs BERT-style encoders frozen with a linear head, or fine-tunes their top layers or LoRA updates with it.

Concepts in this lesson