Repository navigation
Studio: per-layer NVFP4 image policies, flashinfer FP4 backend and a gated auto row - #10730
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f952e4b63a
ℹ️ 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".
| recorded = (str(record.get("policy_id", "")).strip(), int(record.get("policy_version"))) | ||
| except (TypeError, ValueError): | ||
| return False | ||
| return recorded == (str(policy.policy_id), int(policy.version)) |
There was a problem hiding this comment.
Bind gate approval to the loaded checkpoint digest
When a configured NVFP4 checkpoint is rebuilt or replaced under the same base and policy version, this returns true solely from all_pass and the policy identity; the recorded checkpoint_sha256, repo_id, and filename are never matched to the artifact that resolve_prequant_source actually loads. The checked-in record already contains multiple Z-Image artifacts for one policy, so AUTO can approve bytes other than those whose render quality passed. Verify the downloaded digest against the matching record or pin an immutable artifact revision before lifting the deny.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable with the hosted repos: resolve_prequant_source derives Z-Image-Turbo-NVFP4.pt, which is the artifact the passing record names; the RTN file is hosted for A/B only and no row resolves it. Pinning digests against a future re-upload is hardening, not a bug on a well-formed session.
| from core.inference.diffusion_nvfp4_linear import ACT_SCALES_KEY | ||
|
|
||
| # The flashinfer backend converts a layer only when it finds its scale here. | ||
| metadata[ACT_SCALES_KEY] = {fqn: float(value) for fqn, value in sorted(act_scales.items())} |
There was a problem hiding this comment.
Compare baked scales during second-build verification
For a build using --bake-activation-scales, these values materially control FlashInfer activation quantization but are stored only in metadata, while --verify-against compares packed weight fingerprints exclusively. Two builds made with different calibration inputs, or one with nondeterministic or corrupted amax measurements, therefore have identical weight fingerprints and can pass the mandatory publication check despite producing different inference behavior. Include the baked scales and their calibration contract in the reproducibility comparison.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The second build is a reproduction gate for the packed payloads; the baked scales are measured from rendered samples, so an equality check on them would fail legitimate republishes on ordinary float nondeterminism, and reaching the described outcome requires running the second build with different inputs.
| declared = counts.get(PRECISION_NVFP4) | ||
| if declared is not None and declared != len(fqns): |
There was a problem hiding this comment.
Verify the policy's exact NVFP4 layer assignment
For a v3 policy checkpoint, this validates only that the declared NVFP4 count equals the length of nvfp4_fqns; _validate_policy subsequently compares only the policy identity and aggregate counts. A mislabeled or rebuilt artifact can therefore place NVFP4 tensors on a different set of layers, retain the expected counts and policy version, and be accepted even though the accuracy gate applies to an exact per-layer assignment. Compare the listed FQNs with the resolved policy assignment and verify that the corresponding state-dict weight types match.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The builder derives nvfp4_fqns from the resolved policy, so a legitimately built artifact matches by construction; a mislabeled foreign artifact is outside what the loader defends against.
| "all_pass": bool(results.get("all_pass")), | ||
| "num_pairs": results.get("num_pairs"), | ||
| "num_passed": results.get("num_passed"), |
There was a problem hiding this comment.
Recompute gate success from the recorded results
A malformed or internally inconsistent results file can enable AUTO because bool(results.get("all_pass")) treats values such as the JSON string "false" as true and neither this writer nor the reader checks that num_passed == num_pairs or that every recorded case passed. Thus an incomplete or failed campaign can be committed as an enabling verdict despite the tool's fail-closed contract. Require a literal boolean and derive the verdict from consistent counts and per-case outcomes before appending the record.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
results.json is written by the gate harness, not by hand, and append_record already refuses all_pass false without --allow-fail, so the fail-closed contract holds for the input the harness produces.
|
|
||
|
|
||
| DEFAULT_IMAGE_CALIB_GRID = "1024" | ||
| DEFAULT_VIDEO_CALIB_GRID = "832x480x25" |
There was a problem hiding this comment.
Choose a family-valid default video calibration grid
Any MiniMax-H3 calibration that omits --calib-resolution receives this 25-frame default and is then unconditionally rejected by frame_count_refusal: H3 declares a minimum of 124 frames on a 17k + 5 frame lattice. Consequently the newly advertised default calibration workflow cannot run for that supported video family without an undocumented mandatory override. Derive the default frame count from fam.default_num_frames or otherwise choose a value valid for the resolved family's lattice.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
MiniMax-H3 declares no nvfp4 artifact and these build flags require --scheme nvfp4, so this is not a shipped workflow, and the refusal is loud and names the lattice. A default taken from the family's frame count is a follow-up, not a defect.
| regressed = sorted( | ||
| (fqn for fqn, score in scores.items() if not score.get("improved")), | ||
| key = lambda fqn: (scores[fqn].get("ratio") is None, scores[fqn].get("ratio") or 0.0), | ||
| ) | ||
| allowed = regressed[: max(0, int(max_regressions))] |
There was a problem hiding this comment.
Needs a non-finite error that nothing has observed, plus a non-default opt-in setting above zero; the default path already skips such a layer.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5cd31b8751
ℹ️ 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".
| if isinstance(value, torch.Tensor): | ||
| return value.detach().to(device = device, dtype = dtype).reshape(1).clone() | ||
| return torch.tensor([float(value)], device = device, dtype = dtype) |
There was a problem hiding this comment.
Reject invalid baked activation scales
When a hosted or operator-supplied checkpoint contains 0, a negative value, NaN, or infinity in act_global_scales, this conversion accepts it because float(value) and the tensor path perform no range or finiteness check. nvfp4_linear_from_torchao then divides per_tensor_scale by that value to form alpha, so FlashInfer conversion succeeds but inference can produce invalid or silently corrupted outputs instead of falling back to torchao; the packed-weight fingerprint does not cover this metadata. Require each baked scale to be finite and strictly positive before constructing any replacement.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The only producer of act_global_scales drops non-finite and non-positive amax values and the builder errors on any layer left without a scale, so such an entry means a hand-edited artifact.
| key = (m, module.in_features, module.out_features) | ||
| if key in _TUNED_SHAPES: | ||
| continue |
There was a problem hiding this comment.
Key prewarm completion by CUDA device
When a long-lived Studio process loads NVFP4 models first on one GPU and then on another, the second GPU skips autotuning for every matching (M, K, N) because _TUNED_SHAPES is process-global and this key contains no device or capability. The second device can consequently enter CUDA-graph capture with FlashInfer's default tactic—the exact condition this prewarm is intended to prevent—especially on heterogeneous Blackwell cards. Include the CUDA device/capability in the key, or clear the cache when the selected GPU changes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
FlashInfer's autotuner cache is process-global and device-blind (its key is op, runner and profile, with no device), so the tactic profiled on the first card is what choose_one returns on the second; a per-device key would only repeat a profiling pass whose result is already cached.
| cols = k // 16 | ||
| # The leading dim is NOT m whenever the padding is non-trivial. Reproduce that, not m. | ||
| total = _swizzled_sf_numel(m, cols, 128) | ||
| return ( | ||
| x.new_empty((m, k // 2), dtype = torch.uint8), | ||
| x.new_empty((total // cols, cols), dtype = torch.uint8), |
There was a problem hiding this comment.
Preserve padded columns in the fake scale tensor
For an NVFP4 linear whose input width is divisible by the advertised 16-element requirement but not by 64, cols = k // 16 is not divisible by four. _swizzled_sf_numel includes the required four-column padding, but reshaping with the unpadded cols truncates total // cols and produces a fake tensor with both the wrong shape and, in general, fewer elements than FlashInfer returns (for example, five scale columns produce 1020 fake elements instead of 1024). Compiled execution can therefore fail or use incorrect output metadata; shape this result with the padded column count, as sf_matrix_shape already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
For every k the real op accepts the fake matches exactly: flashinfer reshapes the padded buffer with the unpadded column count and raises when k // 16 is not divisible by 4 (verified on a B200 for k = 80 and 528), and every admitted K in the shipped policies and video families is a multiple of 64.
| def normalised(self) -> dict: | ||
| """``{fqn: H / rows}``, divided per layer, since rows differ under an attention trim.""" | ||
| out: dict = {} | ||
| for fqn, hessian in self.hessians.items(): | ||
| rows = max(1, int(self.samples.get(fqn, 0))) | ||
| out[fqn] = hessian / rows | ||
| return out |
There was a problem hiding this comment.
The shipped builds only touch the policy's NVFP4 set (34 to 120 layers), so the transient copy stays far under the budget beside the dense DiT on the cards the builds run on.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0391a5b457
ℹ️ 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".
| pipe = getattr(diffusers, pipeline_cls_name).from_pretrained( | ||
| args.base, | ||
| torch_dtype = torch.bfloat16, | ||
| token = args.hf_token, | ||
| **{component: transformer}, |
There was a problem hiding this comment.
Load modular components before H3 calibration
When MiniMax-H3 calibration uses a valid frame override, pipeline_cls_name is ModularPipeline, whose from_pretrained only opens the modular index; the production H3 loader explicitly calls update_components and then load_components before using the pipeline (video.py's _load_h3_pipeline). This generic path instead proceeds directly to pipe.to() and rendering, leaving the encoders, VAEs, schedulers, and other workflow components unloaded, so H3 calibration still cannot run after the default-frame refusal is addressed. Assemble this family through its modular loading path before rendering.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not a shipped workflow: these build flags require --scheme nvfp4, MiniMax-H3 declares no nvfp4 artifact or policy, and the default grid is refused for H3 before any pipeline is built. Only an explicit frame override reaches that line, for an artifact nothing could load.
| parsed = json.loads(target.read_text(encoding = "utf-8")) | ||
| records = parsed.get("records") if isinstance(parsed, dict) else None | ||
| entries = tuple(record for record in (records or []) if isinstance(record, dict)) |
There was a problem hiding this comment.
Reject gate files with an unknown schema version
If the checked-in gate document has a missing, malformed, or future version, this loader still consumes its records as version 1 and can lift the NVFP4 deny. That defeats GATE_RECORD_VERSION as a schema boundary and is especially unsafe for a fail-closed approval file whose field meanings may change in a later format. Require parsed["version"] == GATE_RECORD_VERSION; otherwise return no evidence.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The gate file is checked into this repo at version 1 and its only writer stamps GATE_RECORD_VERSION; a future-version document needs a maintainer commit, which would carry the reader change with it.
| rows = 1 | ||
| for dim in shape[:-1]: | ||
| rows *= dim | ||
| if rows > 0: | ||
| counts.add(rows) | ||
| return tuple(sorted(counts)[:8]) |
There was a problem hiding this comment.
Include merged stream sizes in NVFP4 prewarm
For the FLUX.1 CUDA-graph path, the top-level call supplies image and encoder streams as separate tensors, but FluxSingleTransformerBlock concatenates them before the policy-selected norm.linear layers run. This helper tunes only each tensor's individual row count, so it never tunes the actual merged M; the subsequent warmup runs that shape outside flashinfer.autotune(True) and capture records the default tactic, defeating the prewarm on the hosted FLUX NVFP4 path. Add the merged stream row count, or derive row counts from the affected layer activations.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The premise does not hold on flux: the policy's NVFP4 layers are single_transformer_blocks.*.norm.linear, AdaLayerNormZeroSingle's linear over the timestep embedding, so the merged stream never reaches a quantised GEMM there and the row count is the batch size, which the prewarm seeds. An untuned shape under capture takes flashinfer's default tactic, a speed difference only.
| "z-image": _AutoPrefer( | ||
| floor = (10, 0), schemes = (TQ_FP8, TQ_NVFP4, TQ_MXFP8, TQ_INT8), gated = True | ||
| ), | ||
| "flux.1": _AutoPrefer(floor = (10, 0), schemes = (TQ_FP8, TQ_NVFP4, TQ_MXFP8, TQ_INT8), gated = True), |
There was a problem hiding this comment.
Require FP8 support before selecting a mixed NVFP4 policy
For gated Z-Image and FLUX.1 loads, AUTO reaches nvfp4 precisely after the FP8 smoke probe fails, but these policy artifacts are predominantly FP8 (237 and 461 FP8 linears respectively). The selector then probes only whole-model NVFP4 support and can choose the mixed checkpoint even though the same FP8 execution path it embeds was just proven unusable, causing the first FP8 policy layer to fail or produce the non-finite output that made the FP8 rung fall through. Offer policy NVFP4 only when both the NVFP4 and FP8 smoke probes pass.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A gated row is ordered fp8 then nvfp4, so auto reaches the policy artifact exactly when the fp8 probe declines; requiring that probe would make the hosted z-image and flux checkpoints explicit-only, which is a design choice rather than a triage fix. An install whose torchao lacks the activation floor also cannot unpickle the artifact's fp8 half (the required globals include the fp8 kwargs class), so it falls to dense rather than rendering black.
| regressed = sorted( | ||
| (fqn for fqn, score in scores.items() if not score.get("improved")), | ||
| key = lambda fqn: (scores[fqn].get("ratio") is None, scores[fqn].get("ratio") or 0.0), | ||
| ) | ||
| allowed = regressed[: max(0, int(max_regressions))] |
There was a problem hiding this comment.
Needs a non-finite error that nothing has observed, plus a non-default opt-in setting above zero; the default path already skips such a layer.
| def normalised(self) -> dict: | ||
| """``{fqn: H / rows}``, divided per layer, since rows differ under an attention trim.""" | ||
| out: dict = {} | ||
| for fqn, hessian in self.hessians.items(): | ||
| rows = max(1, int(self.samples.get(fqn, 0))) | ||
| out[fqn] = hessian / rows | ||
| return out |
There was a problem hiding this comment.
The shipped builds only touch the policy's NVFP4 set (34 to 120 layers), so the transient copy stays far under the budget beside the dense DiT on the cards the builds run on.
|
@codex review |
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 98bbea407d
ℹ️ 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".
| for rule in policy.rules: | ||
| hits = sorted(fqn for fqn in admitted if fqn not in assignment and rule.matches(fqn)) | ||
| if len(hits) != rule.expect: |
There was a problem hiding this comment.
Preserve policy matching through LoRA wrappers
When a nonzero LoRA is requested with NVFP4, _load_dense_quant_pipeline attaches PEFT adapters before calling this policy code, so each targeted linear is renamed under a .base_layer child and additional lora_A/lora_B linears appear. The exact suffix checks here consequently find zero policy targets, and even normalized suffixes would fail the aggregate count because adapter linears are included as BF16; PolicyMismatch is then caught by quantize_transformer, causing the requested NVFP4+LoRA load to fail or fall back instead of quantizing the frozen base layers. Match policy names through .base_layer while excluding adapter-side linears from the policy counts.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
NVFP4 with a LoRA is refused upstream: supports_lora lists nvfp4 and mxfp8 as blocked and the load fails with the message naming the int8 and fp8 builds, so the policy mismatch is the refusal the design already prescribes rather than a wrong outcome on a supported request.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2916d04ed8
ℹ️ 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".
| def forward(self, x): | ||
| shape = x.shape | ||
| flat = x.reshape(-1, self.in_features) |
There was a problem hiding this comment.
Keep protected dequantization out of CUDA graphs
When step protection is enabled together with the default/max CUDA-graph path, this full-weight dequantization executes while GraphedForward._capture is recording the protected branch. CUDA graphs retain the storage addresses needed for replay in their graph pool, so the dense BF16 weight and its larger decoding workspaces cease to be transient and add a persistent dense-weight-sized allocation to a load planned around packed NVFP4 residency; tight-card loads can therefore lose much of the memory saving or fail during the first protected capture. Run protected calls eagerly, or explicitly account for and reuse a bounded graph workspace.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Measured on a B200 with real flashinfer layers under capture: the retained pool growth is identical at 2 and 16 layers of one shape (218 MiB) and at 6 and 18 layers over four shapes (1010 MiB), so the pool reuses one layer's transients per distinct shape rather than keeping every dense weight. Bounded and only on an env-gated lever that is off by default; the fp32 dequant workspace is worth chunking separately.
…he card tag resolves A GGUF load that names no base_repo takes it from the repo card at load time, but the network-free route gate saw no base and refused NVFP4 under the Qwen-Image family deny that the Qwen-Image-2512 gate record lifts. When the family denies NVFP4 and the base is not known yet, judge the scheme on the base a passing record covers; the loader still refuses any other base once the card resolves.
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
The gate loader caches on (path, mtime_ns, size). The test rewrote one path three times and its first and third documents are the same size, so on Windows' coarse write clock the third read served the first document and the test failed there. Write the two flux documents to separate files.
… too On max, automatic dynamic generalises the sequence length at the first new resolution, and a torchao fp8 FLUX single block then raises inductor CantSplit (reproduced on a real-dimension block: 4096 -> 1024 image tokens), dropping the DiT to eager for the session. Compile that case static, as the default tier already does; bf16 keeps automatic dynamic, which handled the same shapes.
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
…loth into r10730 # Conflicts: # studio/backend/tests/test_nvfp4_diffusion_flag.py
…loth into r10730 # Conflicts: # studio/backend/core/inference/video.py
Add --component (default transformer) for the subfolder, metadata and upload name, and resolve video families so the Wan and HunyuanVideo denoisers can be built.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
Summary
Per-layer NVFP4 for the image DiTs, a flashinfer
mm_fp4backend for the NVFP4 linears, and a reviewed gate record that is the only thing allowed to put nvfp4 into theautoladder. The tooling that builds and gates these checkpoints is NOT in this repo: it lives in the private scripts repo, and this PR is the runtime half that loads what it produces. Stacked on the generic video NVFP4 PR #10729 (base branchstudio-nvfp4-video); retarget tomainonce that one merges.Whole-model NVFP4 does not pay on the image DiTs: the investigation measured it at LPIPS 0.51 on qwen-image and well above fp8 on z-image and flux. What does pay is a per-layer policy that puts NVFP4 on the few linears whose activations tolerate it and keeps fp8 everywhere else. That is a memory lever at fp8-parity quality, not a speed win, so:
autoorder, and only for a base that has a reviewed gate record measured on the backend that serves the device (every checked-in record is flashinfer, so torchao installs keep nvfp4 out of auto);transformer_quant=nvfp4on an ungated base, Windows, sm_121, an install without flashinfer) keeps the torchao path this PR does not change.Policies (
diffusion_nvfp4_policy.py)A policy is a table of exact dotted-suffix rules with expected counts. Resolution asserts every count, so a diffusers rename breaks the build instead of shipping a different model.
zimg_rg76_v1attention.to_qandattention.to_k,feed_forward.w1in layers 0-5 and both noise refinersadaLN_modulation.0at 256 x 15360)flux_r420_v1norm_out.linear)qwen21_r020_v1attn.to_q/to_k,img_mlp.gate_layer/proj,norm_out.linear)qwen2512_m120_attn8_v1img_mod.1,txt_mod.1and all eight attention projectionsqwen_p02_v1img_mod.1/txt_mod.1The z-image, flux, qwen-image-2.1 and 2512 rows are points on a storage/quality frontier solved per model, picked by one rule: the paired LPIPS(vgg) gap to the model's own fp8 build must stay at or under 0.05 at the upper 95% bootstrap bound. Each hosted artifact was re-measured against that bound on 48 held-out pairs (24 frozen prompts x seeds 1234 and 4321, 1024 px, flashinfer backend):
zimg_rg76_v1flux_r420_v1qwen21_r020_v1qwen2512_m120_attn8_v1The first choice for flux (
flux_r600_v1, 8.78 GB) measured +0.044 [0.034, 0.053] and the first for qwen-image-2.1 (qwen21_r040_v1, 5.87 GB) +0.039 [0.022, 0.057], so each steps back one frontier point. Rules that select single blocks are written as one exact rule per block, so every count is still asserted. The earlierzimg_f8mod_toq34_v1andflux_mod_single_v1are gone rather than kept resolvable, so an artifact built at either is refused on load.t_embedder.mlp.*on z-image stays bf16 by construction:TimestepEmbedder.forwardreadsmlp[0].weight.dtype. A policy checkpoint is quantised in two passes with disjoint fqn filters (nvfp4 first, then fp8), both configs through_quiet_config, with the resulting weight types asserted afterwards.Checkpoint format
Policy checkpoints carry the
_v3format tag, biconditional with a declared policy (policy_id,policy_version, counts), and are refused with ConvRot._validate_checkpointchecks the declared policy against the in-tree resolution for(family, base). One real bug fixed on the way:_fp8_activation_floor_presentreturned on the first tensor withact_quant_kwargs, which on a mixed dict can be an NVFP4Tensor withouthp_value_lb, so it would have refused every policy checkpoint.Activation global scales are BAKED at build time and carried in the artifact (per fqn in metadata
act_global_scales; a whole-model video artifact declares them at the top level). This removes the running-min activation-scale state the investigation's layer carried, which was not capture-safe and was the mechanism behind the flux black-frame latch. The flashinfer backend refuses an artifact without baked scales and falls back to torchao.flashinfer backend (
diffusion_nvfp4_ops.py,diffusion_nvfp4_linear.py)One hosted artifact in torchao payload format, re-expressed (never requantised) into flashinfer buffers at load:
qdata->wq, the swizzled 128x4scale->w_sf(byte-identical to flashinfer'sdo_shuffle=Falselayout, checked as a CUDA test before anything else was built),per_tensor_scale == 1/w_gsf,alpha = per_tensor_scale / a_gsf. Two custom opsunsloth_nvfp4::quantizeandunsloth_nvfp4::mmwithregister_fakeso the layer compilesfullgraph=Truewith no graph breaks. Every flashinfer call sits insidewith torch.cuda.device(t.device); a source test enforces it (a missing guard has taken cards down on a multi-GPU host). A one-element barrier between quantiser and GEMM works around flashinfer launching the CUTLASS kernel with PDL while the kernel'sgriddepcontrolis compiled out.UNSLOTH_NVFP4_BACKEND=auto|torchao|flashinfer.autopicks flashinfer only when it imports, the capability is in {(10,0), (10,3), (12,0)} and a guarded per-device preflight (128x256 quantise +mm_fp4) passes; an explicitflashinferthat fails falls back to torchao with a warning. sm_121 and Windows are torchao by construction.nvfp4_prewarmrunsflashinfer.autotuneinsideGraphedForward's warm-up so no tuning runs under capture, and any other (M, K, N) (a video's token count, Z-Image's patchified plus caption sequence) tunes on its first eager GEMM, once per process, and capture is poisoned if a layer reports unbaked scales. The status route and the loaded-models badge showtransformer_quant_backend.Gate record and the ladder
nvfp4_gate_record.jsonis a reviewed, checked-in list keyed by(family, base_repo, policy_id, policy_version, checkpoint_sha256).nvfp4_gate_passedre-resolves the in-tree policy, so bumping a policy invalidates its verdict._FAMILY_AUTO_PREFERrows for z-image, flux.1, qwen-image and qwen-image-2.1 aregated: the head(fp8, nvfp4, mxfp8, int8)applies only where a record covers THIS base;_family_deniedlifts the qwen nvfp4 deny for a gated base only (Qwen-Image-2512 today, never Qwen/Qwen-Image); nvfp4 under auto also requires a usable prequant source._FAMILY_TRAIN_SCHEME_DENYgets nvfp4 for every family._POLICY_STEADY_FACTORreplaces the whole-model 0.33 factor for the policy families inestimate_dense_quantand the inference info route.Per-step precision on the same bytes (
diffusion_nvfp4_protect.py, opt-in, default off)UNSLOTH_NVFP4_PROTECT_STEPS=0,1,2,3,-1(orauto: the first 8 percent of steps and the last) makes the flashinfer layers run W4A16 at the named denoising steps: the packed weight is dequantised to a transient bf16 tensor and multiplied with the unquantised activation, everywhere else the NVFP4 GEMM runs as usual. No second resident operand (peak identical, steady +152 KiB for 304 one-element scale buffers); the step index comes from a wrapper aroundscheduler.stepinstalled for the duration of one video generation; under compile the switch is a per-load bool so an armed load traces two variants (measuredunique_graphs= 2, no recompiles across 50 steps) and an unarmed load traces the one that shipped; under graph capture the branch joins the cache key. Flashinfer backend only: on a load that stayed on torchao the controller refuses to arm and logs it, so no step is ever reported as protected when nothing ran. On the image side it wraps each chunk's pipeline call, doubles the graph cap once when it discovers the split (one captured graph per branch per shape, the second branch sharing the pool: +0.07 GB on z-image 1024), and suspends itself duringnvfp4_prewarmso the FP4 tactic is tuned even when the first capture lands on a protected step (a live ordering bug found by the end-to-end check). A step whose forward the step cache skips is simply not protected.Wan2.2-TI2V-5B, 1280x704x121, 50 steps, held-out LPIPS against bf16, paired against fp8:
The five-step schedule closes a quarter of the W4A4-to-fp8 gap for 2.6 percent of the speed at byte-identical memory, which is what the investigation measured for this lever. It does not reach fp8, so it ships as an opt-in and no auto row depends on it. The protected set is per model. On HunyuanVideo-1.5 480p the same schedule takes the paired gap against fp8 from +0.116 to +0.028 over 32 held-out pairs (95 percent upper bound +0.061, SSIM 0.521 against fp8's 0.475, 1.07x fp8), the closest any small video family gets, and still short of the +0.02 / +0.05 bar, so 480p stays an explicit opt-in as well.
On the image policies the lever is inert by construction and measured as such: with 34 of 271 (z-image) and 38 of 499 (flux) linears at 4 bits and the rest fp8, protecting even every step moves held-out LPIPS by +0.003 (z-image) and -0.009 (flux) with every 95 percent interval spanning zero, at 1.00x to 1.03x fp8 speed. The whole-model image numbers in the investigation do not transfer to these mixed policies and are not claimed here.
Wan2.2-T2V-A14B under auto
The generic video PR measured its four families through the promotion gates against the hosted NVFP4 artifacts on this backend. Wan2.2-T2V-A14B is the one that passes every gate: p50 denoise 432 s against fp8's 482 s (1.115x, 5 of 5 rotations), steady resident 26.2 GiB against 38.6, held-out LPIPS 0.356 against fp8's 0.431 (paired gap -0.075, 95 percent upper bound -0.025), SSIM 0.571 against 0.510. The same artifact on the torchao kernels is 0.86x fp8, so the row is conditional:
_AutoPrefergains abackendfield and the A14B head(nvfp4, fp8, mxfp8, int8)applies only whereselect_nvfp4_backendwould pick flashinfer for the device, through a lazy probe that answers False on any failure (the module stays stdlib-only at import for the smoke-probe child). Both callers share the one walk, so the condition cannot apply to one and not the other. Wan 5B, HunyuanVideo 480p and 720p fail the accuracy gate and stay explicit opt-ins.Fixing this exposed a dead path:
_video_auto_denoiser_schemenever passedhas_prequant, and nvfp4 requires a pre-quant source under auto, so no video family could have reached nvfp4 under auto however the head was ordered. The probe now uses the same all-components-or-none resolver the coverage check uses, so the plan and the pull cannot disagree and a dual-expert family with one artifact stays on fp8. The explicit-request path is untouched. The image pipeline seed planner (_pipeline_planned_denoiser_scheme) had the same gap and now resolves through_planned_quant_scheme, with the base and checkpoint probe also passed to its lower-rung walk.flux compile fix (
diffusion_speed.py)Found while measuring: FLUX.1's dense quant path (bf16, fp8 and nvfp4 alike) failed on the first compiled render with
InductorError: CantSplit: 15360*s31 + 15360*s87 not divisible by s31 + s87. diffusers'FluxSingleTransformerBlockconcatenates the text and image streams inside the regionally compiled block, so underdynamic=Truethe two lengths are separate symbols and inductor's ownModcannot cancel15360*(a+b) / (a+b)(stock sympy can).mark_staticdoes not help becausedynamic=Trueoverrides it, and marking only the text length leaves an equally unprovableMod. Stream-merging DiTs now compile regionally withdynamic=False, the same flag themaxtier and the U-Net path already use, andcompiled_shapes_are_staticreports it so the compile cache re-saves per shape. No torch internals are touched, so nothing is version-gated.Measurements
B200, torch 2.12.1+cu130, torchao 0.18, flashinfer 0.6.6, CUDA graphs on, one arm per process.
Accuracy gate (24 to 28 held-out pairs, bf16 reference, flashinfer backend, graphs on; the harness is in the private scripts repo, its verdicts are the checked-in gate record):
zimg_rg76_v1(hosted)flux_r420_v1(hosted)qwen21_r020_v1(hosted)qwen2512_m120_attn8_v1(hosted)zimg_f8mod_toq34_v1flux_mod_single_v1qwen_p02_v1Speed vs fp8, measured at the earlier policies and not repeated for the re-picked ones (3 warm-ups, 20 renders, median; z-image 9 steps, flux 4 steps):
The compile fix alone is 2.05x at 1024 and 2.34x at 512 on flux fp8. Ship criterion for the flashinfer arm was >= 0.97x fp8 at both resolutions; z-image and flux pass, qwen has no arm to measure (refused by the runtime, correctly, because it has no gate record).
M-2 backend x graphs smoke matrix: 16 configurations, all render, no refusals, no black or non-finite output.
Hosted checkpoints (private pending review):
unsloth/Z-Image-Turbo-NVFP4(Z-Image-Turbo-NVFP4.pt),unsloth/FLUX.1-schnell-NVFP4(FLUX.1-schnell-NVFP4.pt),unsloth/Qwen-Image-2.1-NVFP4(Qwen-Image-2.1-NVFP4.pt) andunsloth/Qwen-Image-2512-NVFP4(Qwen-Image-2512-NVFP4.pt), each built at the policy above and each in the gate record. The 2512 record lifts the qwen-image nvfp4 deny for the 2512 base only; Qwen/Qwen-Image keeps it.unsloth/Qwen-Image-NVFP4exists privately for further work but no family row references it.Tests
New test files:
test_diffusion_nvfp4_policy.py,test_diffusion_nvfp4_backend.py,test_diffusion_nvfp4_linear.py,test_diffusion_nvfp4_gate.py,test_nvfp4_load_error_message.py; extendedtest_diffusion_transformer_quant.py,test_diffusion_prequant.py,test_diffusion_speed.py,test_video_prequant.py,test_diffusion_more_families.py.test_diffusion_nvfp4_gate.pycovers the shipped record and every way it does or does not become a verdict; the tests for the writer that produces a record went with the writer to the private scripts repo. CUDA-gated tests (payload byte equivalence torchao vs flashinfer, M=1 GEMM sanity, converted layer vs torchao forward at M in {1, 512, 4096, 16384}, fullgraph compile, capture and replay, multi-device guard) run on a B200: 25 passed.Full
studio/backend/testson this branch (test_blender_managed.pyexcluded), 826 files in 10 batches: 41542 passed, 125 failed, 242 skipped, 15 errors. That run predates the build tooling moving to the private scripts repo, so it counted two test files and part of a third that are no longer in this tree; nothing else in the count moved. Every failing id reproduces on the merge base (95feb6979) file by file, in 19 files none of which this PR touches (chat generation lease and supervisor, llama admission, mcp_*, native audio, openai catalog, gpu arch gate, offload planner seam, sandbox files, studio_api).hub/tests: 683 passed. One pre-existing full-suite hazard noted for the record:test_password_prompt_backstop.py::test_an_unattended_pty_does_not_block_a_raw_bind_foreverblocks forever in a single-process run of the whole suite and passes alone and in batches, on both trees.Not changed
_AUTO_LADDERtiers. nvfp4 enters only through the gated per-family heads.unsloth/FLUX.1-schnell-FP8is stale on this branch (built beforeactivation_value_lb; the loader refuses it and quantises at run time). Separate rebuild.Evidence
The loaded-models card on a B200, from two isolated installs driven by one Playwright scene. BEFORE is
df2f93036, then the head ofstudio-nvfp4-video(#10729) this branch is stacked on, not main; AFTER isd8210fb7e8. Both branches have moved since and neither move touches this surface. At the current heads,git diff df2f93036 166439a879andgit diff d8210fb7e8 6cc072b9f8are empty understudio/frontend,studio/backend/models/andstudio/backend/main.py; over every other file in the tree they change no line that is not a comment, once the build tooling that moved to the private scripts repo is set aside. So the pair still stands.Load:
unsloth/Z-Image-Turbo-GGUFQ4_K_M withtransformer_quant="nvfp4", so the dense fast path replaces the GGUF and the NVFP4 denoiser is a run-time torchao build.Image · z-image · NVFP4 · cudabecomesImage · z-image · NVFP4 · torchao · cuda, and/api/inference/images/statusgoes from notransformer_quant_backendto"torchao".torchao rather than FlashInfer is the right answer for this load and is the point of the change: an in-memory build bakes no activation scales, so
convert_nvfp4_backenddeclines and the denoiser stays on the torchao path. Before this PR that load and a FlashInfer one both readNVFP4and nothing told them apart.One limit of these two installs, stated so the picture is not read for more than it says:
install.sh --localresolved torch 2.11.0+cu130 and torchao 0.17.0 and pulled no flashinfer at all, identically on both sides, so the FlashInfer branch was out of reach there whatever the checkpoint carried. What the pair shows is that the row now names the kernel path and that this load reportstorchao; the FlashInfer branch itself is held bytest_diffusion_nvfp4_backend.pyand measured in #10731.NVFP4 kill switch
NVFP4 for image and video generation is off by default until the hosted
unsloth/*-NVFP4repos are public.UNSLOTH_NVFP4_DIFFUSION=1(alsotrue,yes,on) restores the full NVFP4 behaviour of this stack, including private-repo access through the user's HF token; anything else, or unset, disables it. The default lives in one constant,NVFP4_DIFFUSION_DEFAULTinstudio/backend/core/inference/diffusion_nvfp4_flag.py, so turning it on for everyone later is a one-line change. The switch is read at call time throughnvfp4_diffusion_enabled().Added on this branch, with the switch off:
_FAMILY_AUTO_PREFERrows (z-image, flux.1, qwen-image, qwen-image-2.1, wan2.2-t2v-a14b) are dropped whole before the gate record or the backend probe is consulted._resolve_backendanswers torchao without importing flashinfer.nvfp4_preflightandnvfp4_prewarmdo nothing.The gates on main's surfaces and #10729's are on #10729.