Repository navigation
Studio: NVFP4 flashinfer backend kernel items (device guard, persistent barrier, bias path, cached dispatch) - #10731
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: 7e87ca6da5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| from .diffusion_nvfp4_linear import reset_nvfp4_state | ||
| reset_nvfp4_state() |
There was a problem hiding this comment.
Do not reset another backend's live CUDA-graph state
This unconditional process-global reset is unsafe when the sibling image backend still has an NVFP4 CUDA graph resident—for example, a GPU image model can coexist with a CPU video pipeline because the GPU arbiter only excludes competing GPU owners. Unloading that CPU video state clears the shared barrier tensor and then calls clear_gpu_cache(), while the image graph still contains a recorded zero_ kernel targeting the barrier's address; a later replay can therefore access freed or reused memory. Scope these caches to the owning model/backend, or reset them only after every graph that references them has been uninstalled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable. Ownership in the GPU arbiter is exclusive and a video load evicts the image backend; both media routes gate on the host-wide device target, so on any host where a flashinfer NVFP4 graph can exist the video target is never cpu, and a cpu target means no image CUDA graph exists. Within each backend uninstall_all runs before reset_barriers, and the video reset sits inside the committed-state branch.
|
@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. |
|
Checked the device guard coverage in studio/backend/core/inference/diffusion_nvfp4_ops.py and the persistent barrier and cached dispatch paths, and the bit-identity numbers line up with the switches described. Will review once #10730 lands and this retargets to main. |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
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. 🚀 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". |
…nt barrier, bias path, cached dispatch) (unslothai#10731) * studio: whole-model NVFP4 for the video families with hosted pre-quantized denoisers Wan2.2-TI2V-5B, Wan2.2-T2V-A14B (both experts), HunyuanVideo-1.5 480p and 720p run NVFP4 on the torchao backend from hosted pre-quantized denoisers, so a load never quantises 5 to 28 GB of dense weights on the fly. Every admitted linear (min 512 features, in and out divisible by 16) is NVFP4; nothing is per-layer here. - one shared auto walk with a per-family head in front of it, and divisible_for_scheme - ZeroRowSafeLinear, a live bug: torchao's nvfp4 activation path raises on HunyuanVideo-1.5's empty image stream on every text-to-video render - loader gates on the packed-weight fingerprint, the component and require_divisible - conventional video pre-quant seeding, all components or none, with the memory plan taking the artifact's resident size rather than the dense build peak - registry rows for the four hosted NVFP4 repos nvfp4 stays an explicit opt-in here; no family gets an auto row on this branch. The tooling that builds and fingerprints these artifacts is not in this repo. It lives in the private scripts repo with the rest of the quant generation tooling. * studio: per-layer NVFP4 image policies, flashinfer FP4 backend and a gated auto row Whole-model NVFP4 does not pay on the image DiTs. A per-layer policy that puts NVFP4 on the few linears whose activations tolerate it and keeps fp8 everywhere else does: a memory lever at fp8-parity quality, not a speed win. - diffusion_nvfp4_policy.py: exact dotted-suffix rules with expected counts, so a diffusers rename breaks the resolution instead of shipping a different model - the _v3 policy checkpoint format, biconditional with a declared policy, and baked activation global scales in place of the running-min calibration that was behind the flux black-frame latch - diffusion_nvfp4_ops.py / diffusion_nvfp4_linear.py: a flashinfer mm_fp4 backend that re-expresses the torchao payload rather than requantising it, with two custom ops so the layer compiles fullgraph with no graph breaks - diffusion_nvfp4_protect.py: per-step W4A16 on the same bytes, opt-in, default off - the reviewed gate record, the only thing that can put nvfp4 into the auto ladder, and the conditional Wan2.2-T2V-A14B row that needs flashinfer to be the selected backend - diffusion_speed.py: stream-merging DiTs compile regionally with dynamic=False, which is what FLUX.1's CantSplit inductor failure needed The tooling that builds, calibrates and gates these artifacts is not in this repo. It lives in the private scripts repo with the rest of the quant generation tooling. * studio: NVFP4 flashinfer backend kernel items (device guard, persistent barrier, bias path, cached dispatch) Four items on the flashinfer NVFP4 path, all found while measuring it: - every flashinfer call sits inside a device guard, enforced by a source test, because a missing guard has taken cards down on a multi-GPU host - the one-element barrier between quantiser and GEMM becomes persistent rather than allocated per call, which is what makes it capture-safe - diffusion_nvfp4_bias.py: a Triton bias add with a measured numel floor and ceiling, so the kernel only runs where it beat the eager path - the backend dispatch is resolved once per load and cached, instead of re-probing per layer Carries the same strip as the branches below it: the quant generation tooling lives in the private scripts repo, not here. * Studio: trim NVFP4 kernel comments * Tighten the comments and docstrings on the video prequant path Collapse the long single-line comments this branch added to the repo's wrap width, shorten the prose docstrings to the parts that say why, and drop the test docstrings that only restate the test name. Comments, docstrings and whitespace only: no code changes. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the NVFP4 image comments and docstrings * Studio: trim NVFP4 kernel docstrings * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix pipeline prequant tests for the selector's base_repo keyword Z-Image now hosts an NVFP4 checkpoint, so the no-hosted-artifact case uses mxfp8. * Keep a resident video model's NVFP4 state when a replacement fails early * Prewarm NVFP4 checkpoints in the shared prequant loader * Credit the resident video pipeline's memory in the seed plan * Pin the residency check in the two-expert download plan test * Credit only the target card's resident bytes and fingerprint built checkpoints The residency plan counted every accelerator storage of the old pipeline as reclaimable on the card the new load targets, so switching GPUs could skip the dense denoiser shards on a card that never held them. Count only the target's. The builder never wrote metadata["fingerprint"], so the loader's packed-weight check had nothing to compare against for artifacts it produced. * Studio: name the real reason an explicit transformer quant is declined, not the GPU * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: NVFP4 policy lookup on the pipeline fallback, a protect controller per model * Fingerprint torchao 0.18 Int8Tensor prequant weights torchao >= 0.18 int8 quantization produces Int8Tensor, which the packed fingerprint payload map did not list, so every int8 weight was skipped and the recorded fingerprint verified nothing. Hash its qdata, scale and optional zero point / activation slots, with a stub test and a real torchao round trip that catches a flipped byte. * Plan pipeline denoiser seeds with the base and prequant probe _pipeline_planned_denoiser_scheme asked select_transformer_quant_scheme and auto_scheme_candidates without base_repo or has_prequant, so AUTO dropped every prequant-only rung (the gated nvfp4 head) and the plan could seed a different scheme than the load resolves. Route the winner through _planned_quant_scheme and hand the rung walk the same probe. * Apply the GEMM alignment floor in the offline prequant builder and record it The runtime quantize_ skips Linears whose in/out features miss the scheme's tiling floor, but build_prequant_checkpoint.py did not, so a ragged layer could be baked as a quantized GEMM the runtime leaves dense. The builder now passes divisible_for_scheme(scheme) to make_filter_fn and stamps require_divisible so the loader can verify it. * Autotune each NVFP4 GEMM shape on its first eager call The loaders prewarm only M = 1, and a graph's warm-up only the token counts its top-level inputs imply, so a video's real token count and a graphed Z-Image's patchified plus caption sequence reached mm_fp4 outside flashinfer.autotune and ran the fallback tactic for the whole load. The first eager GEMM of every unseen (M, K, N) now tunes under autotune(True), sharing the prewarm's process-wide set and never inside a capture. * Trim comments * Trim comments * Trim comments * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Treat a hosted prequant this user cannot fetch as no prequant The hosted NVFP4 checkpoints can be private or gated. For a user without access the Hub answers 401 / 403 / 404 on the repo itself: - _prequant_source_hub_entry raised RepositoryNotFoundError, which the planner recorded as a failure, so an explicit NVFP4 download plan came back plan_failed and download-only refused to run. A refused repo now reads as no hosted checkpoint and the dense shards stay in the plan. Transient errors still propagate. - The dense-quant prefetch decision trusted the family table's prequant candidate, so an unreachable checkpoint still kept the base transformer shards out of the staged download and the load pulled them inline after the phase switched to finalizing, outside progress, cancel and the disk check. The prequant now only suppresses the shards when it is cached, local, or the Hub lists it for this user; an unanswerable probe keeps the previous verdict. download_plan passes the user's token to that probe. * Size an unreachable hosted prequant as the dense build at load time The download plan already treats a hosted NVFP4 checkpoint this user cannot fetch (401 / 403 / 404) as no prequant and stages the dense transformer shards. The load did not get that answer: resolve_dense_quant_candidate reads the family table alone, so the candidate stayed prequant. The offload replan then budgeted the small checkpoint (22,930 MiB for a GGUF + NVFP4 pick where main budgets the 28,561 MiB dense build) and forbade the dense fallback the plan had staged the shards for, and the resident path skipped the dense decline in favour of a download that answers 401. The prefetch decision now records the refused scheme in the load kwargs, and load_pipeline sizes and fit-checks that scheme as the dense bf16 build, exactly as when the family names no checkpoint. A reachable or cached checkpoint keeps the prequant budget. * Studio: NVFP4 kill switch for image and video, default off The hosted unsloth/*-NVFP4 checkpoints are still private, so NVFP4 is disabled in general until UNSLOTH_NVFP4_DIFFUSION is set to a truthy value (1, true, yes, on). The default lives in one constant, NVFP4_DIFFUSION_DEFAULT in core/inference/diffusion_nvfp4_flag.py, so turning it on for everyone later is a one-line change. With the switch on, behaviour is unchanged. While it is off: - auto never picks nvfp4 for the dense transformer (ladder and family prefer rows), and no smoke probe is spent on it; - an explicit transformer_quant or text_encoder_quant of nvfp4 gets a 400 "NVFP4 is disabled in this build" from every image and video load and download-plan route, ahead of the precision fallback; - no hosted NVFP4 denoiser or encoder is resolved, seeded, planned or sized, and the Hub helpers never ask about a *-NVFP4 repo; - /images/info estimates and the /api/system dense ladder omit nvfp4, and /api/system reports nvfp4_diffusion so the Precision and Text encoder selects hide NVFP4. The offline builder does not consult the switch. Existing NVFP4 test modules run with it on through a conftest fixture; the default-off behaviour, and that the enabled path is still reachable end to end, are covered in test_nvfp4_diffusion_flag.py. * Studio: keep the diffusion bench NVFP4-capable under the kill switch An explicit --transformer-quant or --text-encoder-quant nvfp4 turns the switch on for the bench itself, like the other developer tools. The switch tests ask auto the way a load does, with a hosted checkpoint where the selector requires one, so the enabled-path check stays meaningful on the branches that add that requirement. * Studio: test the NVFP4 kill switch on the image surfaces With UNSLOTH_NVFP4_DIFFUSION unset, the gated and flashinfer-keyed auto rows are dropped before any gate record or backend probe runs, flashinfer is never imported or preflighted for NVFP4, the hosted FLUX.1-schnell and Z-Image-Turbo NVFP4 rows resolve to nothing and the per-layer policy factor is not applied. With it set, the flashinfer row leads auto again and both hosted repos resolve. * Studio: test that the NVFP4 kill switch keeps the flashinfer dispatch cold The fast dispatch is only reached through nvfp4_preflight and the NVFP4 layers, both behind the switch; with it unset, neither the dispatch probe nor its verify pass runs. * Studio: name how to enable NVFP4 in the disabled backend reason * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: reset a hidden NVFP4 pick to Auto when the backend switch is off A Precision or Text encoder select reseeded to nvfp4 by an earlier load kept that value after a restart turned UNSLOTH_NVFP4_DIFFUSION off: the option was filtered out, so the select rendered blank and the next load or Reapply sent nvfp4 and got a 400. Once /api/system reports the switch off, a held nvfp4 now falls back to auto on the image and video pages. Nothing is reset before system info arrives, since the switch reads off by default until then. * Studio: keep the hosted video denoiser seed for an explicit scheme under Speed off Only an auto precision is rewritten to off under Speed off; an explicit scheme is still quantized (and upgrades the speed), so suppressing the seed staged the dense denoiser for a runtime quantize. Matches diffusion.py. * Studio: treat an uncached hosted prequant as unreachable in local-only mode The loader may not fetch it under local_files_only, so the Hub listing must not keep the load sizing a packed artifact that never arrives. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: update the Speed off video plan test for the kept explicit seed * Studio: refuse an NVFP4 checkpoint loaded directly as the model while NVFP4 is off With UNSLOTH_NVFP4_DIFFUSION off, a hosted NVFP4 repo (or any repo or local path whose pre-quant metadata records scheme nvfp4) picked as the model itself named no precision, so none of the scheme gates saw it. The image and video load and download-plan routes now 400 such a pick with the same disabled message style. Detection reads the recorded scheme of a local file, a local directory or a cached Hub snapshot, then the family NVFP4 repo tables, then the -NVFP4 name. Switched on, the pick proceeds as before. * Studio: format the NVFP4 checkpoint refusal tests * Studio: cover the image family NVFP4 repos in the checkpoint refusal table * Studio: skip pipeline roots and the thread hop in the NVFP4 checkpoint refusal A diffusers pipeline loads from its component folders, so a stray root artifact no longer makes its directory read as an NVFP4 checkpoint. With the switch on the route helper returns before handing anything to a thread. * Studio: re-pick the NVFP4 image policies at the storage/quality frontier Replace the shipped per-layer policies with points from the storage/quality frontier whose paired LPIPS(vgg) gap to the same model's fp8 build stays under 0.05 at the upper 95% bootstrap bound, measured on 48 held-out pairs (24 frozen prompts x seeds 1234 and 4321, 1024 px, flashinfer backend): - z-image: zimg_rg76_v1 (76 nvfp4 / 195 fp8 / 5 bf16), 5.204 GiB, +0.022 [0.002, 0.040] - flux.1 schnell: flux_r420_v1 (187 / 312 / 3), 9.040 GiB, +0.024 [0.016, 0.031] - qwen-image-2.1: qwen21_r020_v1 (48 / 181 / 3), 6.044 GiB, +0.028 [0.012, 0.046] - qwen-image 2512: qwen2512_m120_attn8_v1 (600 / 243 / 3), 14.427 GiB, +0.028 [0.008, 0.050] flux_r600_v1 and qwen21_r040_v1 were built first and missed the bound (+0.044 [0.034, 0.053] and +0.039 [0.022, 0.057]), so each model steps back one frontier point. zimg_f8mod_toq34_v1 and flux_mod_single_v1 are removed, so an artifact built at either is refused on load rather than half-matched. Qwen-Image-2.1 gets a hosted nvfp4 row and a gated auto head like the other image families; Qwen-Image-2512 gets its own nvfp4 variant row while Qwen/Qwen-Image keeps its deny. The gate record now holds the three published GPTQ artifacts (z-image, flux.1 schnell, qwen-image-2.1), each with its 24/28 pair accuracy gate and the paired fp8 result. Steady factors come from measured resident bytes. Everything here stays behind UNSLOTH_NVFP4_DIFFUSION, default off. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: record the Qwen-Image-2512 NVFP4 gate verdict The qwen2512_m120_attn8_v1 GPTQ artifact is now hosted privately at unsloth/Qwen-Image-2512-NVFP4 (sha256 665e8f9a12d3...). It passed the 28 pair accuracy gate on flashinfer with graphs on, and its paired LPIPS(vgg) gap to the 2512 fp8 build is +0.028 [0.008, 0.050] over 48 held-out pairs. The record lifts the qwen-image nvfp4 deny for the 2512 base only; Qwen/Qwen-Image keeps it, which a new test pins. Still behind UNSLOTH_NVFP4_DIFFUSION, default off. * Studio: stamp the built denoiser component and drop an unused metadata reader * Studio: keep the NVFP4 flag and speed-off video plan tests off the runner's own GPU * Studio: pass the base repo to the NVFP4 runtime-quant scheme selector * Studio: keep the flashinfer auto-row test off the runner's own card * Studio: tune the collected-layer dispatch test's shape so it reaches the cached path * Studio: judge an explicit precision on the load's base at the route gate * Studio: name the GPU, not the family deny, when a gated base's NVFP4 is declined The route precision gate already selects on the pipeline base, so a per-base gate record (Qwen-Image-2512) lifts the family deny there. The refusal text was built without that base and reported a missing accuracy record instead of the GPU that declined. Pass the same base. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: judge a GGUF pick's explicit NVFP4 on its gated base before the 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. * Studio: keep the superseded-policy gate test off one rewritten file 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. * Studio: compile a quantised stream-merging DiT static on the max tier 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. * Studio: trim comments in the NVFP4 video layer * Studio: trim comments in the NVFP4 kernels layer * Studio: trim comments in the NVFP4 image layer * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: check the hosted video seed rows before spending a quant smoke probe * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: let the prequant builder target the second Wan A14B expert Add --component (default transformer) for the subfolder, metadata and upload name, and resolve video families so the Wan and HunyuanVideo denoisers can be built. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Let the GGUF quant planner test stub accept base_repo --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Kernel-side items on the flashinfer NVFP4 backend introduced by the per-layer image policy PR #10730. Stacked on
studio-nvfp4-image; retarget tomainonce that one merges. Four items, each behind its own switch, none changing what a render looks like:Device guard audit (
diffusion_nvfp4_ops.py,diffusion_nvfp4_linear.py). Every flashinfer entry point sits insidewith torch.cuda.device(t.device): the quantiser body, the GEMM body spanning barrier and GEMM, the plan builder includingAutoTuner.choose_oneand the cutlass module and cache-buffer getters, the preflight, and the warm-up entry. Skipped inside the traced layer forward underis_compiling()because inductor's wrapper already opens one and a live context manager there is a graph break. A source test banstorch.cuda.set_streamin the subtree (it silently sets the current device; that is how three cards were lost on this host). A CUDA test loads the layer on card 1 with card 0 current.Persistent PDL barrier. flashinfer launches the CUTLASS FP4 GEMM with programmatic dependent launch while the kernel's
griddepcontrolwait is compiled out, so the GEMM can start before the quantiser has finished writing (torch.emptyoutput: 50 of 50 non-finite in the harness; a one-element fill: 0 of 50). The image PR paid atorch.zeros(1)allocation per GEMM. This PR keeps one process-global one-element buffer per device and zeroes it inside themmop body before the GEMM; never allocated during capture (falls back to uncached zeros), reset with the graph pool on unload,UNSLOTH_NVFP4_ZERO_BUFFER=1keeps the full memset for comparison. Not an op argument: a mutable input would go throughauto_functionalizedand clone. A comment above the buffer names what to delete when flashinfer ships the griddepcontrol fix.Eager bias fast path (
diffusion_nvfp4_bias.py).mm_fp4has no bias argument. The fused CUTLASS epilogue from the investigation is dropped: not bit-identical to the unfused path (max abs 2 to 4), sm_100a only, a 104 s nvcc build at runtime, and inductor already fuses the bias into the compiled path where a custom op would block that fusion. What ships is a Triton in-place add on the eager path only, bit-identical toTensor.add_on seven verified shapes, declined underis_compiling(), on non-contiguous input, on a dtype mismatch, without Triton, below 12 M output elements and above 2**31. The floor is measured: the kernel's launch is 20 to 28 us against 5 to 10 us foradd_, so it runs 0.26x to 0.37x below 4 M elements and 0.84x at 1024x10240, then 1.84x at 4096x3840 and 3.4x to 3.8x from 4096x10240 up; flux and qwen-image route only M = 1 GEMMs to nvfp4, where it was pure launch cost.UNSLOTH_NVFP4_FAST_BIAS=0disables it.Cached flashinfer dispatch state (
diffusion_nvfp4_dispatch.py). flashinfer's publicmm_fp4rebuilds its plan and re-transposes the weight on every call: 58 us of host per GEMM. All private-internal touching lives in one file behind an exact version allowlist ("0.6.6") plus a one-shot runtime bit-identity self-check (verify(), run inside the preflight, off the request path).gemm_planreturns None when capturing with a cold key so no profiling launch is baked into a graph; the transpose cache is keyed on(data_ptr, shape), weights only, bounded at 4096, reset on unload.UNSLOTH_NVFP4_FAST_DISPATCH=auto|0|1(1 skips only the version check, neververify). Any other flashinfer release silently uses the public path.Measurements
B200, torch 2.12.1+cu130, flashinfer 0.6.6. The PR 2 arm is the PR 2 worktree, not an env setting: the barrier has no switch back to the per-call allocation, so arms are whole trees and a "knobs off" arm on this tree isolates the barrier.
Per-kernel (commits 2 to 4): persistent barrier saves 1.7 us host per GEMM; cached dispatch 58 to 19 us host per GEMM,
torch.equalon every checked shape; Triton bias 1.6x to 3.7x overadd_, bit-identical.End to end, z-image, 9 steps, 3 warm-ups + 20 timed renders, median of 3 processes per arm:
This PR over the PR 2 tree: graphed 1.016x and 1.011x, un-graphed 1.128x at 512 and 0.992x at 1024. The un-graphed 512 gain is entirely the cached dispatch (the barrier arm shows no end-to-end effect and the compiled path declines the Triton bias). The 1.45x to 1.55x the investigation prototype measured does not reproduce and should not: that prototype had every admitted linear (239) on the flashinfer path, the shipped z-image policy puts 34 there. Wan2.2-TI2V-5B at 1280x704x121, 50 steps, 304 flashinfer linears: 48.15 s to 47.72 s (1.009x), the same with graphs requested or forced off since Studio does not capture a graph for that family.
Bit identity against the PR 2 tree: with deterministic algorithms pinned, every z-image pair is exactly 0 in all four cells. As shipped, the un-graphed compiled path is not reproducible against itself (two runs of the same tree and seed differ by up to 136 levels on 72 percent of pixels when one compiled cold and the other loaded a compile-cache bundle), every cross-tree pair lands inside that spread and several are exactly 0; Wan pairs differ by at most 2 levels on under 0.5 percent of pixels, within the same-arm range. No knob in this PR breaks identity. The compile-cache drift is pre-existing and independent of NVFP4, tracked separately.
Capture inertness: barrier and dispatch workspace pointers unchanged across a
GraphedForwardcapture and 20 replays, one barrier per device, no plan built during a cold capture, replays bit-identical to eager.verify()costs 0.9 ms cold inside a 110 to 130 ms preflight inside a 20 to 35 s load.Tests
test_diffusion_nvfp4_speed.py,test_diffusion_nvfp4_dispatch.py: barrier allocated once per device, not cached during capture,zero_precedesmm_fp4in the stub call log,ZERO_BUFFERenv; every flashinfer call sees the tensor's device with tensors on device 1 and device 0 current; noset_streamin the subtree; dispatch refuses an unknown version, a missing symbol, env off; no plan during capture; transpose cache bounded; fused bias falls back on each condition;reset()clears state. CUDA-gated: barrier bit identity over 50 iterations, fast vs public dispatchtorch.equalat five shapes, fused bias identity on seven shapes, multi-GPU guard, capture and replay identity with a stable barrier pointer.Full
studio/backend/testson this branch (test_blender_managed.pyexcluded), 828 files in 10 batches: 41593 passed, 124 failed, 262 skipped, 15 errors. Every failing id reproduces on the merge base (95feb6979) in the same 19 files none of which this PR touches (see the image PR for the list).hub/tests: 683 passed.Not measured
FLUX.1 and Qwen-Image end to end (the eager path where the Triton bias is live is not a shipped configuration for either); other flashinfer releases (the allowlist makes them the public path by construction); the 1.6 percent graphed z-image gap, three runs per arm do not resolve it and no claim is made for it.
UI evidence
No before/after pair is attached, because nothing a user sees changes, and a pair of identical screens is not evidence of that. What was checked against this PR's own base (
studio-nvfp4-image):studio/frontendis empty,studio/backend/main.pyandstudio/backend/models/are untouched, and no response payload gains or loses a field.reset_nvfp4_state()calls are teardown on paths that already tore down. The rest is kernel internals behindtorch.ops.unsloth_nvfp4, plus four environment switches listed indiffusion_speed.py's module docstring, all unset by default.transformer_quant_backendon/api/inference/images/statusfrom Studio: per-layer NVFP4 image policies, flashinfer FP4 backend and a gated auto row #10730, cannot move here.nvfp4_preflightsetsokfrom the GEMM probe BEFORE the new fast-dispatch check runs, and that check sits inside the sametrywhoseexceptrewrites onlyreason. Adispatch.verifythat fails or raises changes which dispatch path runs, never which backend is reported, so the loaded-models row reads the same on both sides by construction.The claim this PR does make is speed at bit identity, and that is the table above: a picture cannot show that two renders are equal to the last level.
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().This PR adds no new entry point. The fast dispatch is only reached through
nvfp4_preflightand the NVFP4 layers, both behind the switch. A test here checks that neither the dispatch probe nor its verify pass runs with the switch off. The gates themselves are on #10729 and #10730.