Repository navigation
DoRA: compute the weight row norm from the rank-r factored identity (no eye(d_in), no dense B @ A) - #18515
Conversation
…nstead of PEFT's dense B @ A PEFT's DoraLinearLayer.forward builds eye(d_in) -> lora_A -> lora_B and W + s * B @ A for every DoRA module on every forward, only to take a detached row norm. ||W_i + s B_i A||^2 = ||W_i||^2 + 2 s (W A^T)_i . B_i + s^2 B_i (A A^T) B_i^T needs one d_out x d_in x r GEMM and a row reduction of W (arXiv 2603.22276). Accumulated in float32, so closer to an fp64 reference than the dense sum rounded to the weight dtype. The rest of the forward is PEFT's; subclasses, PEFT's eval cache, DTensor or other-device weights and shape mismatches keep PEFT's path. UNSLOTH_DORA_FACTORED_NORM=0 turns it off.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b4514c811
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
… rows stay finite The (W A^T) GEMM wrote a bfloat16 result before the float32 sum, so when s B A nearly cancels W the squared norm could go negative, clamp to 0 and turn magnitude / norm into inf (W=[[1,1]], A=[[1.0078125,1.015625]], B=[[-1]], s=1). The cross term is now a float32 GEMM output (aten mm.dtype on CUDA, else W upcast in bounded row chunks), a float32 A is split into two 16-bit halves so every product is exact, the rank-sized terms run in float64, autocast is off, and the squared norm is floored at the float32 rounding level of its terms. The path now keys on a 16-bit (or dequantized) base weight and reads it as stored, never a float32 copy; float32 bases keep PEFT's dense path.
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
| else: | ||
| A_2 = A_hi | ||
| if _MM_OUT_DTYPE and weight.is_cuda: | ||
| WA = torch.mm(A_2, weight.t(), out_dtype = torch.float32) |
There was a problem hiding this comment.
This FP16-input GEMM still loses enough precision on an RTX 3090 to fail the new near-cancellation test. On PyTorch 2.11.0+cu130 at c2eb72b, the FP16 base / FP32 adapter CUDA case has a maximum row-norm error of 1.022% against FP64 (the test allows 0.5%). Repro: python -m pytest -q tests/test_dora_factored_norm.py -k near_cancellation.
With the same initialized tensors, using FP32 operands for just this cross term in bounded row chunks reduced the error to 0.079% and all 26 tests passed. At input width 1,024, using the same near-cancellation construction in a PEFT linear layer, the LoRA A gradient differed from PEFT by 2.11% in relative L2 at seed 2. It was 0.019% with that change. Could this dtype combination use a more accurate cross term on Ampere?
| WA = _cross_term_fp32(weight, lora_A_weight).to(acc) | ||
| base = torch.linalg.vector_norm(weight, ord = 2, dim = 1, dtype = torch.float32).to(acc).square_() | ||
| cross = (WA.t() * B).sum(1).mul_(2.0 * scaling) | ||
| quad = ((B @ (A @ A.t())) * B).sum(1).mul_(scaling * scaling) |
There was a problem hiding this comment.
Could the dispatch account for adapter rank and GPU before selecting the two FP64 GEMMs here? On an RTX 3090, rank-256 DoRA took 261.1 ms/step on this head, 95.2 ms on the merge base, and 94.8 ms on the same head with UNSLOTH_DORA_FACTORED_NORM=0. In one profiled head step the three FP64 GEMM kernels accounted for 183 ms of GPU time.
I used a locally initialized 28-layer Qwen3-0.6B configuration through FastLanguageModel, all seven projections, BF16, batch 2 × 128 tokens, per-block compilation enabled, gradient checkpointing off, and fused AdamW. Each arm ran in a fresh process on the same card and checkpoint. The numbers are median wall time for steps 7–16, including forward, backward and optimizer update. Keeping PEFT’s dense path for this high-rank configuration would avoid the slowdown.
… XPU, fp16 accumulation fallback (unslothai#18629) Follow-up fixes for unslothai#18515, found while re-checking the PRs merged on 2026-11-19. One commit per fix; every fix has a test that fails on main and passes here. | Fix | Follows up | Severity | |---|---|---| | DoRA norm: float64 rank terms only on CPU and on CUDA / ROCm up to rank 32 | unslothai#18515 | P1 | | DoRA norm: float32 fallback for float16 weights under allow_fp16_accumulation | unslothai#18515 | P1 | ## Tests (this branch vs main `54af93780b`, CPU) - New and changed tests: main 9 failed / 12 passed, this branch 21 passed. Each test loads the code of its own tree. - Neighbouring suites on this branch: DoRA suites: 40 passed. - `prepush_gate.py` passes. ## DoRA norm: float64 rank terms only on CPU and on CUDA / ROCm up to rank 32 (follows up unslothai#18515) #### DoRA factored norm: float64 rank terms only where float64 exists and is cheap ##### What broke unslothai#18515 computes the rank-sized terms of the factored DoRA norm (`A @ A.T`, `B @ (A @ A.T)`) in float64 on every device except MPS (`_rank_dtype` in `unsloth/kernels/dora.py`). That causes two problems. 1. **Intel Arc XPUs have no float64.** PyTorch raises `Required aspect fp64 is not supported on the device` there (intel/torch-xpu-ops#628, pytorch/pytorch#147731; Unsloth already guards the same case in Studio, unslothai#14848). The patch is installed at import with no fallback, so every DoRA forward on such a device fails, where PEFT's dense path ran before. 2. **High-rank DoRA is slow on consumer NVIDIA cards.** The rank terms cost `4 r^2 (d_in + d_out)` float64 FLOPs per call, and float64 runs at 1/64 rate on T4, L4 and RTX cards. At `d_in = d_out = 4096`: | r | float64 FLOPs | cross-term bf16 GEMM FLOPs | float64 time on an L4 (about 0.49 TFLOPS) | |---|---|---|---| | 16 | 4.2 M | 1.07 G | about 9 us (launch bound) | | 64 | 67 M | 4.3 G | about 0.14 ms | | 256 | 1.07 G | 17.2 G | about 2.2 ms | The cross-term GEMM reads W once (about 0.1 ms on an L4). At rank 256 the float64 part is about 20x that. A reported RTX 3090 measurement of a rank-256 Qwen3-0.6B DoRA step was 261 ms on this code vs 95 ms with `UNSLOTH_DORA_FACTORED_NORM=0`, with 183 ms of it in the float64 GEMMs. ##### Fix `_rank_dtype(device, rank)`: - float64 on CPU. - float64 on CUDA (including ROCm) up to rank 32. - float32 everywhere else: MPS, XPU, and CUDA above rank 32. The rank is a static weight shape, so the choice adds no guard, recompile or host query. float32 rank terms lose precision only when the user enables TF32. With realistic updates they stay within 1e-5 of fp64 at rank 64 and 256. ##### Tests New `tests/test_dora_factored_norm_fp64_devices.py` (CPU, prints the `dora.py` it loaded): - The rank dtype per device and rank. - The float32 rank path produces no float64 tensor (a TorchFunctionMode raises on any float64 output, as the device would). - Accuracy against an fp64 oracle: realistic, 97% cancellation, and ranks 64 / 256. | Arm | Result (new file + `tests/test_dora_factored_norm.py`) | |---|---| | origin/main 635532f | 7 failed, 28 passed | | this branch | 35 passed | ##### Not covered - Not run on a real Intel Arc GPU. - The step-time change was not timed here. The float64 cost above is a FLOP estimate plus the reported RTX 3090 measurement. ## DoRA norm: float32 fallback for float16 weights under allow_fp16_accumulation (follows up unslothai#18515) #### DoRA factored norm: chunked float32 cross term for float16 under allow_fp16_accumulation ##### What broke unslothai#18515 computes the DoRA cross term with `torch.mm(A_2, W.t(), out_dtype = torch.float32)` on CUDA. cuBLAS refuses float16 inputs with a float32 output when `torch.backends.cuda.matmul.allow_fp16_accumulation` is on. The check is in `aten/src/ATen/cuda/CUDABlas.cpp`, `gemm_internal<at::Half, float>` and `gemm_and_bias` (torch 2.10 and 2.14): `TORCH_CHECK(false, "gemm input type at::Half and output type float is not supported with allowFP16AccumulationCuBLAS")` So every float16 DoRA forward crashed with that flag set. A Colab L4 and A100 (torch 2.14.1) run of the factored norm reproduced the RuntimeError on origin/main. ##### Fix Only when the weight is float16 and the flag is on, the cross term takes the existing chunked float32 GEMM: W upcast in 64 MiB row chunks, which is exact for float16 values. Every other case keeps `mm.dtype` unchanged. The common path gains one host-side flag read and no kernels. Reading the flag inside a trace is a graph break (`torch._C._get_cublas_allow_fp16_accumulation`). The helper therefore goes through `torch.compiler.assume_constant_result`, so a compiled graph takes the value at trace time. It is compile-clean under `fullgraph = True` on torch 2.10 and 2.14. ##### Tests New `tests/test_dora_factored_norm_fp16_accumulation.py` (CPU; the CUDA route is selected with a patched `is_cuda` and a spy on `torch.mm`; prints the `dora.py` it loaded): - float16 / bfloat16 weight, with the flag off and on. Only float16 with the flag on skips `mm(..., out_dtype = ...)`. The norm stays within 1e-5 of fp64 in all four cells. - Reading the flag compiles under `fullgraph = True` with no graph break. | Arm | Result (new file + `tests/test_dora_factored_norm.py`) | |---|---| | origin/main 635532f | 2 failed, 22 passed | | this branch | 24 passed | ##### Not covered - Not run on a GPU here. - Two edge cases are left as they are on main: - a float32 `lora_A` entry above 65504 with a float16 base gives a NaN norm; - the low half of the float16 split is subnormal at Kaiming scale. The Colab L4 / A100 runs showed no loss from that (fp64-oracle error about 1.5e-7 on both arms); T4 and RTX cards were not run. ## Not proven here Intel Arc XPU was not run (no XPU available); the float64 crash is shown with a device stub. The fp16 subnormal precision concern did not show on T4, L4 or A100 and is untested on consumer Ampere cards. A float32 lora_A above 65504 with a float16 base still gives a NaN norm (unchanged from main).
…(#18610) DoRA computes the norm of each row of `W + scale * B @ A` from three terms. When the adapter nearly cancels the base weight, rounding in the cross term changes the norm and the adapter gradients. On an RTX 3090, the existing FP16 near-cancellation test exceeds its 0.5% tolerance on upstream `ba4979c497`, which includes #18629. Compiling the operation with Inductor's default settings also drops precision when splitting a float32 adapter into high and low parts. [Original report on #18515](unslothai/unsloth#18515 (comment)) The CUDA kernel accumulates 32-element dot products with a separately rounded FP32 addition. It splits the adapter inside the kernel so the split survives compilation. The kernel reads strided weights directly and keeps the dense adapter update out of memory. ### Accuracy Maximum row-norm error against the dense FP64 reference on an RTX 3090, PyTorch 2.11.0+cu130. FP16 base, FP32 adapter, rank 8, seed 2, input width 256. | Execution | Upstream ba4979c | This PR | | --- | ---: | ---: | | Eager | 1.022% | 0.102% | | Compiled with Inductor | 13.010% | 0.097% | At input width 1,024 the eager norm error fell from 3.612% to 0.083%. With the same construction in a PEFT linear layer, LoRA A gradient error relative to PEFT’s dense forward fell from 2.898% to 0.070%. The same FP16 and BF16 near-cancellation probe passed in eager and compiled mode with PyTorch 2.6.0 / Triton 3.2.0 and PyTorch 2.7.1 / Triton 3.3.1. ### Training benchmark A locally initialized 28-layer Qwen3-0.6B checkpoint through `FastLanguageModel`, all seven projections, FP16 base, FP32 DoRA adapters, batch size 2, sequence length 128, per-block compilation, fused AdamW. Each arm used the same checkpoint and batches in two fresh processes. Times are median wall time across 44 synchronized forward/backward/optimizer steps after 10 warmups per process. | Rank | Upstream ba4979c | This PR | Peak allocated, both | | --- | ---: | ---: | ---: | | 32 | 53.52 ms | 51.76 ms | 2,056 MiB | | 256 | 62.83 ms | 62.74 ms | 3,964 MiB | With the upstream high-rank change included, both branches ran rank 256 in about 63 ms per step. The profiler counted 196 launches of the new kernel in one training step at each rank. ### Verification On `be168f0930`, all 83 focused tests passed, including DoRA accuracy and gradient tests, the upstream rank-dtype and FP16-accumulation fallback tests, and the repository's Triton launch and parameter checks. CUDA Compute Sanitizer reported zero memory errors across 16 strided, partial-tile and empty-shape cases. The RTX 3090 also passed the FP16 cancellation check with cuBLAS FP16 accumulation enabled and disabled. ### Takeover update On an L4 with torch 2.14, the cross term from `torch.mm(..., out_dtype=float32)` has a relative error of about 1e-6 to 8e-6. When the adapter nearly cancels the base weight, that turns into a 4 to 17% row-norm error in eager mode. Under Inductor the error reaches up to 322%, because the high/low adapter split loses its low half. With this kernel both stay at 0.1 to 2.8%. Without cancellation every variant is about 1e-7. On the merge base, the existing `test_near_cancellation[fp16, fp32 adapter, cuda]` fails on the L4 with an error of 1.022%, and it passes here. torch 2.6 never uses the `out_dtype` path and is unaffected. Changes on top of the original commits: - The split count is an unspecialized runtime argument, so one kernel variant serves every projection shape. It was 3 variants eager and 4 under compile. - Off the Triton path (CPU, pre-Ampere, ROCm), the float32 adapter is rounded to the base dtype by masking its bits. Inductor no longer zeroes the low half there. - `UNSLOTH_DORA_TRITON=0` turns the kernel off. In eager mode, a failed launch warns once and falls back to cuBLAS. Checks: 0 graph breaks with `fullgraph=True` on torch 2.6 / Triton 3.2 and torch 2.14 / Triton 3.8, no recompiles, no host syncs, 1 kernel variant. A Qwen3-0.6B DoRA step launches the kernel 784 times (0 with the kill switch). On an L4, step time is within 0 to 1.4% of the merge base at ranks 16 and 256 across two VMs, with peak memory unchanged. Open: an fp16 base with adapter values above 65504 still gives NaN, the same as on main. --------- Co-authored-by: danielhanchen <[email protected]>
Summary
DoRA needs the row norm
||W + s * B @ A||of every adapted weight on every forward. PEFT'sDoraLinearLayer.forwardgets it by building the dense update:torch.eye(d_in)pushed throughlora_Aandlora_B, thenW + s * lora_weightand its row norm. That is several weight-sized passes and temporaries per DoRA module per forward, and twice per step under gradient checkpointing. Every fused LoRA path infast_lora.pyalready steps aside for DoRA, so Unsloth users withuse_dora = Truepay all of it.The norm only needs rank-sized work (arXiv 2603.22276, "Scaling DoRA: High-Rank Adaptation via Factored Norms and Fused Kernels"):
One
d_out x d_in x rGEMM and one row reduction ofWreplace the dense update. The 16-bit (or dequantized) base weight is read as stored; no float32 copy of it is made.Changes
unsloth/kernels/dora.py(new):factored_dora_weight_normandpatch_peft_dora_factored_norm, which wrapspeft.tuners.lora.dora.DoraLinearLayer.forward. Only the norm changes. Magnitude / norm scale, bias handling and the dropout path stay exactly as PEFT has them, and the norm is still detached (DoRA paper section 4.3), so no gradient path changes.s * B @ Anearly cancelsW, the squared norm is a small difference of large terms. So:aten::mm.dtypeon CUDA, otherwiseWis upcast in bounded row chunks. It is never rounded to 16 bits.lora_Ais split into two 16-bit halves, stacked into one operand, soWis still read once and every product is exact.A/B.ENABLE_DORA_CACHING), DTensor / sharded weights, adapter or base weights on another device (ephemeral GPU offload), and non-2D or mismatched shapes.UNSLOTH_DORA_FACTORED_NORM=0turns it off.+=on a module-level int guards on its value, so every call recompiled until Unsloth's per-block compile gave up and ran the block eagerly.unsloth/models/_utils.py, next to the other PEFT patches.tests/test_dora_factored_norm.py, CPU, plus CUDA cases when a GPU is present:nn.Linear/Conv1D(fan_in_fan_out).W=[[1,1]],A=[[1.0078125,1.015625]],B=[[-1]],s=1.||W_i||) for bf16 / fp16Wand bf16 / fp32A.torch.compile.Results
Speed, Colab L4, unsloth at the merge base vs the same install with the two changed files.
FastLanguageModel,use_dora = True, Llama-3.2-3B, bf16, r = 16, all 7 projections, bs 2 x 1024, Unsloth gradient checkpointing and per-block compile. Each arm ran in its own process, 3 reps of 5 timed steps after 2 warmup steps. Times are median ms per step with the spread across reps.headoffis the head tree withUNSLOTH_DORA_FACTORED_NORM=0, a second A/A against base. Two separate L4 VMs:Head is faster than every base and headoff rep on both VMs, and peak memory drops by 0.32 GiB. The two A/A arms (base and headoff) differ by 14 ms on VM 2 and 56 ms on VM 1. On VM 1 that gap is larger than the head-vs-base gain (50 ms), so read the speedup as about 3% to 5%.
Plain HF + PEFT without Unsloth's compile, at the first revision (before the precision changes above): 1.27x to 1.34x per step at r = 16, 32 and 64 for Llama-3.2-3B and Qwen3-4B, bf16 and 4-bit. Unsloth's per-block compile already fuses PEFT's dense path, which is why the gain inside Unsloth is smaller.
Accuracy, through
FastLanguageModelon Llama-3.2-1B-Instruct and Qwen3-0.6B, bf16 and 4-bit, after 3 training steps solora_Bis nonzero. Every DoRA module is compared against an fp64 dense norm. Unsloth keeps LoRA weights in float32, so PEFT's dense path there runs in float32:In the near-cancellation test the factored norm stays within 5e-3 of fp64 (bf16 PEFT: up to 4.8e-2). The bf16 cross term at the first revision produced 0 or inf there.
Under Unsloth's per-block compile (Llama-3.2-1B, profiler, one step),
triton_poi_fused_eye_0no longer runs; the factored norm kernels run for all 112 DoRA modules in both the forward and the checkpoint replay. There are no recompiles, and the graph-break set is the same as base.Test plan
pytest tests/test_dora_factored_norm.py: 19 passed on CPU, 26 on a CUDA machine (the CUDA cases add themm.dtypepath). The previous revision fails the counterexample, the near-cancellation, the autocast and the norm-identity tests.FastLanguageModel, bf16 and 4-bit, two models.mm.dtypeis gated off on HIP), T4 fp16, multi-GPU (FSDP2 falls back to PEFT on DTensor weights).