Repository navigation
Studio: refuse a single-file diffusion load that would exhaust host RAM instead of crashing - #14510
Conversation
An fp8 or fp8_scaled ComfyUI Krea 2 file (13 GB) on a GPU with no fp8 runtime is widened to bf16 in host RAM (about 26 GB) before the denoiser is placed. With too little free memory the process was killed (Linux OOM killer, Windows commit limit), taking the whole app down instead of failing the load. Price the new host memory from the safetensors header (tensors already at the compute dtype stay memory-mapped and cost nothing) and refuse with a readable message before any widening, in both the original-layout loader and the ComfyUI-quantized loader. UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0 skips the check.
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. |
With an fp16 pipeline and _keep_in_fp32_modules the ComfyUI loader only postpones the dtype choice; with no fp8 runtime (never available off bf16) every quantized layer is still expanded. Price those layers as widened, and block formats under a key map, which are always dequantized.
An nvfp4 header describes packed uint8 with K / 2 columns, while the dequantization allocates the dense N x K weight, so the check counted half of it. nvfp4 is the only packed ComfyUI format the loader reads; int8, fp8 and mxfp8 store one code per element.
The header estimate could not see per-layer choices the loader makes later, so it kept drifting from what was really written: layers a runtime filter rejects are still dequantized, a kept nvfp4 weight gets a nibble-swapped copy plus untiled scales, and FNUZ float8 tensors were skipped entirely. A HostRamBudget now holds free RAM minus the small-host reserve for the whole load. The header estimate still refuses up front (it now prices FNUZ float8 too), and every allocating helper (dequant, dequant_block, the nibble swap, scale untiling, dtype casts, segment joins) charges the budget before it allocates, so the load is refused before the allocation that would not fit instead of running the host out of memory.
With UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0 (or host RAM unreadable) the budget could never refuse, but it was still installed and charged by every helper. Leave it inactive so the kill switch costs nothing. [skip ci]
The in-load check summed every allocation it was told about and never released any, so it over-counted copies freed again before the next layer (the nibble-swapped codes and untiled scales of an nvfp4 fallback load, a false refusal of a load that fits) and still missed copies made where nothing charged (the row reorder torch.cat of a key-mapped layer such as MiniMax-H3's fc1, the tiled scale buffer of a runtime Linear). Keep the header estimate as the first gate, then before each allocation refuse only if it plus the small-host reserve exceeds the host's live available memory (host_ram_mib, cgroup capped). Freed buffers come back in the next reading and unchecked copies show up in it. The key map join and tile_scales now check their own allocation too. The kill switch still installs no check, and the error text is unchanged. [skip ci]
Arm the in-load check by the widened estimate as well as the file size: a 900 MiB nvfp4 file widens to 3.6 GiB of bf16, so a small file is exempt only when its estimate is small too. Dequantize fallback nvfp4 / mxfp8 layers in bounded row chunks straight into the output and check the output plus one chunk of int32 / float32 intermediates before starting, instead of the output alone. Every op is per row, so the result is bit-identical to one pass. Check every full-size host copy the loaders make before it is made: row reorders of kept codes and their scales rebuilt by a stock converter, the joined codes and scales of a runtime block Linear, the HunyuanImage row join, and contiguous copies of non-contiguous kept codes.
…8 dequant peak A HostRamShortfallError raised during the narrow-tag conversion was caught by the retry handler and the conversion ran again at full float64 width, where a converter's joins allocate more before the next check. Re-raise it. That is the only broad except in the single-file loaders that wraps a host RAM check. int8 / fp8 dequantization holds float32 codes and their float32 product together, and ConvRot's batched matmul a float32 copy and result on top, so check 8 bytes per element (12 with ConvRot) before starting instead of the output size alone. [skip ci]
…timate, bound the nibble swap A load whose file and header estimate were both under the floor was never checked, even when a runtime filter then rejected layers the estimate assumed kept and dequantized them. Arm the check once the allocations it is asked about reach the floor; the check itself still reads live free memory. The up-front estimate priced every tensor in the header, while a bundled checkpoint read through keep_key loads only its DiT, so a float32 VAE or vocoder could refuse a DiT load that fits. Pass the same key filter in. swap_nibbles held the left shift, the right shift and their OR at once (three packed copies). Fill one output in bounded row chunks instead, checked for the output plus one chunk; bit-identical. [skip ci]
… allocate untile_scales with a block count that is not a multiple of 4 holds the permuted padded buffer and the trimmed copy at once; check both together. When the narrow-tag conversion fails for an ordinary reason, the full-width float64 retry can be materialized by the converter at 8 bytes per weight element before any checked helper runs; check that peak before retrying. [skip ci]
|
@codex review |
1 similar comment
|
@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". |
… again (#14544) `pre-commit.ci` is red on every PR opened or pushed since #14490 merged (#14510, #14515, #14543 so far), and it cannot push its autofix ("a conflict occurred when applying fixes to the pr"). #14490 landed `_run_single_flight(*args, _run = run, _lock = lock, **kwargs)` in `unsloth/kernels/moe/grouped_gemm/interface.py` on one line, which is not what `ruff-format-with-kwargs` produces, and pre-commit.ci runs the hook over all files. Running the hook over all 4525 tracked Python files on main changes only this one signature. This PR is that formatter output and nothing else. It is a fixed point: running the hook again leaves it unchanged. ## Testing - `tests/test_formatter_fixed_point.py` on main: fails, naming `unsloth/kernels/moe/grouped_gemm/interface.py`. - Same test on this branch: 16 passed.
…heck test (#14561) `test_block_dequant_is_checked_for_its_peak_intermediates[nvfp4]` (added in #14510) failed on #14558's Backend CI `(Python 3.13, a-k)` run (job 119452419222), on the same base where main's run passed it. #14558 only touches Laya files: ``` E AssertionError: ([50298880], 56627200) E assert ([50298880] and 50298880 >= (0.9 * 56627200)) ``` The test samples `RssAnon` while `dequant_block` runs and requires the host RAM charge to cover 90% of the growth. `RssAnon` is process-wide, so in a busy xdist worker anything else allocating at the same time is counted as the dequant's peak. Run alone, the charge is close to exact. Charge / growth over 12 local runs each: | format | min | max | |---|---|---| | nvfp4 | 0.963 | 1.038 | | mxfp8 | 0.990 | 1.078 | CI's 0.889 is about 6 MB of unrelated growth. The product's estimate is right; the measurement was noisy. ## Change The measurement runs three times, and the smallest growth is the one checked against the same 0.9 bar. Unrelated activity can only add to a reading, so the minimum is the closest to the dequant's own peak, and the guard keeps its strength. ## Testing - Three back-to-back runs of both parameters: pass. - Sabotage: charging only the bf16 output, without the chunk intermediates, in `diffusion_comfy_block.py` fails both formats (`[33554432] vs ~50 MB`).
…dening would offload or crowd host RAM (#14549) ## 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-free `NativeWeightOnlyLinear` (scheme fp8). It does not add a parallel path. - `load_comfy_quant_transformer` and `load_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. - `NativeWeightOnlyLinear` now also accepts e5m2 codes. The compile cache keys stored e5m2 layers apart from e4m3fn ones (e4m3fn keys are unchanged). Under `torch.compile` it 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. - Offloaded renders of a pipe with stored fp8 run under `no_grad`. Under `inference_mode`, the keep-host offload could not track the moved buffers, so every offload copied 12 GB back to new host memory. - A LoRA selected at load keeps the widened path. A LoRA added at generation time on a stored load is refused, with the reload hint, the same way as for the nvfp4 / mxfp8 runtime layers. MPS (no float8) and H3 (torchao-only residency path) keep today's behaviour. ### 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: - the planner prices the single file both ways, and stores fp8 when the widened plan would not keep the denoiser resident (offload or streaming), or when the widened weights would leave less than 4 GB of host RAM free; the plan is then re-priced at the stored size. An offloaded plan is priced with the backends an offloaded load keeps (torchao fp8 does not survive the offload hooks), so a resident fp8 runtime cannot hide the widened size. When that offloaded price is the smaller one (the int8 / fp8 twin only an offloaded load runs), the image load keeps those backends even if the re-made plan fits resident, as the video path does. Linears in the transformer's `_keep_in_fp32_modules` are never stored and are priced widened (fp32 on an fp16 load); - video loads store under an offloaded plan, and when the stored price is smaller the plan is re-made at it; a load that then fits resident keeps fp8 storage. A resident video DiT follows the same host RAM rule as an image single file: it stores fp8 when widening would leave less than 4 GB of host RAM free; - FNUZ float8 files (`F8_E4M3FNUZ` / `F8_E5M2FNUZ`) are priced widened and never stored, since every loader widens them; - `UNSLOTH_DIFFUSION_FP8_STORAGE=1` stores on every load that can; `0` never stores (today's behaviour). Planner output for the Krea 2 fp8 file on simulated cards (header-only probe): | free VRAM | before | after | |---|---|---| | 24 / 28 / 32 GiB | group offload, transformer streamed every step | fp8 stored, transformer resident (text encoders streamed once) | | 40 / 48 GiB | transformer resident | unchanged (widened) | | 16 GiB | streamed | streamed, half the bytes per step | ### 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. - The estimate and the planner's resident size use the same header rule (`fp8_stored_by_header`, a 2-D float8 weight outside the fp32-kept modules). - The stored path charges the row scales it allocates through `charge_host_ram`. - Any layer the loader still widens is charged live, as before. - With `UNSLOTH_DIFFUSION_FP8_STORAGE=0` the 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 with `UNSLOTH_DIFFUSION_FP8_STORAGE=0`. | arm | host RssAnon peak | transformer | VRAM peak | s/step eager | s/step compiled | |---|---|---|---|---|---| | widened (base) | 25.6 GiB | 23.9 GiB | 36.4 GiB (compiled 33.8) | 0.165, 0.184 (A/A 0.169) | 0.114, 0.127 | | fp8 stored | 2.3 GiB | 12.2 GiB | 24.8 GiB (compiled 22.1) | 0.240, 0.272 | 0.127, 0.128 | 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 - Eager, resident: bit-identical to the widened load on every image, for both the fp8_scaled and the plain fp8 file. - Model offload: bit-identical on every image. - Compiled: bit-identical in 7 of 9 fresh compiles. The other 2 differ by LPIPS at most 0.0005 (PSNR at least 54 dB). Fresh compiles of the widened model on main are not bit-reproducible either (1 of 6 differed). ## Tests New CPU tests fail on main and pass here: - stored dtype and bytes; - layer forward parity against the dequant formula (bf16 / fp16 / fp32, e4m3fn / e5m2, per-tensor / per-row); - all 256 codes for the integer decode, plus a compiled `fullgraph` with no graph break; - plain fp8 Krea 2 storage; - the default rule, the kill switch, LoRA refusal, offload grad mode, video backends and plan sizing; - the host RAM check: with free RAM between the stored and the widened need, a plain fp8 or fp8_scaled file loads when stored and is refused with `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 - No real sm_80 / sm_75 GPU or ROCm card was run. The no-runtime path was forced on a B200, and the Triton fp8 limit below sm_89 is handled by the integer decode, but it was not executed on that hardware. - The resident-on-24-32 GiB result is planner output; it was not measured on a real card of that size. - FLUX-style plain fp8 files that go through diffusers `from_single_file` are still widened by diffusers. - MPS keeps the widened path.
… 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>
Summary
Loading a custom Krea 2 safetensors from the custom models folder (the ComfyUI
diffusion_modelsfile, usually fp8 or fp8_scaled, 13 GB) could take the whole app down (#14474). Studio already supports these files: the family is detected from the header, the DiT comes from the file and the text encoder / VAE fromkrea/Krea-2-Turbo. What kills the process is host RAM:load_original_layout_transformer, which widens every fp8 tensor to the compute dtype in host RAM (value.to(want)). That is about 23 to 26 GB of new memory for the 13B Krea 2 DiT.load_comfy_quant_transformer. On a GPU with no fp8 runtime (anything below sm_89, such as the reporter's RTX 3060 Ti), every layer is dequantized to bf16 the same way.This PR prices the new host memory from the safetensors header before any widening. Tensors already at the compute dtype stay memory-mapped and cost nothing. When the widened weights plus the small-host reserve do not fit in free RAM, the load is refused with a readable error. This applies to both loaders and to every family that uses them:
UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0(the existing small-host switch) skips the check, and loads under 1 GiB of widening are never checked.Evidence
scale_weight/scaled_fp8,model.diffusion_model.prefix, diffusers layout) all load throughDiffusionBackend.load_pipelinefrom a custom folder onmain. The load path itself is fine.main: the process is SIGKILLed (exit 137) with no Python error.mainvs this branch:tests/test_diffusion_single_file_host_ram.py. Four tests fail onmainand pass here: the fp8 file is refused before any weight is read, the fp8_scaled file with no fp8 runtime is refused, a bf16 file is never refused, and the widened byte count matches. Two pass on both: the same files load when there is room, and the kill switch / unreadable RAM never refuse.test_diffusion_comfy_quant.py,test_diffusion_krea2.py,test_diffusion_single_file_krea2_hunyuanimage.py,test_diffusion_single_file_registry.py,test_diffusion_small_host.py,test_hub_safetensors_single_file.py,test_video_comfy_quant.py. No change between base and head.Review follow-ups
The header estimate alone kept missing per-layer choices the loader makes later (layers a runtime filter rejects, fp16 deferred dequantization, the packed NVFP4 width, FNUZ float8, nibble-swapped NVFP4 copies, key-map row reorders, tiled scale buffers). So the header estimate is now only the first gate, refusing before any read. During the load, every helper that allocates host memory (
_dequant,dequant_block,swap_nibbles,untile_scales,tile_scales, the dtype casts in both loaders, the segment join, the key-maptorch.cat) checks its allocation against the host's live available memory (cgroup-capped, about 0.5 ms per reading) minus the reserve, and the load is refused before the allocation that would not fit. Because it reads live memory rather than keeping a running total, freed buffers count as free again and a copy made where nothing checks still shows up in the next reading. Files under 1 GiB are not checked, andUNSLOTH_DIFFUSION_HOST_RAM_CHECK=0installs no check at all.Real-size check: a 13.2 GiB Krea 2 fp8_scaled ComfyUI file (rebuilt from the bf16 transformer) loading at bf16 on CPU, with a simulated 64 GiB host whose free memory falls as the process's anonymous memory grows (measured peak 23.26 GiB, reserve 6.4 GiB):
Each review item has a test that fails before its fix and passes after, including a 48-layer NVFP4 fallback load that fits and was refused by the earlier running-total version.
Not covered