Repository navigation
Launch eager RMSNorm and LayerNorm kernels through triton_launch - #13889
Merged
Merged
Conversation
Eager CUDA calls of the five RMSNorm kernels and the four LayerNorm kernels go through triton_launch.launch, skipping Triton's per-call argument binding once a specialization is warm. Runtime arguments now come before the constexprs in each kernel signature so launch() can take them; every call site passes the constexprs by keyword. Traced launches (wrap_triton, and torch.compile tracing Fast_Layernorm) keep kernel[grid]; HIP keeps Triton's path. Block settings are cached per width and triton.cdiv is replaced by its integer formula.
Codex Review SummaryThis 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. Another round soon, please! 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". |
danielhanchen
added a commit
that referenced
this pull request
Oct 15, 2026
…3909) With #13846 merged, main (d303bac) is still red in Backend CI and Repo tests, from three regressions that landed in the last few hours. Each is reproduced locally on main and fixed here. ## 1. `test_text_io_names_its_encoding[drafter.py]` (from #13806) ``` drafter.py:222: subprocess(text = True) without encoding ``` `core/training/drafter.py` runs the drafter capability probe in a child interpreter with `text = True` and no encoding, so the parent decodes the child's output with the locale codec (cp1252 on Windows, ASCII under a C locale). The guard is right and the code is what changes: the call now passes `encoding = "utf-8", errors = "replace"`, and the child gets `PYTHONIOENCODING=utf-8` so it writes what the parent reads. That matches how `core/training/worker.py` runs its own probes. The payload line is `json.dumps` output, so nothing parsed changes. ## 2. `test_backfill_splits_a_quant_suffix_the_way_the_backend_does` (from #13899) ``` AssertionError: MXFP ``` #13899 widened the GGUF known-quant pattern from `MXFP...` to `(?:MX|NV)FP...` so NVFP4 files get their own variant key. That change is right, and it was made consistently in all three places that must agree: `core/inference/llama_cpp.py` (`_GGUF_KNOWN_QUANT_RE`), `hub/utils/gguf.py` (`_GGUF_QUANT_RE`) and the frontend's `model-identity.ts` (`QUANT_TOKEN_SOURCE`). The test was checking that the literal substring `MXFP` appears in `llama_cpp.py`, which it no longer does. The test now checks the property it was standing in for: it reads the pattern string out of both Python modules with `ast` (adjacent literals joined as Python joins them) and the TypeScript constant, asserts all three are identical, and asserts the shared pattern still fully matches `MXFP4`, `NVFP4`, `IQ4_XS`, `TQ1_0`, `Q4_K_M`, `Q8_0`, `BF16`, `F16` and `F32`. That is stricter than before, since a pattern edited on one side only now fails, and it no longer breaks on a correct rewording. ## 3. `test_every_tracked_python_file_is_already_formatted` Formatter drift (pinned ruff 0.6.9 via `scripts/run_ruff_format.py`), output only, no logic change: | file | from | | --- | --- | | `studio/backend/core/inference/llama_cpp.py`, `offload_layout.py`, `tests/test_nemotron35_bolt_super.py`, `tests/test_nemotron35_planner.py` | #13899 | | `studio/backend/tests/test_muse_spark.py` | #13903 | | `tests/test_norm_fast_launch.py`, `unsloth/kernels/layernorm.py` | #13889 | | `tests/test_remote_code_class_and_expert_submodules.py`, `unsloth/models/_utils.py` | #13851 | | `tests/test_triton_fp_fusion.py` | #13846 | ## Verification - `tests/test_formatter_fixed_point.py` (ruff 0.6.9): fails on main, 16 passed here. - `tests/studio/test_model_picker_contracts.py` and `tests/test_runtime_text_encoding.py`: 210 passed. - `studio/backend/tests/test_text_io_encoding.py`, `test_nemotron35_bolt_super.py`, `test_drafter_training.py`: all pass except `test_capability_child_process_runs_for_real`, which fails identically on main without this change on this host (it runs the probe in a real child interpreter) and is not failing in CI. - Sabotage on the rewritten picker guard: dropping `NV` from the pattern in `hub/utils/gguf.py` only, or in `model-identity.ts` only, fails it; restored, it passes. - Sabotage for (1) is main itself: without the encoding, the guard fails as quoted above.
danielhanchen
added a commit
that referenced
this pull request
Oct 15, 2026
…p guards (#13936) Two more checks are red on main (7382805), seen on #13915 and #13922's run, both reproduced locally on main. ## `test_no_raw_pixel_text_utilities` (from #13850) ``` Raw px text utilities ignore the UI font size preference; use the text-ui-* / leading-ui-* tokens in index.css instead: features/studio/sections/token-preview-dialog.tsx: text-[12.5px] features/studio/sections/token-preview-dialog.tsx: text-[9px] ``` The new token preview dialog sized three text runs with raw `text-[12.5px]` / `text-[9px]`, so they stay fixed when the user changes Settings > UI font size while the rest of Studio scales. The contract is right and the dialog is what changes. `index.css` has exact tokens for both sizes, `--text-ui-12p5: calc(0.78125rem * var(--ui-font-scale, 1))` and `--text-ui-9: calc(0.5625rem * var(--ui-font-scale, 1))`, so this swaps to `text-ui-12p5` / `text-ui-9`. At the default scale of 1 those resolve to the same 12.5px and 9px, so the dialog renders the same as today; the only difference is that it now follows the font size setting. No screenshots: there is nothing visible to compare at the default scale. ## `test_no_skip_guard_reads_a_spoofable_accelerator_probe` (from #13830 and #13889) ``` test_fp8_rowwise_gemv_blackwell_gate.py:47: torch.cuda.is_available() test_norm_fast_launch.py:189: torch.cuda.device_count() ``` `tests/_zoo_aggressive_cuda_spoof.py` patches the torch.cuda probes to report a GPU process-wide for the version-compat suites, so a skip guard that reads them un-skips on a CPU-only runner whenever it shares a pytest session with those suites. Both guards now ask `has_real_cuda()` from `tests/_shared/real_accelerator.py` (answered before any spoof), the form the rest of the tree uses: `not has_real_cuda()` for the FP8 GEMV exactness test, and `not has_real_cuda() or torch.cuda.device_count() < 2` for the two-GPU norm test, matching `test_rms_layernorm_multirow.py`. On a real GPU the predicate is the same as before. ## Verification - `tests/studio/test_ui_font_scale_contract.py`: fails on main as above, 12 passed here. Prettier clean. - `tests/python/test_accelerator_skip_guards.py`: fails on main as above, 24 passed here. - On CPU, `test_fp8_rowwise_gemv_blackwell_gate.py` and `test_norm_fast_launch.py`: 6 passed, 4 skipped (the GPU cases, with their reasons), same as main. - Not run here: the GPU cases themselves. This host's CUDA torch environment fails bitsandbytes CUDA setup at collection, unrelated to this change; the test bodies are untouched.
danielhanchen
added a commit
to Imagineer99/unsloth
that referenced
this pull request
Oct 16, 2026
… frozen operands, no CE eviction hint on H100 (unslothai#13967) Fixes from a post-merge audit of unslothai#13831, unslothai#13889 and unslothai#13893, checked on T4, A100, H100, B200 and AMD gfx1151. Each item has a test that fails on main and passes here. ## Changes - **Eager RMSNorm / LayerNorm launch when the fast launcher is off (unslothai#13889).** On ROCm and with `UNSLOTH_TRITON_FAST_LAUNCH=0`, every norm call went through the fast-launch wrapper (heuristics expansion, an extra call) before reaching `kernel[grid]`. It now calls Triton directly in that case, as before unslothai#13889. The launch condition also checks `torch.compiler.is_compiling()` first, so compiled graphs no longer guard on the mutable launcher flag (a launcher fallback recompiled every compiled LayerNorm). - **Grouped GEMM backward skips gradients nobody needs (unslothai#13831 follow-up).** `GroupedGemm.backward` always ran the dW kernel and allocated the (E, N, K) dW unless the caller passed `dX_only`, and none of the MoE callers do. With frozen experts (LoRA, dequantized bnb 4-bit / FP8 experts) that is a wasted kernel and buffer per projection per step. It now follows `ctx.needs_input_grad`, so a frozen W gets no dW and a constant X no dX; trainable operands are unchanged. - **No chunked cross entropy eviction hint on H100 (unslothai#13893).** `evict_first` on the chunked forward measured slower on H100 (sm_90): 2048 x 262144 bf16 logits 437.6 -> 448.2 us (+2.4%, base spread 1.2%), 4096 x 128256 429.8 -> 436.6 us. It is now off on sm_90 as it already was on sm_100; T4 / L4 / A100 keep it, where unslothai#13893 measured it faster. - **CE eviction hint test (unslothai#13893).** Compiles each architecture's own target (so sm_80+ exercises the L2 cache-policy lowering) and skips on Triton 3.2, whose `ASTSource` has no `constexprs`. ## Tests - New `tests/test_grouped_gemm_frozen_weight_grad.py`: which backward kernels run for each (X, W) `requires_grad` combination, gradients vs an fp32 reference. 2 of 4 fail on main (frozen W, frozen X). - `tests/test_norm_fast_launch.py`: with the launcher off, no call goes through `launch()`; flipping the launcher flag does not recompile a compiled LayerNorm (both fail on main). - `tests/test_cross_entropy_eviction_hints.py`: sm_90 gets no hint (fails on main). - B200, torch 2.14 / Triton 3.8, including the `gpu`-marked tests: the touched test files pass (173 passed, 13 skipped). Earlier heads also passed on torch 2.7.1 / Triton 3.3.1 and torch 2.10. - `tests/test_norm_fast_launch.py`: the eager half of `test_compiled_calls_never_use_fast_launch` now expects `launch()` only when fast launch is on, so it holds on ROCm and with `UNSLOTH_TRITON_FAST_LAUNCH=0` (33 passed with the launcher off, 45 with it on). ## Training A/B (base = merge base, same seed and data, 30 steps unless noted) | Job | GPU | Step time (base -> PR) | Peak memory (base -> PR) | Loss | |---|---|---|---|---| | Grouped GEMM, frozen experts (E 128, H 2048, I 768, 4096 tokens, top 8) | A100 | 13.52 -> 7.72 ms (-42.9%) | 3.60 -> 2.85 GB (-20.8%) | identical | | Grouped GEMM, frozen experts (20 steps) | T4 | 812.5 -> 672.1 ms (-17.3%) | 2.60 -> 2.60 GB | identical | | MoE LoRA SFT (tiny Qwen3 MoE) | A100 | 28.26 -> 27.09 ms (-4.1%) | 74.1 -> 52.5 MB (-29.1%) | within tolerance | | MoE LoRA SFT (tiny Qwen3 MoE) | T4 | 42.41 -> 42.51 ms (+0.2%, noise) | 44 -> 44 MB | within tolerance | | Dense LoRA SFT | T4 | 324.96 -> 318.60 ms (-2.0%) | 1.33 -> 1.33 GB | within tolerance | All five runs report no regression against the A/B tolerances. ## Other GPUs - AMD gfx1151 (Strix Halo, ROCm 7.13, torch 2.11), at 7fc770d (later commits only change CUDA-only gates): the touched test files at base, head and the merge with main: 43 passed / 24 skipped at base, 56 passed / 0 failed / 24 skipped at head. No test that passed at base fails here. - H100 (sm_90): with the hint off, the chunked cross entropy forward compiles to PTX identical to the kernel before unslothai#13893 (Triton 3.8), so H100 runs exactly the pre-unslothai#13893 code. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen
added a commit
to Etherll/unsloth
that referenced
this pull request
Oct 18, 2026
…test fixes across torch 2.10 - 2.14 (unslothai#14122) Follow-up fixes from a re-verification of the recent kernel PRs (unslothai#13828, unslothai#13829, unslothai#13830, unslothai#13831, unslothai#13840, unslothai#13851, unslothai#13889, unslothai#13893, unslothai#13967, unslothai#14026, unslothai#14027) across T4, L4, A100, H100, RTX PRO 6000, B200 and gfx1151, on torch 2.10 to 2.14. Main itself showed no regression for default training or inference. These are the real gaps the re-verification turned up. ## Changes **NVFP4 fused GEMM row gate scales with the weight shape** (`unsloth/kernels/nvfp4.py`) - The old gate was one row limit per GPU (A100 64, L4 256, RTX PRO 6000 128). It picked the fused kernel in cells where fused is slower than dense: up to 2.4x on A100, 2.5x on L4 and 5.9x on RTX PRO 6000. For example, at 64 rows with N = K = 4096 it was +12% on RTX PRO 6000 and +4.5% on A100. - The limit is now `clamp(max(N * K // div, k_rows), floor, max_rows)`, with separate forward and dX entries per capability. Weights with N or K not a multiple of 128 run the masked edge tiles, so they only get the floor. - The constants were fitted to a bf16 sweep: rows 1 to 256, ten (N, K) shapes, timed with CUDA graphs, interleaved arms and an A/A spread. - `UNSLOTH_NVFP4_FUSED=0` / `1` and `UNSLOTH_NVFP4_FUSED_MAX_ROWS` keep their meaning. Unmeasured GPUs (H100, T4, others) stay dense as before. Confirmation pass, 90 cells per GPU: | GPU | old gate: fused picked but slower than dense | new gate | new slower than old by more than max(noise, 10%) | |---|---|---|---| | A100 | 11 | 0 | 1 (dX, 32 rows, 2048x2048, +16%) | | L4 | 23 | 0 | 2 (fwd, 256 rows, 5120x5120, +43%; fwd, 128 rows, 3072x768, +10%) | | RTX PRO 6000 | 21 | 0 | 0 | Fixing those three cells would push a neighbouring shape that loses onto fused, so they are left as they are. **MoE fallback grouped GEMM configs fit the GEMM** (`unsloth/kernels/moe/autotune_cache.py`) - These are the configs used with `UNSLOTH_MOE_DISABLE_AUTOTUNE=1`, or when autotuning fails (for example OOM on a 16 GB card). They used fixed tiles, and the kernels assert `N % BLOCK_SIZE_N == 0` and `K % BLOCK_SIZE_K == 0`. So intermediate sizes such as 1408 (DeepSeek-V2-Lite, Qwen1.5-MoE), 352 and 2880 crashed. - The tiles now shrink to the largest power of two (at least 16) that divides each GEMM's N and K. Configs that already worked (Qwen3-30B-A3B, Qwen3-235B, Mixtral, OLMoE) are byte-identical. - The heuristic 64x64x256, 4-stage dX config needs 122,880 B of shared memory, more than L4 and RTX PRO 6000 have (101,376 B). It raised OutOfResources there for every shape. On sm_80+ with that limit it now drops to 3 stages (81,920 B), reading the limit of the current device. T4, A100, H100 and B200 configs are unchanged. **Tests** - `test_norm_fast_launch`: run the narrow-row self-check before measuring the compiled call. On torch 2.10 to 2.12, Dynamo reaches that one-time check with `is_compiling()` False, and the test counted its eager launches. The compiled graph never used the fast launcher. - `test_cross_entropy_eviction_hints`: skip an arch the active ptxas cannot target. Once Inductor sets `TRITON_PTXAS_PATH`, the CUDA 13 ptxas has no sm_52 to sm_72. - `test_layernorm_compiled_matches_eager_bytes`: also run in fp16, and skip bf16 on GPUs without native bf16. Inductor skips bf16 graphs there, so `fullgraph=True` fails in plain torch too. ## Validation - **CPU tests:** new tests `test_nvfp4_fused_gate_shape.py` (27) and `test_moe_fallback_tile_dims.py` (60) pass on torch 2.10 and 2.14. - **GPU, base (main) vs this branch:** - Colab L4 (torch 2.11, 2.14), RTX PRO 6000 (2.14), T4 (2.10, 2.14): no test fails on the branch that passes on main. - Norm self-check test: fails on main on torch 2.10 and 2.11, passes here. - **MoE fallback, one MoE block driven exactly as unsloth-zoo calls it:** - T4: main crashes on 1408 / 352 / 2880. This branch trains them, with forward and all gradients within about 6e-4 of an fp32 reference. - L4 and RTX PRO 6000: the heuristic path crashes on main for every shape and trains here. - Unchanged shapes are bit-identical to main. 768 timing is unchanged on T4, L4 and RTX PRO 6000. - **NVFP4 GPU tests:** 105 passed on A100, L4 and RTX PRO 6000. The fused vs dense outputs match. Not covered: NVFP4 timing on H100 (no allocation) and in fp16; the MoE heuristic smem change on T4 is covered by CPU tests and earlier T4 runs of the same configs.
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.
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.
Problem
At small shapes the fast RMSNorm and LayerNorm are host bound: a forward + backward costs 370 to 530 us of host time on a Colab A100 against about 135 to 170 us for torch's own ops, while the kernels themselves take under 10 us. Profiling one call, about 70% of each Triton launch's host time is Triton's Python dispatch (argument binding, specialization, cache key, the heuristics wrapper), not the driver launch.
Change
Eager CUDA launches of every RMSNorm kernel (
unsloth/kernels/rms_layernorm.py: forward, forward_rows, backward, backward_rows, sum of dW partials) and every LayerNorm kernel (unsloth/kernels/layernorm.py: forward, backward, dW / dB backward, sum of partials) now go throughtriton_launch.launch, the direct launcher the NF4 dequant and GEMV already use: the first call per specialization goes through Triton, later ones call the compiled kernel directly.launchneeds that order); every call passes constexprs by keyword. Which arguments are constexpr is unchanged.torch.compile(thetriton_op/wrap_tritonops, and LayerNorm's tracedFast_Layernorm), non-CUDA tensors, and HIP (wherelaunchdisables itself).UNSLOTH_TRITON_FAST_LAUNCH=0turns it off.calculate_settingsis cached per width on the eager path, andtriton.cdivcalls are inlined.Results
Outputs are byte-identical to main: 2270 tensors per stack (Y, dX, dW, dB; RMSNorm gemma and not, widths 64 / 100 / 128 / 4096 / 5000, rows 0 / 1 / 7 / 129 / 1184, frozen and trainable; LayerNorm with and without bias, every frozen / trainable combination; fp32 / fp16 / bf16), compared in separate processes on torch 2.14 / Triton 3.8 and on torch 2.7.1 / Triton 3.3.
Host time per forward + backward, median of 5 interleaved rounds with a second main arm as the A/A (torch 2.11, Triton 3.6):
autograd.Functionplus output allocation, which this does not touch.Tests
tests/test_norm_fast_launch.py: a second eager forward + backward makes noJITFunction.runcalls; compiled (fullgraph) RMSNorm and LayerNorm make nolaunchcalls; CUDA graph capture, a non-default stream and a second device give the same bytes as the normal path. The engagement and compile cases fail on main; forcing launches onto the wrong stream fails 21 of the 24 graph / stream cases.tests/test_triton_fp_fusion.pyalso checks the 9_launchcall sites forenable_fp_fusion.test_rmsnorm_weight_grad,test_rms_layernorm_multirow,test_rmsnorm_gradient_layout,test_rms_rope_compile,test_layernorm_weight_grad,test_layernorm_gradient_layout,test_high_precision_layernorm_coverage,test_layernorm_precision_env_scope) plus the above (-o addopts=""): 962 passed, 19 skipped on torch 2.14 / transformers 5.17; on transformers 4.57.6, 960 passed and the same 2test_rms_rope_compilecases fail as on main (test_tiny_llama_decoder_layers_compile_fullgraph,test_tiny_llama_causal_lm_compiles_fullgraph). Earlier run: 619 passed withUNSLOTH_TRITON_FAST_LAUNCH=0.Not covered: torch 2.6 / Triton 3.2 (if its launcher signature differs,
launchfalls back to Triton's own path), and ROCm (fast launch is disabled there by construction).