Skip to content

refactor(model-manager): own the quantized single-file load sequence in one module - #10443

Merged
joshistoast merged 15 commits into
mainfrom
fix-issue-10302
Dec 3, 2026
Merged

joshistoast merged 15 commits into
mainfrom
fix-issue-10302

Conversation

@joshistoast

@joshistoast joshistoast commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Loading a quantized single-file checkpoint is an ordered sequence (recover nvfp4 payloads, int8 markers and fp8 scales; reserve RAM before anything widens; keep or fold; cast; install; load; attach scales). Every family loader assembled it by hand, and the order lived only in comments repeated per loader.

invokeai/backend/quantization/single_file_checkpoint.py now owns it:

  • SingleFileCheckpoint.recover(sd, ...) takes the side channels out in the order they need. It has one key-conversion point, right after the nvfp4 pop; everything after it reads the model's key space.
  • checkpoint.install(model, dtype, ...) makes the one reservation, folds or keeps, casts, installs packed layers, calls the family's load, clears the dict and attaches the kept scales.

A family supplies only what is its own: reading the file, its key conversion, building the model, skip patterns, its load_state_dict policy and its log lines. It states which formats it decodes (int8, accept_int4, nvfp4, scaled_fp8); there is no per-family parameter.

Loaders now behind the module:

  • Transformers: FLUX.1, FLUX.2, FLUX.3, Krea-2, Qwen-Image, Qwen-Image-2.1, Z-Image, Anima, Ideogram 4, MOSS-Image, LTX-2.
  • Encoders: T5, CLIP, Qwen3, Qwen2.5-VL, Qwen3-VL (and its vision tower), Qwen3.5, the Qwen3.5 text LLM, LTX-2's Gemma-4.

Not moved, on purpose: Wan (it streams payloads against header metadata), the GGUF paths (unpack_ggml_at_load already owns their reservation), MiniMax H3 (it never casts), LTX-2's dense components (they cast before a model exists) and Mistral (its own fold has to be unified onto the shared one first, which changes behaviour).

Loaded modules are byte-identical to main for every moved path. Behaviour differences:

  • Reservations.
    • FLUX.2 reserves once on the non-keep path instead of twice; the single figure covers both old ones.
    • T5's fold path now counts the recovered scale bytes it used to leave out.
    • The Qwen3 encoder no longer charges an LM head it never loads.
  • Refusal wording.
    • FLUX.1 and FLUX.2 no longer claim the header was not read.
    • Refusals on Krea-2 native files and on the Qwen2.5-VL and Qwen3-VL encoders name converted keys, because markers are read after the key conversion.
    • The side-channel refusal of MOSS-Image, the Qwen3.5 encoder and the text LLM starts with the architecture ("Qwen3.5 checkpoint carries ...") instead of the file name.
    • The Qwen3-VL vision tower's MXFP8 refusal has a different text.
  • New refusals of files that could not load correctly.
    • T5 and CLIP refuse an int8 file before reserving room (it used to fail at load_state_dict, after the reservation).
    • CLIP refuses any quantization side channel (a scaled-fp8 CLIP file used to load unscaled).
    • The format-support page already lists these as refused.
  • Self-contradictory or stray-key files.
    • FLUX.2 ignores a stale int8 header entry on a dense weight (it used to fail at the swap).
    • FLUX.2 refuses int8 markers in a file with no int8 weights (it used to load through the fp8 path); FLUX.1 already did.
    • A per-tensor marker beats a conflicting int8 header entry on FLUX.1 and FLUX.2.
    • FLUX.2 no longer strips stray 0-dim tensors; the non-strict load ignores them.
    • Krea-2 decodes an unrotated int8 norm stored as .scale (it used to refuse the file), and drops a marker on a module with no weight with an INFO line.
    • The Qwen3 encoder ignores an odd lm_head (unmarked int8, unreadable scale) instead of refusing the file; the head is tied and never loaded.
    • The Gemma-4 encoder refuses a dense file with a stray weight scale, .input_scale, or a non-int8 .comfy_quant marker before reserving room.
    • CLIP refuses a dense file carrying a stray marker or scale key (it used to ignore the key).
  • Logs. Texts and conditions are kept, with two exceptions: the "scale did not reach a module" warning of the Qwen2.5-VL and Qwen3-VL encoders now uses the loader's architecture name, and the Qwen3 encoder's key-count line is a pre-install count. Lines that used to print mid-sequence print after the load.

Related Issues / Discussions

Part of #10302. What remains of it is Mistral, which needs its own fold replaced by the shared one first. The three _storage_format copies named in the issue were already merged by #10171.

Follow-up noted during review: MXFP8 scale grids are still decoded before the reservation, as on main; the module could now fix that.

QA Instructions

  • Byte identity. Every call of 25 loader entry points was recorded across the loader and family tests on the base and again on this branch, running the base's test files against this branch's code (about 600 loads), plus isolated runs of both sides for tests this branch had to adapt. Module classes, parameter and buffer bytes (non-persistent scale buffers included), dtypes, shapes and full-precision flags are identical in every compared load. The only differences are the reservation figures and refusal texts listed above (FLUX.2 [8128056, 8390144] -> [8390200]; T5 [23360] -> [23416]).
  • Differential runs. The base and branch loaders were driven side by side on inputs the tests do not cover:
    • FLUX.2 scaled fp8 (per-tensor and per-row scales, fused qkv, both scale spellings, raw e4m3 and e5m2) and int8;
    • Krea-2 native int8 and int4, per tensor and header-only, with W8A8 input scales and mixed int8 + nvfp4;
    • Qwen-Image-2.1 int8 with a fused gate/up layer;
    • Qwen3 encoder int8 with and without an LM head;
    • T5 and CLIP with stray markers and scales, and real int8 files;
    • FLUX.3's ModelOpt nvfp4 build, including when its re-layout copies are made relative to the reservation.
  • Tests. pytest -n 6 on tests/backend/model_manager/load, tests/backend/quantization and the family directories (anima, flux, flux2, flux3, ideogram4, krea2, ltx2, moss_image, qwen2_5_vl, qwen3, qwen3_5, qwen3_vl, qwen_image_2_1, t5, text_llm, z_image): 3999 passed, 5 failed. The same 5 fail on main on this machine: test_16_channel_vae_loader.py::test_an_ldm_layout_file_is_converted_and_loses_no_tensor and four test_qwen_vl_bnb_lora.py cases.
  • Module suite. tests/backend/quantization/test_single_file_checkpoint.py: format × keep/fold on small CPU tensors, the conversion contract, and each format capability. Mutating the module (reserve after the fold, drop a reservation term, flip hint precedence, pop nvfp4 after the conversion, skip the dict clear, keep side channels on the object, ignore a capability flag) fails it.
  • Family wiring. Each family's conversion and header handling has a test that fails when it is replaced by the identity (Krea-2, Z-Image, FLUX.3, Qwen2.5-VL, Qwen3-VL). One survivor: Qwen-Image-2.1's header re-keying for fused gate/up hints, whose split helper has its own unit test.
  • Lint. ruff@0.11.2 check and format --check on the changed files: clean.
  • Not run. CPU only, no accelerator. No family E2E run; every family listed above is affected. The docs site was not built.

Review

Material findings resolved:

  • The first conversion hook renamed keys after the scheme was decided and carried the side channel itself, which fit only Krea-2. It is now a single conversion point where the converter carries the side channel.
  • A read-only view of the recovered layers taken before install kept every folded scale grid alive through the fold. install now empties the dicts in place.
  • FLUX.3's ModelOpt re-layout had moved in front of the reservation; on the memory-mapped BFL file that is several GiB of unreserved allocation. A payload now carries its layout and is re-laid out as each layer is installed, after the reservation, as on main.
  • T5 and CLIP read int8 markers they cannot decode, so a stray marker beside a float weight refused a T5 file that used to load. Families now state int8 as a capability, and T5 loads such a file as before.
  • The Gemma-4 encoder silently accepted a stray weight scale; it refuses again.
  • Test gaps: the Qwen2.5-VL encoder's documented refusals (unnamed MXFP8, weight_scale_inv) and Krea-2's header-only native int8 route had lost their tests; both are restored. Loader-level tests were added where a scheme had none (Anima scaled fp8, Qwen-Image-2.1 int8, a dense Gemma-4 load).

Remaining risks and limits:

Checklist

  • The PR has a short but descriptive title, suitable for a changelog
  • Meaningful regression coverage added / updated where needed; obsolete tests/code removed
  • Persisted-state and API changes include required migrations / compatibility validation
  • Relevant performance/efficiency opportunities considered; material claims have evidence
  • Material review findings resolved and relevant checks rerun
  • Documentation added / updated (if applicable)
  • Updated What's New copy (if doing a release after this PR)

…leCheckpoint

`recover` takes nvfp4 payloads, int8 markers and fp8 scales out of a state dict in the order they need, with one
key-conversion point after the nvfp4 pop. `install` reserves once before anything widens, folds or keeps, casts,
installs packed layers, loads, clears the dict and attaches the kept scales.
…eCheckpoint

FLUX.2 converts keys at the shared conversion point for both schemes and reserves once, after the model is built,
instead of once before the fold and once after. The loaded modules are unchanged.
The native key conversion carries the side channel across the rename for both schemes, so int8 and int4 markers are
read under diffusers names like the fp8 scales. A native int8 layer named per tensor or only in the header is tested.
@github-actions github-actions Bot added python PRs that change python files backend PRs that change backend files python-tests PRs that change python tests docs labels Dec 1, 2026
…it decodes

`SingleFileCheckpoint.recover` takes `int8` and `scaled_fp8` beside `accept_int4` and `nvfp4`. Without `int8` no
marker is read and every int8 weight is refused; without `scaled_fp8` a file carrying a quantization side channel is
refused before any room is reserved.
…gleFileCheckpoint

The encoder's key remap runs at the shared conversion point, so its int8 refusals name transformers keys. Loaded
modules and reservations are unchanged.
…gleFileCheckpoint

Loaded modules and reservations are unchanged. Anima gains a scaled fp8 load test, kept and folded, through a
`net.`-prefixed header.
…h SingleFileCheckpoint

The native conversion and the bundled-key filter run at the shared conversion point. The Qwen3 encoder drops its
LM head before the side channels are read, so the head is no longer charged to the reservation.
A ModelOpt nvfp4 payload carries its layout and is re-laid out as each layer is installed, so the copies are still
made after the reservation that counts them.
…gleFileCheckpoint

The LTX-2 Gemma-4 encoder refuses a stray weight scale before reserving room instead of at the strict assign.
Loaded modules and reservations are unchanged.
…Checkpoint

Covers T5, CLIP, the Qwen3-VL encoder and vision tower, the Qwen3.5 encoder and the Qwen3.5 text LLM. T5 and CLIP
refuse an int8 file, and CLIP any quantization side channel, before reserving room; T5's fold reservation now
counts the recovered scales.

@Pfannkuchensack Pfannkuchensack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran this against every quantized single file we have locally, comparing the merge base (ed418f3) with 899ad33. No blockers from my side.

Load diff. 64 files went through each side's registered loader on the CPU. For each one I hashed every module of the result (class, parameters with requires_grad, buffers with their persistence flag, tensor attributes such as kept scales) and recorded the sizes passed to make_room.

  • Transformers:
    • FLUX.1: int8, Krea fp8_scaled, Fill bf16
    • FLUX.2: Klein 4B fp8/int8/bf16, 9B fp8, Dev fp8mixed
    • FLUX.3: bf16, FP8, int8, nvfp4
    • Krea-2: fp8_scaled ×2, int4 mixed, int8, nvfp4
    • Qwen-Image: Edit-2511 fp8, 2512 int8, Edit-2511 int8
    • Qwen-Image-2.1: FP8, int8, bf16
    • Z-Image: fp8 ×2, int8 mixed, nvfp4
    • Anima: 2.9B int8, base bf16/fp8, 3.8B
    • Ideogram 4: fp8_scaled, int8
    • MOSS-Image: FP8, int8, bf16
    • LTX-2.5 22B: int8, nvfp4
  • Encoders:
    • LTX Gemma-4
    • T5 ×3, CLIP ×2
    • Qwen3 ×6, Qwen2.5-VL ×4 (nvfp4 included), Qwen3-VL ×6
    • Qwen3.5 encoder ×2, Qwen3.5 as text LLM ×2

All 64 produce byte-identical modules. Two files differ only in their reservations, and both match the description:

File Before This PR
FLUX.2 Klein base 4B [7751089152, 7771536384] [7771536384]
Qwen3 8B int8 9441306624 8196646912 (the unread lm_head, 151936 × 4096 × bf16)

Generation. FLUX.2 Klein 4B fp8 with its single-file Qwen3 4B encoder, 1024², 4 steps, seed 1234, on an RTX 4090 through the API (scripts/family_e2e, one warm-up and two measured runs per side). The images are pixel-identical. The VRAM peak is the same (20,488 MB). Median time is 2.20 s before and 2.34 s here, within the run-to-run spread I see between server starts.

The tests pass locally apart from the known LFS-pointer fixture (test_16_channel_vae_loader).

Low

  1. An nvfp4 file in a family that doesn't decode nvfp4 isn't refused in recover. The module docstring says a format the family does not decode "is refused here, before anything is reserved". With nvfp4=False, scaled_fp8=True (Anima, FLUX.1 Krea/Fill, FLUX.2, Ideogram 4, Qwen-Image-2.1), the packed payload goes through: scaled_fp8 drops its scale keys as stray side channel, the reservation is made, and the file fails in load_state_dict with a size mismatch on the packed weight. With scaled_fp8=False, the side-channel refusal catches it as intended. Checking for nvfp4 payloads when nvfp4=False (pop_nvfp4_layers already knows how to find them) would make the docstring true and give a readable error. I haven't checked whether the old per-family loaders refused this earlier; either way it's the new contract that promises it.

  2. consumed_by is only exercised for Krea-2. FLUX.2 (flux.py:964) and Qwen3.5 (qwen3_5_encoder.py:135) pass it too, but dropping it there leaves their tests green. A file with an unmarked int8 tensor the model doesn't consume (the case that motivated the argument) would pin it per family.

  3. Loader-level refusals lost their tests. The Qwen-Image transformer and encoder tests for a header entry that doesn't say whether the weight was rotated are gone (test_qwen_image_int8_convrot_loader.py, test_qwen_image_nvfp4_loader.py). The config-level refusal is still tested, but int8_in_header=True routes the loader through a different path. test_z_image_fp8_wiring.py also lost test_state_dict_is_released_before_the_fp8_cast and test_assign_true_really_aliases_the_state_dict. test_single_file_checkpoint.py covers the generic order, but not that Z-Image's load callback still loads with assign=True into the dict install clears.

  4. Behaviour changes without a test:

    • the Krea-2 .scale int8 norm
    • the FLUX.2 marker refusal and the stale header
    • Qwen3's unmarked lm_head
    • CLIP's stray-marker refusal

    The load diff above confirms the real files behave the same, but nothing keeps them that way.

  5. One refusal isn't in the description: a dense Gemma-4 file with a stray .input_scale or a non-int8 .comfy_quant is now refused (ltx2.py:655, scaled_fp8=False). That's reasonable, it just deserves a line in the list.

Nits

  • Some capability flags work as policy switches. LTX-2 sets scaled_fp8=True only to shed leftover side-channel keys (the comment at ltx2.py:355 says so). MOSS ties scaled_fp8 to torchao_fp8. T5 sets int8_in_header with int8=False. A separate "drop stray side-channel keys" flag would keep scaled_fp8 meaning "decodes scaled fp8".
  • Some refusals still sit in the families' conversion or load hooks (LTX-2, the Krea-2 vision tower, Z-Image's tie_weights) rather than in recover. Fine where they need the built model, but worth a sentence in the module docstring.
  • install's docstring says one reservation covers everything "before anything in the dict is widened". MXFP8 block-scale grids are already decoded to float32 in recover (decode_mx_block_scales, about 1.45 GiB on the Comfy Krea-2 MXFP8 build per load_plan.py). The reservation counts them, but they are resident before it is made.

Scope the NVFP4 check to transformer weights and ignore bundled FLUX components.

Separate LTX-2 metadata cleanup from scaled FP8 decoding and cover loader edge cases.

@Pfannkuchensack Pfannkuchensack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked at 9c6f94f. I ran the same 64 single files through the loaders again. The result is unchanged from the previous head: 62 byte-identical to the merge base, and the same two reservation differences (FLUX.2 Klein base 4B, Qwen3 8B int8). That includes the FLUX.2 files with the bundled-component filter and the three LTX-2 files with drop_stray_fp8_sidecars.

The follow-ups look good to me:

  • recover now refuses nvfp4 in a family that doesn't decode it, before the conversion and again on the converted keys, so the docstring holds. Turning the refusal off fails test_a_family_without_nvfp4_support_refuses_packed_layers_before_conversion.
  • consumed_by is pinned per family. Dropping it fails the FLUX.1 test (unmarked_int8) and the Qwen3.5 test.
  • The loader-level refusals and the Z-Image assign=True / release tests are back. The new behaviour (Krea-2 .scale norm, FLUX.2 stale header and marker refusal, Qwen3 lm_head, CLIP stray keys) now has tests.
  • LTX-2 no longer borrows scaled_fp8 to shed stray keys, and the MXFP8 timing is documented.

A correction to my previous comment: flux.py:964 is in the FLUX.1 loader, not FLUX.2. The point was about FLUX.1, and the new FLUX.1 test covers it.

One nit: reject_unsupported_nvfp4_layers runs before the int8/int4 markers are read and treats any uint8 .weight with a weight_scale as nvfp4. A packed int4 file in a family that decodes int8 but not int4 (FLUX.1, FLUX.2, …) is therefore refused with the nvfp4 message instead of the int4 one. It's still refused, only the text points at the wrong format.

Tests pass locally apart from the known LFS-pointer fixture (test_16_channel_vae_loader). No further findings from my side.

A uint8 weight with a block scale but no global scale whose marker or header entry names another format,
such as int4_tensorwise, is now refused under that format's name instead of as nvfp4. A global scale still
means nvfp4 whatever the marker says, and the set of refused files is unchanged.

@Pfannkuchensack Pfannkuchensack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked f5e7279 against 9c6f94f. The refusal now names the declared format: a packed layer with only a block scale is refused under its marker's or header's format, while a global scale or an nvfp4 declaration still means nvfp4. The set of refused layers is the same as before, only the message changes, so the load results from my last pass still hold. The new test pins the int4 message. CI is green. Approving.

Optional nit, not reachable today: recover runs this check for every family with nvfp4=False, so a family that later takes int4 without nvfp4 would have its int4 layers refused here before extract_int8_convrot_markers sees them. Krea-2, the only accept_int4=True loader, decodes nvfp4, so nothing hits this now.

The unsupported-nvfp4 refusal reads only uint8 weights, and packed int4 codes are int8, so a family that
decodes int4 but not nvfp4 still recovers its int4 layers. The test keeps it that way.
@joshistoast
joshistoast enabled auto-merge December 3, 2026 01:07
@joshistoast
joshistoast added this pull request to the merge queue Dec 3, 2026
Merged via the queue into main with commit 861f229 Dec 3, 2026
36 checks passed
@joshistoast
joshistoast deleted the fix-issue-10302 branch December 3, 2026 01:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend PRs that change backend files docs python PRs that change python files python-tests PRs that change python tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants