Skip to content

Fix CUDA DoRA row-norm accuracy under cancellation and torch.compile - #18610

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
0xalkinun:codex/fix-dora-fp16-norm
Nov 23, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
0xalkinun:codex/fix-dora-fp16-norm

Conversation

@0xalkinun

@0xalkinun 0xalkinun commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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

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.

@0xalkinun

Copy link
Copy Markdown
Contributor Author

@codex review

@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-23T15:43:41.895806Z b042fa5 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 97444c0902

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

@0xalkinun

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: be168f0930

ℹ️ 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 added a commit that referenced this pull request Nov 21, 2026
## Problem

`Repo tests (CPU, rest-2)` fails on `main` since #18625 and on every PR
based on it (for example #17742, #18032, #18610, #18740):

```
test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[3]
AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding,
so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8" ...
  'tests/test_tp_vocab_parallel_gloo.py:307: open()'
```

## Cause

#18625 added a source check to `tests/test_tp_vocab_parallel_gloo.py`
that reads `unsloth/models/llama.py` with a bare `open(...)`. On Windows
that uses the locale code page, so it would raise `UnicodeDecodeError`
once `llama.py` carries a non-ASCII byte. The guard is right; the new
read is missing its encoding.

## Fix

Pass `encoding = "utf-8"` to that `open()`. One line, test-only.

## Verification

- On `main`: `tests/test_source_read_encoding.py -k
checked_in_file_reads` fails (`[3]`, naming this line).
- With this change: 16 passed, and
`tests/test_tp_vocab_parallel_gloo.py` passes (11 passed).
@danielhanchen danielhanchen self-assigned this Nov 23, 2026
… the kernel path

Pass SPLITS and the GEMM sizes as unspecialized runtime ints so every projection shape
shares one compiled kernel instead of one per split count. Off the Triton path (CPU,
pre-Ampere, ROCm), round the float32 adapter to the base dtype by masking its bits, since
Inductor elides the lowp -> float32 cast pair and the old split lost its low half when
compiled. Add UNSLOTH_DORA_TRITON=0 and fall back to cuBLAS if the kernel fails to launch.
…lized

Unspecializing M, N and K dropped Triton's 16-divisibility hints and made the rank 256
cross term about 35% slower on an L4. Only SPLITS changes between projection shapes, so
it is the one argument left unspecialized; aligned shapes still share one variant.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9f84872395

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

Comment thread tests/test_dora_factored_norm.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: b042fa52cd

ℹ️ 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 19f49d7 into unslothai:main Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants