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 NoneInspect 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()}