REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: learn and merge a frozen-base low-rank adapter

Low-rank adaptation trains a small update while retaining a frozen base matrix.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Project: learn and merge a frozen-base low-rank adapter →

Your task

For finite base [out,in], xs [N,in] and ys [N,out], train only A [rank,in] and B [out,rank]. Initialize A=randn*.1, B=zeros under a local seed. Predict linear(xs,base)+linear(linear(xs,A),B)/rank; use Adam lr=.05 and mean squared error for positive steps. Base remains frozen and caller lists unchanged. Return base, a, b, merged=base+B@A/rank, history of pre-update losses, final loss and merged predictions as lists/scalars. Rank is a positive integer <=min(out,in). Preserve caller CPU RNG.

Starter

import torch


def fit_low_rank(base, xs, ys, rank, steps, seed):
    return None
Inspect the worked answer
import math
import torch
from torch import nn
from torch.nn import functional as F


def fit_low_rank(base, xs, ys, rank, steps, seed):
    if type(rank) is not int or rank < 1 or type(steps) is not int or steps < 1:
        raise ValueError('positive rank and training steps required')
    frozen = torch.tensor(base, dtype=torch.float32)
    x, y = torch.tensor(xs, dtype=torch.float32), torch.tensor(ys, dtype=torch.float32)
    if frozen.ndim != 2 or x.ndim != 2 or y.ndim != 2 or x.shape[0] != y.shape[0] or x.shape[1] != frozen.shape[1] or y.shape[1] != frozen.shape[0] or min(x.shape) < 1 or rank > min(frozen.shape):
        raise ValueError('aligned nonempty data and feasible adapter rank required')
    if any(not bool(torch.isfinite(t).all()) for t in (frozen, x, y)):
        raise ValueError('finite model and data required')
    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(seed)
        a = nn.Parameter(torch.randn(rank, frozen.shape[1]) * .1)
        b = nn.Parameter(torch.zeros(frozen.shape[0], rank))
        optimizer = torch.optim.Adam([a, b], lr=.05)
        history = []
        for step in range(steps):
            optimizer.zero_grad(set_to_none=True)
            prediction = F.linear(x, frozen) + F.linear(F.linear(x, a), b) / rank
            loss = F.mse_loss(prediction, y)
            loss.backward()
            optimizer.step()
            history.append(float(loss.detach()))
        merged = frozen + b.detach() @ a.detach() / rank
        with torch.no_grad():
            final_loss = float(F.mse_loss(F.linear(x, merged), y))
        return {'base': frozen.tolist(), 'a': a.detach().tolist(), 'b': b.detach().tolist(),
                'merged': merged.tolist(), 'history': history, 'loss': final_loss,
                'predictions': F.linear(x, merged).tolist()}

About this algorithm

How Project: learn and merge a frozen-base low-rank adapter works

The idea

LoRA, low-rank adaptation, fine-tunes a model without touching its original weights. In place of a full update to a weight matrix of shape [out, in], it trains two thin matrices, A [rank, in] and B [out, rank]. Their product B @ A has the full shape but only rank times (in + out) trainable numbers.

The bet is that a useful update needs only a few directions. B starts at zero, so at first the adapter changes nothing and training begins from the base model's behaviour. Afterwards the product can be folded into the base, merged = base + B @ A / rank, leaving one ordinary matrix with no extra cost at inference. This Lab scales the update by 1 / rank.

How it works

  1. Validate the shapes and require rank to be between 1 and min(out, in).
  2. Under a local seed, set A = randn * 0.1 and B = zeros, so the first prediction equals the base model's.
  3. Predict with linear(xs, base) + linear(linear(xs, A), B) / rank.
  4. Compute mean squared error and let Adam update only A and B, while base receives no gradient.
  5. Append each loss, measured before its update, to history.
  6. Fold the adapter in with merged = base + B @ A / rank and predict from the merged matrix alone.

What it costs

Trainable
rank·(in + out)
Frozen
in·out
After merge
no extra inference cost

The adapter trains rank times (in + out) numbers in place of in times out, and once merged into the base matrix it adds nothing to inference time.

Where it is used

  • Hugging Face's PEFT library adds LoRA adapters to the attention projection matrices of large language models.
  • Stable Diffusion users share small LoRA files that add a style or subject to a multi-gigabyte base model.
  • QLoRA trains LoRA adapters over a 4-bit quantized base, enough to fine-tune a 65 billion parameter model on one 48 GB GPU.

Watch out for

  • Starting both A and B at zero: each one's gradient is multiplied by the other, so both stay zero forever.
  • Merging with a different scale than training used, such as base + B @ A without / rank: merged predictions no longer match.
  • Handing base to the optimizer or leaving it trainable: the frozen weights drift and the adapter no longer describes the change.