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.
What runs in CodeSplash
- Text encoder (MiniLM + linear head) Not verified yet
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
Three ways to reuse a network
ReadTransfer 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:
| Way | What trains | Typical use |
|---|---|---|
| Frozen features | Only 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 |
| Adapters | A small number of added weights, the network frozen (LoRA, adapters, prefixes) | More rows, limited memory, many tasks sharing one base |
| Fine-tuning | Some or all of the network's own weights | Enough rows, and wording or images the pretrained network doesn't separate |
Start from a fitted head
ReadA 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): 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
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 1.250 | 1.016 | 0.2944 | 0.5413 |
| 2 | 1 | 16 | 0.8459 | 0.6932 | 0.6607 | 0.3799 |
| 3 | 1 | 16 | 1.131 | 0.8933 | 0.2397 | 0.2539 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_166 | 1.472 |
| review text__emb_139 | 1.466 |
| review text__emb_274 | 1.349 |
| review text__emb_168 | 1.313 |
| review text__emb_301 | 1.310 |
| review text__emb_148 | 1.247 |
| review text__emb_167 | 1.232 |
| review text__emb_255 | 1.217 |
| review text__emb_212 | 1.188 |
| review text__emb_17 | 1.163 |
| review text__emb_271 | 1.151 |
| review text__emb_302 | 1.141 |
| review text__emb_142 | 1.115 |
| review text__emb_283 | 1.112 |
| review text__emb_356 | 1.055 |
| review text__emb_58 | 1.034 |
| review text__emb_331 | 1.031 |
| review text__emb_27 | 0.9883 |
| review text__emb_311 | 0.9678 |
| review text__emb_273 | 0.9578 |
| review text__emb_143 | 0.9511 |
| review text__emb_300 | 0.9421 |
| review text__emb_93 | 0.9400 |
| review text__emb_161 | 0.9237 |
| review text__emb_287 | 0.8624 |
| review text__emb_86 | 0.8577 |
| review text__emb_38 | 0.8472 |
| review text__emb_263 | 0.8407 |
| review text__emb_232 | 0.8390 |
| review text__emb_289 | 0.8325 |
Encoder training (final model)
| Setting | Value |
|---|---|
| Training | Fine-tune the top layers |
| Layers adapted | 5–6 of 6 |
| Trainable numbers | 3,549,316 |
| Epochs run | 0 |
| 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))
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
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 1.250 | 1.016 | 0.2944 | 0.5413 |
| 2 | 1 | 16 | 0.8459 | 0.6932 | 0.6607 | 0.3799 |
| 3 | 1 | 16 | 1.131 | 0.8933 | 0.2397 | 0.2539 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_166 | 1.472 |
| review text__emb_139 | 1.466 |
| review text__emb_274 | 1.349 |
| review text__emb_168 | 1.313 |
| review text__emb_301 | 1.310 |
| review text__emb_148 | 1.247 |
| review text__emb_167 | 1.232 |
| review text__emb_255 | 1.217 |
| review text__emb_212 | 1.188 |
| review text__emb_17 | 1.163 |
| review text__emb_271 | 1.151 |
| review text__emb_302 | 1.141 |
| review text__emb_142 | 1.115 |
| review text__emb_283 | 1.112 |
| review text__emb_356 | 1.055 |
| review text__emb_58 | 1.034 |
| review text__emb_331 | 1.031 |
| review text__emb_27 | 0.9883 |
| review text__emb_311 | 0.9678 |
| review text__emb_273 | 0.9578 |
| review text__emb_143 | 0.9511 |
| review text__emb_300 | 0.9421 |
| review text__emb_93 | 0.9400 |
| review text__emb_161 | 0.9237 |
| review text__emb_287 | 0.8624 |
| review text__emb_86 | 0.8577 |
| review text__emb_38 | 0.8472 |
| review text__emb_263 | 0.8407 |
| review text__emb_232 | 0.8390 |
| review text__emb_289 | 0.8325 |
Encoder training (final model)
| Setting | Value |
|---|---|
| Training | Fine-tune the top layers |
| Layers adapted | 5–6 of 6 |
| Trainable numbers | 3,549,316 |
| Epochs run | 0 |
| 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)
)
Frozen and fine-tuned, side by side
ReadText 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
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 0.7937 | 0.5614 | 0.7500 | 0.7460 |
| 2 | 1 | 16 | 0.9206 | 0.4923 | 0.7500 | 0.7460 |
| 3 | 1 | 16 | 0.7656 | 0.5421 | 0.7500 | 0.7500 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_301 | 0.8534 |
| review text__emb_356 | 0.7815 |
| review text__emb_142 | 0.7447 |
| review text__emb_255 | 0.6827 |
| review text__emb_168 | 0.6621 |
| review text__emb_225 | 0.6568 |
| review text__emb_86 | 0.6081 |
| review text__emb_93 | 0.6065 |
| review text__emb_175 | 0.5842 |
| review text__emb_270 | 0.5752 |
| review text__emb_137 | 0.5685 |
| review text__emb_165 | 0.5658 |
| review text__emb_144 | 0.5626 |
| review text__emb_232 | 0.5352 |
| review text__emb_91 | 0.5280 |
| review text__emb_257 | 0.5148 |
| review text__emb_203 | 0.5128 |
| review text__emb_161 | 0.5071 |
| review text__emb_283 | 0.5020 |
| review text__emb_313 | 0.4941 |
| review text__emb_37 | 0.4924 |
| review text__emb_362 | 0.4824 |
| review text__emb_263 | 0.4805 |
| review text__emb_166 | 0.4795 |
| review text__emb_293 | 0.4731 |
| review text__emb_275 | 0.4468 |
| review text__emb_281 | 0.4385 |
| review text__emb_115 | 0.4376 |
| review text__emb_311 | 0.4334 |
| review text__emb_167 | 0.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
))
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
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 0.7937 | 0.5614 | 0.7500 | 0.7460 |
| 2 | 1 | 16 | 0.9206 | 0.4923 | 0.7500 | 0.7460 |
| 3 | 1 | 16 | 0.7656 | 0.5421 | 0.7500 | 0.7500 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_301 | 0.8534 |
| review text__emb_356 | 0.7815 |
| review text__emb_142 | 0.7447 |
| review text__emb_255 | 0.6827 |
| review text__emb_168 | 0.6621 |
| review text__emb_225 | 0.6568 |
| review text__emb_86 | 0.6081 |
| review text__emb_93 | 0.6065 |
| review text__emb_175 | 0.5842 |
| review text__emb_270 | 0.5752 |
| review text__emb_137 | 0.5685 |
| review text__emb_165 | 0.5658 |
| review text__emb_144 | 0.5626 |
| review text__emb_232 | 0.5352 |
| review text__emb_91 | 0.5280 |
| review text__emb_257 | 0.5148 |
| review text__emb_203 | 0.5128 |
| review text__emb_161 | 0.5071 |
| review text__emb_283 | 0.5020 |
| review text__emb_313 | 0.4941 |
| review text__emb_37 | 0.4924 |
| review text__emb_362 | 0.4824 |
| review text__emb_263 | 0.4805 |
| review text__emb_166 | 0.4795 |
| review text__emb_293 | 0.4731 |
| review text__emb_275 | 0.4468 |
| review text__emb_281 | 0.4385 |
| review text__emb_115 | 0.4376 |
| review text__emb_311 | 0.4334 |
| review text__emb_167 | 0.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): 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
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 0.7778 | 0.6033 | 0.6875 | 0.6587 |
| 2 | 1 | 16 | 0.9365 | 0.3821 | 0.8750 | 0.8730 |
| 3 | 1 | 16 | 0.8438 | 0.4716 | 0.8750 | 0.8750 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_301 | 0.8519 |
| review text__emb_356 | 0.7799 |
| review text__emb_142 | 0.7437 |
| review text__emb_255 | 0.6816 |
| review text__emb_168 | 0.6614 |
| review text__emb_225 | 0.6561 |
| review text__emb_93 | 0.6065 |
| review text__emb_86 | 0.6061 |
| review text__emb_175 | 0.5859 |
| review text__emb_270 | 0.5755 |
| review text__emb_137 | 0.5684 |
| review text__emb_165 | 0.5658 |
| review text__emb_144 | 0.5616 |
| review text__emb_232 | 0.5348 |
| review text__emb_91 | 0.5271 |
| review text__emb_257 | 0.5131 |
| review text__emb_203 | 0.5116 |
| review text__emb_161 | 0.5046 |
| review text__emb_283 | 0.4995 |
| review text__emb_313 | 0.4926 |
| review text__emb_37 | 0.4920 |
| review text__emb_362 | 0.4827 |
| review text__emb_263 | 0.4787 |
| review text__emb_166 | 0.4786 |
| review text__emb_293 | 0.4726 |
| review text__emb_275 | 0.4465 |
| review text__emb_281 | 0.4363 |
| review text__emb_115 | 0.4361 |
| review text__emb_311 | 0.4321 |
| review text__emb_167 | 0.4312 |
Encoder training (final model)
| Setting | Value |
|---|---|
| Training | Fine-tune the top layers |
| Layers adapted | 6 of 6 |
| Trainable numbers | 1,774,852 |
| Epochs run | 2 |
| Final training loss | 0.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))
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
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 0.7778 | 0.6033 | 0.6875 | 0.6587 |
| 2 | 1 | 16 | 0.9365 | 0.3821 | 0.8750 | 0.8730 |
| 3 | 1 | 16 | 0.8438 | 0.4716 | 0.8750 | 0.8750 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_301 | 0.8519 |
| review text__emb_356 | 0.7799 |
| review text__emb_142 | 0.7437 |
| review text__emb_255 | 0.6816 |
| review text__emb_168 | 0.6614 |
| review text__emb_225 | 0.6561 |
| review text__emb_93 | 0.6065 |
| review text__emb_86 | 0.6061 |
| review text__emb_175 | 0.5859 |
| review text__emb_270 | 0.5755 |
| review text__emb_137 | 0.5684 |
| review text__emb_165 | 0.5658 |
| review text__emb_144 | 0.5616 |
| review text__emb_232 | 0.5348 |
| review text__emb_91 | 0.5271 |
| review text__emb_257 | 0.5131 |
| review text__emb_203 | 0.5116 |
| review text__emb_161 | 0.5046 |
| review text__emb_283 | 0.4995 |
| review text__emb_313 | 0.4926 |
| review text__emb_37 | 0.4920 |
| review text__emb_362 | 0.4827 |
| review text__emb_263 | 0.4787 |
| review text__emb_166 | 0.4786 |
| review text__emb_293 | 0.4726 |
| review text__emb_275 | 0.4465 |
| review text__emb_281 | 0.4363 |
| review text__emb_115 | 0.4361 |
| review text__emb_311 | 0.4321 |
| review text__emb_167 | 0.4312 |
Encoder training (final model)
| Setting | Value |
|---|---|
| Training | Fine-tune the top layers |
| Layers adapted | 6 of 6 |
| Trainable numbers | 1,774,852 |
| Epochs run | 2 |
| Final training loss | 0.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.
Adapters train far fewer weights
ReadText 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
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 0.6182 | 0.6875 | 0.7000 | 0.6940 |
| 2 | 1 | 16 | 0.7621 | 0.6250 | 0.6556 | 0.5822 |
| 3 | 1 | 16 | 0.5206 | 0.8125 | 0.8111 | 0.8030 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_142 | 1.022 |
| review text__emb_381 | 0.9445 |
| review text__emb_253 | 0.9327 |
| review text__emb_89 | 0.8786 |
| review text__emb_25 | 0.8353 |
| review text__emb_60 | 0.7920 |
| review text__emb_139 | 0.7838 |
| review text__emb_181 | 0.7481 |
| review text__emb_182 | 0.7455 |
| review text__emb_367 | 0.7370 |
| review text__emb_118 | 0.7298 |
| review text__emb_293 | 0.7156 |
| review text__emb_295 | 0.7153 |
| review text__emb_178 | 0.6845 |
| review text__emb_159 | 0.6720 |
| review text__emb_247 | 0.6538 |
| review text__emb_4 | 0.6520 |
| review text__emb_194 | 0.6199 |
| review text__emb_85 | 0.6125 |
| review text__emb_261 | 0.5852 |
| review text__emb_232 | 0.5752 |
| review text__emb_324 | 0.5696 |
| review text__emb_264 | 0.5688 |
| review text__emb_2 | 0.5642 |
| review text__emb_192 | 0.5575 |
| review text__emb_354 | 0.5571 |
| review text__emb_197 | 0.5562 |
| review text__emb_346 | 0.5535 |
| review text__emb_16 | 0.5482 |
| review text__emb_40 | 0.5472 |
Encoder training (final model)
| Setting | Value |
|---|---|
| Training | LoRA, rank 4, α 8 |
| Layers adapted | 5–6 of 6 |
| Trainable numbers | 13,060 |
| Epochs run | 2 |
| Final training loss | 0.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))
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
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 16 | 0.6182 | 0.6875 | 0.7000 | 0.6940 |
| 2 | 1 | 16 | 0.7621 | 0.6250 | 0.6556 | 0.5822 |
| 3 | 1 | 16 | 0.5206 | 0.8125 | 0.8111 | 0.8030 |
Feature importance
| Feature | Importance |
|---|---|
| review text__emb_142 | 1.022 |
| review text__emb_381 | 0.9445 |
| review text__emb_253 | 0.9327 |
| review text__emb_89 | 0.8786 |
| review text__emb_25 | 0.8353 |
| review text__emb_60 | 0.7920 |
| review text__emb_139 | 0.7838 |
| review text__emb_181 | 0.7481 |
| review text__emb_182 | 0.7455 |
| review text__emb_367 | 0.7370 |
| review text__emb_118 | 0.7298 |
| review text__emb_293 | 0.7156 |
| review text__emb_295 | 0.7153 |
| review text__emb_178 | 0.6845 |
| review text__emb_159 | 0.6720 |
| review text__emb_247 | 0.6538 |
| review text__emb_4 | 0.6520 |
| review text__emb_194 | 0.6199 |
| review text__emb_85 | 0.6125 |
| review text__emb_261 | 0.5852 |
| review text__emb_232 | 0.5752 |
| review text__emb_324 | 0.5696 |
| review text__emb_264 | 0.5688 |
| review text__emb_2 | 0.5642 |
| review text__emb_192 | 0.5575 |
| review text__emb_354 | 0.5571 |
| review text__emb_197 | 0.5562 |
| review text__emb_346 | 0.5535 |
| review text__emb_16 | 0.5482 |
| review text__emb_40 | 0.5472 |
Encoder training (final model)
| Setting | Value |
|---|---|
| Training | LoRA, rank 4, α 8 |
| Layers adapted | 5–6 of 6 |
| Trainable numbers | 13,060 |
| Epochs run | 2 |
| Final training loss | 0.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.
Comparing on equal terms
CheckpointA 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.
Common mistakes
ReadCheck: transfer
CheckpointCheck 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.
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