v9.1.1
Menu

Merge a LoRA Update into the Base Weight

mediumPROEfficient Adaptation & Hallucination MetricsVision-Language ModelsVLM 1: Vision-Language Models

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

W′=W+αr BAW' = W + \frac{\alpha}{r}\, B A

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

Input
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]]
Reasoning
  • Infer the rank rr from the number of rows in matrix AA. Since AA is a 1×21 \times 2 matrix, r=1r = 1.
  • Compute the low-rank update product BABA. Multiplying BB (2×12 \times 1) by AA (1×21 \times 2) yields a 2×22 \times 2 matrix: [1.00.0][1.01.0]=[1.01.00.00.0]\begin{bmatrix} 1.0 \\ 0.0 \end{bmatrix} \begin{bmatrix} 1.0 & 1.0 \end{bmatrix} = \begin{bmatrix} 1.0 & 1.0 \\ 0.0 & 0.0 \end{bmatrix}
  • Calculate the scaling factor αr\frac{\alpha}{r} using the given α=2.0\alpha = 2.0 and r=1r = 1: 2.01=2.0\frac{2.0}{1} = 2.0
  • Scale the product matrix by the factor to get the update term: 2.0×[1.01.00.00.0]=[2.02.00.00.0]2.0 \times \begin{bmatrix} 1.0 & 1.0 \\ 0.0 & 0.0 \end{bmatrix} = \begin{bmatrix} 2.0 & 2.0 \\ 0.0 & 0.0 \end{bmatrix}
  • Add this update to the base weight WW element-wise to obtain the merged weight W′W': [1.00.00.01.0]+[2.02.00.00.0]=[3.02.00.01.0]\begin{bmatrix} 1.0 & 0.0 \\ 0.0 & 1.0 \end{bmatrix} + \begin{bmatrix} 2.0 & 2.0 \\ 0.0 & 0.0 \end{bmatrix} = \begin{bmatrix} 3.0 & 2.0 \\ 0.0 & 1.0 \end{bmatrix}
  • The final output is [[3.0, 2.0], [0.0, 1.0]]

Constraints

  • W is d_out x d_in, A is r x d_in, B is d_out x r.
  • Scale the update by alpha / r where r = len(A).
  • Round to 4 decimals; avoid -0.0.

Learn this in

More from VLM 1: Vision-Language Models

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.