peft icon indicating copy to clipboard operation
peft copied to clipboard

add_weighted_adapter(combination_type="svd"): exact factorized SVD instead of decomposing the dense delta

Open jontb opened this issue 1 month ago • 8 comments

Feature request

For combination_type="svd", _svd_generalized_task_arithmetic_weighted_adapter builds the dense update ΔW = Σᵢ wᵢ·sᵢ·BᵢAᵢ and calls torch.linalg.svd on the full out×in matrix. On LLM-sized layers this dominates the merge. With PEFT main (21c63ee) on an RTX 5060 Ti (float32, TF32 off), merging two r=16 LoRA adapters takes about 11.8 s for a single 4096×4096 Linear, and 13.3 s for 11008×4096. That cost is paid for every targeted layer.

For plain additive LoRA, ΔW is already low-rank: ΔW = B·A with B = [w₁s₁B₁, …] (out×R) and A = [A₁; …] (R×in), R = Σrᵢ. A reduced QR on each side plus an SVD of the small R×R core gives the same truncated SVD in exact arithmetic, and never materializes ΔW:

qb, rb = torch.linalg.qr(B)         # B: out x R
qa, ra = torch.linalg.qr(A.T)       # A: R x in
u, s, vh = torch.linalg.svd(rb @ ra.T, full_matrices=False)
lora_B = qb @ (u[:, :k] * s[:k])
lora_A = vh[:k] @ qa.T

Results, using the same factors, device and dtype. Error is measured in float64 against the exact sum and against the optimal rank-k (Eckart–Young) error:

Layer, adapters Current (full_matrices=True, default driver) Best dense (full_matrices=False, gesvd) torch.svd_lowrank(niter=2) Factorized QR
4096×4096, 2× r16 9.8 s 2.5 s 4.2 ms 0.6 ms
4096×4096, 4× r64 15.4 s 2.4 s 6.4 ms 7.1 ms
11008×4096, 4× r64 13.0 s 2.6 s 16.3 ms 8.8 ms
  • Accuracy. Across 22 cases (shapes 1024² to 11008×4096, r16/r64, 2 or 4 adapters, signed weights), QR's error was within 3e-10 of the optimum. float32 dense SVD was up to 2e-5 above the optimum, and svd_lowrank(niter=2) up to 2.1e-3.
  • CPU. For 4096×4096 on 6 threads, dense SVD takes about 6.4 s and QR 1.4–2.9 ms.
  • Low-rank alternative. svd_lowrank on the dense delta recovers most of the speed. The factorized path is exact, ranges from about as fast to 7× faster in these cases, and needs no dense out×in buffer, so I think it's the better fix.
  • Memory. It also avoids task_arithmetic stacking n dense out×in deltas.

Proposed scope:

  • Use the factorized path for combination_type="svd" on LoRA Linear, Conv1D (fan_in_fan_out) and Embedding layers, upcasting fp16/bf16 factors to float32 (linalg.qr has no low-precision kernels) and casting back.
  • If svd_rank exceeds R, pad with zero components, which is what the current full_matrices=True path effectively returns.
  • Keep the dense path for:
    • conv layers;
    • the TIES/DARE/magnitude-prune SVD variants, where elementwise pruning breaks the low-rank structure;
    • svd_clamp, because the quantile clamp depends on the sign and rotation of the singular vectors, so outputs would change beyond floating-point noise (0.3–3% in my tests);
    • R ≥ min(out, in).
  • svd_driver/svd_full_matrices would only apply on the dense path.

I prototyped this against main's dense path through add_weighted_adapter itself. Merged deltas agree to about 1e-5 relative in float32 (bf16 rounding in bf16) for Linear, Conv1D, Embedding, signed weights, mixed ranks, adapters missing from some layers, and svd_rank > R. An exact cancellation gives about 1e-6 absolute instead of exact zero.

Question for you: would you prefer this as the default for plain svd (outputs change only at floating-point level or at near-tied singular values, so a release note per the method-changes skill), or as an opt-in flag?

Your contribution

I'd like to implement this and would appreciate being assigned.

The PR would include:

  • the factorized path with a dense fallback;
  • tests comparing it with the dense path: signed and zero weights, mixed ranks, rank deficiency, exact cancellation, svd_rank > R, fan_in_fan_out, embeddings, bf16, and each fallback case;
  • a short docs note.

I used an AI coding assistant (Claude Code) to help write the benchmark and prototype scripts. I've reviewed the results and will review and test every line of any PR myself. Happy to share the benchmark scripts.

jontb avatar Oct 29 '26 20:10 jontb

Hi! This looks like a nice improvement. Would a PR be welcome? If so, I'd like to implement the factorized path (QR on each side plus an SVD of the small core) for plain additive LoRA, keep the dense fallback for the other cases, and add tests checking numerical equivalence with the current dense SVD on small layers.

shupandee avatar Nov 04 '26 04:11 shupandee

Hi @shupandee, thanks for the interest! I offered to implement this in the issue description, under "Your contribution", and I've already prototyped the factorized path and checked it against the current dense path through add_weighted_adapter (numbers above). Following the contributing guide, I'm waiting for a maintainer to triage the issue before opening a PR, so I'll leave the assignment to them.

jontb avatar Nov 04 '26 15:11 jontb

Thanks @jontb, I missed that you'd offered under "Your contribution", sorry about that! I'll step back. Happy to help test or review once your PR is up.

shupandee avatar Nov 04 '26 16:11 shupandee

+1 on replacing the dense $O(d_{\text{out}} d_{\text{in}} \min(d_{\text{out}}, d_{\text{in}}))$ SVD in _svd_generalized_task_arithmetic_weighted_adapter with the QR-reduced core SVD ($B = Q_B R_B$, $A^T = Q_A R_A$, $\text{svd}(R_B R_A^T)$).

While building loraspectra (a standalone Rust spectral auditor, Eckart-Young compressor, and SVD merger for .safetensors LoRA files), we benchmarked this exact QR-core factorization extensively across F32/F16/BF16 adapters and wanted to share two numerical observations that might be useful for the PEFT PR:

  1. Speedup & Precision at 4096 x 4096 (r=64):

    • Reducing to the $R \times R$ core ($M = R_B R_A^T$) gives a 1,050x–2,680x speedup on CPU (0.47 ms–2.97 ms vs 371 ms–3,940 ms for dense SVD on smaller projections, and 128 ms on 4096 x 4096, r=64), with max singular value deviation $\max_i |\sigma_i^{\text{QR}} - \sigma_i^{\text{dense}}| \le 1.08 \times 10^{-13}$ when accumulated in float64.
    • Peak workspace drops by 62x on 4096 x 4096 (4.19 MiB vs 262.18 MiB for materializing $\Delta W$).
  2. Edge Case When Merging Collinear / High-Overlap Adapters in Low Precision (f16 / bf16):

    • When stacking $B = [w_1 s_1 B_1, \dots, w_k s_k B_k]$ across multiple adapters fine-tuned on related tasks (or checkpoints from the same training trajectory), columns of $B$ and rows of $A$ can have high principal subspace overlap ($\sigma_{\max}(U_1^T U_2) \to 1$).
    • Upcasting B and A.T to float32/float64 before calling torch.linalg.qr (and computing rb @ ra.T + svd in float64 before casting lora_B/lora_A back to the target adapter dtype) avoids loss of orthogonality in $Q_B, Q_A$ when $R_B$ is ill-conditioned.
    • Additionally, if two adapters have opposing signs along shared top singular directions (destructive task interference), projecting the secondary adapter's right-singular subspace orthogonal to the primary adapter before the QR-core SVD (ortho-svd benchmark in loraspectra) prevents singular value cancellation that plain additive SVD merge still suffers from.

SalyyS1 avatar Nov 11 '26 16:11 SalyyS1

Thanks @jontb for the suggestion!

Since this approach is very LoRA-specific I'd be interested if you tested against svd_lowrank while tuning the q parameter with 1.2r - 2r? If that is roughly comparable with QR factoring, I would prefer that over the specific solution.

githubnemo avatar Nov 11 '26 17:11 githubnemo

@githubnemo One thing to keep in mind with svd_lowrank(q=2r) is that it still operates on the dense d_out x d_in matrix. Under the hood it materializes the full delta_W in memory and runs (2 + 2 * niter) dense matrix multiplications of shape (d_out x d_in) @ (d_in x q). On an 11008 x 4096 layer in float32 that still allocates ~180 MB for delta_W per layer, and when an adapter has a flat singular value spectrum the randomized subspace iteration can lose accuracy near the truncation boundary even at q=2r.

The QR path works directly on the stacked (B, A) factors without ever allocating the dense d_out x d_in matrix, and gives the exact SVD up to floating point precision in about 5 lines of torch.linalg calls.

SalyyS1 avatar Nov 11 '26 18:11 SalyyS1

Thanks @githubnemo. I hadn't tuned q before (the table above used q = k + 10), so I ran that sweep: torch.svd_lowrank on the dense delta with q = 1.2k, 1.5k and 2k, where k is the output rank (svd_rank, by default the largest adapter rank). Same setup as before: RTX 5060 Ti, float32, error measured in float64 as the excess over the optimal rank-k error, worst of 5 seeds for svd_lowrank.

Layer, adapters QR svd_lowrank q=1.2k q=1.5k q=2k q=Σr+10
4096×4096, 2× r16 0.6 ms, 2e-11 4.1 ms, 4e-4 4.1 ms, 2e-7 4.4 ms, 3e-11 5.2 ms, 4e-11
4096×4096, 4× r16 1.4 ms, 1e-11 6.3 ms, 2e-3 6.4 ms, 9e-5 6.6 ms, 1e-7 9.1 ms, 2e-11
4096×4096, 4× r64 7.2 ms, 9e-10 9.7 ms, 2e-3 10.4 ms, 8e-5 12.1 ms, 2e-7 23.6 ms, 1e-10
4096×4096, 8× r16 3.3 ms, 6e-11 10.8 ms, 5e-3 10.9 ms, 2e-3 11.2 ms, 9e-5 18.8 ms, 3e-11
11008×4096, 4× r64 8.9 ms, 5e-10 20.4 ms, 2e-3 21.6 ms, 8e-5 23.8 ms, 3e-7 48.4 ms, 1e-10

(niter=2, the default. For scale, the optimal rank-k relative error in these cases is 0.08 to 0.41.)

So yes, I'd call it roughly comparable:

  • Speed. svd_lowrank is 1.3× to 15× slower than QR here, but both are milliseconds against roughly 10–15 s for the current path. On CPU (6 threads, 4096×4096) it is about 0.15–0.6 s against 1–26 ms for QR and about 6.4 s for the dense SVD.
  • Accuracy. At q=2k the excess error is at most 3e-7 in the 2- and 4-adapter cases and 9e-5 with 8 adapters. With factors that have no spectral decay (the flat-spectrum case @SalyyS1 mentions) q=2k is still exact for 2 adapters, and gives up to 9e-5 with 4 adapters and 3e-3 with 8. It becomes exact to float32 precision once q covers the rank of the merged delta, i.e. q ≥ Σ rᵢ; niter=6 also closes most of the gap at about 1.5–2× the time.
  • Memory. As @SalyyS1 points out, it still builds the dense out×in delta: 192 MiB / 516 MiB peak for the two shapes, against 5–34 MiB for QR. That is no worse than today's path, which builds the same delta.
  • Determinism. The result depends on the global RNG state, so two merges of the same adapters differ slightly unless seeded.

Given that, I'm happy to go with svd_lowrank if you prefer the more general solution. It also has the advantage of applying unchanged to conv layers and to the TIES/DARE SVD variants, where the QR path can't be used (I haven't measured accuracy there; those deltas are not low-rank, so the truncation would be approximate).

If we go that way, one suggestion: since the adapter ranks are known in _svd_generalized_task_arithmetic_weighted_adapter, q could default to min(Σ rᵢ, min(out, in)) plus a small oversample for plain svd, which makes the result exact for additive LoRA (last column), with a cap or a q argument for the pruned variants. Would you want it as the default for combination_type="svd", or behind an option?

As before, I used an AI coding assistant (Claude Code) for the benchmark script and have checked the results myself; happy to post the script.

jontb avatar Nov 13 '26 00:11 jontb

@jontb Thanks a lot for the analysis!

For now I prefer the more general solution of using svd_lowrank. We can always come back and implement the special case of QR decomposition at a later point in time if the need arises.

If we go that way, one suggestion: since the adapter ranks are known in _svd_generalized_task_arithmetic_weighted_adapter, q could default to min(Σ rᵢ, min(out, in)) plus a small oversample for plain svd, which makes the result exact for additive LoRA (last column), with a cap or a q argument for the pruned variants. Would you want it as the default for combination_type="svd", or behind an option?

I think defaulting to min(sum(ranks), min(out, in)) is a good idea, the user should probably be able to pass svd_lowrank_niter and svd_lowrank_q as an override. svd_lowrank: bool should be used as a flag to signify the use of svd_lowrank.

Feel free to open a PR!

/peft-triage approved @jontb

githubnemo avatar Nov 16 '26 18:11 githubnemo