Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
"""Qwen-Image's single-file loaders keep Comfy's nvfp4 builds packed.
Both Comfy files mix nvfp4 with scaled fp8, and an fp8 fold multiplies every `.weight_scale` into its weight -- nvfp4's
block scales included. So what these tests pin is the order: the nvfp4 layers leave the state dict before any fp8
handling, come back packed under the paths the model uses (the encoder's legacy `model.X` keys become
`model.language_model.X`), and one reservation is made before anything is widened. The transformer's scaled fp8 layers
are folded unless fp8 compute or the model's fp8 storage setting keeps them; the encoder's are folded unless the
device can hold or multiply float8 (`test_qwen_image_encoder_fp8.py`). The compute
dtype is bf16, as in production: the packed global scale must not be cast.
"""
import dataclasses
import json
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
import torch
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_QwenImage_Config
from invokeai.backend.model_manager.configs.qwen_vl_encoder import QwenVLEncoder_Checkpoint_Config
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
apply_custom_layers_to_model,
)
from invokeai.backend.model_manager.load.model_loaders import qwen_image
from invokeai.backend.model_manager.load.model_loaders.qwen_image import (
QwenImageCheckpointModel,
QwenVLEncoderCheckpointLoader,
)
from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
from tests.fixtures.loader_seams import Seam, prepare
from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors, quantize_convrot
from tests.fixtures.safetensors_files import served_checkpoint
COMPUTE_DTYPE = torch.bfloat16
def _nvfp4_tensors(path: str, shape: tuple[int, int]) -> tuple[dict[str, torch.Tensor], torch.Tensor]:
"""Comfy ships an activation scale beside each layer, which the loader has no use for -- so it has
to be dropped rather than reach `load_state_dict`, and it is here for that reason alone."""
tensors, expected = nvfp4_signed_tensors(path, torch.randint(0, 2, shape, dtype=torch.bool))
tensors[f"{path}.input_scale"] = torch.tensor(1.0)
return tensors, expected
def _packed_bytes(rows: int, columns: int) -> int:
return rows * columns // 2 + rows * (columns // 16) + 4
def _marker(fmt: str) -> torch.Tensor:
return comfy_quant_marker({"format": fmt})
#: Both single-file encoder cells drive the same entry, so the driver is declared once.
ENCODER_SEAM = Seam(
loader=QwenVLEncoderCheckpointLoader,
module=qwen_image,
entry="_load_text_encoder_from_singlefile",
patches_device=True,
sets_torch_dtype=False,
casts_fp8_storage=False,
)
def _patch_common(monkeypatch: pytest.MonkeyPatch, state_dict: dict, metadata: dict) -> list[bool]:
"""Patch file access and devices; return a log for `_record_fold`."""
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.qwen_image.load_safetensors_checkpoint",
served_checkpoint(state_dict),
)
monkeypatch.setattr(qwen_image, "read_safetensors_metadata", lambda _path, _logger: metadata)
monkeypatch.setattr(qwen_image.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))
monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: COMPUTE_DTYPE)
return []
def _record_fold(monkeypatch: pytest.MonkeyPatch, loader, log: list[bool], *names: str) -> None:
"""At every call of the named `qwen_image` functions, log whether room had been made yet."""
for name in names or ("dequantize_fp8_scaled",):
original = getattr(qwen_image, name)
def recording(*args, _original=original, **kwargs):
log.append(loader._ram_cache.make_room.called)
return _original(*args, **kwargs)
monkeypatch.setattr(qwen_image, name, recording)
class _TinyQwenImageTransformer(torch.nn.Module):
"""The diffusers module names Comfy's Qwen-Image build uses, at toy width."""
_skip_layerwise_casting_patterns = ["pos_embed", "norm"]
def __init__(self, **_kwargs) -> None:
super().__init__()
block = torch.nn.Module()
block.attn = torch.nn.Module()
block.attn.to_q = torch.nn.Linear(64, 128)
block.img_mlp = torch.nn.Module()
block.img_mlp.net = torch.nn.ModuleList([torch.nn.Module()])
block.img_mlp.net[0].proj = torch.nn.Linear(64, 256)
block.txt_mlp = torch.nn.Module()
block.txt_mlp.net = torch.nn.ModuleList([torch.nn.Identity(), torch.nn.Identity(), torch.nn.Linear(64, 128)])
self.transformer_blocks = torch.nn.ModuleList([block])
self.img_in = torch.nn.Linear(64, 128)
@pytest.mark.parametrize("mode", ["fold", "fp8_compute", "fp8_storage"])
def test_the_transformer_keeps_nvfp4_packed_and_scaled_fp8_only_where_something_uses_it(
monkeypatch: pytest.MonkeyPatch, tmp_path, mode: str
) -> None:
"""Scaled fp8 layers stay fp8, with their own scale, for the fp8 matmul or for fp8 storage the model asks for; with
neither they are folded. Under fp8 storage the dense remainder goes to fp8 too, but not the scaled layers, whose
cast hooks would drop their scale."""
import diffusers
from invokeai.backend.model_manager.load import load_default
from invokeai.backend.model_manager.taxonomy import SubModelType
torch.manual_seed(0)
state_dict: dict[str, torch.Tensor] = {}
expected: dict[str, torch.Tensor] = {}
header: dict[str, dict[str, str]] = {}
for path, shape in (
("transformer_blocks.0.attn.to_q", (128, 64)),
("transformer_blocks.0.img_mlp.net.0.proj", (256, 64)),
):
tensors, weight = _nvfp4_tensors(path, shape)
state_dict.update(tensors)
state_dict[f"{path}.bias"] = torch.randn(shape[0])
expected[path] = weight
header[path] = {"format": "nvfp4"}
fp8_values = torch.randint(-8, 9, (128, 64)).float()
fp8 = "transformer_blocks.0.txt_mlp.net.2"
state_dict[f"{fp8}.weight"] = fp8_values.to(torch.float8_e4m3fn)
state_dict[f"{fp8}.weight_scale"] = torch.tensor(0.5)
state_dict[f"{fp8}.input_scale"] = torch.tensor(1.0)
state_dict[f"{fp8}.bias"] = torch.randn(128)
header[fp8] = {"format": "float8_e4m3fn"}
state_dict["img_in.weight"] = torch.randn(128, 64)
state_dict["img_in.bias"] = torch.randn(128)
log = _patch_common(monkeypatch, state_dict, {"_quantization_metadata": json.dumps({"layers": header})})
monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _TinyQwenImageTransformer, raising=False)
monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: mode == "fp8_compute")
monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)
checkpoint = tmp_path / "qwen_image_nvfp4.safetensors"
checkpoint.touch()
loader = object.__new__(QwenImageCheckpointModel)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
loader._torch_device = torch.device("cpu")
loader._logger = MagicMock()
_record_fold(monkeypatch, loader, log, "dequantize_fp8_scaled", "split_fp8_scaled_layers")
# The storage cast allocates an fp8 copy per weight; the loaded state dict must no longer hold the originals.
entries_at_storage_cast: list[int] = []
loader._apply_fp8_to_nn_module = lambda *args, **kwargs: (
entries_at_storage_cast.append(len(state_dict)),
QwenImageCheckpointModel._apply_fp8_to_nn_module(*args, **kwargs),
)
biases = {path: state_dict[f"{path}.bias"] for path in expected}
config = Main_Checkpoint_QwenImage_Config.model_construct(
path=str(checkpoint),
name="qwen_image_nvfp4",
default_settings=SimpleNamespace(fp8_storage=mode == "fp8_storage"),
)
model = loader._load_model(config, SubModelType.Transformer)
for path, weight in expected.items():
module = model.get_submodule(path)
assert isinstance(module, NVFP4Linear), path
assert module.weight.dtype is torch.uint8, path
assert module.weight_scale_2.dtype is torch.float32, path
# A float32 activation, not the compute dtype: torch 2.7's CPU bf16 GEMM faults with an illegal
# instruction on part of GitHub's windows runner fleet. These values are exact in either width.
x = torch.randn(3, module.in_features, dtype=torch.float32)
# The bias keeps the width the load rounded it to; the forward upcasts it to the activation.
expected_out = torch.nn.functional.linear(x, weight, biases[path].to(COMPUTE_DTYPE).float())
torch.testing.assert_close(module(x), expected_out)
fp8_layer = model.transformer_blocks[0].txt_mlp.net[2]
if mode == "fold":
assert torch.equal(fp8_layer.weight, (fp8_values * 0.5).to(COMPUTE_DTYPE))
assert getattr(fp8_layer, "weight_scale", None) is None
else:
assert fp8_layer.weight.dtype is torch.float8_e4m3fn
assert torch.equal(fp8_layer.weight.float(), fp8_values)
assert torch.equal(fp8_layer.weight_scale.float(), torch.tensor(0.5))
assert model.img_in.weight.dtype is (torch.float8_e4m3fn if mode == "fp8_storage" else COMPUTE_DTYPE)
assert getattr(model.img_in, "weight_scale", None) is None
# Through the cache's custom layers, as denoising runs it: a cast hook on the kept layer would upcast its codes
# without the scale before CustomLinear could apply it.
fp8_bias = fp8_layer.bias.detach().to(COMPUTE_DTYPE)
apply_custom_layers_to_model(model)
x = torch.randn(3, 64, dtype=torch.float32)
expected_fp8_out = torch.nn.functional.linear(x, (fp8_values * 0.5).to(COMPUTE_DTYPE).float(), fp8_bias.float())
torch.testing.assert_close(model.transformer_blocks[0].txt_mlp.net[2](x), expected_fp8_out)
# The reservation lands before the fold and before the split, whichever runs.
assert log == ([True, True] if mode == "fold" else [True])
assert entries_at_storage_cast == ([0] if mode == "fp8_storage" else [])
# Counted by hand: the packed layers as stored; their biases, the fp8 layer's bias and the dense input projection at
# bf16; the fp8 weight at bf16 when folded and one byte per element when kept. The side-channel scales are recovered
# before the reservation and are no longer in the state dict it sizes -- the seam reserves through `reserve_for_load`,
# which is handed them too and charges them. Four bytes here, for the one scalar `weight_scale`: the `input_scale` of
# 1.0 is an uncalibrated placeholder that `_usable_input_scale` drops, so nothing is charged for it.
packed = _packed_bytes(128, 64) + _packed_bytes(256, 64)
fp8_weight = 128 * 64 * (COMPUTE_DTYPE.itemsize if mode == "fold" else 1)
dense = (128 + 256) + 128 + (128 * 64 + 128)
recovered_scale = torch.tensor(0.5).element_size()
loader._ram_cache.make_room.assert_called_once_with(
packed + fp8_weight + dense * COMPUTE_DTYPE.itemsize + recovered_scale
)
class _TinyQwenVL(torch.nn.Module):
"""transformers' `Qwen2_5_VLForConditionalGeneration` layout at toy width: the language model and the vision tower
under `model.`, the LM head at the top."""
def __init__(self, _config) -> None:
super().__init__()
layer = torch.nn.Module()
layer.self_attn = torch.nn.Module()
layer.self_attn.q_proj = torch.nn.Linear(64, 128)
layer.mlp = torch.nn.Module()
layer.mlp.down_proj = torch.nn.Linear(64, 128, bias=False)
self.model = torch.nn.Module()
self.model.language_model = torch.nn.Module()
self.model.language_model.layers = torch.nn.ModuleList([layer])
self.model.visual = torch.nn.Module()
self.model.visual.proj = torch.nn.Linear(8, 4)
self.lm_head = torch.nn.Linear(64, 32, bias=False)
def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transformers_paths(
monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
import transformers
torch.manual_seed(1)
state_dict: dict[str, torch.Tensor] = {}
expected: dict[str, torch.Tensor] = {}
for legacy, shape in (("model.layers.0.self_attn.q_proj", (128, 64)), ("model.layers.0.mlp.down_proj", (128, 64))):
tensors, weight = _nvfp4_tensors(legacy, shape)
state_dict.update(tensors)
state_dict[f"{legacy}.comfy_quant"] = _marker("nvfp4")
expected[legacy.replace("model.", "model.language_model.", 1)] = weight
state_dict["model.layers.0.self_attn.q_proj.bias"] = torch.randn(128)
fp8_marker = _marker("float8_e4m3fn")
# The fp8_scaled encoder's own scale spelling, beside the marker the nvfp4 build adds. The released nvfp4 file ships
# the LM head in scaled fp8; it is not loaded.
fp8_values = torch.randint(-8, 9, (4, 8)).float()
for legacy, weight in (("visual.proj", fp8_values), ("lm_head", torch.randint(-8, 9, (32, 64)).float())):
state_dict[f"{legacy}.weight"] = weight.to(torch.float8_e4m3fn)
state_dict[f"{legacy}.scale_weight"] = torch.tensor(0.5)
state_dict[f"{legacy}.scale_input"] = torch.tensor(1.0)
state_dict[f"{legacy}.comfy_quant"] = fp8_marker
state_dict["visual.proj.bias"] = torch.randn(4)
log = _patch_common(monkeypatch, state_dict, {})
monkeypatch.setattr(transformers, "Qwen2_5_VLForConditionalGeneration", _TinyQwenVL, raising=False)
monkeypatch.setattr(
transformers.AutoConfig,
"from_pretrained",
lambda *_args, **_kwargs: SimpleNamespace(torch_dtype=None, tie_word_embeddings=False),
)
checkpoint = tmp_path / "qwen_2.5_vl_7b_nvfp4.safetensors"
checkpoint.touch()
loader = object.__new__(QwenVLEncoderCheckpointLoader)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
loader._torch_device, loader._logger = torch.device("cpu"), MagicMock()
_record_fold(monkeypatch, loader, log)
q_bias = state_dict["model.layers.0.self_attn.q_proj.bias"]
model = loader._load_text_encoder_from_singlefile(
QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint))
)
for path, weight in expected.items():
module = model.get_submodule(path)
assert isinstance(module, NVFP4Linear), path
assert module.weight_scale_2.dtype is torch.float32, path
# A float32 activation, not the compute dtype: torch 2.7's CPU bf16 GEMM faults with an illegal
# instruction on part of GitHub's windows runner fleet. These values are exact in either width.
x = torch.randn(3, module.in_features, dtype=torch.float32)
bias = q_bias.to(COMPUTE_DTYPE).float() if module.bias is not None else None
torch.testing.assert_close(module(x), torch.nn.functional.linear(x, weight, bias))
assert list(model.lm_head.parameters()) == []
assert torch.equal(model.model.visual.proj.weight, (fp8_values * 0.5).to(COMPUTE_DTYPE))
assert log == [True]
# Counted by hand: the packed layers as stored, the q_proj bias and the folded vision projection at bf16, and that
# projection's recovered scale (the 1.0 `scale_input` is an uncalibrated placeholder, charged nothing). Its marker
# is consumed by the extraction before the reservation. The LM head, scales and marker included, costs nothing.
packed = 2 * _packed_bytes(128, 64)
widened = 128 + (4 * 8 + 4)
recovered_scale = torch.tensor(0.5).element_size()
loader._ram_cache.make_room.assert_called_once_with(packed + widened * COMPUTE_DTYPE.itemsize + recovered_scale)
#: The shared encoder seam computes in float32; the int8 cells need bf16, since a blanket cast to it is what would ruin
#: the float32 scales.
BF16_ENCODER_SEAM = dataclasses.replace(ENCODER_SEAM, compute_dtype=COMPUTE_DTYPE)
def _expected_bias(source: dict[str, torch.Tensor], layer: Int8ConvrotLinear) -> torch.Tensor | None:
"""The bias the source file holds, rounded to the compute dtype by the load. Only `q_proj` has one in the toy."""
bias = source.get("model.layers.0.self_attn.q_proj.bias")
return bias.to(COMPUTE_DTYPE).float() if layer.bias is not None else None
def _tiny_encoder(monkeypatch: pytest.MonkeyPatch):
"""Stand in for the 7B module tree: the vendored config is real, the model class is `_TinyQwenVL`."""
import transformers
monkeypatch.setattr(transformers, "Qwen2_5_VLForConditionalGeneration", _TinyQwenVL, raising=False)
def _int8_encoder_state_dict(
rotated: bool, marked: bool = True
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
"""The two language-model projections int8, with the activation scale an unrotated build adds; and what each
must decode to, keyed by the path the module tree gives it."""
torch.manual_seed(2)
state_dict: dict[str, torch.Tensor] = {}
expected: dict[str, torch.Tensor] = {}
for legacy, shape in (("model.layers.0.self_attn.q_proj", (128, 64)), ("model.layers.0.mlp.down_proj", (128, 64))):
weight = torch.randn(shape)
if rotated:
payload = quantize_convrot(weight, group_size=64)
codes, scale, round_trip = payload.codes, payload.scale, payload.dequantized
marker = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 64}
else:
scale = (weight.abs().max() / 127.0).to(torch.float32)
codes = torch.clamp(torch.round(weight / scale), -128, 127).to(torch.int8)
round_trip = codes.float() * scale
marker = {"format": "int8_tensorwise"}
state_dict[f"{legacy}.input_scale"] = torch.tensor(1.0)
state_dict[f"{legacy}.weight"] = codes
state_dict[f"{legacy}.weight_scale"] = scale
if marked:
state_dict[f"{legacy}.comfy_quant"] = comfy_quant_marker(marker)
expected[legacy.replace("model.", "model.language_model.", 1)] = round_trip
state_dict["model.layers.0.self_attn.q_proj.bias"] = torch.randn(128)
state_dict["lm_head.weight"] = torch.randn(32, 64)
state_dict["visual.proj.weight"] = torch.randn(4, 8)
state_dict["visual.proj.bias"] = torch.randn(4)
return state_dict, expected
@pytest.mark.parametrize("rotated", [True, False], ids=["rotated_column_scale", "unrotated_scalar_scale"])
def test_the_encoder_keeps_int8_layers_int8_under_their_transformers_paths(monkeypatch, tmp_path, rotated) -> None:
"""The fold the encoder runs for fp8 would multiply the scale in and skip the inverse rotation, so the int8 layers
are claimed first. Their markers sit under the legacy names and follow the remap with their weights."""
state_dict, expected = _int8_encoder_state_dict(rotated)
checkpoint = tmp_path / "qwen_2.5_vl_7b_int8.safetensors"
checkpoint.touch()
run = prepare(BF16_ENCODER_SEAM, monkeypatch, state_dict=state_dict, metadata=None, geometry=_tiny_encoder)
model = run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))
for path, weight in expected.items():
layer = model.get_submodule(path)
assert isinstance(layer, Int8ConvrotLinear), path
assert layer.convrot is rotated, path
assert layer.weight.dtype is torch.int8, path
# The blanket cast to the compute dtype must not reach the scale.
assert layer.weight_scale.dtype is torch.float32, path
# A float32 activation: torch's CPU bf16 GEMM faults on part of the windows runner fleet.
x = torch.randn(3, 64)
bias = _expected_bias(state_dict, layer)
torch.testing.assert_close(layer(x), torch.nn.functional.linear(x, weight, bias), rtol=1e-4, atol=1e-4)
# The W8A8 activation scale has nothing to attach to.
assert not hasattr(layer, "input_scale")
assert list(model.lm_head.parameters()) == []
assert model.model.visual.proj.weight.dtype is COMPUTE_DTYPE
# Counted by hand: the int8 weights as stored, their fp32 scales, and the bias and vision projection at
# bf16. Markers and activation scales are dropped and cost nothing.
int8 = 2 * 128 * 64
scales = (2 * 128 * 4) if rotated else 2 * 4
dense = 128 + (4 * 8 + 4)
assert run.reserved == [int8 + scales + dense * COMPUTE_DTYPE.itemsize]
@pytest.mark.parametrize("rotated", [True, False], ids=["rotated", "unrotated"])
def test_an_encoder_build_that_names_its_layers_only_in_the_header_loads_under_the_remapped_paths(
monkeypatch, tmp_path, rotated
) -> None:
"""The header names the layers in the legacy layout, like the keys; the markers made from it follow the remap."""
state_dict, expected = _int8_encoder_state_dict(rotated, marked=False)
legacy = ("model.layers.0.self_attn.q_proj", "model.layers.0.mlp.down_proj")
entry = {"format": "int8_tensorwise", "convrot": rotated, **({"convrot_groupsize": 64} if rotated else {})}
metadata = {"_quantization_metadata": json.dumps({"layers": dict.fromkeys(legacy, entry)})}
checkpoint = tmp_path / "qwen_2.5_vl_7b_int8_header.safetensors"
checkpoint.touch()
run = prepare(BF16_ENCODER_SEAM, monkeypatch, state_dict=state_dict, metadata=metadata, geometry=_tiny_encoder)
model = run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))
for path, weight in expected.items():
layer = model.get_submodule(path)
assert isinstance(layer, Int8ConvrotLinear), path
assert layer.convrot is rotated, path
x = torch.randn(3, 64)
torch.testing.assert_close(
layer(x), torch.nn.functional.linear(x, weight, _expected_bias(state_dict, layer)), rtol=1e-4, atol=1e-4
)
def test_an_encoder_header_entry_that_does_not_say_whether_the_weight_was_rotated_is_refused(
monkeypatch, tmp_path
) -> None:
state_dict, _ = _int8_encoder_state_dict(rotated=True, marked=False)
layers = {
path: {"format": "int8_tensorwise"}
for path in ("model.layers.0.self_attn.q_proj", "model.layers.0.mlp.down_proj")
}
checkpoint = tmp_path / "qwen_2.5_vl_7b_int8_ambiguous.safetensors"
checkpoint.touch()
run = prepare(
BF16_ENCODER_SEAM,
monkeypatch,
state_dict=state_dict,
metadata={"_quantization_metadata": json.dumps({"layers": layers})},
)
with pytest.raises(ValueError, match="does not say whether the weight was rotated"):
run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))
assert run.reserved == []
def test_an_encoder_file_mixing_int8_and_nvfp4_layers_loads_both_under_one_reservation(monkeypatch, tmp_path) -> None:
state_dict, expected = _int8_encoder_state_dict(rotated=True)
nvfp4_legacy = "model.layers.0.mlp.down_proj"
for suffix in ("weight", "weight_scale", "comfy_quant"):
del state_dict[f"{nvfp4_legacy}.{suffix}"]
del expected["model.language_model.layers.0.mlp.down_proj"]
tensors, nvfp4_weight = _nvfp4_tensors(nvfp4_legacy, (128, 64))
state_dict.update(tensors)
state_dict[f"{nvfp4_legacy}.comfy_quant"] = _marker("nvfp4")
checkpoint = tmp_path / "qwen_2.5_vl_7b_int8_nvfp4.safetensors"
checkpoint.touch()
run = prepare(BF16_ENCODER_SEAM, monkeypatch, state_dict=state_dict, metadata=None, geometry=_tiny_encoder)
model = run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))
q_proj = model.get_submodule("model.language_model.layers.0.self_attn.q_proj")
assert isinstance(q_proj, Int8ConvrotLinear)
packed = model.get_submodule("model.language_model.layers.0.mlp.down_proj")
assert isinstance(packed, NVFP4Linear)
x = torch.randn(3, 64)
torch.testing.assert_close(packed(x), torch.nn.functional.linear(x, nvfp4_weight))
# The int8 q_proj with its fp32 scale, the packed layer as stored, and the dense bias and vision projection at
# bf16: one call that covers both schemes.
dense = 128 + (4 * 8 + 4)
assert run.reserved == [128 * 64 + 128 * 4 + _packed_bytes(128, 64) + dense * COMPUTE_DTYPE.itemsize]
def test_an_encoder_int8_weight_without_a_marker_is_refused_before_the_cache_is_evicted(monkeypatch, tmp_path) -> None:
"""Nothing says whether the codes were rotated, and cast as raw integers they generate noise. The refusal has to
come before `make_room`, and before the config fetch between them: reserving room for a load that cannot finish
evicts whatever else the user had resident."""
state_dict, _ = _int8_encoder_state_dict(rotated=True)
del state_dict["model.layers.0.mlp.down_proj.comfy_quant"]
checkpoint = tmp_path / "qwen_2.5_vl_7b_int8_convrot.safetensors"
checkpoint.touch()
run = prepare(ENCODER_SEAM, monkeypatch, state_dict=state_dict, metadata=None)
with pytest.raises(ValueError, match="no readable int8_tensorwise marker"):
run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))
assert run.reserved == []
def test_an_encoder_marked_only_convrot_is_refused(monkeypatch, tmp_path) -> None:
"""A marker without a format names no scheme; the folds that used to take it would have rotated nothing."""
state_dict, _ = _int8_encoder_state_dict(rotated=True)
for legacy in ("model.layers.0.self_attn.q_proj", "model.layers.0.mlp.down_proj"):
state_dict[f"{legacy}.comfy_quant"] = comfy_quant_marker({"convrot": True})
checkpoint = tmp_path / "qwen_2.5_vl_7b_convrot_only.safetensors"
checkpoint.touch()
run = prepare(ENCODER_SEAM, monkeypatch, state_dict=state_dict, metadata=None)
with pytest.raises(ValueError, match=r"int8 weight\(s\) with no readable int8_tensorwise marker"):
run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))
assert run.reserved == []
def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_evicted(monkeypatch, tmp_path) -> None:
"""The degraded half-state, at the seam rather than at the detector.
A packed uint8 weight with a block-scale grid and no `weight_scale_2` is the shape a guard keyed
on `weight_scale_2` -- what the decode keys on -- lets straight through. `find_nvfp4_layers`
refuses it, and `test_nvfp4.py` pins that; what only a seam can answer is whether this loader
still reaches the detector *before* it asks the cache for room, which nothing but the order of
those two statements secures.
"""
state_dict = {
# 128 rows and a 16-block grid: a whole number of cuBLAS tiles, i.e. a layer a real build
# could hold. The refusal reads only the key pairing and the uint8 dtype, so it fires either
# way -- but a shape no build can contain is the wrong thing to assert the state against.
"model.layers.0.self_attn.q_proj.weight": torch.zeros(128, 128, dtype=torch.uint8),
"model.layers.0.self_attn.q_proj.weight_scale": torch.zeros(128, 16).to(torch.float8_e4m3fn),
}
checkpoint = tmp_path / "qwen_2.5_vl_7b_nvfp4_half.safetensors"
checkpoint.touch()
run = prepare(ENCODER_SEAM, monkeypatch, state_dict=state_dict, metadata=None)
with pytest.raises(ValueError, match="with a weight_scale but no weight_scale_2"):
run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))
assert run.reserved == []
def test_the_transformer_refuses_an_nvfp4_layer_missing_its_global_scale_before_the_cache_is_evicted(
monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
"""The same degraded half-state at the transformer seam, which had no `Seam` of its own.
The encoder cell above covers the other Qwen-Image seam; this one is the transformer. Declared
through the shared driver rather than the hand-rolled loader the cells above use, because
`run.reserved` is the assertion: the recorded reservations are what say "before", where a
`MagicMock` would only say "not called at all".
"""
import diffusers
state_dict = {
"img_in.weight": torch.randn(128, 64),
"img_in.bias": torch.randn(128),
"transformer_blocks.0.attn.to_q.weight": torch.zeros(128, 32, dtype=torch.uint8),
"transformer_blocks.0.attn.to_q.weight_scale": torch.zeros(128, 4).to(torch.float8_e4m3fn),
}
checkpoint = tmp_path / "qwen_image_nvfp4_half.safetensors"
checkpoint.touch()
seam = Seam(
loader=QwenImageCheckpointModel,
module=qwen_image,
entry="_load_from_singlefile",
compute_dtype=COMPUTE_DTYPE,
patches_device=True,
# This entry reads neither: `_torch_dtype` is read nowhere in `qwen_image`, and the fp8
# storage cast is called from `_load_model`. Stubbing them would hide one that started.
sets_torch_dtype=False,
casts_fp8_storage=False,
)
run = prepare(
seam,
monkeypatch,
state_dict=state_dict,
metadata=None,
geometry=lambda patch: patch.setattr(
diffusers, "QwenImageTransformer2DModel", _TinyQwenImageTransformer, raising=False
),
)
with pytest.raises(ValueError, match="with a weight_scale but no weight_scale_2"):
run.load(Main_Checkpoint_QwenImage_Config.model_construct(path=str(checkpoint), name="qwen_image_nvfp4_half"))
assert run.reserved == []