Repository navigation
Studio: run Ada FP8 precise accumulate through a unit-scale GEMM plus a fused scale epilogue - #13793
Conversation
On Ada, torch._scaled_mm with row-wise scales runs a CUTLASS 2.x stream-K kernel while the per-tensor form runs cuBLASLt. Route torchao's per-row Float8Tensor GEMM through the unit-scale form and apply the same row / column scales (and bias) in fp32 afterwards, which Inductor fuses into the consumer. Engages only on sm_89, bf16 output, row-wise scales, >= 1024 rows. UNSLOTH_DIFFUSION_FP8_UNIT_SCALE=0 disables it.
L4 end to end: fast accumulate (the default) shows no gain from the unit-scale form (klein 0.501 vs 0.499 s/step, Z-Image 0.799 vs 0.795, inside the A/A spread), while precise accumulate goes 1.074 -> 0.515 (klein) and 1.721 -> 0.853 (Z-Image). Leave fast-accumulate calls on torchao's kernel so the default stays bit-identical; drop the row floor to 1 for precise calls.
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. |
|
The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e5981592c3
ℹ️ 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".
| from .diffusion_fp8_unit_scale import install as _install_fp8_unit_scale | ||
| _install_fp8_unit_scale() |
There was a problem hiding this comment.
Install the patch for every prequantized FP8 load
When an FP8 checkpoint uses the supported pickle container, _load_prequant_checkpoint() calls _torch_load_prequant() directly, so _torchao_api() never runs and this installer is skipped; the same happens for safetensors when UNSLOTH_PREQUANT_NATIVE_REBUILD=0. On sm_89 with precise accumulation, those prequantized models therefore retain the slow row-wise GEMM and miss the optimization entirely. Invoke the installer from the common prequant load path after torchao is loaded rather than only from the native decoder.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in cbbe33e. The install now runs from _load_prequant_checkpoint, the common path for both containers, after the checkpoint is read, so the pickle container and safetensors with UNSLOTH_PREQUANT_NATIVE_REBUILD=0 get the sm_89 dispatch too. The call in prequant_native._torchao_api is removed, since every native decode goes through the same loader. install() is idempotent and returns early off sm_89, so non-FP8 and non-Ada loads are unaffected. Covered by test_every_prequant_container_installs_the_dispatch (pickle and safetensors).
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cbbe33e771
ℹ️ 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".
| and a_data.shape[0] >= min_rows | ||
| and (force or not use_fast_accum) | ||
| ): | ||
| _COUNTS["unit_scale"] += 1 |
There was a problem hiding this comment.
Skip mutable counters while compiling
On sm_89, quantized denoisers are run through torch.compile, so mutating _COUNTS inside this traced wrapper makes Dynamo guard on a changing module global and recompile the block on every call; the fallback counter at line 129 has the same problem. This can exhaust the recompile limit or drop the required quantized path to eager execution, negating the optimization. The existing compiled wrapper in studio/backend/core/inference/video_wan_fused.py:523-526 explicitly avoids counters while torch.compiler.is_compiling() for this reason, so these increments should likewise be eager-only.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a763e74. Both counters now increment only when torch.compiler.is_compiling() is false, the same pattern video_wan_fused uses, so a traced block never mutates or guards on the module-global dict. stats() therefore counts eager calls only. Covered by test_counters_stay_untouched_while_compiling.
| UNIT_SCALE_ENV = "UNSLOTH_DIFFUSION_FP8_UNIT_SCALE" | ||
| MIN_ROWS_ENV = "UNSLOTH_DIFFUSION_FP8_UNIT_SCALE_MIN_ROWS" |
There was a problem hiding this comment.
Fingerprint the unit-scale graph switches
When an operator changes either of these environment variables between runs, the traced FP8 graph changes between the stock row-wise GEMM and this unit-scale epilogue, but neither variable is included in diffusion_compile_cache.py's _GRAPH_SWITCHES. Consequently, a pre-warmed compile bundle can be reported as a hit even though it contains no artifacts for the selected graph, forcing the expensive compilation again and leaving the stale bundle unreplaced. Add both the enable/disable switch and the value-carrying row threshold to the compile-cache fingerprint.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a763e74. UNSLOTH_DIFFUSION_FP8_UNIT_SCALE (default auto, so 0 and 1 both key) and UNSLOTH_DIFFUSION_FP8_UNIT_SCALE_MIN_ROWS (raw value, 256 being the default) are now in _GRAPH_SWITCHES, so a bundle compiled with the other graph is a miss instead of a false hit. Covered by test_unit_scale_switches_key_the_compile_cache.
| out_dtype = torch.bfloat16, | ||
| use_fast_accum = use_fast_accum, | ||
| ) | ||
| out = acc.float() * a_scale.float() * b_scale.float() |
There was a problem hiding this comment.
Unwrap legacy scaled_mm results
On a supported Studio environment that retains torch 2.4 with its matching torchao, torch._scaled_mm returns (output, amax) rather than a tensor, so the first qualifying precise-accumulation call fails at acc.float() even though the 32-row smoke probe never exercises this branch. The repository's _unit_scaled_mm helper in studio/backend/core/training/diffusion_frozen_fp8.py:40-41 explicitly unwraps this tuple for torch versions below 2.5; this wrapper needs the same compatibility handling before applying the epilogue.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a763e74. The unit-scale branch now unwraps a tuple result from torch._scaled_mm (torch older than 2.5 returns (out, amax)) before the epilogue, matching _unit_scaled_mm in diffusion_frozen_fp8. Covered by test_legacy_scaled_mm_tuple_is_unwrapped.
…egacy scaled_mm tuple
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a763e74062
ℹ️ 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".
| "UNSLOTH_TORCHAO_INDUCTOR_CONFIG": "off", | ||
| "UNSLOTH_NVFP4_BACKEND": "raw:auto", | ||
| "UNSLOTH_DIFFUSION_FP8_UNIT_SCALE": "auto", | ||
| "UNSLOTH_DIFFUSION_FP8_UNIT_SCALE_MIN_ROWS": "raw:256", |
There was a problem hiding this comment.
Keep zero row thresholds in the cache fingerprint
When UNSLOTH_DIFFUSION_FP8_UNIT_SCALE_MIN_ROWS=0, _min_rows() accepts it and clamps the effective threshold to 1, but the generic raw: handling in _switch_value() treats "0" as an off word and omits it from the fingerprint. That makes this graph variant collide with the default 256-row variant, so an existing compile bundle can be reported as a hit even though calls with 1–255 rows now trace through a different GEMM path. Preserve zero in the key (or normalize it to the effective value 1) for this numeric switch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5f916ce. The row threshold now has its own key kind in _GRAPH_SWITCHES: it is keyed on the value _min_rows() actually uses, max(1, int(value)), so 0 keys as 1 and no longer collides with the 256 default, while junk (which _min_rows() treats as the default) adds no key. Covered by the extended test_unit_scale_switches_key_the_compile_cache, which checks the key against _min_rows() for 0, 1 and junk.
| ckpt = load_prequant_safetensors(path, mmap = bool(kwargs.get("mmap"))) | ||
| else: | ||
| ckpt = _torch_load_prequant(path, **kwargs) | ||
| _install_fp8_unit_scale() |
There was a problem hiding this comment.
Install the dispatcher for ComfyUI FP8 prequant loads
When the resolved checkpoint is a ComfyUI-format FP8 file, load_prequantized_transformer() takes the comfy_scan is not None branch and calls load_comfy_prequant() before ever reaching _read_prequant_for(), while diffusion_comfy_quant.py:1219 constructs the same torchao Float8Tensor weights directly. Consequently this newly added hook is never called for that supported prequant path, and an Ada run with transformer_quant_fast_accum: false retains the slow row-wise GEMM. Invoke the installer from a path shared by the ComfyUI branch as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5f916ce. The ComfyUI branch of load_prequantized_transformer now calls _install_fp8_unit_scale() right after load_comfy_prequant, since those files never go through _load_prequant_checkpoint. Covered by test_comfy_prequant_load_installs_the_dispatch.
…install for ComfyUI fp8 loads
|
@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". |
…itch key check test_graph_switches_key_apart_only_off_their_default indexed its flip table by the switch default and raised KeyError on the new rows:256 kind of UNSLOTH_DIFFUSION_FP8_UNIT_SCALE_MIN_ROWS. Rows switches now check that the default value and junk keep the key and that 1 moves it.
…on the first check The epilogue upcast the bf16 accumulator into its own fp32 buffer and then built two more. bf16 * fp32 already promotes, so the first multiply makes the only fp32 buffer and the rest run in place: bitwise the same result, Inductor fuses either form, and an eager run (no Triton, or a family that does not compile) saves a [M, N] fp32 buffer and a pass. Measured on L4, torch 2.11, eager klein mlp_in 18.74 -> 16.03 ms, qkv 10.19 -> 8.79 ms. The accumulate-mode check moves first, so the default fast accumulate falls through to torchao after one comparison.
torch's FX graph and AOTAutograd caches key on the Dynamo graph, which reads F.linear on a Float8Tensor whether or not the dispatcher is installed. A row-wise graph cached by an earlier run (before this change, or with UNSLOTH_DIFFUSION_FP8_UNIT_SCALE=0) was therefore reloaded after install, so the compiled path kept the slow row-wise GEMM, and the kill switch kept the unit-scale one after a run that had it. Measured on B200 with a shared TORCHINDUCTOR_CACHE_DIR: the installed run's generated code called the row-wise _scaled_mm. install() now adds an unsloth_fp8_unit_scale=<min rows>[:force] segment to torch.compiler.config.cache_key_tag (other segments kept) and uninstall() removes it. New tests: the tag round trip on CPU, and on an sm_89+ GPU a base process then an installed process sharing one inductor cache, checking the installed process's generated code feeds unit scales (fails without the tag).
…s set torch keys every FX graph / AOTAutograd artifact on torch.compiler.config.cache_key_tag, which the fp8 unit-scale dispatcher now sets while installed. A Studio bundle saved without it (an Ada fp8 precise run before this change) would still be a manifest hit, miss inside torch, recompile on every load and never be rewritten. The environment fingerprint now carries the tag when it is non-empty, so untagged processes keep their existing keys and bundles. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
… in the CFG routers, and test fixes (#14420) ## Summary Follow-up fixes for the recently merged Studio diffusion work: two runtime fixes (the VAE OOM ladder under a multi-GPU component split, and bitwise comparison of expanded timesteps in the CFG routers) and five test fixes. Each change is its own commit. ### 1. VAE OOM step (a) frees only what sits on the VAE's card (#13802 with #13725) **What was broken.** Under a component split the VAE decodes on a secondary card while the denoiser stays resident on the primary. When that decode ran out of memory, `DecodeSession.free_others` reset the denoiser's CUDA graphs on the primary card and counted that as "released". The ladder then retried the same untiled decode on the secondary card, which ran out of memory again before it reached the tiled rung, and the denoiser lost its captured graphs for nothing. `_release_groups` had the same problem with resident offload groups on the primary card. A failed re-pin was also deferred against the VAE's card instead of the groups' own card. **Fix.** Graph handles are filtered to the VAE's card, using the card the graph was recorded on (or its module's card when nothing has been recorded yet). Resident-group modules are filtered by `_unsloth_resident_device`. This is the same filtering `_hook_torchao_resident` and `_move_components` already do with `_placement(comp, self.device)`. `release_resident_groups` takes an optional `device` filter. It is only passed when the pipeline has resident groups on more than one card, so single-card calls are unchanged. Anything whose card cannot be read is still freed, as before. **Tests** (`test_diffusion_vae_oom.py`, all fail on main): - `test_split_vae_oom_leaves_the_other_cards_graphs_alone`: a decode on cuda:1 with graphs on cuda:0 goes straight from the untiled decode to the tiled one, and no graph is reset. - `test_split_vae_oom_still_drops_graphs_on_its_own_card`: only the cuda:1 handle is reset. - `test_split_vae_oom_releases_only_groups_on_its_own_card`: groups on cuda:0 are left alone and nothing is deferred against them. With groups on both cards, the release is limited to cuda:1. - `test_release_resident_groups_device_filter`: the new filter releases only the matching card's groups, and with no filter every card's groups are released. ### 2. Expanded scalars compare bitwise in the CFG routers (#13725, #13787) **What was broken.** `_bitwise_equal` in `diffusion_multigpu.py` flattens both tensors, calls `contiguous()` and views them as `uint8`. WanPipeline passes `timestep = t.expand(batch)`. For a one-element tensor `contiguous()` is a no-op whatever the stride, so the stride-0 timestep reached `view(torch.uint8)`, which raised, and the comparison returned False for two equal timesteps. #13787 CFG batching uses it through `_record_template`, `_matches` and the branch merge. On Wan it missed three times in a row and turned itself off. CFG-parallel's prediction check uses the same helper. **Fix.** A small `_as_bytes` helper takes a dense copy only when the flattened tensor still has a non-unit stride. `_bitwise_equal` and `_unchanged_since_launch` both use it. Bitwise semantics are unchanged: equal NaN bits match, and -0.0 and 0.0 do not. The CFG batcher's three call sites all go through `_bitwise_equal`, so they are covered by the same fix. **Tests** (both fail on main): - `test_bitwise_equal_on_an_expanded_scalar` (`test_diffusion_multigpu.py`): `torch.tensor(941).expand(1)` against a clone and a fresh expand, plus NaN, signed zero and `_unchanged_since_launch`. - `test_wan_expanded_timesteps_serve_the_second_branch` (`test_diffusion_cfg_batch.py`): a Wan-style loop that passes `t.expand(batch)` to each branch. It matches the two-call reference with 4 hits, 0 misses, and batching stays on. On main it gets 0 hits. ### 3. Seeded denoiser cancel test pins the text encoder (#13715) **What was broken.** On a CUDA host, an unset `text_encoder_quant` also plans the hosted FP8 Wan text encoder. The load then fetched two artifacts and `test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event` failed its exact single-fetch assertion. It passed only with the GPU hidden. **Fix.** The test passes `text_encoder_quant = "off"`, so it checks only what it is about: the denoiser fetch carries the load's cancel event. **Test.** Fails on main with a GPU visible and passes after. It passes both ways with the GPU hidden. ### 4. FLUX.2 FBCache test invalidates the child registry cache (#14401) **What was broken.** On diffusers 0.39 and 0.40, `enable_cache` does not drop the child-registry list that an earlier uncached render cached. `test_fbcache_on_flux2_skips_and_matches_the_full_pass` then failed with `ValueError: No context is set`. Production already calls `_invalidate_child_registry_cache` after `enable_cache` in `apply_step_cache`. Only the test helper skipped it. diffusers 0.41 invalidates the list itself. **Fix.** The test's `_render` helper calls `dc._invalidate_child_registry_cache(model)` after `enable_cache`. **Test.** With diffusers 0.39.0 the test failed before and the whole file passes after (7 passed). It also passes on the pinned diffusers. ### 5. Stream encode tests skip when diffusers cannot import the Wan VAE (#14405) **What was broken.** `pytest.importorskip("diffusers")` succeeds on the lazy top-level module. The next line, `from diffusers import AutoencoderKLWan`, can then raise `RuntimeError` (for example with a broken bitsandbytes), which aborted collection of the whole pytest run. **Fix.** Catch `ImportError` and `RuntimeError` on those imports and skip the module, as the other diffusion tests do. **Test.** In an environment with a broken bitsandbytes, collection errored before and the module is skipped after. In the Studio environment all 9 tests still run and pass. ### 6. Multi-GPU planner tests pin the host facts they read (#13725, #13793) **What was broken.** On a host with one GPU, 11 tests in `test_diffusion_multigpu.py` failed. `make_selection` drops ordinals at or above the real `torch.cuda.device_count()` and cards below the primary's capability, so `make_selection(0, [0, 1])` returned None on a one-card machine. An AMD Strix Halo CI runner (one integrated gfx1151) showed exactly these 11. `test_diffusion_fp8_unit_scale.py` gated on `get_device_capability() >= (8, 9)`, which passes on ROCm because ROCm reports the gfx version (gfx1151 gives (11, 5)), and torchao then refuses fp8 there. **Fix.** Tests only. The autouse fixture pins the card count and the capability check (tests that probe those filters still override them), and the fp8 GPU gate returns False on a HIP torch, matching Studio, which already declines torchao fp8 on ROCm. New test `test_two_discrete_rocm_cards_split_like_cuda`: with HIP set and two cards at capability (11, 0), the planner selects both and splits onto card 1, as on CUDA. **Tests.** Spoofed host (HIP + one integrated card, HIP + two discrete cards, one CUDA card without HIP): 11 failed before, 114 passed after on each. Normal CPU host: 133 passed, 1 skipped. ### 7. The ROCm APU pool discount applies only to HIP device snapshots (#14379) **What was broken.** `_rocm_linux_apu_os_room_outside_pool` (`diffusion_memory.py`) gave any unified-memory reading the smaller Linux ROCm APU reserve on a ROCm build, without checking the snapshot's device. On a ROCm host, a mocked Apple (`mps`) snapshot in `test_diffusion_unified_load_override.py` got that reserve, so two refusal tests failed. A real ROCm build never produces an `mps` reading, so the user impact is close to zero. **Fix.** The discount now requires a `cuda` device snapshot (`cuda` or `cuda:N`). `test_flux3_prompt_upsampler.py` also pins `torch.__version__` in the tests that stand in for a CUDA build (Studio reads `+rocm` there too) and pins the card count in its warm fixture, which read the real host. **Tests.** The new `mps` / `cpu` reserve test fails without the fix and passes with it. Prompt upsampler: 164 passed on a spoofed APU, two discrete ROCm cards, two CUDA cards and plain CPU. ## Tests Base is origin/main and head is this branch. Same host and same Studio venv (diffusers 0.41 dev, torch 2.13). Failing test IDs were compared, not counts. - CPU, GPU hidden: test_diffusion_vae_oom.py, test_diffusion_vae_oom_faults.py, test_diffusion_measured_placement.py, test_diffusion_offload_cuda_graph.py, test_diffusion_learned_peaks.py, test_diffusion_int8_gemm.py, test_video_stream_residency.py, test_diffusion_offload_prefetch.py, test_diffusion_small_host_prefetch.py, test_diffusion_fbcache_mixed_stream.py, test_video_stream_encode.py, test_diffusion_multigpu.py. Base: 3912 passed, 125 skipped, 0 failed. Head: 3916 passed (the 4 new tests), 125 skipped, 0 failed. No failing IDs on either side. - One GPU visible: test_video_prequant.py. Base: 1 failed (`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`), 85 passed. Head: 86 passed. - CPU, GPU hidden: test_diffusion_cfg_batch.py, test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py, test_video_multigpu_wiring.py. Base: 128 passed. Head: 130 passed (the 2 new tests). No failures on either side. - test_diffusion_fbcache_mixed_stream.py on diffusers 0.39.0: 1 failed before, 7 passed after. Wan2.1-T2V-1.3B end to end on a Kaggle T4 capped at 7.25 GiB (streamed offload, fp32, 480x320, 17 frames, 6 steps, guidance 5, seed 1234). Base and head ran on the two T4s of one kernel, each on its own CPU slice: | Run | s/step | CFG batch | |---|---|---| | base, CFG batching off | 5.96 | not armed | | base, auto | 8.55 | 0 hits, 3 misses (timestep 941 vs 941), then off | | head, CFG batching off | 5.58 | not armed | | head, auto | 5.55 | 2 hits, 0 misses, then off: measured no gain (batched pair 5.42 s vs plain pair 5.39 s) | - The 43% slowdown on base is gone. On this streamed T4 placement a batched pair is no faster than two plain calls, so the batcher's own timing gate turns it off, as designed. - The batching-off latents are identical on base and head (`829b889b587d13f6`), so the plain path is unchanged. The two batched steps are not bit-exact, as documented for CFG batching. ## Not verified - CFG-parallel on two real cards: test_diffusion_multigpu_cuda.py needs two CUDA cards in one process and was skipped. - No real two-GPU decode that runs out of memory. The split case is covered by CPU tests that use real `torch.device("cuda", N)` indices with fake graph handles and resident modules. - diffusers 0.40.0 was not run. Its source lacks the same invalidation as 0.39.0.
…t engages, chunked eager scaling (#14665) ## Summary Follow-up to #13793 (sm_89 precise-accumulate fp8 via a unit-scale `_scaled_mm` and an fp32 scale epilogue). It fixes four problems. 1. **Installed where it can never engage.** `install()` ran from `_make_quant_config` for every fp8 config, and from `_load_prequant_checkpoint` for every prequant checkpoint, int8 and nvfp4 included. On any Ada host it installed in auto mode even under Studio's default fast accumulate, where the dispatcher never engages. Installing sets the process-wide `torch.compiler.config.cache_key_tag`, which `environment_fingerprint` also adds to the Studio bundle key. So after one fp8 or prequant load, every later compile in the process got a second cache key, a bf16 or GGUF model included. The cost was one extra cold compile per model and load order. It never caused a wrong hit. 2. **Inconsistent kill switch.** The compile-cache switch key reads `UNSLOTH_DIFFUSION_FP8_UNIT_SCALE=none` as off, but `_mode()` read it as auto and installed anyway. 3. **Eager peak memory.** The eager epilogue `acc * a_scale.float()` materialized a full fp32 `[M, N]` buffer and then a second bf16 output. That is four times the output size, with no memory admission check. 4. **Wrong error bound in the docs.** The module docstring stated a relative error of at most 2^-9. bf16 has 8 significand bits, so round-to-nearest unit roundoff is 2^-8. That bounds the absolute output error by 2^-8 of `|acc * a_scale * b_scale|`. A bias that cancels the product leaves the output's relative error unbounded: an exact dot product of 257 with scale 1/257 and bias -1 gives -0.0039 instead of 0. The PR #13793 description repeats the 2^-9 figure. ## Fix - `install(fast_accum=...)` and a new `can_engage()`: in auto mode it no longer installs for a load running fast accumulate. Precise and unknown accumulate still install, and so does `force`. - `_make_quant_config(fp8)` passes the resolved accumulate. - The ComfyUI prequant branch passes the load's resolved accumulate. - `_load_prequant_checkpoint` reads the checkpoint metadata. int8 checkpoints never install. fp8 baked at fast accumulate (the builder's default) does not install. Precise fp8, nvfp4 (a policy over fp8) and checkpoints with no recorded accumulate install, as before. - `_mode()` uses the same off and on words as the compile-cache switch key, so `none` is off in both. - Eager epilogue: the fp32 product is formed one row chunk at a time (about 16M elements, 64 MiB) and written back into the bf16 accumulator. The elementwise ops and their order are unchanged, so the output is bitwise the same. Under `torch.compile` the fused expression is kept as is. - The docstring now states the correct bound. Residual, by design: once a precise-accumulate fp8 model has installed the dispatcher, the tag stays for the rest of the process. That is required for the cache to stay consistent with the patched torchao entry point. ## Measured B200, force mode (`UNSLOTH_DIFFUSION_FP8_UNIT_SCALE=1`, so the dispatcher runs off sm_89), eager, precise accumulate, bias on. Values are peak allocation above the inputs. | shape (M x K x N) | torchao row-wise | main dispatcher | this branch | |---|---:|---:|---:| | 4608 x 3072 x 18432 | 162 MiB | 648 MiB | 226 MiB | | 4096 x 3072 x 3072 | 24 MiB | 96 MiB | 72 MiB | The output checksum is identical between main and this branch on both shapes. ## Tests `tests/test_diffusion_fp8_unit_scale.py`. Each new test fails on main and passes here: - `test_auto_never_installs_for_fast_accumulate` - `test_fp8_quant_config_installs_only_for_precise_accumulate` - `test_prequant_checkpoint_installs_only_when_its_fp8_layers_can_engage` (the int8 and fp8-fast cases; the precise, nvfp4 and unrecorded cases pass on both) - `test_every_off_word_of_the_compile_cache_key_turns_the_dispatcher_off` - `test_eager_epilogue_writes_into_the_accumulator_bitwise_as_before` (with and without bias): the output aliases the accumulator and is bitwise equal to the old fused expression. The whole file passes, including the GPU test `test_compiled_graph_after_a_cached_rowwise_one_uses_the_dispatcher`, so the compiled graph still takes the dispatcher.
Problem
On Ada (sm_89: L4, RTX 4090, RTX 6000 Ada), FP8 with precise accumulate (
transformer_quant_fast_accum: false) runs about 2x slower than fast accumulate._resolve_fast_accumalready records this: Z-Image-Turbo on an RTX 6000 Ada took 6.39 s precise vs about 3.1 s fast.The cost is not the tensor cores. torchao's per-row FP8 linear calls
torch._scaled_mmwith an [M, 1] activation scale and a [1, N] weight scale. On sm_89 PyTorch sends that row-wise form to a CUTLASS 2.x stream-K kernel, while the per-tensor form goes to cuBLASLt. At the FLUX.2-klein / Z-Image / Qwen-Image-2.1 1024 px linear shapes on an L4 (torch 2.14.1):Change
New
studio/backend/core/inference/diffusion_fp8_unit_scale.py, installed from the FP8 quant config and the prequantized FP8 loader.torch._scaled_mmwith unit scales into bf16. The same per-row and per-column scales (and bias) are then applied in fp32. Undertorch.compileInductor fuses that multiply into the consumer.use_fast_accum=False, bf16 output, row-wise scales, no output scale, and at least 256 activation rows (measured on L4: below that, either kernel takes a few tens of microseconds).UNSLOTH_DIFFUSION_FP8_UNIT_SCALE=0turns it off.=1forces it on any arch and both accumulate modes (testing only).UNSLOTH_DIFFUSION_FP8_UNIT_SCALE_MIN_ROWSoverrides the row floor.diffusion_fp8_unit_scale.stats(). Both switches are part of the compile-cache key.Results
Speed, Colab L4, FP8, precise accumulate, compiled default tier, 1024 px:
Precise accumulate now costs about the same as fast accumulate instead of 2.2x.
Quality, Colab L4, 16 prompts with paired seeds, LPIPS against a bf16 render of each prompt. The base is this PR's merge base, run in the same job:
UNSLOTH_DIFFUSION_FP8_UNIT_SCALE=0, Z-Image is byte-identical to main (3/3) and klein is at LPIPS 0.0000 against main (klein's compiled renders are not bit-repeatable on L4).Compile cache keying (added)
torch's FX graph and AOTAutograd caches key on the Dynamo graph. That graph reads
F.linearon a Float8Tensor whether or not the dispatcher is installed. So a row-wise graph cached by an earlier run (before this change, or withUNSLOTH_DIFFUSION_FP8_UNIT_SCALE=0) was reloaded after install. The compiled path then kept the slow row-wise GEMM, and the kill switch could keep the unit-scale one.unsloth_fp8_unit_scale=<min rows>[:force]totorch.compiler.config.cache_key_tag. Other tag segments are kept, anduninstall()removes it.cache_key_tagwhen it is non-empty. A bundle saved without the dispatcher is therefore a miss, not a hit that recompiles every time and is never rewritten. Untagged processes keep their existing keys.TORCHINDUCTOR_CACHE_DIR: the installed process's generated code called the row-wise_scaled_mm. With the tag it calls the unit-scale one. The new GPU testtest_compiled_graph_after_a_cached_rowwise_one_uses_the_dispatcherfails without the tag and passes with it.Eager epilogue (changed)
The epilogue is now
acc * a_scale(bf16 times fp32 promotes) followed by in-placemul_/add_. Before, it upcast into its own fp32 buffer and then built two more. The result is bitwise the same, and Inductor generates identical code for both forms. Eager runs (no Triton, or families that do not compile) save one fp32 [M, N] buffer and one pass. Colab L4, torch 2.14.1, eager, precise:Independent L4 check (compiled, precise, torch 2.14.1 + torchao 0.18, fresh compile per arm, median of 3 interleaved rounds)
Output against main: relative L2 difference 0.0028. Against the bf16 Linear, both arms are at 0.0368. No graph breaks, base or head.
Tests
tests/test_diffusion_fp8_unit_scale.py(CPU) covers:Not covered