Skip to content

Frozen, adapted or fine-tuned: transfer on equal terms

Reuse a pretrained network three ways - frozen features with a new head, a few adapted weights, or fine-tuning its layers - and compare them fairly, with the same rows, folds and budget.

Applied ~15 min8 steps

What runs in CodeSplash

You will be able to

  • Name the three ways to reuse a pretrained network and what each one trains
  • Explain why fine-tuning starts from a fitted head (linear probing, then fine-tuning)
  • Read trainable-parameter counts and fold spreads side by side
  • Set up a comparison of full fine-tuning, frozen features and adapters on equal terms

Read first

01

Three ways to reuse a network

Read

Transfer learningTransfer learningReusing a network trained on a large dataset as the start for a new task, so a few hundred images can be enough. starts from a network trained on a large dataset. There are three ways to use it:

WayWhat trainsTypical use
Frozen featuresOnly a new head on the network's outputs (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.)Few rows; the pretrained features already separate the classes
AdaptersA small number of added weights, the network frozen (LoRA, adapters, prefixes)More rows, limited memory, many tasks sharing one base
Fine-tuningSome or all of the network's own weightsEnough rows, and wording or images the pretrained network doesn't separate
02

Start from a fitted head

Read

A new head starts from random weights. Fine-tune it together with the encoder from there, and the first large, noisy gradients flow into the pretrained layers and scramble features that were fine. Linear probing, then fine-tuningLinear probing, then fine-tuningFit the new head on frozen features first, then fine-tune encoder and head together starting from that head. fits the head on frozen features first and fine-tunes from that point.

CodeSplash's Text encoder fine-tunes this way. With zero epochs, fine-tuning returns the frozen model with its fitted head:

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

Text encoder (MiniLM + linear head): cross-validated RMSE 1.076 ± 0.208 over 3 folds; RMSE on the locked test set 0.751 (n = 12).

CV RMSE
1.076
SD across folds
0.2077
Test RMSE
0.7509

Cross-validation

FoldRepeatnRMSEMAER²MAPE
11161.2501.0160.29440.5413
21160.84590.69320.66070.3799
31161.1310.89330.23970.2539

Feature importance

FeatureImportance
review text__emb_1661.472
review text__emb_1391.466
review text__emb_2741.349
review text__emb_1681.313
review text__emb_3011.310
review text__emb_1481.247
review text__emb_1671.232
review text__emb_2551.217
review text__emb_2121.188
review text__emb_171.163
review text__emb_2711.151
review text__emb_3021.141
review text__emb_1421.115
review text__emb_2831.112
review text__emb_3561.055
review text__emb_581.034
review text__emb_3311.031
review text__emb_270.9883
review text__emb_3110.9678
review text__emb_2730.9578
review text__emb_1430.9511
review text__emb_3000.9421
review text__emb_930.9400
review text__emb_1610.9237
review text__emb_2870.8624
review text__emb_860.8577
review text__emb_380.8472
review text__emb_2630.8407
review text__emb_2320.8390
review text__emb_2890.8325

Encoder training (final model)

SettingValue
TrainingFine-tune the top layers
Layers adapted5–6 of 6
Trainable numbers3,549,316
Epochs run0
Final training loss—
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 1098e15b5b449385
# 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 <- "stars"
FEATURES <- c("product")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
  encoder = "minilm",
  penalty = 0.001,
  max_iter = 100,
  mode = "fine_tune",
  train_layers = 2,
  epochs = 0,
  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/regression_fine_tune_zero_epochs/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 = 16L
)
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/regression_fine_tune_zero_epochs/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/regression_fine_tune_zero_epochs/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

# Training "fine_tune" (cs_ttune_*, twin of codesplash.text.encoder_tune): the top 2 encoder layers adapt
# too (all of their weights). Each fit
# first fits the head exactly as the frozen model does (every embedding dimension kept), then trains encoder and head
# together with Adam on the same penalized loss. The design carries each row's position in a key column inside the
# text's embedding group, so every mode (train, score, explain) finds the text behind a design row.
TEXT <- ENCODE_TEXT[1]
.keyed <- cs_ttune_add_key_column(df, EMBED, design)
df <- .keyed$df
design <- .keyed$design
TEXTS <- cs_ttune_frame_texts(df[[TEXT]])
# The trainer (set up above by the deep driver: training options, live progress, fold labels, checkpoints) runs
# the Adam phase of every fit; a stopped run resumes each fit from its last checkpoint.
TUNER <- cs_ttune_tuner(cs_ttune_load_encoder("minilm"), "fine_tune", as.integer(PARAMS$train_layers))

# `prep` is this fit's design (training) or the saved one (score, explain): its key mean reads positions back.
.tune_rows <- function(X) {
  cols <- cs_ttune_columns(cs_ml_design_names(prep), TEXT, as.character(unlist(EMBED[[TEXT]])))
  key_mean <- utils::tail(as.numeric(unlist(prep$embed_state[[TEXT]]$mean)), 1L)
  pos <- cs_ttune_row_positions(X, cols$key, key_mean, nrow(df))
  list(cols = cols, texts = TEXTS[pos + 1L])
}

fit_model <- function(X, y, w) {
  r <- .tune_rows(X)
  cs_ttune_fit(TUNER, X, y, w, r$texts, r$cols, TASK, length(CLASSES), LAMBDA, as.integer(PARAMS$max_iter),
               as.integer(PARAMS$epochs), as.numeric(PARAMS$learning_rate), as.integer(PARAMS$batch_size), SEED,
               rank = as.integer(PARAMS$lora_rank), alpha = as.numeric(PARAMS$lora_alpha))
}

predict_model <- function(model, X) {
  # Ties within 1e-12 are set equal, as in frozen mode, so the first class wins in both engines.
  r <- .tune_rows(X)
  eta <- cs_ttune_predict_linear(TUNER, model, X, r$texts, r$cols, TASK)
  if (TASK == "multiclass") {
    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))
  }
  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(setdiff(names, cs_ttune_key_column(TEXT)), 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_ttune_extend_result(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
), model, TUNER))
Python

Text encoder (MiniLM + linear head): cross-validated RMSE 1.076 ± 0.208 over 3 folds; RMSE on the locked test set 0.751 (n = 12).

CV RMSE
1.076
SD across folds
0.2077
Test RMSE
0.7509

Cross-validation

FoldRepeatnRMSEMAER²MAPE
11161.2501.0160.29440.5413
21160.84590.69320.66070.3799
31161.1310.89330.23970.2539

Feature importance

FeatureImportance
review text__emb_1661.472
review text__emb_1391.466
review text__emb_2741.349
review text__emb_1681.313
review text__emb_3011.310
review text__emb_1481.247
review text__emb_1671.232
review text__emb_2551.217
review text__emb_2121.188
review text__emb_171.163
review text__emb_2711.151
review text__emb_3021.141
review text__emb_1421.115
review text__emb_2831.112
review text__emb_3561.055
review text__emb_581.034
review text__emb_3311.031
review text__emb_270.9883
review text__emb_3110.9678
review text__emb_2730.9578
review text__emb_1430.9511
review text__emb_3000.9421
review text__emb_930.9400
review text__emb_1610.9237
review text__emb_2870.8624
review text__emb_860.8577
review text__emb_380.8472
review text__emb_2630.8407
review text__emb_2320.8390
review text__emb_2890.8325

Encoder training (final model)

SettingValue
TrainingFine-tune the top layers
Layers adapted5–6 of 6
Trainable numbers3,549,316
Epochs run0
Final training loss—
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 1098e15b5b449385
# 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_*)
from codesplash.text import encoder_tune as cstune  # fine-tuning / LoRA of the top layers (twin: codesplashr cs_ttune_*)

# %% Data and split plan
TARGET = "stars"
FEATURES = ["product"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
    "encoder": "minilm",
    "penalty": 0.001,
    "max_iter": 100,
    "mode": "fine_tune",
    "train_layers": 2,
    "epochs": 0,
    "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/regression_fine_tune_zero_epochs/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=16,
)
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/regression_fine_tune_zero_epochs/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/regression_fine_tune_zero_epochs/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"]

# Training "fine_tune" (codesplash.text.encoder_tune): the top 2 encoder layers adapt too
# (all of their weights). Each fit
# first fits the head exactly as the frozen model does (every embedding dimension kept), then trains encoder and
# head together with Adam on the same penalized loss. The design carries each row's position in a key column
# inside the text's embedding group, so every mode (train, score, explain) finds the text behind a design row.
TEXT = ENCODE_TEXT[0]
df = cstune.add_key_column(df, EMBED, design)
TEXTS = cstune.frame_texts(df[TEXT])
# The trainer (set up above by the deep driver: training options, live progress, fold labels, checkpoints)
# runs the Adam phase of every fit; a stopped run resumes each fit from its last checkpoint.
TUNER = cstune.Tuner(cstune.load_encoder("minilm"), "fine_tune", int(PARAMS["train_layers"]))


def _rows(X):
    # `prep` is this fit's design (training) or the saved one (score, explain): its key mean reads positions back.
    cols = cstune.columns(list(prep.names), TEXT, EMBED[TEXT])
    pos = cstune.row_positions(X, cols["key"], prep.embed_state[TEXT]["mean"][-1], len(df))
    return cols, cstune.texts_at(TEXTS, pos)


def fit_model(X, y, w):
    cols, texts = _rows(X)
    return cstune.fit(
        TUNER, X, y, w, texts, cols, TASK, len(CLASSES), LAMBDA, int(PARAMS["max_iter"]), int(PARAMS["epochs"]),
        float(PARAMS["learning_rate"]), int(PARAMS["batch_size"]), SEED, rank=int(PARAMS["lora_rank"]),
        alpha=float(PARAMS["lora_alpha"]),
    )


def predict_model(model, X):
    # Ties within 1e-12 are set equal, as in frozen mode, so the first class wins in both engines.
    cols, texts = _rows(X)
    eta = cstune.predict_linear(TUNER, model, X, texts, cols, TASK)
    if TASK == "multiclass":
        P = cslin.softmax_rows(eta)
        m = P.max(axis=1, keepdims=True)
        return np.where(P >= m - 1e-12, m, P)
    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([n for n in names if n != cstune.key_column(TEXT)], 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(
    cstune.extend_result(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,
    ), model, TUNER)
)
03

Frozen and fine-tuned, side by side

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 (MiniLM + linear head)Recorded · Python and R agreeRecorded 2026-11-25 · 423 values compared
R

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

CV ROC AUC
0.8527
SD across folds
0.0797
Test ROC AUC
0.8889

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
11160.77780.60330.68750.6587
21160.93650.38210.87500.8730
31160.84380.47160.87500.8750

Feature importance

FeatureImportance
review text__emb_3010.8519
review text__emb_3560.7799
review text__emb_1420.7437
review text__emb_2550.6816
review text__emb_1680.6614
review text__emb_2250.6561
review text__emb_930.6065
review text__emb_860.6061
review text__emb_1750.5859
review text__emb_2700.5755
review text__emb_1370.5684
review text__emb_1650.5658
review text__emb_1440.5616
review text__emb_2320.5348
review text__emb_910.5271
review text__emb_2570.5131
review text__emb_2030.5116
review text__emb_1610.5046
review text__emb_2830.4995
review text__emb_3130.4926
review text__emb_370.4920
review text__emb_3620.4827
review text__emb_2630.4787
review text__emb_1660.4786
review text__emb_2930.4726
review text__emb_2750.4465
review text__emb_2810.4363
review text__emb_1150.4361
review text__emb_3110.4321
review text__emb_1670.4312

Encoder training (final model)

SettingValue
TrainingFine-tune the top layers
Layers adapted6 of 6
Trainable numbers1,774,852
Epochs run2
Final training loss0.327766
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 fffec14925458a2a
# 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 = "fine_tune",
  train_layers = 1,
  epochs = 2,
  learning_rate = 0.0005,
  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_fine_tune_top_layer/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 = 16L
)
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_fine_tune_top_layer/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_fine_tune_top_layer/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

# Training "fine_tune" (cs_ttune_*, twin of codesplash.text.encoder_tune): the top 1 encoder layers adapt
# too (all of their weights). Each fit
# first fits the head exactly as the frozen model does (every embedding dimension kept), then trains encoder and head
# together with Adam on the same penalized loss. The design carries each row's position in a key column inside the
# text's embedding group, so every mode (train, score, explain) finds the text behind a design row.
TEXT <- ENCODE_TEXT[1]
.keyed <- cs_ttune_add_key_column(df, EMBED, design)
df <- .keyed$df
design <- .keyed$design
TEXTS <- cs_ttune_frame_texts(df[[TEXT]])
# The trainer (set up above by the deep driver: training options, live progress, fold labels, checkpoints) runs
# the Adam phase of every fit; a stopped run resumes each fit from its last checkpoint.
TUNER <- cs_ttune_tuner(cs_ttune_load_encoder("minilm"), "fine_tune", as.integer(PARAMS$train_layers))

# `prep` is this fit's design (training) or the saved one (score, explain): its key mean reads positions back.
.tune_rows <- function(X) {
  cols <- cs_ttune_columns(cs_ml_design_names(prep), TEXT, as.character(unlist(EMBED[[TEXT]])))
  key_mean <- utils::tail(as.numeric(unlist(prep$embed_state[[TEXT]]$mean)), 1L)
  pos <- cs_ttune_row_positions(X, cols$key, key_mean, nrow(df))
  list(cols = cols, texts = TEXTS[pos + 1L])
}

fit_model <- function(X, y, w) {
  r <- .tune_rows(X)
  cs_ttune_fit(TUNER, X, y, w, r$texts, r$cols, TASK, length(CLASSES), LAMBDA, as.integer(PARAMS$max_iter),
               as.integer(PARAMS$epochs), as.numeric(PARAMS$learning_rate), as.integer(PARAMS$batch_size), SEED,
               rank = as.integer(PARAMS$lora_rank), alpha = as.numeric(PARAMS$lora_alpha))
}

predict_model <- function(model, X) {
  # Ties within 1e-12 are set equal, as in frozen mode, so the first class wins in both engines.
  r <- .tune_rows(X)
  eta <- cs_ttune_predict_linear(TUNER, model, X, r$texts, r$cols, TASK)
  if (TASK == "multiclass") {
    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))
  }
  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(setdiff(names, cs_ttune_key_column(TEXT)), 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_ttune_extend_result(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
), model, TUNER))
Python

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

CV ROC AUC
0.8527
SD across folds
0.0797
Test ROC AUC
0.8889

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
11160.77780.60330.68750.6587
21160.93650.38210.87500.8730
31160.84380.47160.87500.8750

Feature importance

FeatureImportance
review text__emb_3010.8519
review text__emb_3560.7799
review text__emb_1420.7437
review text__emb_2550.6816
review text__emb_1680.6614
review text__emb_2250.6561
review text__emb_930.6065
review text__emb_860.6061
review text__emb_1750.5859
review text__emb_2700.5755
review text__emb_1370.5684
review text__emb_1650.5658
review text__emb_1440.5616
review text__emb_2320.5348
review text__emb_910.5271
review text__emb_2570.5131
review text__emb_2030.5116
review text__emb_1610.5046
review text__emb_2830.4995
review text__emb_3130.4926
review text__emb_370.4920
review text__emb_3620.4827
review text__emb_2630.4787
review text__emb_1660.4786
review text__emb_2930.4726
review text__emb_2750.4465
review text__emb_2810.4363
review text__emb_1150.4361
review text__emb_3110.4321
review text__emb_1670.4312

Encoder training (final model)

SettingValue
TrainingFine-tune the top layers
Layers adapted6 of 6
Trainable numbers1,774,852
Epochs run2
Final training loss0.327766
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 fffec14925458a2a
# 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_*)
from codesplash.text import encoder_tune as cstune  # fine-tuning / LoRA of the top layers (twin: codesplashr cs_ttune_*)

# %% 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": "fine_tune",
    "train_layers": 1,
    "epochs": 2,
    "learning_rate": 0.0005,
    "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_fine_tune_top_layer/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=16,
)
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_fine_tune_top_layer/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_fine_tune_top_layer/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"]

# Training "fine_tune" (codesplash.text.encoder_tune): the top 1 encoder layers adapt too
# (all of their weights). Each fit
# first fits the head exactly as the frozen model does (every embedding dimension kept), then trains encoder and
# head together with Adam on the same penalized loss. The design carries each row's position in a key column
# inside the text's embedding group, so every mode (train, score, explain) finds the text behind a design row.
TEXT = ENCODE_TEXT[0]
df = cstune.add_key_column(df, EMBED, design)
TEXTS = cstune.frame_texts(df[TEXT])
# The trainer (set up above by the deep driver: training options, live progress, fold labels, checkpoints)
# runs the Adam phase of every fit; a stopped run resumes each fit from its last checkpoint.
TUNER = cstune.Tuner(cstune.load_encoder("minilm"), "fine_tune", int(PARAMS["train_layers"]))


def _rows(X):
    # `prep` is this fit's design (training) or the saved one (score, explain): its key mean reads positions back.
    cols = cstune.columns(list(prep.names), TEXT, EMBED[TEXT])
    pos = cstune.row_positions(X, cols["key"], prep.embed_state[TEXT]["mean"][-1], len(df))
    return cols, cstune.texts_at(TEXTS, pos)


def fit_model(X, y, w):
    cols, texts = _rows(X)
    return cstune.fit(
        TUNER, X, y, w, texts, cols, TASK, len(CLASSES), LAMBDA, int(PARAMS["max_iter"]), int(PARAMS["epochs"]),
        float(PARAMS["learning_rate"]), int(PARAMS["batch_size"]), SEED, rank=int(PARAMS["lora_rank"]),
        alpha=float(PARAMS["lora_alpha"]),
    )


def predict_model(model, X):
    # Ties within 1e-12 are set equal, as in frozen mode, so the first class wins in both engines.
    cols, texts = _rows(X)
    eta = cstune.predict_linear(TUNER, model, X, texts, cols, TASK)
    if TASK == "multiclass":
        P = cslin.softmax_rows(eta)
        m = P.max(axis=1, keepdims=True)
        return np.where(P >= m - 1e-12, m, P)
    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([n for n in names if n != cstune.key_column(TEXT)], 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(
    cstune.extend_result(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,
    ), model, TUNER)
)

The frozen encoder with a penalized logistic head scores a CV ROC AUC of 0.827 (SD 0.083 across folds). Fine-tuning the top layer trains 1,774,852 encoder weights and scores 0.853 (SD 0.080). With 48 training rows, that gap is well inside the fold spread.

04

Adapters train far fewer weights

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

Text encoder (MiniLM + linear head): cross-validated log loss 0.634 ± 0.122 over 3 folds; log loss on the locked test set 0.445 (n = 12).

CV log loss
0.6336
SD across folds
0.1215
Test log loss
0.4448

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
11160.61820.68750.70000.6940
21160.76210.62500.65560.5822
31160.52060.81250.81110.8030

Feature importance

FeatureImportance
review text__emb_1421.022
review text__emb_3810.9445
review text__emb_2530.9327
review text__emb_890.8786
review text__emb_250.8353
review text__emb_600.7920
review text__emb_1390.7838
review text__emb_1810.7481
review text__emb_1820.7455
review text__emb_3670.7370
review text__emb_1180.7298
review text__emb_2930.7156
review text__emb_2950.7153
review text__emb_1780.6845
review text__emb_1590.6720
review text__emb_2470.6538
review text__emb_40.6520
review text__emb_1940.6199
review text__emb_850.6125
review text__emb_2610.5852
review text__emb_2320.5752
review text__emb_3240.5696
review text__emb_2640.5688
review text__emb_20.5642
review text__emb_1920.5575
review text__emb_3540.5571
review text__emb_1970.5562
review text__emb_3460.5535
review text__emb_160.5482
review text__emb_400.5472

Encoder training (final model)

SettingValue
TrainingLoRA, rank 4, α 8
Layers adapted5–6 of 6
Trainable numbers13,060
Epochs run2
Final training loss0.256879
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 e7ba173d10456bf3
# 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 <- "product"
FEATURES <- c("stars")
TASK <- "multiclass"
CLASSES <- c("coffee maker", "headphones", "running shoes")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
  encoder = "minilm",
  penalty = 0.001,
  max_iter = 100,
  mode = "lora",
  train_layers = 2,
  epochs = 2,
  learning_rate = 0.002,
  batch_size = 20,
  lora_rank = 4,
  lora_alpha = 8,
  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/multiclass_lora/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(
    stars = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "standard",
  indicators = FALSE,
  embed = EMBED,
  embed_pcs = 16L
)
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/multiclass_lora/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/multiclass_lora/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

# Training "lora" (cs_ttune_*, twin of codesplash.text.encoder_tune): the top 2 encoder layers adapt
# too (LoRA updates to their query and value weights). Each fit
# first fits the head exactly as the frozen model does (every embedding dimension kept), then trains encoder and head
# together with Adam on the same penalized loss. The design carries each row's position in a key column inside the
# text's embedding group, so every mode (train, score, explain) finds the text behind a design row.
TEXT <- ENCODE_TEXT[1]
.keyed <- cs_ttune_add_key_column(df, EMBED, design)
df <- .keyed$df
design <- .keyed$design
TEXTS <- cs_ttune_frame_texts(df[[TEXT]])
# The trainer (set up above by the deep driver: training options, live progress, fold labels, checkpoints) runs
# the Adam phase of every fit; a stopped run resumes each fit from its last checkpoint.
TUNER <- cs_ttune_tuner(cs_ttune_load_encoder("minilm"), "lora", as.integer(PARAMS$train_layers))

# `prep` is this fit's design (training) or the saved one (score, explain): its key mean reads positions back.
.tune_rows <- function(X) {
  cols <- cs_ttune_columns(cs_ml_design_names(prep), TEXT, as.character(unlist(EMBED[[TEXT]])))
  key_mean <- utils::tail(as.numeric(unlist(prep$embed_state[[TEXT]]$mean)), 1L)
  pos <- cs_ttune_row_positions(X, cols$key, key_mean, nrow(df))
  list(cols = cols, texts = TEXTS[pos + 1L])
}

fit_model <- function(X, y, w) {
  r <- .tune_rows(X)
  cs_ttune_fit(TUNER, X, y, w, r$texts, r$cols, TASK, length(CLASSES), LAMBDA, as.integer(PARAMS$max_iter),
               as.integer(PARAMS$epochs), as.numeric(PARAMS$learning_rate), as.integer(PARAMS$batch_size), SEED,
               rank = as.integer(PARAMS$lora_rank), alpha = as.numeric(PARAMS$lora_alpha))
}

predict_model <- function(model, X) {
  # Ties within 1e-12 are set equal, as in frozen mode, so the first class wins in both engines.
  r <- .tune_rows(X)
  eta <- cs_ttune_predict_linear(TUNER, model, X, r$texts, r$cols, TASK)
  if (TASK == "multiclass") {
    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))
  }
  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(setdiff(names, cs_ttune_key_column(TEXT)), 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_ttune_extend_result(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
), model, TUNER))
Python

Text encoder (MiniLM + linear head): cross-validated log loss 0.634 ± 0.122 over 3 folds; log loss on the locked test set 0.445 (n = 12).

CV log loss
0.6336
SD across folds
0.1215
Test log loss
0.4448

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
11160.61820.68750.70000.6940
21160.76210.62500.65560.5822
31160.52060.81250.81110.8030

Feature importance

FeatureImportance
review text__emb_1421.022
review text__emb_3810.9445
review text__emb_2530.9327
review text__emb_890.8786
review text__emb_250.8353
review text__emb_600.7920
review text__emb_1390.7838
review text__emb_1810.7481
review text__emb_1820.7455
review text__emb_3670.7370
review text__emb_1180.7298
review text__emb_2930.7156
review text__emb_2950.7153
review text__emb_1780.6845
review text__emb_1590.6720
review text__emb_2470.6538
review text__emb_40.6520
review text__emb_1940.6199
review text__emb_850.6125
review text__emb_2610.5852
review text__emb_2320.5752
review text__emb_3240.5696
review text__emb_2640.5688
review text__emb_20.5642
review text__emb_1920.5575
review text__emb_3540.5571
review text__emb_1970.5562
review text__emb_3460.5535
review text__emb_160.5482
review text__emb_400.5472

Encoder training (final model)

SettingValue
TrainingLoRA, rank 4, α 8
Layers adapted5–6 of 6
Trainable numbers13,060
Epochs run2
Final training loss0.256879
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 e7ba173d10456bf3
# 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_*)
from codesplash.text import encoder_tune as cstune  # fine-tuning / LoRA of the top layers (twin: codesplashr cs_ttune_*)

# %% Data and split plan
TARGET = "product"
FEATURES = ["stars"]
TASK = "multiclass"
CLASSES = ["coffee maker", "headphones", "running shoes"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
    "encoder": "minilm",
    "penalty": 0.001,
    "max_iter": 100,
    "mode": "lora",
    "train_layers": 2,
    "epochs": 2,
    "learning_rate": 0.002,
    "batch_size": 20,
    "lora_rank": 4,
    "lora_alpha": 8,
    "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/multiclass_lora/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={
        "stars": "numeric",
    },
    levels={
    },
    impute="median",
    scale="standard",
    indicators=False,
    embed=EMBED,
    embed_pcs=16,
)
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/multiclass_lora/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/multiclass_lora/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"]

# Training "lora" (codesplash.text.encoder_tune): the top 2 encoder layers adapt too
# (LoRA updates to their query and value weights). Each fit
# first fits the head exactly as the frozen model does (every embedding dimension kept), then trains encoder and
# head together with Adam on the same penalized loss. The design carries each row's position in a key column
# inside the text's embedding group, so every mode (train, score, explain) finds the text behind a design row.
TEXT = ENCODE_TEXT[0]
df = cstune.add_key_column(df, EMBED, design)
TEXTS = cstune.frame_texts(df[TEXT])
# The trainer (set up above by the deep driver: training options, live progress, fold labels, checkpoints)
# runs the Adam phase of every fit; a stopped run resumes each fit from its last checkpoint.
TUNER = cstune.Tuner(cstune.load_encoder("minilm"), "lora", int(PARAMS["train_layers"]))


def _rows(X):
    # `prep` is this fit's design (training) or the saved one (score, explain): its key mean reads positions back.
    cols = cstune.columns(list(prep.names), TEXT, EMBED[TEXT])
    pos = cstune.row_positions(X, cols["key"], prep.embed_state[TEXT]["mean"][-1], len(df))
    return cols, cstune.texts_at(TEXTS, pos)


def fit_model(X, y, w):
    cols, texts = _rows(X)
    return cstune.fit(
        TUNER, X, y, w, texts, cols, TASK, len(CLASSES), LAMBDA, int(PARAMS["max_iter"]), int(PARAMS["epochs"]),
        float(PARAMS["learning_rate"]), int(PARAMS["batch_size"]), SEED, rank=int(PARAMS["lora_rank"]),
        alpha=float(PARAMS["lora_alpha"]),
    )


def predict_model(model, X):
    # Ties within 1e-12 are set equal, as in frozen mode, so the first class wins in both engines.
    cols, texts = _rows(X)
    eta = cstune.predict_linear(TUNER, model, X, texts, cols, TASK)
    if TASK == "multiclass":
        P = cslin.softmax_rows(eta)
        m = P.max(axis=1, keepdims=True)
        return np.where(P >= m - 1e-12, m, P)
    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([n for n in names if n != cstune.key_column(TEXT)], 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(
    cstune.extend_result(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,
    ), model, TUNER)
)

With LoRA of rank 4 on two layers, only 13,060 encoder weights train. That is a different task (three classes), so its score isn't comparable with the two runs above. What carries over is the scale: adapters train a small fraction of what fine-tuning does, which keeps the stored update small and leaves the base network untouched.

05

Comparing on equal terms

Checkpoint

A fair comparison of frozen features, adapters and fine-tuning holds everything else fixed:

  • the same rows and folds, and the same held-out test rows, touched once;
  • the same tuning budget for each: if fine-tuning gets a learning-rate search, so does the probe's penalty;
  • the same seeds, then a few more seeds, because small-data fine-tuning varies from seed to seed;
  • the fold spread next to every score, and the trainable-parameter count and training time next to it.

Check yourself

Fine-tuning gets a CV score 0.02 above the frozen probe. Its fold SD is 0.08, and only fine-tuning had its learning rate tuned. What do you conclude?

Show the answer

Answer: b

The gap is a quarter of the fold spread and the tuning budgets differ. Equalize the budget, then look again with more seeds.

06

Common mistakes

Read
07

Check: transfer

Checkpoint

Check yourself

Which way of reusing a pretrained network leaves every pretrained weight unchanged and stores only a small extra set of weights per task?

Show the answer

Answer: b

Adapters freeze the base network. A frozen probe also leaves it unchanged, but trains only a head on its outputs rather than weights inside it.

Check yourself

Why fit the head on frozen features before fine-tuning the encoder?

Show the answer

Answer: a

A fitted head sends small, sensible gradients into the encoder from the first step.

Check yourself

You have 60 labeled reviews and a pretrained text encoder. Which do you try first?

Show the answer

Answer: a

With few rows, the frozen encoder is the cheap, stable baseline. Fine-tuning has to beat it on the same folds by more than the spread.

08

Recap

Recap
  • Reuse a network as frozen features, through adapters, or by fine-tuning its own weights.
  • Fine-tune from a fitted head (LP-FT) so early steps don't scramble pretrained features.
  • Report trainable parameters, time and fold spread next to every score.
  • Compare on equal terms: same rows, folds, seeds and tuning budget.

Concepts in this lesson