Skip to content

LayerNorm / RMSNorm: per-GPU num_warps tables - #15180

Merged
danielhanchen merged 3 commits into
mainfrom
ln-warps
Oct 25, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
ln-warps

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The Triton LayerNorm and RMSNorm kernels take their num_warps from calculate_settings, which only looks at the block size. A sweep over hidden size and GPU found that a different warp count is faster in some cases, and that the best count for the forward + frozen-weight backward often differs from the best one for the weight-gradient (dW) backward.

Change

  • Lookup: unsloth/kernels/utils.py gets norm_num_warps(table, n_cols, num_warps, device). It returns table[(capability, n_cols)] on CUDA devices and the existing default everywhere else (CPU, ROCm, widths and GPUs that have no entry).
  • Tables: layernorm.py and rms_layernorm.py each get two tables, one for the forward + frozen-W backward and one for the dW backward. The dW kernel and its program count use their own table.
  • Cost: the lookup is cached per (width, device, path) for eager calls. Under torch.compile it is computed directly, so it adds no graph break. Host time per call stays within main's range: _settings takes 209-222 ns against 145-253 ns on main.
  • Unchanged: the multirow RMSNorm path and the fused add + RMSNorm inference kernel keep their current warps.
  • Opt-out: UNSLOTH_NORM_ARCH_WARPS=0 turns the tables off.

Table entries

An entry is in the table only if it held up when this branch was run against main on torch 2.14.1. The method:

  • one Colab or Kaggle VM per tier, with main and this branch in separate processes;
  • order main, branch, main for 5 rounds;
  • each arm runs the real Fast_Layernorm / Fast_RMS_Layernorm forward and backward as a CUDA graph of 10 calls.

An entry is kept only when:

  • at least one cell wins outside the A/A band (main vs main), and every branch round beats every main round;
  • no cell is slower than max(A/A, 1%).

Cells: rows 2k and 16k, bf16 and fp16 (fp16 only on T4).

GPU kernel path hidden: warps (default -> table) speedup range across cells max A/A
T4 LayerNorm fwd + frozen-W bwd 2560 / 4096: 8 -> 16 1.016-1.049 0.6%
T4 LayerNorm dW 4096: 8 -> 16 1.031-1.068 0.2%
T4 RMSNorm fwd + frozen-W bwd 1024 / 2048 / 2560 / 4096 / 5120 / 8192: 4->8, 8->16, 8->16, 8->32, 16->32, 16->32 1.027-1.069 0.4%
A100 LayerNorm fwd + frozen-W bwd 2560: 8 -> 2 0.998-1.315 8.3%
A100 LayerNorm dW 5120: 16 -> 32 1.124-1.186 0.1%
L4 LayerNorm fwd + frozen-W bwd 2048: 8 -> 4 0.998-1.132 0.5%
L4 RMSNorm dW 2560 / 4096: 8->4, 8->2 1.000-1.208 0.4%
H100 LayerNorm fwd + frozen-W bwd 2560 / 5120: 8->2, 16->4 1.017-1.490 0.4%
H100 LayerNorm dW 5120: 16 -> 32 1.206-1.214 0.1%
H100 RMSNorm fwd + frozen-W bwd 5120: 16 -> 4 1.003-1.185 0.1%
RTX PRO 6000 LayerNorm fwd + frozen-W bwd 5120: 16 -> 4 0.998-1.108 3.2%
RTX PRO 6000 LayerNorm dW 4096: 8 -> 16 1.002-1.167 0.2%
RTX PRO 6000 RMSNorm dW 1024 / 2560 / 5120 / 8192: 4->8, 8->4, 16->8, 16->4 1.004-1.200 5.9%

Dropped: two T4 LayerNorm candidates did not replicate, so they are not in the table: forward at 2048, and dW at 1024 (0.898-1.007).

Earlier lead: an earlier lead of about 1.25x for 4 warps at hidden 4096 did not hold on any timed tier:

  • A100: about 1.01x;
  • H100: 1.023x;
  • RTX PRO 6000: 0.989x;
  • T4: slower.

Accuracy: outputs are not bitwise equal to the default, because the reduction order changes. Every entry's maximum error against an fp64 reference is within one ulp of the default's maximum error, in fp16 and bf16, for 1, 777 and 4096 rows.

dX mismatch on table GPUs: dX from the dW backward can now differ in the last bits from dX of the frozen-W backward, because the two paths use different warps. Both stay within that bound.

End to end

LoRA training step: 16-bit, batch 2, sequence 1024, r 16, 20 steps; median of steps 6-20, main / branch / main interleaved over 2 rounds. Losses match between arms.

With LoRA the norm weights are frozen, so only the forward + frozen-W entries can move a LoRA step.

GPU model (hidden) main ms / step this PR speedup A/A
T4 (fp16) Qwen3-4B (2560) 3141.5 3128.8 1.0040 0.05%
H100 Qwen3-14B (5120) 343.6 343.9 0.9992 0.19%
A100 Qwen3-4B (2560), no entry used 331.2 332.1 0.9974 0.03%
L4 Qwen3-4B (2560), no entry used 1302.8 1285.1 1.0137 2.87%
RTX PRO 6000 Qwen3-4B (2560), no entry used 205.7 205.8 0.9996 0.01%
  • T4: visible at +0.4%.
  • Other GPUs: within noise. On A100, L4 and RTX PRO 6000 no kernel changes for this model by design; main's own step times spread 0.35% between rounds on A100.
  • Full fine-tuning: the dW entries only show up end to end in full fine-tuning, which was not timed.

Tests

New tests/test_norm_arch_warps.py (9 tests) covers:

  • routing: other GPUs, CPU, HIP, the kill switch, and widths not in a table;
  • table sanity;
  • the fp64 accuracy check above for every entry.

Bypassing the lookup fails 8 of the 9.

The 16 norm test files plus the new test, on B200:

torch main this PR
2.14 887 passed, 20 skipped 896 passed, 20 skipped
2.10 887 passed, 20 skipped 896 passed, 20 skipped

The 9 extra passes are the new test.

Not covered

  • B200: no table entries; its timing needs an exclusive card.
  • Timing scope: each GPU has one replication run on torch 2.14.1 (T4 has three, counting the sweep). Other torch versions were timed on 2.11 only, in the sweep.
  • Full fine-tuning: no full fine-tuning step timing.
  • Widths: hidden sizes outside 1024 / 2048 / 2560 / 4096 / 5120 / 8192 keep the default warps.

Measured on T4, L4, A100, H100 and RTX PRO 6000: the forward + frozen-W
backward and the dW backward each take a per (compute capability, width)
warp count where a sweep found it faster outside A/A in some cell, never
slower, >= 3% geomean, with max error vs fp64 no worse than the default.
UNSLOTH_NORM_ARCH_WARPS=0 restores calculate_settings everywhere.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T03:08:03.722067Z f708b74 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. Swish!

Reviewed commit: 82870a885a

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

Copy link
Copy Markdown
Member Author

The Repo tests (CPU, studio) run here has one failure from this PR: tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe flags

test_norm_arch_warps.py:112: torch.cuda.is_available()

tests/_zoo_aggressive_cuda_spoof.py patches torch.cuda.is_available() to True for the whole process, so on a CPU-only runner that skip stops skipping whenever it shares a session with tests/version_compat or tests/vllm_compat. The guard wants the real probe first, for example:

from real_accelerator import has_real_cuda

@pytest.mark.skipif(not has_real_cuda(), reason = "needs CUDA")

(tests/_shared is on sys.path from the root conftest.) The other reds on this run (the footer test, and test_single_row_cached_attention on the Core legs) are from main and are fixed by #15181 and #15182; merging main in clears them.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f708b749dd

ℹ️ 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 9016429 into main Oct 25, 2026
@danielhanchen
danielhanchen deleted the ln-warps branch October 25, 2026 03:14
danielhanchen added a commit that referenced this pull request Oct 25, 2026
## Summary

#15180 (per-GPU num_warps tables) added `tests/test_norm_arch_warps.py`,
whose CUDA case skips with `torch.cuda.is_available()`.
`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
rejects that on main, so `Repo tests (CPU, studio)` is red on unrelated
PRs (for example #15189):

```
test_norm_arch_warps.py:114: torch.cuda.is_available()
```

`tests/_zoo_aggressive_cuda_spoof.py` patches
`torch.cuda.is_available()` to True for the whole process, so on a
CPU-only runner that skip stops skipping whenever it shares a session
with `tests/version_compat` or `tests/vllm_compat`. The test is wrong
here, not the kernels.

## Change

- `tests/test_norm_arch_warps.py`: skip on `has_real_cuda()` from
`tests/_shared/real_accelerator.py`, as `test_block_compile.py`,
`test_bnb_nf4_override.py` and others do.

## Verification

- `tests/python/test_accelerator_skip_guards.py`: `1 failed, 23 passed`
on main, `24 passed` with this change.
- `tests/test_norm_arch_warps.py` on CPU: `5 passed, 4 skipped`, the
same as before.
- On a GPU host `has_real_cuda()` is True, so the CUDA cases still run
there. On a CPU host it is False.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 25, 2026
…ngs cache (unslothai#14727)

unslothai#13889 cached `calculate_settings` per width with `functools.lru_cache`,
bypassing the cache only when `torch.compiler.is_compiling()` is true.
Under `torch.compile(dynamic=True)` the traced `unsloth::rms_layernorm`
op runs its fake implementation outside Dynamo, where `is_compiling()`
is False but the width is a `SymInt`, so the cache tries to hash it:

```
Dynamo failed to run FX node with fake tensors: call_function unsloth.rms_layernorm(...): got TypeError('unhashable type: non-nested SymInt')
```

So a compiled RMSNorm with `fullgraph=True, dynamic=True` fails on main,
where it traced in one graph before unslothai#13889 (d64b080).

Fix: `_settings` also calls `calculate_settings` directly when the width
is not a plain `int`. Eager calls still hit the cache (the width there
is always an `int`), so the host path is unchanged apart from one
`type()` check. The same guard goes into `layernorm.py`, which got the
same cache in unslothai#13889.

Measured on one B200, torch 2.11.0, Triton 3.6.0, compiled norm with
`fullgraph=True, dynamic=True`, sequence lengths 64 / 80 / 96 / 127,
widths 64 and 4096, fp32 and bf16:

| Tree | Result |
|---|---|
| d64b080 (before unslothai#13889) | pass, one graph |
| b67f20f (unslothai#13889) | TypeError in the fake run |
| main | TypeError in the fake run |
| this branch | pass, matches eager bytes |

Update after syncing with main: unslothai#15180 moved `_settings` to a
per-(capability, width) num_warps table (`norm_num_warps`), whose
`table.get((capability, n_cols))` hashes the width again. On NVIDIA that
second lookup kept the same TypeError, so `norm_num_warps` now matches a
symbolic width by equality. Measured on a G4 (sm120): with only the
`_settings` guard, `test_rms_layernorm_dynamic_shapes[4096-*]` still
fails; with both it passes.
`tests/test_norm_settings_symbolic_width.py::test_a_symbolic_width_reads_the_cuda_warps_table`
(CPU, capability patched) covers it and fails without the fix.

Tests:
- `tests/test_norm_settings_symbolic_width.py` (CPU): a symbolic width
skips the cache and returns `calculate_settings`'s answer; an int width
still uses the cache. The symbolic cases fail on main and pass here.
- `tests/test_rms_rope_compile.py::test_rms_layernorm_dynamic_shapes`
(GPU): compiled `fullgraph=True, dynamic=True` forward and backward
match eager bytes across three lengths, Llama and Gemma variants. Fails
on main (4 of 4), passes here.
- The rest of `test_rms_rope_compile.py`, the multirow, triton_launch
and weight-grad norm suites pass on this branch, except the two
tiny-Llama fullgraph tests, which fail the same way on main.
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