Skip to content

Adapting with few parameters: LoRA, QLoRA, adapters, prefixes and soft prompts

Instead of updating every weight, train a small add-on. Compute a LoRA update, see what QLoRA quantizes, place adapters, prefixes and soft prompts in the network, and run LoRA on a text encoder in CodeSplash.

Advanced ~16 min9 steps

What runs in CodeSplash

You will be able to

  • Write the LoRA update and count its trainable parameters
  • Explain what QLoRA keeps in low precision and what it doesn't
  • Tell apart adapters, prefix tuning and soft prompts by where they act
  • Say what parameter-efficient tuning saves, and what it doesn't

Read first

01

Train a small change, not the model

Read

Full fine-tuning updates every weight and needs a full copy of the model per task. LoRALoRAFine-tuning that freezes a weight matrix W and trains a small low-rank update B·A added to it, scaled by α/r. freezes the pretrained weight W and learns a low-rank change:

W′=W+αr BA,B∈Rd×r,  A∈Rr×kW' = W + \frac{\alpha}{r}\, B A, \qquad B \in \mathbb{R}^{d \times r},\; A \in \mathbb{R}^{r \times k}

With rank r far below d and k, BA has r(d + k) parameters instead of dk. In the reference program, a rank-1 update with α = 2 turns the identity matrix's top-left 1 into 1.20 and its bottom-right 1 into 0.94. B starts at zero, so training starts exactly from the pretrained model, and BA can be merged into W afterwards at no cost.

DExplorable · LoRA: rank, parameters and error

How much of a weight update can a low-rank adapter capture, and what does it save?

3

The toy 24 × 16 update ΔW is built from this many directions, plus noise.

0.10

Small changes in every direction, which no low rank captures.

2

ΔW ≈ BA with B 24 × r and A r × 16; the best such fit is the truncated SVD.

Layer width for counting

Trainable parameters of one square layer, full versus LoRA.

rank 2direction 1 … 16

Toy update: 80 adapter numbers against 384 for the full 24 × 16 matrix. Layer of width 4,096: 16,384 against 16,777,216.

Relative error
0.414
Energy kept
0.828
LoRA parameters (one layer)
16384
Share of full fine-tuning
0.0010
  • Puzzle: Find the smallest rank that keeps 95% of the update's energy.
  • Puzzle: On the 4,096-wide layer, train less than 0.5% of the full layer's parameters.LoRA's count grows with r(d + k), not d × k. The frozen weights still sit in memory, though.
A rank-2 adapter keeps 82.8% of the update's energy (relative error 0.414). On a 4,096-wide layer it trains 16,384 numbers instead of 16,777,216 (0.10%). The update has more directions than the adapter can hold, so some of it is lost.

A rank-2 adapter keeps 82.8% of the update's energy (relative error 0.414). On a 4,096-wide layer it trains 16,384 numbers instead of 16,777,216 (0.10%). The update has more directions than the adapter can hold, so some of it is lost.

02

LoRA on a text encoder

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)
)

In Text encoder, Training: LoRA adds rank-4 updates to the query and value weights of MiniLM's top two layers and trains them with the classifier head. That is 13,060 trainable weights; fine-tuning one whole layer of the same encoder trains 1,774,852.

Cross-validated log loss is 0.634 over three folds of a few dozen reviews: too little data to say whether LoRA helps here. On small data, compare against the frozen encoder on the same folds before adapting anything.

03

QLoRA: a 4-bit base

Read

QLoRAQLoRATrain LoRA adapters on top of a base model stored in 4 bits, so a large model fine-tunes on one smaller GPU. stores the frozen base weights in 4-bit precision and trains LoRA factors in higher precision on top. In the reference program the base weights are rounded to a 0.1 grid before the update is added, giving 0.20 and 0.37 on the diagonal.

Quantizing the base cuts the memory for weights roughly fourfold against 16-bit. Gradients still flow through the dequantized weights, activations still take memory, and the rounding changes the base model the adapter is trained on.

DExplorable · Quantization: scale, zero point and error

What does storing weights in 8 or 4 bits cost, and why does one large weight make it worse?

4

Each weight becomes one of 2^bits levels.

Scheme

Symmetric centers the levels on 0; asymmetric shifts them to cover the weights' actual range.

Scale shared by

Smaller groups adapt to local ranges but store more scales.

0.0

Replace the first weight with this value (0 = no outlier).

Scale (first group)
0.5994
Mean squared error
0.03108
Largest error
0.2981
SQNR (dB)
15.60
Bytes
130
  • Puzzle: With an outlier of 10 or more, get SQNR above 18 dB at 4 bits.
  • Puzzle: Store the weights in under a quarter of fp16's bytes with SQNR above 10 dB.
4-bit symmetric quantization with one scale for all 256 weights: scale 0.5994, 11 levels used, SQNR 15.6 dB, largest error 0.298. Storage is 130 bytes, 3.9× smaller than fp16.

4-bit symmetric quantization with one scale for all 256 weights: scale 0.5994, 11 levels used, SQNR 15.6 dB, largest error 0.298. Storage is 130 bytes, 3.9× smaller than fp16.

04

Other places to add parameters

Read
  • Adapters insert a small bottleneck block after a layer: down-project, nonlinearity, up-project, added back to the input. In the reference program the hidden state becomes 0.428 and −0.214. They add a little computation at prediction time unless removed.
  • Prefix tuning learns extra key and value vectors that every attention layer sees as if they came before the input. In the reference program two prefix keys take 0.226 and 0.196 of the attention.
  • Soft prompts learn a few input embeddings only. The reference program prepends two vectors of two numbers: 4 trainable numbers, and the input grows to 5 positions.
05

Fewer trainable parameters, less memory?

Predict

Predict first

LoRA trains under 1% of a model's parameters. How much less memory does training need than full fine-tuning?

Memory drops in proportion to trainable parametersOptimizer memory drops a lot, but the frozen weights and the activations still need memoryMemory stays exactly the same
Reveal

Much less optimizer state and gradient memory, since those scale with trainable parameters. But the frozen weights must still be loaded, and activations for backpropagation still scale with batch size and sequence length. The saving is large but far from 99%.

DExplorable · How much memory does a model need?

Where does a language model's memory go — weights, KV cache, optimizer state — and does it fit on this Mac?

Model

Hypothetical decoders; the first is the reference workflow's own.

2048

Tokens held in the KV cache (and the length of the attention scores).

1

Sequences processed at once; the KV cache grows with it.

Weight format

Bits per stored weight; the llama.cpp types include their block scales.

KV cache format

Bytes per stored key or value.

Use

Training adds gradients and optimizer state; LoRA adds them only for the adapters.

8

LoRA only: rank of each adapter.

LoRA targets

LoRA only: which matrices get adapters.

16

Under half is “fits”, under 85% “tight”, as the app's own estimate says.

this Mac (16 GB)
  • Weights: 0.31 GiB
  • KV cache: 0.02 GiB
  • Runtime overhead (10%): 0.03 GiB
  • Verdict: fits (2%)
  • This model's KV heads (grouped-query)
  • One KV head per query head
Parameters
168059904
Weight bytes
336119808
KV cache bytes
25165824
Trainable parameters
0
Total bytes
397414195
Share of this Mac's memory
0.023
  • Puzzle: Make the larger decoder fit (under half) a 16 GB Mac for inference with a 4,096-token context.
  • Puzzle: With LoRA training less than 1% of the parameters, find a case where the total is still more than half of full fine-tuning's.
Reference decoder (168M parameters): 168,059,904 parameters, 0.31 GiB of weights in fp16 and a 0.02 GiB KV cache for 2,048 tokens. Total 0.37 GiB: 2% of 16 GB, so it fits. These are logical tensor sizes, not measured memory.

Reference decoder (168M parameters): 168,059,904 parameters, 0.31 GiB of weights in fp16 and a 0.02 GiB KV cache for 2,048 tokens. Total 0.37 GiB: 2% of 16 GB, so it fits. These are logical tensor sizes, not measured memory.

06

Small updates can still forget

Read

Training few parameters limits how far a model can move, but doesn't stop it from losing skills the new data doesn't exercise. A LoRA adapter tuned on one domain can still degrade others: catastrophic forgettingCatastrophic forgettingA network trained further on new data losing what it learned from its old data. is smaller, not zero.

Check retained capability on held-out data from the old task, as the character-language-model workflow in this track does. Record the base model's exact revision with any adapter: an adapter only works on the weights it was trained against.

DExplorable · Forgetting: fine-tuning, EWC and replay

Why does training on a new task erase an old one, and what can hold on to it?

While learning task B

What, if anything, remembers task A during the second phase.

3.0

L2 and EWC only: how hard the weights are pulled back toward task A's.

0.30

Replay only: share of each batch drawn from task A.

100

Gradient steps on task A, then the same number on task B.

0.10

Step size in both phases.

0.04A before2.80A after0.04B after
  • Task A's loss contours
  • Task B's loss contours
  • Training on A
  • Then on B
Task A loss after B
2.802
Task B loss
0.044
Forgetting (rise in A's loss)
2.758
Fine-tuning's forgetting
2.758
  • Puzzle: Keep task A's loss under 0.15 while bringing task B's under 1.0.
  • Puzzle: With replay, cut forgetting to under a quarter of plain fine-tuning's.
Plain fine-tuning: task A's loss goes from 0.044 to 2.802 while task B's ends at 0.044. Plain fine-tuning would forget 2.76. Task A's Fisher information is 1.35 for the first weight and 0.041 for the second: A barely cares about the second weight, so a pull that treats both weights alike also blocks what B needs.

Plain fine-tuning: task A's loss goes from 0.044 to 2.802 while task B's ends at 0.044. Plain fine-tuning would forget 2.76. Task A's Fisher information is 1.35 for the first weight and 0.041 for the second: A barely cares about the second weight, so a pull that treats both weights alike also blocks what B needs.

07

Where it stands in CodeSplash

Read
EntryIn CodeSplash
LoRA (LNG067)Runs in CodeSplash: Text encoder, Training: LoRA on MiniLM or any of its other encoders
QLoRA, prefix tuning, adapters, soft prompts (LNG068–LNG070, LNG078)Explained here
08

Check: parameter-efficient adaptation

Checkpoint

Check yourself

A weight matrix is 768 × 768. How many trainable parameters does a rank-8 LoRA update add?

Show the answer

Answer: b

B is 768 × 8 and A is 8 × 768: 2 × 768 × 8 = 12,288, about 2% of the full matrix.

Check yourself

Why is LoRA's B initialized to zero?

Show the answer

Answer: a

With BA = 0 at the start, the first forward pass equals the pretrained model's; the update grows from there.

Check yourself

In QLoRA, what is stored in 4-bit precision?

Show the answer

Answer: b

The base model is quantized to save memory; the small LoRA factors stay in higher precision and are what training updates.

Check yourself

Why can a QLoRA adapter behave differently when attached to the original 16-bit base model?

Show the answer

Answer: b

Quantization changes the base the adapter learned to correct. Evaluate with the same base precision you deploy.

Check yourself

Where do prefix tuning's learned vectors act?

Show the answer

Answer: b

Prefix vectors look like context that precedes the input at every layer, steering attention without changing weights.

Check yourself

What does prefix tuning cost at prediction time that LoRA, once merged, doesn't?

Show the answer

Answer: a

Merged LoRA weights cost nothing extra; prefixes lengthen every attention computation.

Check yourself

What does a Houlsby adapter look like?

Show the answer

Answer: b

The residual connection lets the adapter start near the identity, and the bottleneck keeps it small.

Check yourself

Why might a team prefer LoRA over adapters for a latency-sensitive service?

Show the answer

Answer: b

Merged LoRA leaves the architecture unchanged. Adapter blocks stay in the forward pass.

Check yourself

What does soft prompt tuning learn?

Show the answer

Answer: b

The learned vectors needn't correspond to any real words; only they are trained.

Check yourself

Soft prompts tend to work better with which kind of model?

Show the answer

Answer: b

The original study found the gap to full fine-tuning closes as model size grows; small models gain less.

Check yourself

A LoRA adapter tuned on legal text raises legal accuracy. What should you check before using it for general questions?

Show the answer

Answer: b

Few trainable parameters limit change, they don't prevent it. Measure retained capability.

09

Recap

Recap
  • LoRA learns W + (α/r)BA with B starting at zero; it can be merged afterwards.
  • QLoRA keeps the base in 4-bit and trains LoRA on top; deploy with the precision you trained against.
  • Adapters add bottleneck blocks, prefix tuning adds attention keys and values, soft prompts add input embeddings.
  • Fewer trainable parameters save optimizer memory, not activations, and reduce forgetting without preventing it.

Concepts in this lesson