Repository navigation
DoRA factored norm: fp32 rank terms on GPUs above rank 32, no fp64 on XPU, fp16 accumulation fallback - #18629
Merged
Merged
Conversation
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.
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. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
Tests (this branch vs main
54af93780b, CPU)prepush_gate.pypasses.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_dtypeinunsloth/kernels/dora.py). That causes two problems.Intel Arc XPUs have no float64. PyTorch raises
Required aspect fp64 is not supported on the devicethere ([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.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. Atd_in = d_out = 4096: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):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 thedora.pyit loaded):tests/test_dora_factored_norm.py)Not covered
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 whentorch.backends.cuda.matmul.allow_fp16_accumulationis on. The check is inaten/src/ATen/cuda/CUDABlas.cpp,gemm_internal<at::Half, float>andgemm_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.dtypeunchanged. 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 throughtorch.compiler.assume_constant_result, so a compiled graph takes the value at trace time. It is compile-clean underfullgraph = Trueon torch 2.10 and 2.14.Tests
New
tests/test_dora_factored_norm_fp16_accumulation.py(CPU; the CUDA route is selected with a patchedis_cudaand a spy ontorch.mm; prints thedora.pyit loaded):mm(..., out_dtype = ...). The norm stays within 1e-5 of fp64 in all four cells.fullgraph = Truewith no graph break.tests/test_dora_factored_norm.py)Not covered
lora_Aentry above 65504 with a float16 base gives a NaN norm;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).