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.

31.0 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Hermetic dispatch tests check routing only; round-trip tests need the real torchao and safetensors."""

from __future__ import annotations

import json
import os
import sys

import pytest

# A sibling test may put this directory on sys.path and import this file top-level.
try:
    from ._torchao_installed import needs_torchao
except ImportError:
    from _torchao_installed import needs_torchao

import core.inference.diffusion_prequant as pq
import core.inference.prequant_safetensors as ps
from core.inference.diffusion_families import DiffusionFamily


def _family(**overrides) -> DiffusionFamily:
    return DiffusionFamily(
        **{
            "name": "test-fam",
            "base_repo": "org/base",
            "pipeline_class": "TestPipeline",
            "transformer_class": "TestTransformer",
            **overrides,
        }
    )


@pytest.mark.parametrize(
    ("name", "expected"),
    [
        ("Model-FP8.safetensors", True),
        ("Model-FP8.SAFETENSORS", True),
        ("/abs/path/to/Model-FP8.safetensors", True),
        ("Model-FP8.pt", False),
        ("transformer_fp8.pt", False),
        # Dispatch is on the extension asked of the Hub, not a substring or sniff.
        ("safetensors-notes.pt", False),
        (None, False),
        ("", False),
    ],
)
def test_is_safetensors_checkpoint(name, expected):
    assert ps.is_safetensors_checkpoint(name) is expected


def test_load_dispatches_on_extension(monkeypatch):
    """The two readers are picked by name, and neither is consulted for the other's file."""
    calls = []
    monkeypatch.setattr(
        ps, "load_prequant_safetensors", lambda path, **kw: calls.append(("safetensors", path))
    )
    monkeypatch.setattr(
        pq, "_torch_load_prequant", lambda path, **kw: calls.append(("pickle", path))
    )
    pq._load_prequant_checkpoint("/x/Model-FP8.safetensors")
    pq._load_prequant_checkpoint("/x/Model-FP8.pt", map_location = "cpu")
    assert calls == [("safetensors", "/x/Model-FP8.safetensors"), ("pickle", "/x/Model-FP8.pt")]


def test_safetensors_needs_no_pickle_allowlist(monkeypatch):
    """A safetensors checkpoint names no constructors, so the pickle gate must not refuse it."""
    monkeypatch.setattr(pq, "_register_prequant_safe_globals", lambda: False)
    monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: True)

    assert pq.restricted_prequant_load_supported("fp8") is False
    assert pq.restricted_prequant_load_supported("fp8", "Model-FP8.pt") is False
    assert pq.restricted_prequant_load_supported("fp8", "Model-FP8.safetensors") is True


def test_safetensors_gate_still_needs_torchao_helpers(monkeypatch):
    """The other direction: no flatten/unflatten means no safetensors load, so say so up front
    rather than letting planning drop the dense shards for a file nothing can read."""
    monkeypatch.setattr(pq, "_register_prequant_safe_globals", lambda: True)
    monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: False)
    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",
]


@pytest.mark.parametrize(("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(
        prequant_repos = (("fp8", "org/model-fp8"),),
        prequant_filenames = (("fp8", "Model-FP8.safetensors"),),
    )
    monkeypatch.setattr(pq, "_register_prequant_safe_globals", lambda: False)
    monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: True)

    src = pq.usable_prequant_source(fam, "fp8")
    assert src is not None
    assert src.filename == "Model-FP8.safetensors"


def test_usable_source_still_refused_when_nothing_is_readable(monkeypatch):
    """A derived <Model>-<SCHEME>.safetensors name is a guess, not evidence that a readable source
    exists."""
    fam = _family(prequant_repos = (("fp8", "org/model-fp8"),))
    monkeypatch.setattr(pq, "_register_prequant_safe_globals", lambda: False)
    monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: True)
    monkeypatch.setattr(pq, "cached_checkpoint_path", lambda source, **kw: None)
    assert pq.usable_prequant_source(fam, "fp8") is None


def test_a_cached_safetensors_artifact_is_evidence_enough(monkeypatch):
    """The other side of that guard: once the file is actually THERE, the pickle-less install may
    plan for it. A cached candidate is evidence, exactly as a family-declared name is."""
    fam = _family(prequant_repos = (("fp8", "org/model-fp8"),))
    monkeypatch.setattr(pq, "_register_prequant_safe_globals", lambda: False)
    monkeypatch.setattr(ps, "safetensors_prequant_supported", lambda: True)
    monkeypatch.setattr(
        pq, "cached_checkpoint_path", lambda source, **kw: "/cache/model-FP8.safetensors"
    )
    src = pq.usable_prequant_source(fam, "fp8")
    assert src is not None and src.filename == "model-FP8.safetensors"


def test_the_derived_chain_puts_safetensors_first_and_keeps_the_pickles(monkeypatch):
    """Safetensors is preferred, and a .pt-only repo still resolves both names."""
    fam = _family(prequant_repos = (("fp8", "unsloth/Model-FP8"),))
    src = pq.resolve_prequant_source(fam, "fp8")
    assert src.candidate_filenames == (
        "Model-FP8.safetensors",
        "Model-FP8.pt",
        "Model-FP8-ComfyUI.safetensors",
        "transformer_fp8.pt",
    )


def test_local_scheme_probe_reads_the_header_only(monkeypatch, tmp_path):
    """The scheme probe reads only the safetensors header, never the pickle reader."""
    path = tmp_path / "local-FP8.safetensors"
    path.write_bytes(b"not really safetensors")

    def _boom(*a, **kw):
        raise AssertionError("the pickle reader was used for a safetensors artifact")

    monkeypatch.setattr(pq, "_torch_load_prequant", _boom)
    monkeypatch.setattr(
        ps,
        "read_prequant_header",
        lambda p: {"format": pq.PREQUANT_FORMAT, "metadata": {"scheme": "int8"}},
    )
    assert pq.local_prequant_scheme(str(path)) == "int8"


def test_local_scheme_probe_rejects_a_foreign_format(monkeypatch, tmp_path):
    path = tmp_path / "other.safetensors"
    path.write_bytes(b"x")
    monkeypatch.setattr(
        ps,
        "read_prequant_header",
        lambda p: {"format": "someone_elses_v1", "metadata": {"scheme": "int8"}},
    )
    assert pq.local_prequant_scheme(str(path)) is None


def test_undotted_keys_are_refused_before_a_file_exists():
    """torchao's unflatten splits every key on '.', so a root-level tensor writes fine and can
    never be read back. Refuse at build time, naming the keys."""
    assert ps.unsupported_state_dict_keys({"a.weight": 1, "pos_embed": 2}) == ["pos_embed"]
    assert ps.unsupported_state_dict_keys({"a.weight": 1}) == []


def _real_libs():
    pytest.importorskip("torch")
    pytest.importorskip("safetensors")
    pytest.importorskip("torchao")
    if not ps.safetensors_prequant_supported():
        pytest.skip("torchao is too old for flatten/unflatten_tensor_state_dict")


def test_plain_tensor_round_trip(tmp_path):
    """Plain tensors (the text-encoder artifact's whole state dict) survive with their metadata."""
    _real_libs()
    import torch

    sd = {"enc.layer.weight": torch.ones(4, 4), "enc.layer.bias": torch.zeros(4)}
    meta = {"scheme": "fp8", "base_model_id": "org/base", "min_features": 512}
    path = str(tmp_path / "te.safetensors")
    ps.save_prequant_safetensors(path, fmt = pq.PREQUANT_FORMAT, state_dict = sd, metadata = meta)

    header = ps.read_prequant_header(path)
    assert header == {"format": pq.PREQUANT_FORMAT, "metadata": meta}

    ckpt = ps.load_prequant_safetensors(path)
    assert ckpt["format"] == pq.PREQUANT_FORMAT
    assert ckpt["metadata"] == meta
    assert set(ckpt["state_dict"]) == set(sd)
    for key, value in sd.items():
        assert torch.equal(ckpt["state_dict"][key], value)


def test_plain_reader_matches_real_writer_without_torchao(tmp_path, monkeypatch):
    _real_libs()
    import torch
    from core.inference.diffusion_te_prequant import TE_PREQUANT_FORMAT

    state = {
        "encoder.weight": torch.arange(8).reshape(2, 4).to(torch.float8_e4m3fn),
        "encoder.bias": torch.zeros(2),
        "buffer": torch.ones(1),
    }
    metadata = {"scheme": "fp8", "component": "text_encoder", "base_model_id": "org/base"}
    path = str(tmp_path / "encoder.safetensors")
    ps.save_prequant_safetensors(path, fmt = TE_PREQUANT_FORMAT, state_dict = state, metadata = metadata)
    shared = ps.load_prequant_safetensors(path)

    monkeypatch.setattr(ps, "_torchao_helpers", lambda: None)
    monkeypatch.setitem(sys.modules, "torchao", None)
    plain = ps.load_plain_prequant_safetensors(path)
    assert plain["format"] == shared["format"] == TE_PREQUANT_FORMAT
    assert plain["metadata"] == shared["metadata"] == metadata
    assert set(plain["state_dict"]) == set(shared["state_dict"]) == set(state)
    for name, expected in state.items():
        for actual in (plain["state_dict"][name], shared["state_dict"][name]):
            assert actual.dtype == expected.dtype
            assert torch.equal(actual.float(), expected.float())


def test_header_is_readable_as_a_torchao_checkpoint(tmp_path):
    """torchao metadata is already JSON; encoding it again writes a header is_metadata_torchao rejects."""
    _real_libs()
    import torch
    from safetensors import safe_open
    from torchao.prototype.safetensors.safetensors_utils import is_metadata_torchao

    path = str(tmp_path / "x.safetensors")
    ps.save_prequant_safetensors(
        path,
        fmt = pq.PREQUANT_FORMAT,
        state_dict = {"enc.layer.weight": torch.ones(2, 2)},
        metadata = {"scheme": "fp8"},
    )
    with safe_open(path, framework = "pt") as handle:
        raw = handle.metadata() or {}

    assert is_metadata_torchao(raw)
    assert raw[ps.UNSLOTH_FORMAT_KEY] == pq.PREQUANT_FORMAT
    assert json.loads(raw[ps.UNSLOTH_METADATA_KEY]) == {"scheme": "fp8"}
    assert "tensor_names" in raw


def test_truncated_checkpoint_is_named_not_silently_partial(tmp_path):
    """A file whose header does not account for every tensor is refused with the tensor named,
    rather than reaching load_state_dict as a bare missing-key error."""
    _real_libs()
    import torch
    from safetensors import safe_open
    from safetensors.torch import save_file

    path = str(tmp_path / "x.safetensors")
    ps.save_prequant_safetensors(
        path,
        fmt = pq.PREQUANT_FORMAT,
        state_dict = {"enc.layer.weight": torch.ones(2, 2)},
        metadata = {"scheme": "fp8"},
    )
    with safe_open(path, framework = "pt") as handle:
        raw = dict(handle.metadata() or {})
        tensors = {k: handle.get_tensor(k) for k in handle.keys()}

    tensors["enc.layer.stray"] = torch.zeros(2)
    stray = str(tmp_path / "stray.safetensors")
    save_file(tensors, stray, metadata = raw)

    with pytest.raises(ValueError, match = "does not account for"):
        ps.load_prequant_safetensors(stray)


@pytest.mark.parametrize("scheme", ["fp8", "int8"])
def test_quantized_round_trip_is_exact(tmp_path, scheme):
    """The case the format exists for: torchao weight subclasses, reconstructed bit for bit and
    accepted by ``load_state_dict(strict=True)`` on a module quantized the same way."""
    _real_libs()
    import torch

    if not torch.cuda.is_available():
        pytest.skip("fp8 / int8 quantization needs CUDA")
    from torchao.quantization import quantize_

    from core.inference.diffusion_transformer_quant import _make_quant_config, make_filter_fn

    def build():
        module = (
            torch.nn.Sequential(
                torch.nn.Linear(1024, 1024, bias = False),
                torch.nn.Linear(1024, 1024, bias = True),
            )
            .cuda()
            .bfloat16()
        )
        quantize_(module, _make_quant_config(scheme), filter_fn = make_filter_fn(512))
        return module

    source = build()
    state = {
        k: (v.detach().to("cpu") if hasattr(v, "detach") else v)
        for k, v in source.state_dict().items()
    }
    path = str(tmp_path / f"{scheme}.safetensors")
    try:
        ps.save_prequant_safetensors(
            path, fmt = pq.PREQUANT_FORMAT, state_dict = state, metadata = {"scheme": scheme}
        )
    except ValueError as exc:
        # torchao too old to quantise into a flattenable subclass (int8 < 0.18) must say so; then skip.
        assert "torchao >= 0.18" in str(exc), exc
        pytest.skip(f"this torchao cannot write {scheme} to safetensors: {exc}")

    loaded = ps.load_prequant_safetensors(path)["state_dict"]
    assert set(loaded) == set(state)
    for key, value in state.items():
        got, want = loaded[key], value
        if hasattr(want, "dequantize"):
            assert type(got) is type(want)
            got, want = got.dequantize(), want.dequantize()
        assert torch.equal(got, want)

    build().load_state_dict(loaded, strict = True, assign = True)


def test_the_windows_rocm_torchao_stub_is_not_safetensors_support(monkeypatch):
    """The torchao Windows ROCm stub binds fake callables, so importing them is not safetensors support."""
    import core._torchao_stub as stub
    from core.inference import prequant_safetensors as ps
    from core.inference.diffusion_prequant import restricted_prequant_load_supported

    for name in [k for k in list(sys.modules) if k == "torchao" or k.startswith("torchao.")]:
        monkeypatch.delitem(sys.modules, name, raising = False)
    monkeypatch.setattr(stub, "_is_windows_rocm", lambda: True)
    stub.install_torchao_windows_rocm_stub()
    assert stub.is_stubbed("torchao"), "the stub did not install, so this proves nothing"
    from torchao.prototype.safetensors.safetensors_support import (  # noqa: F401
        unflatten_tensor_state_dict,
    )

    assert ps._torchao_helpers() is None
    assert ps.safetensors_prequant_supported() is False
    assert restricted_prequant_load_supported("fp8", "Model-FP8.safetensors") is False
    assert restricted_prequant_load_supported("fp8", "Model-FP8.pt") is False


@needs_torchao
def test_a_scheme_this_torchao_cannot_flatten_is_reported_before_the_build(monkeypatch):
    """Importing helpers proves nothing; torchao 0.17 int8 cannot flatten, so report it before building."""
    import torchao.quantization as tq
    from core.inference import prequant_safetensors as ps

    quantized: list = []
    monkeypatch.setattr(tq, "quantize_", lambda mod, cfg, **kw: quantized.append(cfg))

    def _refuses(state_dict):
        raise ValueError("Unsupported tensor type: <class 'LinearActivationQuantizedTensor'>")

    monkeypatch.setattr(ps, "_torchao_helpers", lambda: (_refuses, object()))
    assert ps.scheme_is_flattenable("cfg") is False
    assert quantized == ["cfg"], "the probe must actually quantize, not guess from a version"

    monkeypatch.setattr(ps, "_torchao_helpers", lambda: (lambda sd: ({}, {}), object()))
    assert ps.scheme_is_flattenable("cfg") is True

    # An unrelated flatten failure is not evidence the scheme is unsupported.
    def _other(state_dict):
        raise ValueError("something else entirely")

    monkeypatch.setattr(ps, "_torchao_helpers", lambda: (_other, object()))
    assert ps.scheme_is_flattenable("cfg") is None

    def _boom(mod, cfg, **kw):
        raise RuntimeError("config needs CUDA")

    monkeypatch.setattr(tq, "quantize_", _boom)
    monkeypatch.setattr(ps, "_torchao_helpers", lambda: (_refuses, object()))
    assert ps.scheme_is_flattenable("cfg") is None

    monkeypatch.setattr(ps, "_torchao_helpers", lambda: None)
    assert ps.scheme_is_flattenable("cfg") is False


@needs_torchao
def test_the_real_installed_torchao_answers_the_int8_question(monkeypatch):
    """Not a mock: the probe against the torchao actually installed, whichever way it answers."""
    from core.inference.diffusion_transformer_quant import _make_quant_config
    from core.inference.prequant_safetensors import scheme_is_flattenable

    import torchao

    answer = scheme_is_flattenable(_make_quant_config("int8"))
    version = tuple(int(p) for p in torchao.__version__.split("+")[0].split(".")[:2])
    if version < (0, 18):
        assert answer is False, f"torchao {torchao.__version__} should refuse int8 flatten"
    else:
        assert answer is not False, f"torchao {torchao.__version__} should flatten int8"


@needs_torchao
def test_a_root_level_plain_tensor_round_trips_instead_of_failing_the_build(tmp_path):
    """Root-level plain tensors are split before flatten and restored after, so z-image builds survive."""
    torch = pytest.importorskip("torch")
    if not ps.safetensors_prequant_supported():
        pytest.skip("this install cannot write safetensors pre-quant checkpoints")

    state = {
        "blocks.0.linear.weight": torch.arange(16, dtype = torch.float32).reshape(4, 4),
        "x_pad_token": torch.tensor([1.0, 2.0, 3.0]),
        "cap_pad_token": torch.tensor([[4.0, 5.0]]),
    }
    assert ps.unsupported_state_dict_keys(state) == []

    path = str(tmp_path / "roots.safetensors")
    ps.save_prequant_safetensors(path, fmt = "fp8", state_dict = state, metadata = {"scheme": "fp8"})
    back = ps.load_prequant_safetensors(path)["state_dict"]

    assert set(back) == set(state)
    for key, value in state.items():
        assert torch.equal(back[key], value), key


def test_a_root_level_tensor_subclass_is_still_refused_up_front(monkeypatch):
    """The carry-alongside trick only works for PLAIN tensors: reconstructing a subclass is exactly
    the job of the flatten pair that cannot address a root key, so there is nothing to put it in."""
    torch = pytest.importorskip("torch")

    class _Subclass(torch.Tensor):
        pass

    state = {
        "blocks.0.linear.weight": torch.zeros(2, 2),
        "quantized_root": _Subclass(torch.zeros(2)),
    }
    assert ps.unsupported_state_dict_keys(state) == ["quantized_root"]


def test_a_field_a_newer_torchao_added_is_dropped_when_it_is_inert(monkeypatch):
    """Drop the inert reduce_range field torchao 0.18 added, since 0.17's constructor refuses it."""
    calls: list = []

    def _unflatten(tensors, header):
        calls.append(header)
        if "reduce_range" in header["w.weight"]:
            raise ValueError(
                "Failed to create instance of QuantizeTensorToInt8Kwargs: "
                "QuantizeTensorToInt8Kwargs.__init__() got an unexpected keyword argument "
                "'reduce_range'"
            )
        return {"w.weight": object()}, {}

    header = {
        "w.weight": json.dumps(
            {"_type": "Int8Tensor", "_data": {"reduce_range": False, "block_size": [1, 4]}}
        ),
        ps.UNSLOTH_FORMAT_KEY: "fp8_v1",
    }
    pruned = ps._header_without_unconstructible_fields(
        _unflatten, {}, header, path = "artifact.safetensors"
    )
    assert "reduce_range" not in pruned["w.weight"]
    assert json.loads(pruned["w.weight"])["_data"]["block_size"] == [1, 4]
    assert pruned[ps.UNSLOTH_FORMAT_KEY] == "fp8_v1"
    assert len(calls) == 2


def test_a_field_carrying_a_real_setting_is_refused_rather_than_dropped():
    """Dropping a field that is doing something would load the weights under settings the file did
    not ask for. A refusal keeps the dense fallback, which is merely slower."""

    def _unflatten(tensors, header):
        raise ValueError("unexpected keyword argument 'reduce_range'")

    header = {"w.weight": json.dumps({"_data": {"reduce_range": True}})}
    with pytest.raises(ValueError, match = "reduce_range"):
        ps._header_without_unconstructible_fields(
            _unflatten, {}, header, path = "artifact.safetensors"
        )


def test_an_all_zero_tensor_field_a_newer_torchao_added_is_dropped():
    torch = pytest.importorskip("torch")

    def _unflatten(tensors, header):
        if "zero_point" in json.loads(header["blk.w.weight"])["_tensor_data_names"]:
            raise ValueError(
                "Failed to create instance of Int8Tensor: Int8Tensor.__new__() got an "
                "unexpected keyword argument 'zero_point'"
            )
        return {"blk.w.weight": object()}, {}

    tensors = {
        "blk.w._weight_qdata": torch.zeros(2, 4, dtype = torch.int8),
        "blk.w._weight_scale": torch.ones(2, 1),
        "blk.w._weight_zero_point": torch.zeros(2, 1, dtype = torch.int8),
    }
    header = {
        "blk.w.weight": json.dumps(
            {
                "_type": "Int8Tensor",
                "_data": {},
                "_tensor_data_names": ["zero_point", "qdata", "scale"],
            }
        ),
        ps.UNSLOTH_FORMAT_KEY: "v1",
    }
    pruned = ps._header_without_unconstructible_fields(
        _unflatten, tensors, header, path = "artifact.safetensors"
    )
    assert json.loads(pruned["blk.w.weight"])["_tensor_data_names"] == ["qdata", "scale"]
    assert "blk.w._weight_zero_point" not in tensors
    assert pruned[ps.UNSLOTH_FORMAT_KEY] == "v1"


def test_a_non_zero_tensor_field_is_refused_rather_than_dropped():
    torch = pytest.importorskip("torch")

    def _unflatten(tensors, header):
        raise ValueError("unexpected keyword argument 'zero_point'")

    tensors = {"blk.w._weight_zero_point": torch.ones(2, 1, dtype = torch.int8)}
    header = {"blk.w.weight": json.dumps({"_data": {}, "_tensor_data_names": ["zero_point"]})}
    with pytest.raises(ValueError, match = "zero_point"):
        ps._header_without_unconstructible_fields(
            _unflatten, tensors, header, path = "artifact.safetensors"
        )


def test_a_missing_tensor_field_is_refused_rather_than_read_as_zero():
    torch = pytest.importorskip("torch")

    def _unflatten(tensors, header):
        raise ValueError("unexpected keyword argument 'zero_point'")

    names = json.dumps({"_data": {}, "_tensor_data_names": ["zero_point", "qdata", "scale"]})
    tensors = {
        "a.w._weight_zero_point": torch.zeros(2, 1, dtype = torch.int8),
        "b.w._weight_qdata": torch.zeros(2, 4, dtype = torch.int8),
        "b.w._weight_scale": torch.ones(2, 1),
    }
    header = {"a.w.weight": names, "b.w.weight": names}
    with pytest.raises(ValueError, match = "b.w._weight_zero_point"):
        ps._header_without_unconstructible_fields(
            _unflatten, tensors, header, path = "artifact.safetensors"
        )


def test_torchao_older_than_the_floor_is_not_safetensors_support(monkeypatch):
    assert ps._version_tuple("0.14.0") < ps.MIN_TORCHAO_VERSION
    assert ps._version_tuple("0.16.0+cu130") >= ps.MIN_TORCHAO_VERSION
    assert ps._version_tuple("0.19.0+git492be6c") >= ps.MIN_TORCHAO_VERSION
    assert ps._version_tuple(None) >= ps.MIN_TORCHAO_VERSION
    assert ps._version_tuple("dev") >= ps.MIN_TORCHAO_VERSION
    monkeypatch.setattr(ps, "_torchao_version", lambda: "0.14.0")
    assert ps._torchao_helpers() is None
    assert ps.safetensors_prequant_supported() is False


@pytest.fixture
def plain_checkpoint(tmp_path, monkeypatch):
    torch = pytest.importorskip("torch")
    save_file = pytest.importorskip("safetensors.torch").save_file
    monkeypatch.setattr(ps, "_torchao_helpers", lambda: None)

    def write(*, tensors = None, header = None):
        tensors = {"encoder.weight": torch.ones(2, 3)} if tensors is None else tensors
        metadata = {
            ps.UNSLOTH_FORMAT_KEY: "unsloth_prequant_text_encoder_state_dict_v1",
            ps.UNSLOTH_METADATA_KEY: json.dumps({"scheme": "fp8", "component": "text_encoder"}),
            "tensor_names": json.dumps(["encoder.weight"]),
            "encoder.weight": json.dumps({"_type": "Tensor"}),
        }
        metadata.update(header or {})
        path = str(tmp_path / "encoder.safetensors")
        save_file(tensors, path, metadata = metadata)
        return path

    return write


def test_plain_encoder_needs_no_torchao(plain_checkpoint):
    import core.inference.diffusion_te_prequant as te
    import torch

    path = plain_checkpoint(tensors = {"encoder.weight": torch.ones(2, 3).to(torch.float8_e4m3fn)})
    assert te.te_candidate_is_readable(path)
    assert not ps.safetensors_prequant_supported()
    loaded = ps.load_plain_prequant_safetensors(path)
    assert loaded["state_dict"]["encoder.weight"].dtype == torch.float8_e4m3fn
    assert torch.equal(loaded["state_dict"]["encoder.weight"].float(), torch.ones(2, 3))
    assert loaded["metadata"]["scheme"] == "fp8"


def _mapped(path):
    """Whether this process still maps ``path`` (Linux only; None elsewhere)."""
    if not sys.platform.startswith("linux"):
        return None
    real = os.path.realpath(path)
    with open("/proc/self/maps", encoding = "utf-8") as fh:
        return any(line.rstrip().endswith(real) for line in fh)


def test_a_buffer_repointed_at_its_pinned_copy_releases_the_file_mapping(plain_checkpoint):
    """Streaming re-points each host weight at its pinned copy with ``.data =``. A view keeps its base through that,
    so a buffer loaded straight from the file kept the whole safetensors mapping alive for the model's life (8.7 GiB
    for Qwen-Image-2.1's int8 encoder; on Windows the open mapping also blocks deleting the file)."""
    import gc

    import torch

    path = plain_checkpoint(
        tensors = {"encoder.weight": torch.arange(4096 * 64, dtype = torch.float32).reshape(4096, 64)}
    )
    module = torch.nn.Module()
    module.register_buffer(
        "weight", ps.load_plain_prequant_safetensors(path)["state_dict"]["encoder.weight"]
    )
    expected = module.weight.clone()
    assert _mapped(path) in (True, None)
    # the pinned copy, as _GroupPinner / the pin arena re-point it
    module.weight.data = module.weight.clone()
    gc.collect()
    assert _mapped(path) in (False, None)
    os.remove(path)
    assert torch.equal(module.weight, expected)


@pytest.mark.parametrize(
    "header",
    [
        {"tensor_names": '["encoder.weight", "encoder.weight"]'},
        {"tensor_names": '["missing.weight"]'},
        {"tensor_names": '"encoder.weight"'},
        {"tensor_names": "[1]"},
        {"tensor_names": "invalid"},
        {"encoder.weight": '{"_type":"Float8Tensor"}'},
        {"encoder.weight": '{"_type":"Tensor","unexpected":true}'},
        {ps.UNSLOTH_METADATA_KEY: "[]"},
        {ps.UNSLOTH_FORMAT_KEY: ""},
    ],
)
def test_plain_reader_rejects_invalid_headers(plain_checkpoint, header):
    with pytest.raises(ValueError):
        ps.load_plain_prequant_safetensors(plain_checkpoint(header = header))


def test_plain_reader_rejects_unaccounted_tensor(plain_checkpoint):
    import torch
    path = plain_checkpoint(
        tensors = {"encoder.weight": torch.ones(2), "extra.weight": torch.ones(2)}
    )
    with pytest.raises(ValueError, match = "does not account"):
        ps.load_plain_prequant_safetensors(path)


def test_plain_reader_restores_root_buffers(plain_checkpoint):
    import torch

    path = plain_checkpoint(
        tensors = {
            "encoder.weight": torch.ones(2),
            ps.UNSLOTH_ROOT_PREFIX + "buffer": torch.zeros(1),
        }
    )
    state = ps.load_plain_prequant_safetensors(path)["state_dict"]
    assert set(state) == {"encoder.weight", "buffer"}
    assert torch.equal(state["buffer"], torch.zeros(1))


def test_plain_reader_rejects_root_collision(plain_checkpoint):
    import torch
    path = plain_checkpoint(
        tensors = {"buffer": torch.ones(2), ps.UNSLOTH_ROOT_PREFIX + "buffer": torch.zeros(1)},
        header = {"tensor_names": '["buffer"]', "buffer": '{"_type":"Tensor"}'},
    )
    with pytest.raises(ValueError, match = "does not account"):
        ps.load_plain_prequant_safetensors(path)


def test_plain_encoder_gate_requires_safetensors(monkeypatch):
    from core.inference.diffusion_te_prequant import te_candidate_is_readable

    monkeypatch.setitem(sys.modules, "safetensors", None)
    assert not te_candidate_is_readable("encoder.safetensors")
    assert te_candidate_is_readable("encoder.pt")


def test_plain_encoder_resolver_uses_safetensors_without_torchao(monkeypatch):
    from core.inference.diffusion_te_prequant import (
        TePrequantSource,
        _resolve_checkpoint_path,
    )

    pytest.importorskip("safetensors")
    hub = pytest.importorskip("huggingface_hub")
    monkeypatch.setattr(ps, "_torchao_helpers", lambda: None)
    requested = []

    def download(**kwargs):
        requested.append(kwargs["filename"])
        return "/cache/encoder.safetensors"

    monkeypatch.setattr(hub, "hf_hub_download", download)
    source = TePrequantSource(
        kind = "repo",
        location = "org/encoder",
        filename = "encoder.safetensors",
        fallback_filenames = ("encoder.pt",),
    )
    assert (
        _resolve_checkpoint_path(source, None, cache_dir = "/cache") == "/cache/encoder.safetensors"
    )
    assert requested == ["encoder.safetensors"]