Skip to content

Studio: keep nvfp4 / mxfp8 layers packed when no native runtime runs them - #17067

Merged
danielhanchen merged 8 commits into
mainfrom
studio/packed-block-fallback
Nov 8, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio/packed-block-fallback

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Problem

An nvfp4 or mxfp8 single-file checkpoint has no native runtime on most GPUs today: the NVFP4 runtime needs Blackwell plus UNSLOTH_NVFP4_DIFFUSION=1 (off by default), and MXFP8 needs Blackwell. In that case the loader widened every such layer to a persistent bf16 copy at load (the single-file quant loader's _dequant_parts branches). That is 2 bytes per weight instead of 0.5625 (3.56x). The planner then priced the DiT dense and offloaded a model that would have fit packed. Video loads (the video single-file backends and the LTX-2 / LTX-2.5 loaders) never forwarded the block backends at all.

Fix

When the existing fp8-storage rule already chooses compact storage (widening would offload, overrun a tight MPS plan, or leave the host under its reserve), nvfp4 / mxfp8 layers that no native runtime takes are now kept packed:

  • PackedBlockLinear (new diffusion_packed_block.py) holds the decoded codes and plain scales as integer buffers, with per-row tensor scales and input smoothing as int32 views, so offload hooks move them and a module-wide .to(dtype) never casts them.
  • Each forward widens the layer into a transient compute-dtype weight that is bit-identical to the one the load-time widen builds, then runs F.linear (W4A16 / W8A16). Activations are never quantized and nothing is re-quantized.
    • CUDA / ROCm: one fused Triton kernel (integer e2m1 / e4m3 decode, the same multiply order as dequant_block, round-to-nearest-even by integer ops for bf16).
    • Elsewhere: dequant_block in bounded row chunks. On devices without fp8 casts (MPS before torch 2.15), nvfp4 scales are decoded by the exact lookup table and mxfp8 stays dense.
    • Under torch.compile the widen is an opaque custom op with a shape-only fake, so there are no graph breaks and no new recompiles.
  • The planner prices those layers packed (the single-file resident estimate with fp8 storage), so a load that only offloaded because of the bf16 copy can stay resident.
  • Video loads forward the native block backends the image path already used. The NVFP4 switch default and every family accuracy denial are unchanged.
  • Rendering under offload uses no_grad, as for fp8-stored layers. A late LoRA is refused with a message naming the switch.

A load whose dense copy fits keeps today's path byte for byte. A key-mapped (original-layout) family, or a split whose segments carry different input smoothing, still widens at load.

Kill switch: UNSLOTH_DIFFUSION_PACKED_BLOCK_FALLBACK=0 restores the load-time widen.

Evidence

CPU (studio/backend/tests/test_diffusion_packed_block.py, 26 tests):

  • A packed load widens to exactly the dense load's weights and gives exactly its forward, for nvfp4 and mxfp8, in bf16 and fp32, through the fused-qkv row split.
  • Row counts 1 / 17 / 1023 / 1024 / 1025, multi-segment tensor scales (one segment without a scale), and smoothing are all bit-identical through forced small chunks and through one pass.
  • Every code byte against every e4m3 scale byte (NaN scales included) is bit-identical in bf16 / fp16 / fp32 on the torch path, and on the Triton kernel under TRITON_INTERPRET=1.
  • torch.compile(fullgraph=True) gives one frame and the same output. Module casts leave the buffers untouched.
  • The kill switch and a widening pick both keep today's dense load.

Related suites (14 files, 2002 tests): the same 9 failing test IDs on the merge base and on this branch, all pre-existing.

GPU results

End to end on Qwen-Image-2.1 from a public nvfp4 single-file DiT (192 nvfp4 layers: 3.9 GiB packed, 13.3 GiB widened), 1024x1024, 8 steps, bf16, seed 0. A100 80GB limited to 16 GiB (free memory and the allocator fraction). Merge base 22a024f against this branch, arms interleaved, 3 runs each, median (min..max):

merge base this branch
load 49.7 s (49.3..101.1) 19.8 s (19.4..19.8)
first image 18.0 s (17.9..24.6) 9.2 s (9.2..10.4)
warm step 1.79 s (1.79..2.37) 0.73 s (0.70..0.74)
host RSS high-water 33.8 GiB 20.9 GiB
peak VRAM 14.7 GiB 12.3 GiB
host to device copy per step 26.5 GiB 0
DiT 13.3 GiB bf16, streamed from host 3.9 GiB packed, resident
new graphs / graph breaks while rendering 0 / 0 0 / 0

The first run's image is bit-identical to the merge base. Runs 2 and 3 reuse the activation peak learned in run 1, so the encoder and VAE placement differ between the arms, and those images differ by LPIPS 0.0009. The merge base's own run-to-run pairs are identical.

The same file without the 16 GiB limit (dense copy fits): both arms load the identical dense bf16 DiT. Warm step is 0.670 s on both, peak VRAM is 29.2 GiB on both, and the images are bit-identical.

Per layer (bf16 on A100, fp16 on T4):

  • The widen is bit-identical to the load-time widen on every byte pair and on real 4096 / 12288 widths.
  • Resident bytes are 3.54x smaller.
  • The packed forward costs 0.36 to 1.77 ms on A100, against 3.0 to 9.8 ms to stream the dense weight. A resident dense layer is 5% to 45% faster, which is why a load whose dense copy fits keeps it.
  • The widen kernel takes 0.11 to 0.24 ms per layer on A100 and 0.74 to 1.84 ms on T4.
  • torch.compile gives one frame with 0 graph breaks. CUDA graph replay and an offload round trip are bit-identical.

AMD Radeon 8060S (gfx1151, ROCm 7.13, torch 2.11): all 31 new tests pass on the GPU, including the Triton kernel in fp16 and bf16. The related suites show NO_REGRESSION against the merge base; the one failure (test_runtime_forward_matches_the_dequantized_product[mxfp8-False]) fails on both.

Cross-OS (this branch merged with current main): Linux and Windows pass (122 passed, 15 skipped on Windows).

…them

An nvfp4 / mxfp8 single file on a GPU without the native NVFP4 runtime (anything
before Blackwell, or the NVFP4 switch off, which is the default) was widened to a
persistent bf16 copy at load: 2 bytes per weight instead of 0.5625, and the
planner then offloaded a DiT that would have fit packed.

When the fp8-storage rule already picks compact storage (widening would offload
or leave the host under its reserve), such layers now stay packed as integer
buffers and are widened per forward to the exact weights the load-time widen
builds (Triton kernel on CUDA / ROCm, row-chunked torch elsewhere, an opaque
custom op under torch.compile). The planner prices them packed. Video loads
forward the block backends the image path already uses.

UNSLOTH_DIFFUSION_PACKED_BLOCK_FALLBACK=0 restores the old widen.
@danielhanchen danielhanchen self-assigned this Nov 8, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T03:13:42.761122Z 13f0a93 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 13f0a936d8

ℹ️ 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".

danielhanchen added a commit that referenced this pull request Nov 8, 2026
…OS legs (#17107)

## Summary

Two test files on main assume a Linux host. Any PR whose cross-platform
run selects them goes red on the leg that is not Linux, whatever the PR
changed. Two current examples:

```
windows-latest (#17067)
FAILED test_diffusion_comfy_block.py::test_a_many_layer_nvfp4_fallback_load_that_fits_is_not_refused
FAILED test_diffusion_comfy_block.py::test_block_dequant_is_checked_for_its_peak_intermediates[nvfp4]
  ... and four more, all:
FileNotFoundError: [Errno 2] No such file or directory: '/proc/self/status'

macos-15 (#17098)
FAILED test_sd_cpp_args.py::test_native_speed_flags
  assert ['--diffusion-fa'] == ['--diffusion-fa', '--diffusion-conv-direct']
FAILED test_sd_cpp_args.py::test_minimax_h3_video_command_has_all_joint_av_components
  assert ['--offload-to-cpu', '--clip-on-cpu'] == ['--diffusion-fa', '--offload-to-cpu']
```

In both files the product code is right and the tests are wrong.

- **`test_diffusion_comfy_block.py`.** The six memory-peak tests already
skip with `needs /proc/self/status RssAnon` when `_rss_anon_bytes()`
returns `None`. But the helper opens `/proc/self/status` unguarded. Off
Linux it raises `FileNotFoundError` instead of returning `None`, so the
tests error out instead of skipping.
- **`test_sd_cpp_args.py`.** On Apple Metal, sd.cpp deliberately drops
`--diffusion-conv-direct` and adds `--clip-on-cpu` (#13369). Most tests
in the file pin `sys.platform` before they build a command. These two do
not, so on a Mac runner they get the Metal command and compare it
against the Linux one.

## Change

Tests only:

- `_rss_anon_bytes()` returns `None` when `/proc/self/status` cannot be
opened, so the existing skips fire on Windows and macOS. On Linux
nothing changes.
- The file's existing autouse fixture in `test_sd_cpp_args.py`, which
already pins the host probes, also pins `sys.platform` to `linux`. Every
test there now builds the same command on any host unless it sets the
platform itself, as the Metal tests already do. That covers the two
tests above and any later one that forgets the pin.

## Testing

| | result |
|---|---|
| `test_sd_cpp_args.py`, `test_sd_cpp_backend.py`,
`test_diffusion_comfy_block.py` on Linux, this branch | 345 passed, 5
skipped |
| main, Windows and macOS legs of #17067 and #17098 | the failures above
|
| this branch, `test_diffusion_comfy_block.py` + `test_sd_cpp_args.py`
on ubuntu-latest | 156 passed, 5 skipped |
| this branch, same files on macos-15 | 150 passed, 11 skipped (the six
RssAnon tests skip) |
| this branch, same files on windows-latest | 150 passed, 11 skipped
(the six RssAnon tests skip) |
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
@danielhanchen
danielhanchen merged commit 285946a into main Nov 8, 2026
@danielhanchen
danielhanchen deleted the studio/packed-block-fallback branch November 8, 2026 07:08
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
…7132)

Follow-up to unslothai#17067.

## Problem

Max speed fuses QKV projections through diffusers'
`fuse_qkv_projections`, which reads each projection's `.weight` and
concatenates them into new dense `to_qkv` / `to_added_qkv` Linears. The
guard in `_fuse_qkv` (and the matching `fused_qkv_added_bytes` estimate)
only recognised `NativeWeightOnlyLinear`. A `PackedBlockLinear` from
unslothai#17067 materialises a dense matrix from its `.weight` property, so a
packed nvfp4 / mxfp8 transformer got persistent dense QKV copies next to
its packed buffers, exactly when packed storage was picked to keep
resident memory down.

Reproduced with a tiny real `FluxTransformer2DModel` whose Q/K/V are
packed: `_fuse_qkv` returned True and added a dense
`transformer_blocks.0.attn.to_qkv` (96 x 32).

## Fix

One predicate, `_quantised_projections(pipe)`, used by both `_fuse_qkv`
and `fused_qkv_added_bytes`: True when any denoiser (every DiT, and the
pipe's U-Net, which the pipe-level fuse also reaches) holds a native
weight-only Linear or a packed block Linear. Fusion is then skipped with
the existing log line, and the headroom estimate stays at 0 for such
pipes. Dense pipes fuse as before.

## Tests

- `test_qkv_fusion_skips_packed_projections`: a packed denoiser is not
fused, a dense one still is.
- `test_qkv_fusion_of_a_packed_flux_builds_no_dense_to_qkv`: tiny real
`FluxTransformer2DModel` with packed Q/K/V, byte count unchanged and no
`to_qkv` / `to_added_qkv` module after `_fuse_qkv`.

| | `origin/main` | this branch |
|---|---|---|
| the two tests above (CPU) | 2 failed | 2 passed |
| `test_diffusion_packed_block.py`, `test_diffusion_native_quant.py`,
`test_diffusion_drop_unfused_qkv.py`, `test_diffusion_speed.py`,
`test_diffusion_deferred_headroom.py` | | 430 passed, 8 skipped, 1
failed
(`test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data`,
a torchao version mismatch on this host, unrelated and the same on
`main`) |

No runtime path inside a compiled region changes: the check runs once at
optimisation time in eager.

`tests/test_diffusion_packed_block.py` on a Kaggle T4 (CUDA cases
included): 31 passed.
iam-knoit pushed a commit to SynhalaAI/unsloth that referenced this pull request Nov 8, 2026
…thai#17131)

Follow-up to unslothai#17067.

## Problem

`PackedBlockLinear` keeps its nvfp4 / mxfp8 weight as integer buffers
and widens it per forward into `self.compute_dtype`, a plain attribute
set at load. A module-wide `model.to(torch.float16)` (or `.half()`,
`.float()`, `.to(torch.float32)`) casts the bias and every surrounding
module but leaves that attribute on the load dtype, so the next forward
hands `F.linear` an fp16 input and a bf16 weight:

```
RuntimeError: self and mat2 must have the same dtype, but got Half and BFloat16
```

The dense layer this replaces (the pre-unslothai#17067 load) forwards fine after
the same cast.

## Fix

`PackedBlockLinear._apply` runs the cast function on an empty tensor of
the current compute dtype after the normal `_apply`, and adopts the
result when it is bf16 / fp16 / fp32. The packed codes and scales stay
uint8 / int32 (they are integer, so `Module.to(dtype)` never touches
them), and the widen goes straight from the codes to the new dtype,
which is bit-identical to a dense load in that dtype. Moves
(`.to(device)`) and other `_apply` users keep the dtype as is. No new
buffer, so the state dict is unchanged.

## Tests

`test_a_cast_packed_model_forwards_like_a_dense_load_in_that_dtype`
(nvfp4 + mxfp8, fp16 + fp32, `.to()` + `.half()` / `.float()`): the
widened weight is bitwise the dense load's in that dtype and the forward
runs in it. `test_module_casts_and_moves_never_touch_the_packed_buffers`
now also checks the compute dtype follows the cast and returns to the
exact load weight on the way back.

| | `origin/main` | this branch |
|---|---|---|
| `tests/test_diffusion_packed_block.py` (CPU) | 9 failed, 25 passed |
34 passed, 3 skipped |

torch.compile: a cast layer under `fullgraph=True` forward + backward
has 0 graph breaks and matches eager exactly in bf16, fp16 and fp32 (the
compute dtype is a guarded constant, so a cast recompiles once, as any
dtype change does).

GPU (Kaggle T4, torch 2.11, triton 3.6), one packed nvfp4 layer,
`model.to(dtype)`, `torch.compile(fullgraph=True, backend="inductor")`
forward + backward:

| dtype | `origin/main` | this branch |
|---|---|---|
| fp16 | `RuntimeError: ... Half and BFloat16` | 0 graph breaks, equal
to eager |
| fp32 | `RuntimeError: ... Float and BFloat16` | 0 graph breaks, equal
to eager |

`tests/test_diffusion_packed_block.py` on that GPU (CUDA Triton widen
cases included): 37 passed.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
…ai#17133)

Follow-up to unslothai#17068.

## Problem

`dequant_rows` launched the int8 / stored-fp8 Triton widen and ran its
CUDA-graph capture probe without making the operand's GPU current.
Triton picks the launch device and stream from the current device, not
from the tensor arguments (`driver.active.get_current_device()` then
`get_current_stream(device)` in `JITFunction.run`:
[v3.2.0](https://github.com/triton-lang/triton/blob/v3.2.0/python/triton/runtime/jit.py#L568-L569),
[v3.7.1](https://github.com/triton-lang/triton/blob/v3.7.1/python/triton/runtime/jit.py#L713-L714)),
and `torch.cuda.is_current_stream_capturing()` also describes the
current device's stream. A layer on `cuda:1` called while `cuda:0` is
current (an external `device_map` / Accelerate placement, which moves
tensors without a device scope) therefore launches against the wrong
device and stream; a rejected launch is caught and sets the process-wide
`_TRITON_STATE["failed"]`, which turns the fused widen off for every
later layer. The packed nvfp4 launcher from unslothai#17067 already scopes its
launch this way.

## Fix

Both the eligibility check (capture probe included) and the launch now
run inside `torch.cuda.device(codes.device)` when the codes are on CUDA
(a null context otherwise, so the CPU / MPS paths are unchanged). The
widen only runs in eager (`_stored_weight` takes the pure torch path
under `torch.compiler.is_compiling()`), so nothing changes inside
compiled graphs.

## Tests

- `test_the_triton_capture_probe_and_launch_run_on_the_operands_device`
(CPU, device context and capture probe recorded): both see `cuda:1`
while the caller stays on `cuda:0`, and the caller's device is current
again afterwards.
- `test_the_triton_widen_of_a_layer_on_a_non_current_gpu` (needs two
GPUs): int8, e4m3 and e5m2 layers on `cuda:1` widen through Triton with
device 0 current, bitwise equal to the old formula, and the failure
latch stays clear.

| | `origin/main` | this branch |
|---|---|---|
| `tests/test_diffusion_fp8_dequant.py` (CPU) | 1 failed, 39 passed, 12
skipped | 40 passed, 12 skipped |

Two GPUs (Kaggle T4 x2, torch 2.11, triton 3.6), device 0 current, an
int8 and an e4m3 layer on `cuda:1`, `_stored_weight(torch.bfloat16)`:

| | `origin/main` | this branch |
|---|---|---|
| device current at the Triton launch | 0 | 1 |
| `_TRITON_STATE["failed"]` after one call | `ValueError('Pointer
argument (at 0) cannot be accessed from Triton (cpu tensor?)')` | None |
| result | exact (chunked torch fallback), fused widen now off for the
process | exact, through Triton |

`tests/test_diffusion_fp8_dequant.py` on that host (the two-GPU and
single-GPU Triton cases included): 52 passed.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 9, 2026
…7229)

## Problem

NVFP4 only has a native path on NVIDIA Blackwell (compute capability
major >= 10: sm100, sm103, sm110, sm120, sm121). On every older NVIDIA
card (T4 sm75, A100 sm80, 3090 sm86, L4 / 4090 sm89, H100 sm90) an
explicit NVFP4 pick can only run weight-only: the 4-bit codes are
widened to bf16 per layer and the GEMM runs in bf16. Today that means
one of two things. An explicit `transformer_quant="nvfp4"` is refused
with a 409 at preflight. An NVFP4 single file (such as the LTX-2.5
packed path from unslothai#17067) loads weight-only. Both are worse than the INT8
builds we already ship, which use INT8 tensor cores and are more
accurate:

| model | INT8 ConvRot LPIPS vs bf16 | best NVFP4 LPIPS vs bf16
(fake-quant) |
|---|---|---|
| FLUX.2 klein 4B | 0.0335 | 0.128 |
| Z-Image | 0.077 | 0.125 |

## Fix

One helper, `core/inference/diffusion_nvfp4_route.py`, makes the
decision for every entry point:

- the image and video `load` and `download-plan` routes. It runs after
the disabled-NVFP4 refusal and the account checks, and before any
validation, preflight or plan reads the request, so a pre-Blackwell pick
never plans or downloads an NVFP4 file. The route's decision, including
"leave it as is", is handed to `begin_load`, so the plan and the load
always agree;
- `DiffusionBackend.begin_load` and `VideoBackend.begin_load` for direct
callers that skip the routes.

The device is read only for an NVFP4 pick, once per process. When CUDA
is not initialised and every visible card has the same capability, the
reading comes from nvidia-smi, so a plan previewed during training takes
no CUDA context. Otherwise it comes from
`torch.cuda.get_device_capability` per ordinal. ROCm is detected with
the backend's own `rocm_bf16.is_rocm_torch`, because ROCm reports gfx
versions such as 11.x and 12.x through the same call. A failed read is
not cached and leaves the request as it is. Tests replace the reading,
so the whole matrix runs on CPU.

| host | explicit NVFP4 DiT | NVFP4 text encoder | NVFP4 single file /
hosted NVFP4 repo of a known model |
|---|---|---|---|
| NVIDIA sm >= 10 (Blackwell) | unchanged | unchanged | unchanged |
| NVIDIA sm80 to sm90 | INT8 | INT8 | that model's pipeline with INT8 |
| NVIDIA sm75 (T4), image | INT8 (the fp16-card int8 linear from
unslothai#17167), Auto if that is switched off | Auto (no TE int8 below sm80) |
that model's pipeline with INT8 |
| NVIDIA sm75 (T4), video | Auto (video INT8 needs bf16) | Auto | that
model's pipeline with Auto |
| ROCm / XPU / MPS / CPU | Auto | Auto | that model's pipeline with Auto
|

INT8 is the family's normal INT8 resolution: the hosted INT8 ConvRot
checkpoint where one is registered, else on-the-fly int8 with the
family's rotation policy. A family whose profile denies int8 gets Auto.
Off NVIDIA the pick takes whatever Auto picks there, because explicit
INT8 on RDNA is slower than bf16.

What the caller sees: one INFO line (`diffusion.nvfp4_route:
transformer_quant='nvfp4'->'int8' on nvidia sm_89: NVFP4 needs a
Blackwell GPU; using INT8`), and the load's `resolved.transformer_quant`
(and `resolved.text_encoder_quant`) carries `requested: "nvfp4"`,
`value: "int8"`, `status: "fell_back"` and a reason starting `NVFP4
needs a Blackwell GPU; using INT8`. A replaced checkpoint is also named
in `replaced` (`nvfp4:<file>`). The frontend already renders `fell_back`
with the reason as a tooltip, so no UI change is needed. No hard error
is raised for any of these.

Rules:

- **When a checkpoint is replaced.** An NVFP4 single file, or a hosted
NVFP4 repo, is replaced only by the same model's pipeline:
- Image: the explicit `base_repo`, else the base the names spell. The
longest base any family table lists wins, in its canonical spelling, so
FLUX.2 klein 9B, Qwen-Image-2.1-Turbo and FLUX.1 dev map to their own
repos.
- Video: LTX-2.5 distilled files only, since the pack runs only its
distilled DiT. Never an `ltx-2` family file, since 2.0 to 2.3 share a
2.0 pipeline. Other families only when the names spell the pipeline.
- Hosted NVFP4 repos: only when one family owns the repo, or the
filename or `family_override` tells the families apart.
- **When a checkpoint is kept.** It is kept exactly as today, and
logged, when any of these holds:
  - its family or variant cannot be resolved;
  - the pick names its own text-encoder or VAE files;
- the load was not picked by hand (media auto-switch tracks the model by
the path it asked for);
  - the local path does not exist.

A recorded safetensors header scheme wins over the name, and a pickle is
never opened to ask.
- **Mixed boxes.** A load pinned to a card or a `gpu_ids` selection
reroutes when any card it places work on is pre-Blackwell. With no
selection the backend can land on any card, so it reroutes only when
every visible card is pre-Blackwell.
- **NVFP4 prequant path.** An NVFP4 `transformer_prequant_path` is
dropped on a rerouted load rather than handed to the INT8 path. An
explicit non-NVFP4 precision is kept.
- **Master switch off.** With `UNSLOTH_NVFP4_DIFFUSION` off (the default
build), an explicit NVFP4 scheme keeps its existing 400 on every GPU,
and the master switch still decides whether NVFP4 exists at all. NVFP4
single files that load today with the switch off (the LTX-2.5 packed
path) are rerouted.
- **Auto.** Auto already never picks NVFP4 below sm100: the family
`auto_prefer` row has floor (10, 0), and `_AUTO_LADDER` has no NVFP4
rung. A test now checks this for every image and video family, with
every gate record and backend probe forced to pass.
- **Kill switch.** `UNSLOTH_NVFP4_PRE_BLACKWELL_INT8=0` returns every
request untouched (the same object, no annotation), which restores
today's behaviour exactly.

## Known trade-off and limits

- **LTX-2.5 on A100-40.** The priority matrix measured the explicit
NVFP4 packed file at 14.6 s/clip against 16.4 s/clip for INT8, with
LPIPS 0.212 against 0.137. The single-clip run below has the two within
about 2%. INT8 also holds more VRAM (30.9 GiB peak against 23.3 GiB), in
exchange for clearly better quality.
- **Fine-tunes.** A fine-tuned NVFP4 file whose name matches a stock
variant loads that stock variant's INT8 weights.
`UNSLOTH_NVFP4_PRE_BLACKWELL_INT8=0` keeps the file.
- **Mixed boxes with no GPU selection.** On a box with both Blackwell
and pre-Blackwell cards, an explicit NVFP4 with no selection is left as
is.
- **Manual downloads.** The Hub download manager can still fetch an
NVFP4 file the user downloads by hand. Only loads and download plans are
rerouted.
- **MLX.** On Apple Silicon the MLX routing engine takes no route
argument, so a rerouted pick shows the INFO line but not the `fell_back`
annotation.

## Tests

CPU, `tests/test_diffusion_nvfp4_route.py` (308 tests):

- **Routing matrix.** Capabilities {7.5, 8.0, 8.6, 8.9, 9.0, 10.0, 12.0}
x devices {cuda, rocm, mps, cpu, xpu} x picks {explicit DiT nvfp4, TE
nvfp4, hosted NVFP4 source, hosted NVFP4 repo, LTX-2.5 packed NVFP4
file, unknown local NVFP4 file, auto}.
- **Switches.** The kill switch arm for every pick, and the
NVFP4-switch-off arm.
- **Blackwell.** sm100 / sm103 / sm110 / sm120 / sm121 requests come
back untouched (the same request object).
- **Device reading.**
  - mixed boxes, and selections that span cards;
- ROCm reporting 12.0, including wheels that leave `torch.version.hip`
unset;
- nvidia-smi answering without initialising CUDA (identical cards only);
  - an unreadable device that is neither cached nor acted on;
  - an ordinary request never reading the device;
  - no CUDA initialisation while training is active.
- **Variant safety.**
- FLUX.2 klein 9B, Qwen-Image-2.1-Turbo, FLUX.1 dev and LTX-2.5
distilled map to their own pipelines.
- An LTX-2.5 dev file, an LTX-2.3 file and an unspelled FLUX.1 variant
are kept.
- Shared hosted repos (HunyuanVideo-1.5 480p / 720p) are disambiguated
or kept.
  - Component-file picks, hand-free loads and missing paths are kept.
- A bare folder or file path decides the same as its (folder, file)
pair.
- **Entry points.** Every load and download-plan route (image and video)
reroutes after its refusals and account checks. `begin_load` reroutes a
direct caller before validation. An unchanged route decision is handed
to the backend too.
- **No NVFP4 download.** The rerouted Wan 2.2 A14B plan asks no
`*-NVFP4` repo and stages no NVFP4 file, while the same pick under the
kill switch asks `unsloth/Wan2.2-T2V-A14B-NVFP4`.
- **Resolved record.** It reports `requested: nvfp4`, `fell_back`, the
reason and `replaced`, and is unchanged when no route is active.

Three `tests/test_video_routes.py` tests used an explicit nvfp4 on the
CPU test host as the example of a refused scheme. On a CPU host that
pick now goes to Auto, so they now pin a Blackwell device, where NVFP4
still reaches those refusals.

Related suites (52 files: NVFP4, precision, prequant, families, image
and video backends and routes, auto policy, load progress, media
auto-switch): 3992 passed on head (on the last full run, six
timing-sensitive tests failed while the host was loaded and passed when
rerun alone, on head and on the merge base). Across the earlier
head-vs-merge-base runs (`4a45dbd03e`), the failing test IDs were the
same on both sides. Those were
`test_diffusion_load_progress.py::test_quantized_tensor_is_counted_only_after_success_and_hooks_restore[False]`,
which is flaky under xdist and passes alone, and a
`test_diffusion_load_cancel_platform_matrix.py` collection error from a
missing `_sparse_file` helper.

## GPU evidence (Colab L4 sm89 and A100 40GB sm80)

Every arm ran in a fresh process with `UNSLOTH_NVFP4_DIFFUSION=1`. Base
is the merge base `4a45dbd03e`. All runs used an explicit NVFP4 pick
unless the arm says "int8".

| card | model | arm | result | engaged | resolved.transformer_quant |
DiT layers | peak GiB | s/step |
|---|---|---|---|---|---|---|---|---|
| L4 | Z-Image-Turbo 1024, 8 steps | base | refused (409 at preflight) |
- | `'nvfp4' is not usable for family 'z-image' on this GPU` | - | - | -
|
| L4 | Z-Image-Turbo | head | renders | int8 | fell_back, "NVFP4 needs a
Blackwell GPU; using INT8; seeded from the hosted checkpoint
...Z-Image-Turbo-INT8-ConvRot.safetensors" | ConvRotLinear 239 | 14.84 |
0.746 |
| L4 | Z-Image-Turbo | head, kill switch | refused, same text as base |
- | - | - | - | - |
| L4 | Z-Image-Turbo | head, explicit int8 | renders | int8 | applied,
same hosted file | ConvRotLinear 239 | 14.84 | 0.755 |
| L4 | Qwen-Image-2.1-Turbo 1024, 8 steps | base | refused (409 at
preflight) | - | `'nvfp4' is not usable for family 'qwen-image-2.1'` | -
| - | - |
| L4 | Qwen-Image-2.1-Turbo | head | renders | int8 | fell_back, seeded
from ...Qwen-Image-2.1-Turbo-INT8-ConvRot.safetensors | ConvRotLinear
224 | 17.29 | 0.823 |
| L4 | Qwen-Image-2.1-Turbo | head, kill switch | refused, same text as
base | - | - | - | - | - |
| L4 | Qwen-Image-2.1-Turbo | head, explicit int8 | renders | int8 |
applied | ConvRotLinear 224 | 17.29 | 0.831 |
| A100-40 | Z-Image-Turbo | base / head kill switch | refused, same text
| - | - | - | - | - |
| A100-40 | Z-Image-Turbo | head | renders | int8 | fell_back, hosted
INT8 ConvRot | ConvRotLinear 239 | 16.23 | 0.233 |
| A100-40 | Z-Image-Turbo | head, explicit int8 | renders | int8 |
applied | ConvRotLinear 239 | 16.23 | 0.226 |
| A100-40 | LTX-2.5 NVFP4 distilled file, 768x512x49, 8 steps | base |
renders | None (packed W4A16) | "not engaged (dense bf16 DiT loaded)" |
PackedBlockLinear 1176 | 23.26 | 1.061 |
| A100-40 | LTX-2.5 NVFP4 file | head | renders | int8 | fell_back,
"NVFP4 needs a Blackwell GPU; using INT8 from
Lightricks/LTX-2.5-Diffusers instead of
diffusion_models/ltx-2.5-22b-distilled-transformer-nvfp4.safetensors",
`replaced: nvfp4:...` | NativeWeightOnlyLinear 480 (W8A8, g256 ConvRot)
| 30.93 | 1.086 |
| A100-40 | LTX-2.5 NVFP4 file | head, kill switch | renders, same as
base | None | same as base | PackedBlockLinear 1176 | 23.26 | 1.050 |
| A100-40 | LTX-2.5-Diffusers pipeline | head, explicit int8 | renders |
int8 | applied | NativeWeightOnlyLinear 480 | 30.93 | 1.081 |

- Each head NVFP4 arm logged exactly one `diffusion.nvfp4_route:` line,
and base, kill-switch and int8 arms logged none.
- No arm requested an NVFP4 URL from the Hub.
- Each head NVFP4 arm has the same artifact, layer census and render
statistics as the explicit int8 arm, so it is the normal INT8
resolution.
- The kill switch matches base byte for byte on the refusal text, and on
the LTX layer census, peak VRAM and render statistics.
- s/step is one steady image or clip per arm with no A/A repeats, so
treat it as indicative, not a speed claim.

These runs used head `599d6ed542`. The head arms were re-run on
`b01df131b`, after the reworked checkpoint-replacement rules, device
read and decision order, and matched exactly:

- L4 Z-Image-Turbo, head NVFP4: int8, the same hosted INT8 ConvRot file,
the same render statistics.
- L4 Z-Image-Turbo, kill switch: the same refusal text as base.
- A100-40 LTX-2.5 file, head NVFP4: int8 and `replaced`, with the INFO
line `diffusion.nvfp4_route:
diffusion_models/ltx-2.5-22b-distilled-transformer-nvfp4.safetensors ->
Lightricks/LTX-2.5-Diffusers (INT8) on nvidia sm_80`.
- A100-40 LTX-2.5 file, kill switch: identical to base
(PackedBlockLinear 1176, 23.26 GiB).

The commits after that only add the training-active guard on the device
read and trim comments.

**Not proven on hardware:**
- Blackwell (no Blackwell card was available for this run). That path is
covered by CPU tests, which show every sm >= 10 request comes back as
the same object with no reroute and no annotation.
- T4 and the text-encoder NVFP4 pick were not run on a GPU.
- The HTTP routes were exercised on CPU only. The GPU arms used
`begin_load`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant