Skip to content

LoRA and its relatives: QLoRA, DoRA and AdaLoRA

Adapt a frozen weight matrix with a low-rank update, count what it saves, and see what QLoRA (a 4-bit base), DoRA (magnitude and direction) and AdaLoRA (rank where it matters) change.

Advanced ~16 min11 steps

What runs in CodeSplash

You will be able to

  • Write the LoRA update and explain why training starts exactly at the pretrained model
  • Count LoRA's trainable parameters for a weight matrix and a rank
  • Explain what QLoRA quantizes and what it keeps in higher precision
  • Say how DoRA and AdaLoRA change LoRA, and which of them run in CodeSplash

Read first

01

A low-rank update to a frozen matrix

Read

LoRALoRAFine-tuning that freezes a weight matrix W and trains a small low-rank update B·A added to it, scaled by α/r. freezes a weight matrix W0W_0 (d×kd \times k) and learns two thin matrices, BB (d×rd \times r) and AA (r×kr \times k):

W=W0+αr BA.W = W_0 + \frac{\alpha}{r}\, B A .

BB starts at zero, so the first forward pass is exactly the pretrained model. The rank rr caps how much the layer can change; α/r\alpha / r scales the update so that changing rr doesn't change the effective step size much.

In the reference's example, an identity matrix with α=2\alpha = 2, r=1r = 1 and one pair of vectors becomes a matrix whose first entry is 1.2 and last is 0.94: a rank-1 change spread over every entry.

02

What it saves, and what it doesn't

Read

A full update of W0W_0 trains dkdk numbers; LoRA trains r(d+k)r(d + k). For a square layer of width 768 at rank 8, that's 12,288 instead of 589,824, about 2%.

That saving is in trainable weights and their optimizer state. The frozen weights still sit in memory, and the activations that backpropagation stores still grow with batch size, sequence length and depth. Fewer trainable parameters don't mean proportionally less memory.

After training, BABA can be folded into W0W_0. The merged model runs exactly as fast as the original; CodeSplash saves adapted models merged, so they score and explain like any other.

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.

03

LoRA in CodeSplash

In the app
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)
)

The Text encoder's LoRA training adapts two layers at rank 4: 13,060 encoder weights train. Neural-network learners also offer LoRA, DoRA, BitFit and output-layer-only training under Make a model from this → Adapt to new data.

Reference · LNG067 · Runs in CodeSplashLow-Rank Adaptation (LoRA)Adapts a pretrained model by learning low-rank updates to selected weight matrices while freezing the original weights.
04

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 in 4 bits (a data type spaced for normally distributed weights), with the quantization scales themselves quantized. Each product dequantizes the base on the fly; the LoRA matrices and their gradients stay in 16-bit or higher precision. Paged optimizer state absorbs memory spikes.

In the reference's example, a small matrix is rounded to steps of a tenth and then gets a rank-1 update; its first entry comes out as 0.20. The adapter learns on top of the rounded base, so it can partly absorb the rounding error, but the base's own precision is gone.

QLoRA is explained here: it is for large language models on a GPU, which CodeSplash doesn't train.

05

DoRA: magnitude and direction

Read

DoRADoRAAn adapter that splits each weight row into a length and a direction; LoRA updates the direction and the lengths train on their own. splits each weight column into a length and a direction. LoRA updates the direction; a separate vector mm learns the lengths:

W=m⊙W0+BA∥W0+BA∥col.W = m \odot \frac{W_0 + BA}{\lVert W_0 + BA \rVert_{\text{col}}} .

In the reference's example, two columns rescaled to lengths 3 and 2 give a first entry of 1.342. DoRA runs in CodeSplash as an Adapt to new data strategy for neural-network learners; it starts exactly at the base model, like LoRA.

06

AdaLoRA: rank where it matters

Read

AdaLoRAAdaLoRALoRA written as an SVD-like product whose least important singular values are pruned, so rank goes where it matters. writes each update as PΛQP \Lambda Q with a diagonal Λ\Lambda of singular values, scores each one's importance during training, and prunes the weakest. The total rank budget stays fixed, but layers that need more change get more of it.

In the reference's example, singular values with the smallest one pruned leave 0.9 and 0.5 on the diagonal. Importance scores are noisy early in training, so AdaLoRA warms up before pruning. It is explained here.

07

Predict: does LoRA prevent forgetting?

Predict

Predict first

You adapt a model to a new task with LoRA, then merge the adapter. Is the merged model guaranteed to keep its old skills?

Yes: the base weights are frozenNo: the merged model can still lose old skills
Reveal

No. The base weights are frozen, but the merged model is base + update, and the update can move predictions on old tasks as much as fine-tuning would. Keep the unmerged base for old tasks, or check retained skills on held-out old data.

08

What runs here

Read
09

Common mistakes

Read
10

Check: LoRA and its relatives

Checkpoint

Check yourself

A weight matrix is 1,024 × 1,024. How many numbers does LoRA train at rank 8?

Show the answer

Answer: 16384

r(d + k) = 8 × (1,024 + 1,024) = 16,384, against 1,048,576 for the full matrix.

Check yourself

Why does LoRA training start exactly at the pretrained model?

Show the answer

Answer: a

A is random and B is zero, so the update is zero until training moves B.

Check yourself

LoRA trains 1% of a model's weights. Which memory shrinks by roughly that much?

Show the answer

Answer: a

Frozen weights and activations remain. QLoRA attacks the frozen weights by storing them in 4 bits; activation checkpointing attacks the activations.

Check yourself

In QLoRA, what is stored in 4 bits?

Show the answer

Answer: a

The base is quantized and dequantized for each product; the small adapters and their gradients stay in higher precision.

Check yourself

What does DoRA learn that plain LoRA doesn't?

Show the answer

Answer: a

DoRA normalizes W0 + BA column by column and multiplies by a learned magnitude vector.

Check yourself

Where can you run DoRA in CodeSplash?

Show the answer

Answer: a

DoRA is one of the adapter strategies (with LoRA, BitFit and output layer only) for adapting a trained network to new rows.

Check yourself

What does AdaLoRA keep fixed while it trains?

Show the answer

Answer: a

It prunes the singular values with the lowest importance scores and keeps the overall budget, so the rank per layer changes.

Check yourself

Why does AdaLoRA wait before pruning?

Show the answer

Answer: b

Scores computed from a few early steps are unreliable; a warm-up lets them settle.

11

Recap

Recap
  • LoRA learns W0 + (α/r)BA with B = 0 at the start; it trains r(d + k) numbers and can be merged after training.
  • Fewer trainable weights cut gradient and optimizer memory, not the frozen weights or activations.
  • QLoRA stores the base in 4 bits; DoRA learns column lengths separately; AdaLoRA moves rank to where it helps.
  • LoRA and DoRA run in CodeSplash; QLoRA and AdaLoRA are explained here.

Concepts in this lesson