Low-Rank Adaptation (LoRA) trains two small matrices A (shape r x k) and B (shape d x r) while keeping a pretrained weight matrix W0 (shape d x k) frozen. During training the effective weight is W0 + B*A, but at inference time we can fold the adapter directly into the base weights to eliminate any extra computation.
Implement a function merge_lora that takes the frozen weights W0, the LoRA matrices A and B, a scaling factor alpha, the rank r, and a boolean merge. When merge=True, return the merged weight matrix used at inference. When merge=False, treat W0 as a previously merged weight and return the recovered original (unmerged) base weights.
The LoRA update is scaled by alpha/r before being added.