PythiloLesson 8 of 8 · progress kept in this browser

Merge a low-rank adapter without changing its function

A LoRA adapter represents a low-rank update as B times A, scaled by alpha divided by rank. Merging that update into a base weight should produce the same linear output as applying the base and adapter branches separately. Matrix orientation and scaling errors can silently spoil a fine-tuned model.

This exercise uses actual PyTorch matrix multiplication and checks functional equivalence. It does not perform quantization or optimize memory on a GPU. Merging a quantized base, changing dtype or repeatedly applying the same adapter introduces additional numerical and lifecycle decisions that require separate verification.

import torch
base=torch.zeros(2,3)
a=torch.ones(1,3)
b=torch.tensor([[1.],[2.]])
print((base+b@a).shape)
This example uses torch. Run it in the Pythilo app, where these features are available.
Your task

Implement merge_lora(base,a,b,alpha) for base [out,in], a [rank,in], b [out,rank]. Return a new tensor base+(alpha/rank)*(b@a); reject nonmatrix inputs, incompatible shapes or rank<1; do not modify any input.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.

All lessons