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)Review the design
Functional equivalence is the core merge contract. Artifact versioning must record whether an adapter has already been merged, because merging the same update twice changes the model again.
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.
The explanation opens here once every check passes.