Repository navigation
Kernels: request enable_fp_fusion=True explicitly, ahead of Triton 3.9's False default - #13828
Conversation
Triton main (3.9) flips the enable_fp_fusion default to False. Every Unsloth kernel relied on the old default, so on Triton 3.9 they would silently lose FMA contraction: slower, and different numerics (RoPE and GeGLU backward outputs already change bit-wise with TRITON_DEFAULT_FP_FUSION=0 on 3.8). Pass enable_fp_fusion=True at every launch: plain kernel[grid] calls, triton_launch.launch (options are in its cache key), wrap_triton launches inside triton_op, the MoE grouped GEMM (also autotuned) launches, and the int4 warmup that builds the fast-launch CompiledKernel. nf4.py now states its option both ways, keeping the eager dequant path's deliberate False. No knob or Triton patching: TRITON_FORCE_DISABLE_FP_FUSION still wins on Triton main. The option exists on CUDA, HIP and XPU backends since Triton 3.1, so no gating is needed. Outputs on Triton 3.8 are byte-identical to before.
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. |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
# Conflicts: # unsloth/kernels/layernorm.py
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b67ec1fe43
ℹ️ 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".
| Xv = rnd(1, 1, kk) | ||
| out["nf4_gemv"] = (nf4_gemv.gemv_nf4(Xv, *args, (n, kk), dt),) | ||
|
|
||
| if torch.cuda.get_device_capability(device) >= (8, 9) or torch.version.hip: |
There was a problem hiding this comment.
Gate the FP8 probe with ROCm kernel support
On every ROCm host torch.version.hip makes this branch run, but fp8._rocm_fp8e4nv_kernel_supported explicitly reports that this dtype is unsupported before Triton 3.3 and on several architectures through 3.4. Calling fp8_rowwise_gemv directly bypasses the normal _fp8_kernel_unsupported guard, so both parameterized tests fail during Triton compilation on those supported ROCm configurations; gate the probe with that helper instead of treating all HIP devices as FP8-capable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 73297fc: the probe now runs only when fp8._fp8_kernel_unsupported says the FP8 kernel exists on the device, which covers the ROCm arch / Triton table as well as pre-sm89 CUDA.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ca0cd7a08d
ℹ️ 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".
| gemv = (KERNELS / "nf4_gemv.py").read_text() | ||
| assert gemv.count("enable_fp_fusion = True") == 2 | ||
| int4 = (KERNELS / "int4_packed.py").read_text() | ||
| assert "kernel.warmup(*args, grid = grid, **constexprs, enable_fp_fusion = True)" in int4 |
There was a problem hiding this comment.
Stop matching the formatted warmup call as one line
Running pytest tests/test_triton_fp_fusion.py fails unconditionally here: int4_packed.py formats kernel.warmup( and its arguments across multiple lines, so this exact one-line substring is absent even though enable_fp_fusion=True is correctly supplied. Parse the call or normalize whitespace instead of asserting this literal string.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, the pre-commit reformat split the warmup call over three lines. Fixed in the next commit: the test now walks the AST of int4_packed.py and requires every warmup(...) call to pass enable_fp_fusion=True, so formatting no longer matters. tests/test_triton_fp_fusion.py: 4 passed.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
…13887) `Repo tests (CPU, rest)` is red on main since #13828 (e1cdbf4) and on every PR based on it (e.g. #13855): ``` FAILED tests/test_formatter_fixed_point.py::test_every_tracked_python_file_is_already_formatted these tracked files are not a fixed point of the ruff-format-with-kwargs hook, so pre-commit.ci will fail the next PR that edits them: tests/test_triton_fp_fusion.py Fix: python scripts/run_ruff_format.py tests/test_triton_fp_fusion.py ``` #13828 added that test with one generator expression over the 100-column limit. This is the output of `python scripts/run_ruff_format.py tests/test_triton_fp_fusion.py` with the pinned ruff 0.6.9, nothing else: the one `any(...)` call is split over four lines. No logic change. Verification: - `tests/test_formatter_fixed_point.py` (ruff 0.6.9): fails on main as above, 16 passed with this change. - `tests/test_triton_fp_fusion.py`: 2 passed, 2 skipped (no GPU), same as before.
#13749 and #13828 (#13846) #13724 landed with three CI jobs red, #13749 left a picker contract test behind, and #13828 added a test file the formatter and encoding checks reject, so main fails `(Python 3.13, a-k)`, `(Python 3.13, rest)`, `Repo tests (CPU, rest)` and `Repo tests (CPU, studio)` on every PR. This brings those tests back to green. No runtime behaviour changes beyond naming the peak store's encoding. ## What was failing on main (`59ab069b5`) - `test_text_io_names_its_encoding[diffusion_measured_peaks.py]` and `test_shipping_code_names_an_encoding`: the learned-peak store reads with `read_text()` and writes through `os.fdopen(fd, "w")` without an encoding, so the locale decides it (cp1252 on Windows, ASCII under a C locale). - `test_calibration_records_and_reuses_for_any_family`, `test_retagged_peak_is_recorded_under_the_mode_that_ran`: `record_request_peak` now records a keyed peak only when `stream_window_pad_mib(pipe)` can size the placement ("an unknown placement enters neither the keyed table nor the store"). The tests' fake pipe has no placement, so nothing was recorded and `measured_extra_mib` returned `None`. - `test_oom_inside_the_first_offload_apply_unwinds_its_hooks` imports `diffusers.hooks` directly, and the Backend CI runners have no diffusers, so it errors with `ModuleNotFoundError` there instead of skipping. - `test_diffusion_capability_labeled_image_video_gen` (`tests/studio/test_model_picker_contracts.py`) still expects "Image/video gen" in all three Hub files. #13749 split the Hub filter into "Image gen" and "Video gen" and only rewrote the comments that held the old label in the other two. - `test_every_tracked_python_file_is_already_formatted` and `test_checked_in_file_reads_name_an_encoding`: `tests/test_triton_fp_fusion.py` (#13828) is not a fixed point of `scripts/run_ruff_format.py` and reads four kernel sources with `read_text()` and no encoding. - `test_calibration_revision_includes_the_companion_base`: `_calibration_revision` now uses `_peak_model_identity`, which keys on `source@revision` plus `+base@base_revision` for a GGUF or single-file load, not the old bare fingerprint and `|base=` suffix. ## Fix - `diffusion_measured_peaks.py`: `encoding = "utf-8"` on the read and on the write. `json.dump` writes ASCII by default, so existing peak files read the same. - The two peak tests run under a known on-card placement (`stream_window_pad_mib` patched to 0), the case #13724 still records. - The OOM test uses `pytest.importorskip("diffusers.hooks")`, the same guard the rest of the file uses for optional dependencies. It still runs where diffusers is installed. - The label test still checks that no Hub file says "Image to text". It now asserts the filter label `{ value: "diffusion", label: "Image/video gen" }` in `model-type-filter.ts` and the split `Image gen` / `Video gen` options in `view-models.ts`. - `tests/test_triton_fp_fusion.py`: `encoding = "utf-8"` on its four reads, then `python scripts/run_ruff_format.py` on it. - The revision test asserts the new identity format. It still checks the same three things: no base for a pipeline load, the base for a GGUF load, and a different base giving a different key. ## Tests With no GPU visible (as on the CI runners), `test_diffusion_component_sizes.py`, `test_text_io_encoding.py` and `test_diffusion_learned_peaks.py`: 4 failed on main, 984 passed and 0 failed here (with current main merged in). `tests/test_runtime_text_encoding.py`: 9 passed. `tests/studio/test_model_picker_contracts.py`: 201 passed. `tests/test_triton_fp_fusion.py`, `tests/test_formatter_fixed_point.py`, `tests/test_source_read_encoding.py`, `tests/test_runtime_text_encoding.py`: 43 passed, 2 skipped. The OOM test skips cleanly when diffusers is not importable, and passes where it is.
…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.
Problem
Triton main (3.9 dev) flips the default of
enable_fp_fusionto False (third_party/nvidia/backend/compiler.py,knobs.pyTRITON_DEFAULT_FP_FUSION); Triton 3.8 and older default to True. Every Unsloth kernel except the deliberate NF4 dequantFalsepath relies on that default, so once 3.9 ships they would silently stop contractinga * b + cinto FMA: slower, and RoPE, RoPE-QK and the GeGLU approx backward change bits (checked on Triton 3.8 by forcing the default to 0).Change
Every Triton launch in
unsloth/kernelsnow passesenable_fp_fusion = Trueexplicitly, through each launch route:kernel[grid](...): cross entropy (3), fp8 (4), GeGLU (4), SwiGLU (2), LayerNorm (2), NVFP4 dequant, int4 repack.wrap(kernel)[grid](...)used eagerly and undertorch.library.triton_op/wrap_triton: RMSNorm (5), RoPE (2).triton_launch.launch(the flag is part of its cache key): NF4 dequant and the NF4 GEMV.kernel.warmup(...)for the int4 fast launch, and the autotuned MoE grouped GEMM forward / dX / dW (the autotuner passes it to every config).NF4 dequant keeps its deliberate
enable_fp_fusion = Falseeager path; its options now always carry the flag in both directions. No global knob or monkey patch, andTRITON_FORCE_DISABLE_FP_FUSIONstill wins (Triton applies it after explicit options).Compatibility
enable_fp_fusionis a CUDA and HIP compile option on Triton 3.1, 3.2, 3.3, 3.8 and main, so no version gate.wrap_triton/triton_opaccept it on torch 2.6, 2.7.1, 2.10, 2.11, 2.12 and 2.14. torch 2.12 and older drop it inside Inductor, but they ship Triton 3.7 or older where the default is still True.v_fmawith True andv_mul+v_addwithout it.Tests
New
tests/test_triton_fp_fusion.py:unsloth/kernels.TRITON_DEFAULT_FP_FUSION=0(Triton 3.9's default) and=1, an empty Triton cache, running representative kernels and reading each compiled kernel'smetadata.enable_fp_fusion; NF4 dequant must keep a False eager entry and a True traced entry; on CUDA,fma.rnmust be in the PTX of RoPE, GeGLU and SwiGLU.Results:
On Triton 3.8 the outputs of RMSNorm, RoPE, RoPE-QK, cross entropy (plain and chunked), SwiGLU, GeGLU, NF4 dequant (eager and traced), the NF4 GEMV and the fp8 GEMV are byte-identical to main, and stay identical with the default forced to 0. The existing kernel suites (37 files,
-o addopts="") pass the same tests as main on torch 2.14 and 2.7.1.