Skip to content

DoRA factored norm: fp32 rank terms on GPUs above rank 32, no fp64 on XPU, fp16 accumulation fallback - #18629

Merged
danielhanchen merged 4 commits into
mainfrom
kr4-dora-norm
Nov 20, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
kr4-dora-norm

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up fixes for #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 #18515 P1
DoRA norm: float32 fallback for float16 weights under allow_fp16_accumulation #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 #18515)

DoRA factored norm: float64 rank terms only where float64 exists and is cheap

What broke

#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 ([Arc] XPU backend: fp64 not supported intel/torch-xpu-ops#628, GradScaler Not work on Intel Arc GPU pytorch/pytorch#147731; Unsloth already guards the same case in Studio, Studio: keep MiniMax-H3 PDD float64 math on the host on a device without float64 #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 #18515)

DoRA factored norm: chunked float32 cross term for float16 under allow_fp16_accumulation

What broke

#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).

Intel Arc XPUs have no float64 and raise "Required aspect fp64 is not supported
on the device" on any float64 tensor, so the factored DoRA norm crashed every
DoRA forward there. Use float32 rank terms on every device other than CUDA
(incl. ROCm) and CPU, as MPS already did.
The rank-sized 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: about 2.2 ms per call at
r = 256 and d = 4096 on an L4, against a 0.1 ms cross-term GEMM. A rank-256 DoRA
step on an RTX 3090 went from 95 ms to 261 ms. Keep float64 on CPU and on
CUDA / ROCm up to rank 32; use float32 above. The rank is a static weight shape,
so the choice adds no guard or host query.
…w_fp16_accumulation

cuBLAS refuses float16 inputs with a float32 output when
torch.backends.cuda.matmul.allow_fp16_accumulation is on, so the float16
torch.mm(..., out_dtype = torch.float32) cross term crashed every float16 DoRA
forward with that flag set. Fall back to the existing chunked float32 GEMM only
in that case. Reading the flag is a graph break, so it goes through
torch.compiler.assume_constant_result: a trace takes its value as a constant.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T13:56:27.845017Z 172fff4 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 172fff4636

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 0447e1a into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the kr4-dora-norm branch November 20, 2026 14:54
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 23, 2026
…nslothai#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 unslothai#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
unslothai#18515](unslothai#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant