Merge a LoRA Update into the Base Weight
Problem Statement
At inference LoRA is folded into the frozen weight so there is zero added latency: W' = W + (alpha/r) * B A. Implement the merge.
Background
LoRA scales its low-rank update by alpha/r (the "lora_alpha" over rank convention). Given the base weight W (d_out x d_in), factors A (r x d_in) and B (d_out x r), and alpha, the merged weight is
After merging, the adapter can be discarded — the model is a plain dense network again.
Your Task
Implement:
def merge_lora(W, A, B, alpha):
Return the merged d_out x d_in matrix as a nested list rounded to 4 decimals. Infer r from A's row count.
Input Format
- W: d_out x d_in nested list.
- A: r x d_in; B: d_out x r.
- alpha (float).
Output Format
- A d_out x d_in nested list rounded to 4 decimals.
Sample
W = [[1.0, 0.0], [0.0, 1.0]]
A = [[1.0, 1.0]]
B = [[1.0], [0.0]]
print(merge_lora(W, A, B, 2.0))
Output:
[[3.0, 2.0], [0.0, 1.0]]
Example
W = [[1.0, 0.0], [0.0, 1.0]] A = [[1.0, 1.0]] B = [[1.0], [0.0]] print(merge_lora(W, A, B, 2.0))
[[3.0, 2.0], [0.0, 1.0]]
- Infer the rank from the number of rows in matrix . Since is a matrix, .
- Compute the low-rank update product . Multiplying () by () yields a matrix:
- Calculate the scaling factor using the given and :
- Scale the product matrix by the factor to get the update term:
- Add this update to the base weight element-wise to obtain the merged weight :
- The final output is [[3.0, 2.0], [0.0, 1.0]]
Constraints
Wisd_out x d_in,Aisr x d_in,Bisd_out x r.- Scale the update by
alpha / rwherer = len(A). - Round to 4 decimals; avoid
-0.0.