Repository navigation
Studio diffusion: keep fp8 single-file weights stored in fp8 where widening would offload or crowd host RAM - #14549
Conversation
…fp8 GEMM runs A ComfyUI fp8_scaled or plain fp8 diffusion checkpoint loaded where no fp8 GEMM runtime applies (GPUs below sm_89, fp16 / fp32 pipelines, e5m2 codes, offloaded plans, UNSLOTH_DIFFUSION_COMFY_FP8=0) was dequantized to the compute dtype at load, doubling host RAM and VRAM (Krea 2: 13 GB file, 24 GB transformer). Those fp8 Linears now stay stored as fp8 codes plus their per-row scale on the existing torchao-free NativeWeightOnlyLinear and widen per layer inside the forward, as ComfyUI's manual_cast does. The widen is the load-time dequant formula, so outputs are bit-identical. Compiled forwards decode the codes with integer ops (Triton has no e4m3fn convert below sm_89). Offloaded renders of such a pipe run under no_grad so the keep-host offload can track the buffers. A generation-time LoRA is refused with the reload hint, as for the nvfp4 / mxfp8 runtime layers; a LoRA selected at load keeps the dense path. MPS and H3 keep today's behaviour. UNSLOTH_DIFFUSION_FP8_STORAGE=0 restores the dequant.
…d host RAM Per-layer widening costs eager steps (Krea 2 on B200: 0.24-0.27 s/step stored vs 0.15-0.18 widened; compiled is at parity). The planner now prices the single file both ways and keeps fp8 stored only where the widened plan would not keep the denoiser resident, or the widened weights would leave under 4 GB of host RAM; that plan is then re-priced at the stored size, so a load that had to stream the transformer can stay resident (Krea 2 on 24-32 GB cards). Video loads store under an offloaded plan. UNSLOTH_DIFFUSION_FP8_STORAGE=1 stores on every load that can, 0 never.
The host RAM check from #14510 now prices layers fp8 storage keeps at their stored bytes (memory-mapped codes plus fp32 row scales) instead of the widened size, using one header rule (fp8_stored_by_header) shared with the planner's resident size, and the stored path charges the row scales it allocates. A file that fits only stored loads with storage and is refused with UNSLOTH_DIFFUSION_FP8_STORAGE=0.
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. |
[skip ci]
header_has_fp8_weights now recognises F8_E4M3FNUZ / F8_E5M2FNUZ, so the planner and the residency arbiter price them at the widened size the loader builds. fp8 storage keeps only the OCP codes, so the Krea 2 stored estimate keeps the upcast for a file with FNUZ weights and records no storage pick for it.
…loaded fp8 backend The resident estimate probed the int8 / fp8 backends with offload=False, so with torchao fp8 resident but a plan that offloads (balanced on NVIDIA) the fp8 layers were priced at their stored size while the loader, probing with offload=True, loses torchao and widens them. An offloaded plan now re-prices the DiT with the offloaded backends, picks fp8 storage when that is smaller, and otherwise plans at the widened size.
An offloaded plan re-prices the DiT with the offloaded backends (fp8 storage, the int8 twin), but only a larger price re-planned. A smaller one now re-plans too, and the load keeps the backends it was priced with even when the new plan fits resident, so a checkpoint that fits stored is no longer left offloaded. MiniMax H3 keeps its resident torchao path.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5d45aa7e04
ℹ️ 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".
| return ( | ||
| fmt in FP8_FORMATS | ||
| and len(shape or ()) == 2 | ||
| and not any(m in str(name).split(".") for m in (keep_fp32 or ())) |
There was a problem hiding this comment.
Exclude rotated FP8 layers from stored-size pricing
For a valid ComfyUI FP8 layer declared with convrot=true, this predicate reports that the layer can remain stored because it does not consider ComfyQuantLayer.group; consequently comfy_resident_mib(..., fp8_stored=True) prices its weight at one byte per element. The loader explicitly rejects such a layer from the storage path with and not group and instead dequantizes and reverses the rotation into the compute dtype, so an offloaded or forced-storage checkpoint can be planned at roughly half its actual footprint and then fail placement or exhaust memory. Include the rotation group in this shared eligibility rule so pricing matches the loader.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A ComfyUI fp8 layer declared with convrot is not a valid input here: scan_comfy_quant refuses ConvRot on any format other than int8_tensorwise ("ConvRot on float8_e4m3fn"), so the layer never enters scan.layers and refuse_comfy_quant raises before the estimate, the planner or the loader runs. Every fp8 layer that is priced therefore has group == 0, and the loader's and not group can never exclude one. I checked with a convrot fp8 fixture, which is refused at scan time. No change.
…host RAM A resident ComfyUI fp8 video DiT never reached the host RAM rule the image path uses, so a checkpoint that fits host RAM only stored was refused by the load-time budget. Pass the planned DiT price and the available host memory into the video fp8 storage decision. [skip ci]
…d price let the plan fit resident
…ze estimate [skip ci]
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
[skip ci]
…without diffusers runs them
|
@codex review |
1 similar comment
|
@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". |
…nstead of dense (#14631) ## Summary Follow-up to #14549. A denoiser whose single-file fp8 weights stay stored in fp8 was identified by the memory planner as a plain dense denoiser, so it borrowed the dense placement data instead of its own. The stored-fp8 Linear (`NativeWeightOnlyLinear`, fp8 scheme) keeps its codes and per-row scales as buffers (`weight_q`, `weight_scale`). The two planner helpers that decide the denoiser's format only looked at parameters: - `denoiser_quant_label` saw the float biases and norms and returned `dense:float16` / `dense:bfloat16`. - `_pipe_denoisers_hold_packed` returned False. Consequences: 1. `refine_plan_from_loaded_weights` used the fp16 dense eager table as a static seed (`measured_static_seed=True`, 3072 MiB reserve on FLUX.2-klein) for a build that table never measured. The stored layer widens each Linear per call (fp32 codes, fp32 scaled, then the compute dtype: about 160 MiB for a 4096x4096 Linear against 32 MiB of resident bf16 weight). 2. A stored-fp8 load and a widened load of the same file shared one learned-peak key, so the two builds read and wrote each other's measured peaks. ## Changes `studio/backend/core/inference/diffusion_memory.py`: - New `_holds_fp8_stored(module)`, reading the `_unsloth_fp8_stored` count both load paths already set (`diffusion_single_file_converters.py`, `diffusion_comfy_quant.py`). - `_pipe_denoisers_hold_packed` returns True for a stored-fp8 denoiser (any of `transformer`, `transformer_2`, `unconditional_transformer`, `unet`). Refinement then places it the way GGUF and int8 packed denoisers are placed: from a learned peak recorded for its exact build, which includes the per-layer widen. With no learned peak yet, the flat plan stands. - `denoiser_quant_label` returns `fp8_stored:<float dtypes>#<variant digest>` for it. The digest is the existing `graph_variant` tag, which already reads the `weight_q` buffers, so E4M3 and E5M2 codes get different keys. Labels for dense, torchao, GGUF and `packed:int8` denoisers are unchanged, so learned peaks already recorded for them still match. Weight byte accounting (`_loaded_component_mib`), offload sizing and the compile-cache graph variant already count buffers and need no change. No change to the learned-peak store's runtime stamp. Peaks a stored-fp8 run wrote under the dense key before this fix can only be higher than the dense build's own peak, and learned peaks only ever raise a reservation. So the leftover entries make dense placement more cautious, never less safe. Bumping the store version would throw away every recorded peak on every host. ## Tests New `studio/backend/tests/test_diffusion_fp8_stored_label.py` (CPU only, built from the real stored-fp8 layer class): - label: `fp8_stored:` for bf16 and fp16, distinct from the dense label of the same model, E4M3 vs E5M2 distinct, two-expert pipes - the learned-peak key does not collide with the dense build's key - the packed detector sees the stored layers - refinement: no dense static seed; a dense learned peak is not read; its own learned peak places it (`measured_static_seed=False`) - controls: the dense, GGUF and `packed:int8` labels are unchanged, and an fp16 dense load still takes the 3072 MiB static seed
… fp8-storage reserve (unslothai#14758) ## Problem unslothai#14510 refuses a single-file diffusion load that would exhaust host RAM, keeping a reserve of max(3 GB, 10% of RAM) free (`host_reserve_mib`). unslothai#14549 decides whether to keep fp8 weights stored as fp8 or widen them, and it widens whenever the widened load fits with 4 GB free (`FP8_STORAGE_HOST_RESERVE_MIB`). On hosts with more than 40 GB the refusal reserve is the bigger of the two. That leaves a band where the fp8 rule picks the widened load because it fits, and then the refusal rejects that same load. Example: a 64 GB host loading Krea 2 (about 24 GB widened) with 28 to 30.4 GB free. This loaded before unslothai#14510 and is refused on main, even though fp8 storage or the widened load would both fit. ## Change - `diffusion_small_host.py`: `FP8_STORAGE_HOST_RESERVE_MIB` (4096) now lives here, next to a new `single_file_host_reserve_mib(total)` = `min(host_reserve_mib(total), FP8_STORAGE_HOST_RESERVE_MIB)`. - `diffusion_comfy_quant.py`: imports that constant instead of defining its own, so `fp8_storage_wanted` and the refusal read the same value. - `diffusion_single_file_converters.py`: `HostRamBudget` (both the header check and the live per-allocation charge) uses `single_file_host_reserve_mib`. With this, any load the fp8 rule widens passes the refusal. Loads that do not fit even at their cheapest size (fp8-stored where the rule stores it, widened otherwise) are still refused before any read. Hosts up to 40 GB keep exactly the same reserve as before. The small-host route (`decide_small_host`) still uses `host_reserve_mib` and is unchanged. ## Tests New tests in `studio/backend/tests/test_diffusion_single_file_host_ram.py`: - `test_big_host_loads_what_the_fp8_storage_rule_widens[28.5|29.0|30.0|30.3]`: 64 GB host, 24 GB widened. Checks that the fp8 rule widens and the refusal does not fire. Fails on main (refused), passes here. - `test_reserves_cannot_drift`: the refusal reserve is never above the fp8 reserve, and both modules expose the same constant. Fails on main, passes here. - `test_big_host_still_refuses_a_load_that_cannot_fit`: 24 GB widened with 20 GB free is refused. 12 GB stored fits at 20 GB free but is refused at 15 GB free. Passes on both. - `test_small_host_reserve_unchanged[8|16|24|31]`: the reserve is still max(3 GB, 10%) and the refusal boundary sits exactly there. Passes on both. I also ran the 25 related backend test files (small host, comfy quant, comfy block, single-file host RAM, video comfy quant, and others) with `python -m pytest -q -p no:cacheprovider`: 1551 passed, 21 skipped, 1 failed. The one failure, `test_diffusion_component_sizes.py::test_cached_image_families_headers_match_tables`, fails the same way on main. ## Not covered - No real 64 GB host load. The band is checked with spoofed RAM readings and sizes only. - The planner reads available RAM when it makes the fp8 decision, and the loader reads it again later. If free memory drops in between, a load can still be refused. That race was there before this change and this PR does not touch it. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…without MSVC (#17073) ## Summary When a cross-platform run selects `studio/backend/tests/test_diffusion_native_quant.py`, the Windows leg fails both cases of one test. #17068 is a current example: ``` FAILED test_diffusion_native_quant.py::test_fp8_codes_layer_matches_the_dequant_formula_eager_and_compiled[float8_e4m3fn] FAILED test_diffusion_native_quant.py::test_fp8_codes_layer_matches_the_dequant_formula_eager_and_compiled[float8_e5m2] E torch._inductor.exc.InductorError: InvalidCxxCompiler: Compiler: cl is not found. ``` The test is on main (from #14549). Its last step runs `torch.compile(layer, fullgraph = True)` on CPU. Inductor's CPU backend compiles C++ with MSVC on Windows, and the `windows-latest` runner does not put `cl` on PATH. The failure is the runner's missing compiler, not the layer. Every check before that step is platform-independent and passes on Windows: the eager forward against the dequant formula, the weight equality and the zero graph-break check. ## Change `studio/backend/tests/test_diffusion_native_quant.py`, test only: on Windows with no `cl` on PATH, the test skips just before the compiled half, after the eager and graph-break checks have run. The skip reason says why. On Linux, on macOS, and on Windows with MSVC available, the test runs exactly as before. ## Testing | | result | |---|---| | the test on Linux, this branch | 2 passed | | the Windows leg of this PR's cross-platform run | the check for the change |
Summary
A ComfyUI fp8_scaled or plain fp8 diffusion single file loaded where no fp8 GEMM runtime applies (GPUs below sm_89 such as Ampere and T4, fp16 / fp32 pipelines, e5m2 codes, offloaded plans,
UNSLOTH_DIFFUSION_COMFY_FP8=0) is dequantized to the compute dtype at load. That doubles host RAM and VRAM: the Krea 2 Turbo transformer goes from a 13.8 GB file to 23.9 GiB resident.ComfyUI keeps such weights stored as fp8 and widens them one layer at a time at forward time (
cast_bias_weight/QuantizedTensor.dequantize). This PR does the same through machinery Studio already has, the torchao-freeNativeWeightOnlyLinear(scheme fp8). It does not add a parallel path.load_comfy_quant_transformerandload_original_layout_transformer(Krea 2 / HunyuanImage plain fp8) can keep an fp8 Linear as its codes plus a per-row fp32 scale (unit scale for plain fp8). The forward rebuilds(codes.float() * scale).to(dtype), which is the formula the load-time dequant uses, so outputs are bit-identical.NativeWeightOnlyLinearnow also accepts e5m2 codes. The compile cache keys stored e5m2 layers apart from e4m3fn ones (e4m3fn keys are unchanged). Undertorch.compileit decodes the codes with integer ops plus a bitcast, which match the cast bit for bit on all 256 codes. Triton has no e4m3fn convert below sm_89, and this keeps the decode fused into the compiled region on every arch.no_grad. Underinference_mode, the keep-host offload could not track the moved buffers, so every offload copied 12 GB back to new host memory.When it engages (default rule)
The per-layer widen slows eager steps. Compiled steps are at parity. So storage is the default only where the widened load would be worse:
_keep_in_fp32_modulesare never stored and are priced widened (fp32 on an fp16 load);F8_E4M3FNUZ/F8_E5M2FNUZ) are priced widened and never stored, since every loader widens them;UNSLOTH_DIFFUSION_FP8_STORAGE=1stores on every load that can;0never stores (today's behaviour).Planner output for the Krea 2 fp8 file on simulated cards (header-only probe):
Interaction with the single-file host RAM check (#14510)
The up-front header estimate from #14510 now prices the layers fp8 storage keeps at their stored bytes: the codes stay memory-mapped, plus the fp32 row scales. It no longer prices them at the widened size. A load that fits only because of storage is therefore not refused.
fp8_stored_by_header, a 2-D float8 weight outside the fp32-kept modules).charge_host_ram.UNSLOTH_DIFFUSION_FP8_STORAGE=0the same file is priced widened and refused when free RAM is below that need.Measurements
Krea 2 Turbo fp8_scaled single file, built from the bf16 shards (256 block Linears, per-tensor scale). B200 with the fp8 GEMM disabled (
UNSLOTH_DIFFUSION_COMFY_FP8=0) to force the no-runtime path. 1024x1024 images. s/step = (t(12 steps) - t(4 steps)) / 8, 3 prompts per arm. Timing comes from one exclusive card with every arm run twice. The A/A arm is head withUNSLOTH_DIFFUSION_FP8_STORAGE=0.With model offload, the stored load pins 13.0 GiB of transformer host weights instead of 25.0 GiB. VRAM peak drops from 24.6 to 13.6 GiB and RssAnon from 25.9 to 2.6 GiB. Wall time per 12-step image goes from about 3.0 s to 3.6 s.
The compiled path has 1 graph, 1 CUDA graph capture, 0 recaptures and 0 graph breaks on prompts 2+, the same as base.
Parity
Tests
New CPU tests fail on main and pass here:
fullgraphwith no graph break;UNSLOTH_DIFFUSION_FP8_STORAGE=0. The same holds for a resident ComfyUI fp8 video DiT.Results on the related suites (41 files: every planner / loader / host RAM test file plus comfy quant / block, native quant, Krea 2, LoRA, offload, memory, CUDA graph, backend), current main vs this branch: 5926 passed vs 5949 passed, nothing fails on either side.
Not covered
from_single_fileare still widened by diffusers.