Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: nvfp4 safetensors twins: converter 0-dim compare, refuse a twin the installed torchao cannot unflatten (#15977)

Daniel Han1724d98e5669
diff --git a/scripts/convert_prequant_to_safetensors.py b/scripts/convert_prequant_to_safetensors.py
index d1c84fd48b0..ffdaa290a7b 100644
--- a/scripts/convert_prequant_to_safetensors.py
+++ b/scripts/convert_prequant_to_safetensors.py
@@ -140,10 +140,11 @@ def _same(a, b) -> bool:
if isinstance(a, torch.Tensor) and isinstance(b, torch.Tensor):
if a.dtype != b.dtype or tuple(a.shape) != tuple(b.shape):
return False
- # Raw bytes, not torch.equal: -0.0 == 0.0 and NaN != NaN would otherwise decide.
+ # Raw bytes, not torch.equal: -0.0 == 0.0 and NaN != NaN would otherwise decide. Flattened first:
+ # a 0-dim tensor (nvfp4's per-tensor scale) cannot be viewed as bytes of another element size.
return a.numel() == 0 or torch.equal(
- a.detach().contiguous().cpu().view(torch.uint8),
- b.detach().contiguous().cpu().view(torch.uint8),
+ a.detach().contiguous().cpu().reshape(-1).view(torch.uint8),
+ b.detach().contiguous().cpu().reshape(-1).view(torch.uint8),
)
if isinstance(a, tuple) and isinstance(b, tuple):
return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b, strict = True))
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index 6686bc6313b..073105e71ca 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -207,11 +207,12 @@ def _register_prequant_safe_globals() -> bool:
def restricted_prequant_load_supported(
scheme: Optional[str] = None, filename: Optional[str] = None
) -> bool:
- """Per scheme (torchao retires int8 constructors before fp8); with a safetensors filename, answer for that file, which needs no allowlist."""
- from .prequant_safetensors import is_safetensors_checkpoint, safetensors_prequant_supported
+ """Per scheme (torchao retires int8 constructors before fp8); with a safetensors filename, answer for that file, which needs no allowlist
+ but does need a torchao that can rebuild the scheme's subclass (0.16 cannot rebuild nvfp4 / mxfp8)."""
+ from .prequant_safetensors import is_safetensors_checkpoint, safetensors_scheme_supported
if is_safetensors_checkpoint(filename):
- return safetensors_prequant_supported()
+ return safetensors_scheme_supported(scheme)
if not _register_prequant_safe_globals():
return False
key = (scheme or "").strip().lower()
diff --git a/studio/backend/core/inference/prequant_safetensors.py b/studio/backend/core/inference/prequant_safetensors.py
index 0fd97f90274..ec15b0991b3 100644
--- a/studio/backend/core/inference/prequant_safetensors.py
+++ b/studio/backend/core/inference/prequant_safetensors.py
@@ -86,6 +86,40 @@ def safetensors_prequant_supported() -> bool:
return True
+# The torchao weight subclass a scheme's safetensors file is rebuilt into, for schemes torchao added to its
+# safetensors allowlist after the 0.16 floor (0.16 lists neither; 0.17 lists both). fp8 / int8 are in every
+# release at the floor, so they are not listed here.
+_SCHEME_SUBCLASS = {"nvfp4": "NVFP4Tensor", "mxfp8": "MXTensor"}
+
+
+def _torchao_safetensors_subclasses() -> Optional[frozenset]:
+ """Subclass names this torchao's safetensors unflatten can rebuild; None when it cannot be read."""
+ try:
+ from torchao.prototype.safetensors import safetensors_utils
+ except Exception: # noqa: BLE001 - module moved or absent: the feature import elsewhere decides
+ return None
+ names = getattr(safetensors_utils, "ALLOWED_TENSORS_SUBCLASSES", None)
+ if not isinstance(names, (list, tuple, set, frozenset)):
+ return None
+ return frozenset(str(n) for n in names)
+
+
+def safetensors_scheme_supported(scheme: Optional[str] = None) -> bool:
+ """Whether this install can rebuild a ``scheme`` safetensors pre-quant checkpoint.
+
+ torchao 0.16 ships the flatten helpers but cannot unflatten ``NVFP4Tensor`` / ``MXTensor``
+ ("Unsupported tensor type"), so answering the scheme-free question would pick the twin over a
+ loadable ``.pt`` and then fail the read. An unreadable allowlist keeps the scheme-free answer.
+ """
+ if not safetensors_prequant_supported():
+ return False
+ wanted = _SCHEME_SUBCLASS.get((scheme or "").strip().lower())
+ if wanted is None:
+ return True
+ names = _torchao_safetensors_subclasses()
+ return names is None or wanted in names
+
+
def plain_safetensors_supported() -> bool:
"""The layerwise-cast encoder format stores plain tensors, without torchao subclasses."""
try:
diff --git a/studio/backend/tests/test_prequant_native.py b/studio/backend/tests/test_prequant_native.py
index 2998502c1ec..21ee61ffc1a 100644
--- a/studio/backend/tests/test_prequant_native.py
+++ b/studio/backend/tests/test_prequant_native.py
@@ -683,6 +683,66 @@ def test_the_converter_writes_a_text_encoder_with_tied_weights(tmp_path):
)
+def _nvfp4_tensor(seed = 0, act_scale = None):
+ nv = pytest.importorskip("torchao.prototype.mx_formats.nvfp4_tensor")
+ g = torch.Generator().manual_seed(seed)
+ w = torch.randn(128, 64, generator = g).to(torch.bfloat16)
+ return nv.NVFP4Tensor.to_nvfp4(
+ w,
+ per_tensor_scale = nv.per_tensor_amax_to_scale(w.abs().max()),
+ is_swizzled_scales = True,
+ act_per_tensor_scale = act_scale,
+ act_quant_kwargs = nv.QuantizeTensorToNVFP4Kwargs(is_swizzled_scales = True),
+ )
+
+
+def test_the_converters_comparison_takes_a_0_dim_scale():
+ """nvfp4 carries 0-dim fp32 per-tensor scales; viewing those as bytes used to raise mid-conversion."""
+ conv = _converter()
+ one = torch.tensor(0.5)
+ assert conv.compare_state_dicts({"s": one}, {"s": one.clone()}) == []
+ assert conv.compare_state_dicts({"s": torch.tensor(0.0)}, {"s": torch.tensor(-0.0)}) == ["s"]
+ w = _nvfp4_tensor()
+ assert conv.compare_state_dicts({"a.w": w}, {"a.w": _nvfp4_tensor()}) == []
+ assert conv.compare_state_dicts({"a.w": w}, {"a.w": _nvfp4_tensor(seed = 1)}) == ["a.w"]
+ assert conv.compare_state_dicts(
+ {"a.w": w}, {"a.w": _nvfp4_tensor(act_scale = torch.tensor(0.25))}
+ ) == ["a.w"]
+
+
+@needs_helpers
[email protected]("act_scale", [None, 0.25])
+def test_the_converter_writes_a_bit_identical_nvfp4_artifact(tmp_path, act_scale):
+ nv = pytest.importorskip("torchao.prototype.mx_formats.nvfp4_tensor")
+ weight = _nvfp4_tensor(act_scale = None if act_scale is None else torch.tensor(act_scale))
+ src = tmp_path / "Model-NVFP4.pt"
+ torch.save(
+ {
+ "format": pq.PREQUANT_FORMAT,
+ "metadata": {"scheme": "nvfp4", "component": "transformer"},
+ "state_dict": {
+ "blk.proj.weight": weight,
+ "blk.proj.bias": torch.randn(128, dtype = torch.bfloat16),
+ },
+ },
+ str(src),
+ )
+ conv = _converter()
+ rec = conv.convert(str(src), str(tmp_path / "out"), repo = None, revision = None, sha = None)
+ assert rec["verified_bit_identical"] and rec["scheme"] == "nvfp4" and rec["quantized"] == 1
+ a = pq._load_prequant_checkpoint(str(src), map_location = "cpu")["state_dict"]
+ b = pq._load_prequant_checkpoint(rec["dst"], map_location = "cpu", mmap = True)["state_dict"]
+ got, want = b["blk.proj.weight"], a["blk.proj.weight"]
+ assert type(got) is nv.NVFP4Tensor
+ for attr in ("qdata", "scale", "per_tensor_scale", "act_per_tensor_scale"):
+ x, y = getattr(got, attr), getattr(want, attr)
+ assert (x is None) == (y is None) and (x is None or conv._same(x, y)), attr
+ for attr in ("block_size", "orig_dtype", "is_swizzled_scales", "use_triton_kernel"):
+ assert getattr(got, attr) == getattr(want, attr), attr
+ assert repr(got.act_quant_kwargs) == repr(want.act_quant_kwargs)
+ assert conv.compare_state_dicts(a, b) == []
+
+
def test_the_converters_comparison_sees_every_kind_of_difference():
conv = _converter()
w = _int8_tensor()
diff --git a/studio/backend/tests/test_prequant_prefer_cached_pickle.py b/studio/backend/tests/test_prequant_prefer_cached_pickle.py
index 7151329f831..21571e96f25 100644
--- a/studio/backend/tests/test_prequant_prefer_cached_pickle.py
+++ b/studio/backend/tests/test_prequant_prefer_cached_pickle.py
@@ -766,3 +766,74 @@ def test_a_cached_trailing_fp8_twin_is_used_before_an_uncached_own_file(hub):
hub.downloads.clear()
assert _resolve(fp8) == hub.cached[(REPO, "Model-FP8.safetensors")]
assert hub.fetched == ["Model-FP8.safetensors"]
+
+
+# nvfp4: the same preference holds for the hosted NVFP4 repos (image families resolve the twin first).
+NV_REPO = "unsloth/Z-Image-Turbo-NVFP4"
+NV_ST, NV_PT = "Z-Image-Turbo-NVFP4.safetensors", "Z-Image-Turbo-NVFP4.pt"
+# Captured before any fixture stubs it: the nvfp4 cases ask the install's real readability question.
+_REAL_LOAD_SUPPORTED = pq.restricted_prequant_load_supported
+
+
+def nv_hub(hub, monkeypatch):
+ from core.inference import diffusion_nvfp4_flag
+
+ monkeypatch.setenv(diffusion_nvfp4_flag.NVFP4_DIFFUSION_ENV, "1")
+ monkeypatch.setattr(pq, "restricted_prequant_load_supported", _REAL_LOAD_SUPPORTED)
+ if not (_REAL_LOAD_SUPPORTED("nvfp4", NV_ST) and _REAL_LOAD_SUPPORTED("nvfp4", NV_PT)):
+ pytest.skip("this install cannot read nvfp4 checkpoints")
+ hub.hosted = {NV_ST, NV_PT}
+ return hub
+
+
+def _nv_source():
+ """The chain Studio resolves for Z-Image's hosted NVFP4 repo, not a hand-written one."""
+ from core.inference.diffusion_families import detect_family
+
+ fam = detect_family("Tongyi-MAI/Z-Image-Turbo")
+ source = pq.resolve_prequant_source(fam, "nvfp4")
+ assert source.location == NV_REPO
+ assert pq.candidate_filenames_of(source)[:2] == (NV_ST, NV_PT)
+ return source
+
+
+def _nv_resolve(source, **kw):
+ return pq._resolve_checkpoint_path(source, None, None, scheme = "nvfp4", **kw)
+
+
+def test_nvfp4_cached_pickle_is_kept(nv_hub, caplog):
+ nv_hub.cache(NV_PT, NV_REPO)
+ caplog.set_level("INFO")
+ assert _nv_resolve(_nv_source()) == nv_hub.cached[(NV_REPO, NV_PT)]
+ assert NV_ST not in nv_hub.fetched
+ assert f"using the cached {NV_PT}" in caplog.text
+
+
+def test_nvfp4_cached_pickle_offline(nv_hub):
+ nv_hub.cache(NV_PT, NV_REPO)
+ assert _nv_resolve(_nv_source(), local_files_only = True) == nv_hub.cached[(NV_REPO, NV_PT)]
+ assert nv_hub.downloads == [(NV_PT, True)]
+
+
+def test_nvfp4_new_user_downloads_only_the_safetensors(nv_hub):
+ assert _nv_resolve(_nv_source()) == nv_hub.cached[(NV_REPO, NV_ST)]
+ assert nv_hub.fetched == [NV_ST]
+
+
+def test_nvfp4_pickle_only_repo_still_loads_the_pickle(nv_hub):
+ nv_hub.hosted = {NV_PT}
+ assert _nv_resolve(_nv_source()) == nv_hub.cached[(NV_REPO, NV_PT)]
+ assert nv_hub.fetched == [NV_ST, NV_PT]
+
+
+def test_nvfp4_torchao_without_nvfp4_unflatten_downloads_the_pickle(nv_hub, monkeypatch):
+ """torchao 0.16: the twin is hosted but unreadable here, so the hosted .pt is the only download."""
+ utils = pytest.importorskip("torchao.prototype.safetensors.safetensors_utils")
+ monkeypatch.setattr(
+ utils,
+ "ALLOWED_TENSORS_SUBCLASSES",
+ [n for n in utils.ALLOWED_TENSORS_SUBCLASSES if n not in ("NVFP4Tensor", "MXTensor")],
+ )
+ assert _nv_resolve(_nv_source()) == nv_hub.cached[(NV_REPO, NV_PT)]
+ assert nv_hub.fetched == [NV_PT]
diff --git a/studio/backend/tests/test_prequant_safetensors.py b/studio/backend/tests/test_prequant_safetensors.py
index b6c7125e6c3..1eff12bff6d 100644
--- a/studio/backend/tests/test_prequant_safetensors.py
+++ b/studio/backend/tests/test_prequant_safetensors.py
@@ -77,6 +77,55 @@ def test_safetensors_gate_still_needs_torchao_helpers(monkeypatch):
assert pq.restricted_prequant_load_supported("fp8", "Model-FP8.safetensors") is False
+# torchao 0.16's safetensors allowlist, verbatim: flatten helpers present, no NVFP4Tensor / MXTensor.
+_TORCHAO_016_SUBCLASSES = [
+ "Float8Tensor",
+ "Int4Tensor",
+ "Int4TilePackedTo4dTensor",
+ "IntxUnpackedToInt8Tensor",
+ "Int8Tensor",
+ "Int4PlainInt32Tensor",
+]
+
+
[email protected](("scheme", "name"), [("nvfp4", "Model-NVFP4"), ("mxfp8", "Model-MXFP8")])
+def test_a_torchao_that_cannot_unflatten_the_scheme_reads_its_safetensors_as_unreadable(
+ monkeypatch, scheme, name
+):
+ """torchao 0.16 has the helpers but raises 'Unsupported tensor type: NVFP4Tensor' on unflatten:
+ the twin must be skipped for the .pt, not picked and then failed into a dense download."""
+ utils = pytest.importorskip("torchao.prototype.safetensors.safetensors_utils")
+ monkeypatch.setattr(pq, "_register_prequant_safe_globals", lambda: True)
+ monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: True)
+ monkeypatch.setattr(utils, "ALLOWED_TENSORS_SUBCLASSES", list(_TORCHAO_016_SUBCLASSES))
+ assert pq.restricted_prequant_load_supported(scheme, f"{name}.safetensors") is False
+ assert pq.restricted_prequant_load_supported("fp8", "Model-FP8.safetensors") is True
+ assert pq.restricted_prequant_load_supported("int8", "Model-INT8.safetensors") is True
+ assert pq.restricted_prequant_load_supported(None, f"{name}.safetensors") is True
+ monkeypatch.setattr(
+ utils, "ALLOWED_TENSORS_SUBCLASSES", [*_TORCHAO_016_SUBCLASSES, "MXTensor", "NVFP4Tensor"]
+ )
+ assert pq.restricted_prequant_load_supported(scheme, f"{name}.safetensors") is True
+
+
+def test_an_unreadable_torchao_allowlist_keeps_the_scheme_free_answer(monkeypatch):
+ monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: True)
+ monkeypatch.setattr(ps, "_torchao_safetensors_subclasses", lambda: None)
+ assert ps.safetensors_scheme_supported("nvfp4") is True
+ monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: False)
+ assert ps.safetensors_scheme_supported("nvfp4") is False
+
+
+def test_the_installed_torchao_answers_the_nvfp4_question():
+ """Not a stub: the allowlist this install really ships decides (0.17+ lists NVFP4Tensor)."""
+ utils = pytest.importorskip("torchao.prototype.safetensors.safetensors_utils")
+ if not ps.safetensors_prequant_supported():
+ pytest.skip("no safetensors pre-quant support on this install")
+ expected = "NVFP4Tensor" in utils.ALLOWED_TENSORS_SUBCLASSES
+ assert ps.safetensors_scheme_supported("nvfp4") is expected
+ assert pq.restricted_prequant_load_supported("nvfp4", "Model-NVFP4.safetensors") is expected
+
+
def test_usable_source_survives_a_pickle_only_refusal(monkeypatch):
"""Resolve names before the gate, or a safetensors-primary pre-quant is invisible to memory planning."""
fam = _family(