Language models, retrieval, prompting, and language adaptation · Instruction, preference, and parameter-efficient adaptation · LNG067 · Training method
Low-Rank Adaptation (LoRA)
Adapts a pretrained model by learning low-rank updates to selected weight matrices while freezing the original weights.
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Convolutional neural network (CNN) Experimental
- FT-Transformer Experimental
- TabM (parameter-efficient MLP ensemble) Experimental
- Text encoder (MiniLM + linear head) Not verified yet
- Deep neural network (torch MLP) Verified in Python and R
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Complete calculation
- Who ran it
- CodeSplash's own run
- CodeSplash's run
- Verified in Python and R through learn.cnn, learn.ft_transformer, learn.tabm, learn.torch_mlp. The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Adapts a pretrained model by learning low-rank updates to selected weight matrices while freezing the original weights. It reduces trainable-parameter and optimizer-state requirements and enables swapping task-specific adapters.
Question / objective
Can a low-rank weight update capture useful task adaptation while freezing a large base?
Architecture / computational structure
Frozen matrices W0 receive trainable products BA, scaled by alpha/r, in selected modules. Learned quantities are A, B, and explicitly unfrozen heads; rank, target modules, dropout, and scaling are hyperparameters.
Assumptions
Useful task updates may require higher rank or different target layers.
Formula / computational definition
W_eff=W_0+(alpha/r)BA, with frozen W_0 of shape d_out by d_in, A of shape r by d_in, B of shape d_out by r, rank r, and scale alpha. Gradients update A and B only unless additional modules are explicitly unfrozen.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Rank, scaling, targeted modules, adapter dropout, initialization, learning rate, and optional trainable biases or heads.
Fitting, fine-tuning, and adaptation
Use the task's actual loss—classification, language modeling, SFT, or preference training—while updating adapters only. Tune rank/learning rate/targets on validation performance, compare frozen and full-update baselines, and test forgetting. Preserve base/checkpoint identifiers and validate before merging adapters into weights.
How to use and calibrate
Compare task quality, trainable counts, memory, latency, adapter portability, and base-capability retention against full fine-tuning. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.
Example application
Store separate domain adaptations without duplicating every base-model tensor.
Interpretation / pitfalls
Watch out
Fewer trainable weights do not remove forward/backward activation costs, and careless merging can alter precision or overwrite a base checkpoint. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.
Python and R code examples
Full implementation route: PEFT provides documented LoRA configurations and integration with supported models. R bridges through reticulate; native matrix examples calculate the exact low-rank update but do not perform optimizer training.
Example scope: Exact rank-one LoRA matrix update with fixed toy adapter values.
Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.
Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Complete calculation — Exact rank-one LoRA matrix update with fixed toy adapter values.
Shared setup for this chapter
import math
def softmax(xs):
m = max(xs)
es = [math.exp(x-m) for x in xs]
return [e/sum(es) for e in es]
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def matvec(matrix, vector):
return [dot(row, vector) for row in matrix]
def meanvec(rows):
return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]
def sigmoid(x):
return 1/(1+math.exp(-x))
def nll(probabilities):
return -sum(math.log(p) for p in probabilities)
base = [[1,0],[0,1]]; b = [0.2,-0.1]; a = [0.5,0.3]
alpha,rank = 2.0,1
updated = [[base[i][j]+alpha/rank*b[i]*a[j] for j in range(2)] for i in range(2)]
print(updated)
Complete calculation — Exact rank-one LoRA matrix update with fixed toy adapter values.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
base <- diag(2); b <- matrix(c(0.2,-0.1),ncol=1); a <- matrix(c(0.5,0.3),nrow=1)
alpha <- 2; rank <- 1
updated <- base + alpha/rank * (b %*% a)
print(updated)
Sources
- Source 1arxiv.org
From the CodeSplash reference, entry LNG067.