Files
thenoise/tests/test_quantized.py

1079 lines
42 KiB
Python

"""Quantized (INT8/FP8) support: ``QuantizedLinear`` and the generic load helpers.
CPU (comfy_kitchen's eager backend), no GPU and no real checkpoints.
"""
from __future__ import annotations
import json
import pytest
import torch
from comfy_kitchen.tensor import QuantizedTensor
from conftest import (
StubModel,
TINY_DIM,
TinyDiT,
W4A8_GROUP,
bf16_tensors,
comfy_quant,
fp8_pair,
fp8_qt,
int8_checkpoint,
int8_lora_state_dict,
int8_pair,
int8_qt,
int8_realistic_pair,
int8_tensors,
w4a8_checkpoint,
w4a8_marker,
w4a8_qt,
w4a8_tensors,
write_safetensors,
wrapped_fp8_tensor,
wrapped_int8_tensor,
)
from comfy_kitchen.tensor.w4a8_int8 import AsymW4A8Int8Layout
from thenoise.dit.quantized import QuantizedLinear
from thenoise.utils.lora import LoraFactors, LoraMode
from thenoise.utils.loader import (
is_quantized_checkpoint,
load_dit,
load_quantized_state_dict,
load_selected_state,
)
OUT_F, IN_F = 512, 256
# ------------------------------------------------------------- QuantizedLinear
def _bf16_x(rows=4):
return torch.randn(rows, IN_F, dtype=torch.bfloat16)
def test_quantized_linear_bf16_forward():
layer = QuantizedLinear(IN_F, OUT_F, bias=False).requires_grad_(False)
torch.nn.init.ones_(layer.weight)
layer = layer.to(torch.bfloat16) # models are cast to bf16 by the adapter
out = layer(_bf16_x())
assert out.shape == (4, OUT_F)
assert out.dtype == torch.bfloat16
assert not layer._quantized
@pytest.mark.parametrize(
"qt,stored_dtype",
[(wrapped_int8_tensor(), torch.int8), (wrapped_fp8_tensor(), torch.float8_e4m3fn)],
ids=["int8", "fp8"],
)
def test_quantized_linear_load_quantized_and_forward(qt, stored_dtype):
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
assert isinstance(layer.weight, torch.nn.Parameter)
layer.load_quantized(qt)
assert layer._quantized
# The bf16 parameter is dropped (weight is now the quantized buffer) -> the
# memory saving this whole path exists for.
assert isinstance(layer.weight, QuantizedTensor)
assert layer.weight._qdata.dtype == stored_dtype
out = layer(_bf16_x())
assert out.shape == (4, OUT_F)
assert out.dtype == torch.bfloat16
def test_quantized_linear_owns_optional_fp8_activation_scale():
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
assert layer.input_scale is None
layer.load_quantized(wrapped_fp8_tensor(), input_scale=torch.tensor([0.75]))
assert layer.input_scale.item() == pytest.approx(0.75)
assert "input_scale" not in layer.state_dict()
assert layer.input_scale.device == layer.weight.device
def test_fp8_activation_scale_reaches_a_whole_state_load(tmp_path):
from safetensors.torch import save_file
from thenoise.utils.loader import load_dit
path = tmp_path / "fp8.safetensors"
raw = torch.ones(OUT_F, IN_F, dtype=torch.float16).to(torch.float8_e4m3fn)
save_file({"q.weight": raw, "q.scale_weight": torch.tensor(1.0),
"q.scale_input": torch.tensor(0.5),
"scaled_fp8": torch.zeros(1)}, str(path))
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.q = QuantizedLinear(IN_F, OUT_F, bias=False)
with torch.device("meta"):
model = Model()
load_dit(model, str(path), device="cpu", dtype=torch.bfloat16)
assert isinstance(model.q.weight, QuantizedTensor)
assert model.q.input_scale.item() == pytest.approx(0.5)
assert "q.input_scale" not in model.state_dict()
# ComfyUI's two-value legacy marker disables activation quantization.
save_file({"q.weight": raw, "q.scale_weight": torch.tensor(1.0),
"q.scale_input": torch.tensor(0.5),
"scaled_fp8": torch.zeros(2)}, str(path))
with torch.device("meta"):
model = Model()
load_dit(model, str(path), device="cpu", dtype=torch.bfloat16)
assert model.q.input_scale is None
@pytest.mark.parametrize("layout", ["int8", "fp8"])
def test_quantized_linear_bake_lora_requantizes_in_place(layout):
"""The delta is baked into the stored low-bit weight, profile preserved."""
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
if layout == "int8":
qweight, scale = int8_pair()
layer.load_quantized(int8_qt(qweight, scale))
else:
qweight, scale = fp8_pair()
layer.load_quantized(fp8_qt(qweight, scale))
stored_dtype = layer.weight._qdata.dtype
orig_q = layer.weight._qdata.clone()
x = _bf16_x()
base = layer(x)
# LoRA factors: down [r, in], up [out, r]; the baked delta is
# (up @ down) * (alpha/r * multiplier), shaped [out, in].
down = torch.randn(8, IN_F, dtype=torch.bfloat16) * 6
up = torch.randn(OUT_F, 8, dtype=torch.bfloat16) * 6
delta = (up @ down) * (8.0 / down.size(0) * 2.0)
layer.bake_lora(delta)
assert not torch.equal(layer.weight._qdata, orig_q) # requantized in place
assert layer.weight._qdata.dtype == stored_dtype # layout profile preserved
out = layer(x)
# The INT8 GEMM also quantizes activations, so an exact match to
# base + x @ delta^T is impossible; instead verify the LoRA moves the output
# substantially and lands much closer to the delta expectation than to base.
err_to_expected = (out.float() - (base + x @ delta.t()).float()).abs().max()
err_to_base = (out.float() - base.float()).abs().max()
assert err_to_base > 1.0
assert err_to_expected < err_to_base
# ------------------------------------------------------- quantized LoRA undo
def _modes(result) -> dict:
"""``{module path: LoraMode}`` for everything the LoRA touched."""
return {path: undo.mode for path, undo in result.items()}
@pytest.mark.parametrize(
"kwargs",
[
{}, # plain INT8
{"weight_dtype": torch.float8_e4m3fn}, # FP8 (per-tensor scale)
{"prefix": "model.diffusion_model."}, # ComfyUI repackage
],
ids=["int8", "fp8", "int8-wrapped"],
)
def test_apply_lora_bakes_quantized_and_undo_reloads_from_disk(kwargs, tmp_path):
"""Undo reloads the ORIGINAL low-bit weights from the checkpoint by raw key.
The raw key must survive the wrapper-prefix stripping, or a repackaged
checkpoint restores nothing and the LoRA stays baked in.
"""
from thenoise.utils.lora import apply_lora_to_model, undo_lora_on_model
prefix = kwargs.get("prefix", "")
path, tensors = int8_checkpoint(tmp_path / "dit.safetensors", **kwargs)
model = TinyDiT()
load_dit(model, path, device="cpu", dtype=torch.bfloat16)
assert model.q._quantized
orig_q = model.q.weight._qdata.clone()
orig_scale = model.q.weight.params.scale.clone()
assert torch.equal(orig_scale, tensors[f"{prefix}q.weight_scale"])
result = apply_lora_to_model(model, [int8_lora_state_dict()])
assert _modes(result) == {"q": LoraMode.BAKED_QUANTIZED}
assert result["q"].raw_key == f"{prefix}q.weight"
assert result["q"].checkpoint == path
assert not torch.equal(model.q.weight._qdata, orig_q)
undo_lora_on_model(model, result)
assert torch.equal(model.q.weight._qdata, orig_q)
assert torch.equal(model.q.weight.params.scale, orig_scale)
def test_a_second_component_is_undone_from_the_file_it_came_from(tmp_path):
"""Undo reloads a layer from the file it was loaded from, not the model's primary
one. Both experts carry every key name, so the wrong file restores without a sound."""
high_path, _ = int8_checkpoint(tmp_path / "high.safetensors")
low_path, _ = int8_checkpoint(tmp_path / "low.safetensors")
write_safetensors(tmp_path / "style.safetensors", int8_lora_state_dict("q"))
high, low_dit = TinyDiT(), TinyDiT()
load_dit(high, high_path, device="cpu", dtype=torch.bfloat16)
load_dit(low_dit, low_path, device="cpu", dtype=torch.bfloat16)
assert not torch.equal(low_dit.q.weight._qdata, high.q.weight._qdata)
originals = low_dit.q.weight._qdata.clone()
adapter = StubModel(lora_dir=str(tmp_path))
adapter.dit_path = high_path # the adapter's own checkpoint is the other expert
adapter.switch_loras(["style.safetensors:1.0"], low_dit, "dit_low")
assert not torch.equal(low_dit.q.weight._qdata, originals)
adapter.switch_loras(None, low_dit, "dit_low")
assert torch.equal(low_dit.q.weight._qdata, originals)
def _compiled_dit(tmp_path, kind: str):
"""A loaded TinyDiT whose ``q`` layer carries ``kind``'s weights."""
kwargs = {"fp8": {"weight_dtype": torch.float8_e4m3fn}}.get(kind, {})
if kind == "bf16":
path = write_safetensors(tmp_path / "bf16.safetensors", bf16_tensors())
elif kind == "w4a8":
path, _ = w4a8_checkpoint(tmp_path / "w4a8.safetensors")
else:
path, _ = int8_checkpoint(tmp_path / f"{kind}.safetensors", **kwargs)
model = TinyDiT()
load_dit(model, path, device="cpu", dtype=torch.bfloat16)
return model
@pytest.mark.parametrize("kind", ["int8", "fp8", "w4a8", "bf16"])
def test_a_compiled_layer_never_traces_into_a_device_kernel(kind, tmp_path, request):
"""The kernels take raw pointers, so dynamo has to be stopped before them.
INT8 reaches its kernel through a fake-registered op of comfy_kitchen's own, so one
``F.linear`` is already opaque. W4A8 and FP8 reach theirs through plain functions,
where the HIP backend then asks a FakeTensor for a data pointer: W4A8 dies there and
FP8's handler swallows the error, leaving a permanently dequantized graph. Both are
wrapped here. A BF16 layer must stay a plain ``F.linear`` -- wrapping it would cut the
layer off from the elementwise fusion around it for nothing.
The traced graph is asked for rather than a compiled run: ``export`` traces without
executing, so this holds with Inductor off, as the suite runs it.
"""
request.addfinalizer(torch._dynamo.reset)
torch._dynamo.reset()
layer = _compiled_dit(tmp_path, kind).q
assert layer._quantized == (kind != "bf16")
x = torch.randn(3, TINY_DIM[1], dtype=torch.bfloat16)
layer(x)
graph = torch._dynamo.export(layer)(x).graph_module
targets = [str(node.target) for node in graph.graph.nodes if node.op == "call_function"]
if kind == "w4a8":
assert targets == [str(torch.ops.thenoise.w4a8_linear)]
elif kind == "fp8":
assert targets == [str(torch.ops.thenoise.fp8_linear)]
else:
assert not any("thenoise." in target for target in targets), targets
def test_a_calibrated_fp8_layer_keeps_both_halves_of_its_gemm(tmp_path, request):
"""Quantizing the activations stays comfy_kitchen's; only the GEMM is wrapped."""
request.addfinalizer(torch._dynamo.reset)
torch._dynamo.reset()
layer = QuantizedLinear(TINY_DIM[1], TINY_DIM[0], bias=False).to(torch.bfloat16)
layer.load_quantized(fp8_qt(*fp8_pair()), input_scale=torch.tensor(0.25))
x = torch.randn(3, TINY_DIM[1], dtype=torch.bfloat16)
layer(x)
graph = torch._dynamo.export(layer)(x).graph_module
targets = [str(node.target) for node in graph.graph.nodes if node.op == "call_function"]
assert str(torch.ops.comfy_kitchen.quantize_fp8) in targets
assert str(torch.ops.thenoise.fp8_linear) in targets
def test_a_component_cut_out_of_a_multi_component_file_undoes_from_that_file(tmp_path):
"""LTX reads its transformer out of a file that also holds the codecs and projections.
That route hands over a slice rather than a whole file, and it alone knows the raw
names behind the slice, so it is the one that has to record them: without it a baked
layer had nowhere to reload from and no LoRA switch on those checkpoints could end.
"""
from thenoise.utils.lora import apply_lora_to_model, undo_lora_on_model
prefix = "model.diffusion_model."
tensors = int8_tensors(prefix=prefix,
extra={"vae.conv.weight": torch.zeros(2, 2, dtype=torch.bfloat16)})
path = write_safetensors(tmp_path / "all-in-one.safetensors", tensors)
model = TinyDiT()
load_selected_state(
model,
[(path, {raw: raw[len(prefix):] for raw in tensors if raw.startswith(prefix)})],
dtype=torch.bfloat16, device="cpu", what="dit")
assert model.q._quantized
assert model._quantized_restore_map == {"q": (path, f"{prefix}q.weight")}
original = model.q.weight._qdata.clone()
result = apply_lora_to_model(model, [int8_lora_state_dict()])
assert _modes(result) == {"q": LoraMode.BAKED_QUANTIZED}
assert not torch.equal(model.q.weight._qdata, original)
undo_lora_on_model(model, result)
assert torch.equal(model.q.weight._qdata, original)
def test_undoing_a_bake_of_a_layer_with_no_checkpoint_raises():
"""A quantized layer with no file behind it has nothing to reload, and undo says so."""
from thenoise.utils.lora import apply_lora_to_model, undo_lora_on_model
model = TinyDiT(quantized=True)
result = apply_lora_to_model(model, [int8_lora_state_dict()])
assert _modes(result) == {"q": LoraMode.BAKED_QUANTIZED}
assert result["q"].checkpoint is None
with pytest.raises(RuntimeError, match="no originals to reload"):
undo_lora_on_model(model, result)
def test_apply_lora_mixed_quantized_and_bf16_layers():
from thenoise.utils.lora import apply_lora_to_model
model = TinyDiT(quantized=True)
orig_q = model.q.weight._qdata.clone()
orig_plain = model.plain.weight.clone()
loras = int8_lora_state_dict("q") | int8_lora_state_dict("plain")
result = apply_lora_to_model(model, [loras])
assert not torch.equal(model.q.weight._qdata, orig_q) # int8 layer baked
assert not torch.equal(model.plain.weight, orig_plain) # bf16 layer mutated
assert _modes(result) == {
"q": LoraMode.BAKED_QUANTIZED,
"plain": LoraMode.BAKED,
}
# ------------------------------------------------ quant_step (bake-vs-runtime input)
def test_quant_step_reads_a_scale_that_actually_is_one():
"""Per-row int8: the exporter's ``scale`` IS the step, row for row; a single
value broadcasts to every row.
"""
qweight, scale = int8_pair()
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
layer.load_quantized(int8_qt(qweight, scale))
step = layer.quant_step()
assert step.shape == (OUT_F,)
assert torch.allclose(step, scale.reshape(-1))
layer.load_quantized(int8_qt(qweight, torch.tensor([0.25], dtype=torch.float32)))
assert torch.allclose(layer.quant_step(), torch.full((OUT_F,), 0.25))
def test_quant_step_reports_a_step_for_a_packed_layer():
"""A packed layer the loader cannot measure would bake every LoRA by default, so
the step has to be readable from the tensors the export stored.
"""
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
layer.load_quantized(w4a8_qt())
step = layer.quant_step()
assert step is not None
assert step.shape == (OUT_F,)
assert bool((step > 0).all())
@pytest.mark.parametrize("scale", [torch.rand(OUT_F, 4), torch.rand(3), None])
def test_quant_step_declines_a_scale_it_cannot_read(scale):
"""Better no opinion than a wrong one: a non-per-row scale, or an FP8 layout
whose single scale is relative to each weight.
"""
qweight, _ = int8_pair()
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
if scale is None:
layer.load_quantized(wrapped_fp8_tensor())
else:
layer.load_quantized(int8_qt(qweight, scale))
assert layer.quant_step() is None
# ------------------------------------------------------- runtime LoRA on a layer
def _tiny_lora_factors(gain=1.0, rank=8):
return (
torch.randn(rank, IN_F, dtype=torch.bfloat16) * gain,
torch.randn(OUT_F, rank, dtype=torch.bfloat16),
)
def _rel_err(got, expected) -> float:
return ((got.float() - expected.float()).norm() / expected.float().norm()).item()
def test_runtime_lora_adds_the_low_rank_term_without_touching_the_weight():
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
layer.load_quantized(wrapped_int8_tensor(realistic=True))
stored = layer.weight._qdata.clone()
weight = layer.weight.dequantize()
x = _bf16_x()
base = layer(x)
# A delta at 5% of the weight's own RMS: visible in a BF16 output, so a branch
# that is not added (or is added transposed) cannot slip through.
down, up = _tiny_lora_factors()
down = down.float() * (
0.05
* weight.float().pow(2).mean().sqrt()
/ (up.float() @ down.float()).float().pow(2).mean().sqrt()
).to(torch.bfloat16)
delta = (up.float() @ down.float()).float()
layer.set_runtime_lora(down, up)
assert torch.equal(layer.weight._qdata, stored) # no dequantize, no requantize
assert _rel_err(layer(x), base.float() + (x.float() @ delta.t())) < 0.02
# And it really moved the output (a silently missing add-on cannot pass).
assert ((layer(x).float() - base.float()).norm() / base.float().norm()) > 0.02
layer.clear_runtime_lora()
assert torch.equal(layer(x), base)
def test_bake_lora_refuses_a_layer_with_a_runtime_branch():
"""Baking on top of a live branch would apply the LoRA twice."""
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
layer.load_quantized(wrapped_int8_tensor())
layer.set_runtime_lora(*_tiny_lora_factors())
with pytest.raises(RuntimeError, match="runtime LoRA"):
layer.bake_lora(torch.zeros(OUT_F, IN_F, dtype=torch.bfloat16))
# ------------------------------------------------- bake-vs-runtime routing
def test_apply_lora_bakes_a_wide_delta():
"""The normal case is unchanged: bake, free per step, restorable from disk."""
from thenoise.utils.lora import apply_lora_to_model
model = TinyDiT(quantized=True)
stored = model.q.weight._qdata.clone()
result = apply_lora_to_model(model, [int8_lora_state_dict("q")])
assert _modes(result) == {"q": LoraMode.BAKED_QUANTIZED}
assert not torch.equal(model.q.weight._qdata, stored)
def test_apply_lora_applies_a_sub_step_delta_at_runtime():
"""A delta finer than the quantization step is not baked into noise.
The weight stays bit-identical, so undo needs neither a delta nor the
checkpoint: dropping the branch restores the layer exactly.
"""
from thenoise.utils.lora import apply_lora_to_model, undo_lora_on_model
model = TinyDiT(quantized=True)
stored = model.q.weight._qdata.clone()
x = _bf16_x()
base = model.q(x)
sd = int8_lora_state_dict("q", gain=1e-4)
result = apply_lora_to_model(model, [sd])
assert _modes(result) == {"q": LoraMode.RUNTIME}
assert result["q"].raw_key is None # nothing baked -> nothing to reload
assert torch.equal(model.q.weight._qdata, stored)
delta = sd["q.lora_up.weight"].float() @ sd["q.lora_down.weight"].float()
branch = model.q._lora_branch(x)
assert _rel_err(branch, x.float() @ delta.t()) < 0.05
# Nothing was baked: undo works from memory alone.
undo_lora_on_model(model, result)
assert model.q._lora_down is None
assert torch.equal(model.q(x), base)
assert torch.equal(model.q.weight._qdata, stored)
def test_apply_lora_merges_several_loras_on_one_quantized_layer():
"""One decision per layer, on the sum: one branch, summed rank, scales folded."""
from thenoise.utils.lora import apply_lora_to_model, undo_lora_on_model
model = TinyDiT(quantized=True)
first = int8_lora_state_dict("q", gain=1e-4)
second = int8_lora_state_dict("q", gain=2e-4)
second["q.alpha"] = torch.tensor(2.0) # alpha/r = 0.25, on top of the 0.5 weight
result = apply_lora_to_model(model, [first, second], [1.0, 0.5])
assert _modes(result) == {"q": LoraMode.RUNTIME}
assert model.q._lora_down.shape == (16, IN_F) # rank 8 + rank 8, one branch
assert model.q._lora_up.shape == (OUT_F, 16)
delta = (
first["q.lora_up.weight"].float() @ first["q.lora_down.weight"].float()
+ 0.5
* (2.0 / 8.0)
* (
second["q.lora_up.weight"].float()
@ second["q.lora_down.weight"].float()
)
)
x = _bf16_x()
branch = model.q._lora_branch(x)
assert _rel_err(branch, x.float() @ delta.t()) < 0.05
undo_lora_on_model(model, result)
assert model.q._lora_down is None
def test_baking_after_a_runtime_branch_clears_it():
"""A fresh bake must not leave a previous runtime branch stacked on top."""
from thenoise.utils.lora import apply_lora_to_model
model = TinyDiT(quantized=True)
apply_lora_to_model(model, [int8_lora_state_dict("q", gain=1e-4)])
assert model.q._lora_down is not None
result = apply_lora_to_model(model, [int8_lora_state_dict("q")])
assert _modes(result) == {"q": LoraMode.BAKED_QUANTIZED}
assert model.q._lora_down is None
def test_a_delta_the_four_bit_grid_would_erase_stays_at_runtime():
"""One LoRA, two grids: baked into INT8, kept as a branch on the packed weight.
A 16-level codebook makes a packed step about ten times the INT8 one for a layer of
the same width, and style LoRAs were measured at ~1% of a weight's rms — a fraction
of that step. Baking such a delta into W4A8 leaves the layer moved mainly by
requantization noise, so the measured step is what routes it away.
"""
from thenoise.utils.lora import LoraFactors
stored = int8_lora_state_dict("q", gain=1e-3)
factors = LoraFactors(stored["q.lora_down.weight"], stored["q.lora_up.weight"])
int8_layer = QuantizedLinear(IN_F, OUT_F, bias=False)
int8_layer.load_quantized(int8_qt(*int8_realistic_pair()))
packed = QuantizedLinear(IN_F, OUT_F, bias=False)
packed.load_quantized(w4a8_qt())
assert float(int8_layer.quant_step().mean()) < float(packed.quant_step().mean()) / 4
assert int8_layer.apply_lora(factors) is LoraMode.BAKED_QUANTIZED
assert packed.apply_lora(factors) is LoraMode.RUNTIME
assert packed._lora_down is not None
def test_a_wide_delta_still_bakes_into_a_packed_layer_and_undo_reloads_every_scale(tmp_path):
"""Baking is free per step and survives a W4A8 requantize when the delta is wide
enough; undoing it has to reload the group scales, row scales and codebook too, or
the layer comes back decoded through the wrong grid.
"""
from thenoise.utils.lora import apply_lora_to_model, undo_lora_on_model
path, _ = w4a8_checkpoint(tmp_path / "w4a8.safetensors")
model = load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16)
originals = {name: tensor.clone()
for name, tensor in model.q.weight.state_dict("weight").items()}
assert len(originals) == 4 # codes, group scales, row scales, codebook
result = apply_lora_to_model(model, [int8_lora_state_dict("q")])
assert _modes(result) == {"q": LoraMode.BAKED_QUANTIZED}
assert not torch.equal(model.q.weight._qdata, originals["weight"])
undo_lora_on_model(model, result)
restored = model.q.weight.state_dict("weight")
assert set(restored) == set(originals)
for name, tensor in restored.items():
assert torch.equal(tensor, originals[name]), name
# ------------------------------------------------------- the routing metric
def test_bake_ratio_ignores_the_rows_a_fused_lora_never_touches():
"""A ``qkv``/``gate_up`` delta filling part of the rows is measured on that part.
Averaging over the whole fused matrix would report a delta smaller by
``sqrt(rows_touched / rows)`` and send a layer that quantizes fine to runtime.
"""
down = torch.zeros(1, IN_F)
down[0, :64] = 1.0 # the one touched row's delta has norm 8
up = torch.zeros(OUT_F, 1)
up[0, 0] = 1.0
step = torch.ones(OUT_F)
ratio = QuantizedLinear._bake_ratio(LoraFactors(down, up), step).item()
assert abs(ratio - 8.0 / IN_F**0.5) < 1e-5
assert ratio > QuantizedLinear.LORA_BAKE_MIN_RATIO # wide enough: bake
# What a whole-matrix RMS would have claimed instead: 22x smaller -> runtime.
assert 8.0 / (OUT_F * IN_F) ** 0.5 < QuantizedLinear.LORA_BAKE_MIN_RATIO
def test_a_lora_the_layer_cannot_measure_bakes():
"""No step estimate (FP8) and a zero delta both mean "no opinion" -> bake."""
layer = QuantizedLinear(IN_F, OUT_F, bias=False)
layer.load_quantized(wrapped_fp8_tensor())
assert layer.apply_lora(LoraFactors(*_tiny_lora_factors(gain=1e-6))) is (
LoraMode.BAKED_QUANTIZED
)
ratio = QuantizedLinear._bake_ratio(
LoraFactors(torch.zeros(2, 4), torch.zeros(4, 2)), torch.ones(4)
)
assert not ratio > QuantizedLinear.LORA_BAKE_MIN_RATIO
# ------------------------------------------------------ is_quantized_checkpoint
@pytest.mark.parametrize(
"tensors,expected",
[
# INT8 and FP8 both carry a ``.weight_scale`` next to the low-bit weight.
(int8_tensors(), True),
(int8_tensors(weight_dtype=torch.float8_e4m3fn), True),
(w4a8_tensors(), True),
# A wrapped INT8 file is still quantized (the prefix is stripped first).
(int8_tensors(prefix="model.diffusion_model."), True),
(bf16_tensors(), False),
# The check is a header-name heuristic: any ``.weight_scale`` is enough to
# take the quantized load path (which then fails loudly if no low-bit
# weight owns it, rather than silently loading garbage).
({"blocks.0.attn.q_proj.weight_scale": torch.zeros(16, 1)}, True),
],
ids=["int8", "fp8", "packed-w4a8", "int8-wrapped", "bf16", "scale-only"],
)
def test_is_quantized_checkpoint(tmp_path, tensors, expected):
path = write_safetensors(tmp_path / "ckpt.safetensors", tensors)
assert is_quantized_checkpoint(path) is expected
# ------------------------------------------------------------ comfy_quant marker
@pytest.mark.parametrize(
"marker,convrot,groupsize",
[
# A layer quantized with convrot_groupsize=64 must rotate activations
# with 64 at inference, NOT the default 256, or the images are garbage.
(comfy_quant(convrot=True, groupsize=64), True, 64),
# A layer whose in_features were not divisible by the group size is NOT
# ConvRot-rotated: inference must not rotate.
(comfy_quant(convrot=False), False, 256),
# No marker (or an unparseable one) is a pre-comfy_quant artifact.
(None, False, 256),
(torch.zeros(8, dtype=torch.uint8), False, 256),
],
ids=["groupsize-64", "convrot-off", "no-marker", "unparseable-marker"],
)
def test_comfy_quant_marker_drives_the_inference_profile(tmp_path, marker, convrot, groupsize):
path, _ = int8_checkpoint(tmp_path / "int8.safetensors", marker=marker)
model = TinyDiT()
load_dit(model, path, device="cpu", dtype=torch.bfloat16)
assert model.q._quantized is True
assert model.q.weight.params.convrot is convrot
assert model.q.weight.params.convrot_groupsize == groupsize
# --------------------------------------------------- packed W4A8 / W6A8 loads
def test_a_packed_checkpoint_loads_and_runs(tmp_path):
"""A 4-bit export arrives as codes at half width plus the tensors that decode them."""
path, _ = w4a8_checkpoint(tmp_path / "w4a8.safetensors")
model = load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16)
assert model.q._quantized is True
assert model.q.weight.layout_cls is AsymW4A8Int8Layout
assert tuple(model.q.weight.shape) == TINY_DIM # what the module was built for
assert tuple(model.q.weight.storage_shape) == (OUT_F, IN_F // 2) # what the file had
assert model.q.weight.params.group_size == W4A8_GROUP
# A packed layer quantizes its own activations, so it has no calibrated input scale.
assert model.q.input_scale is None
assert model.plain.weight.dtype == torch.bfloat16 # the full-precision part still fits
assert model.q(_bf16_x()).dtype == torch.bfloat16
def test_a_packed_weight_stated_as_another_format_is_refused(tmp_path):
"""The marker is the only claim a packed weight has; contradicting it is not a hint
that can be quietly loaded as the older layout.
"""
path, _ = w4a8_checkpoint(tmp_path / "mixed.safetensors",
marker=w4a8_marker(format="int8_tensorwise"))
with pytest.raises(RuntimeError, match="packed scales while"):
load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16)
@pytest.mark.parametrize("missing", ["q.weight_s_rel", "q.weight_s_channel"])
def test_a_packed_weight_missing_a_scale_raises(missing):
sd = w4a8_tensors()
del sd[missing]
with pytest.raises(RuntimeError, match=f"carries no \\['{missing}'\\]"):
load_quantized_state_dict(TinyDiT(), sd)
def test_a_packed_scale_with_no_weight_of_its_own_raises():
sd = w4a8_tensors()
sd["plain.weight_s_channel"] = torch.zeros(OUT_F, dtype=torch.float32)
with pytest.raises(RuntimeError, match="orphan packed scale"):
load_quantized_state_dict(TinyDiT(), sd)
# --------------------------------------------------- load_quantized_state_dict
def test_load_quantized_state_dict_mixed():
model = TinyDiT()
load_quantized_state_dict(model, int8_tensors())
# The quantized layer switched to INT8...
assert model.q._quantized is True
assert isinstance(model.q.weight, QuantizedTensor)
assert model.q.weight._qdata.dtype == torch.int8
assert model.q.weight.params.scale.dtype == torch.float32
# ...and the full-precision layer was assigned normally.
assert model.plain.weight.dtype == torch.bfloat16
assert model.plain.bias.dtype == torch.bfloat16
# forward runs end-to-end (bf16 in -> bf16 out)
x = _bf16_x()
assert model.q(x).shape == (4, OUT_F)
assert model.q(x).dtype == torch.bfloat16
def test_load_quantized_state_dict_fp8_uses_a_per_tensor_scale():
model = TinyDiT()
sd = int8_tensors(weight_dtype=torch.float8_e4m3fn, scale=torch.tensor(0.5))
load_quantized_state_dict(model, sd)
assert model.q._quantized is True
assert model.q.weight._qdata.dtype == torch.float8_e4m3fn
assert model.q.weight.params.scale.shape == () # per-tensor, not per-row
assert model.q(_bf16_x()).dtype == torch.bfloat16
def test_load_quantized_state_dict_missing_scale_raises():
sd = int8_tensors()
del sd["q.weight_scale"]
with pytest.raises(RuntimeError, match="missing its .weight_scale"):
load_quantized_state_dict(TinyDiT(), sd)
def test_load_quantized_state_dict_orphan_scale_raises():
sd = int8_tensors()
sd["plain.weight_scale"] = torch.zeros(OUT_F, 1, dtype=torch.float32)
with pytest.raises(RuntimeError, match="orphan"):
load_quantized_state_dict(TinyDiT(), sd)
def _fp8_marker(**profile) -> torch.Tensor:
"""A ``comfy_quant`` marker as ComfyUI's FP8 exporter writes it."""
payload = {"format": "float8_e4m3fn", **profile}
return torch.tensor(list(json.dumps(payload).encode("utf-8")), dtype=torch.uint8)
@pytest.mark.parametrize("suffix", [".scale_input", ".input_scale"])
def test_load_quantized_state_dict_installs_the_fp8_activation_scale(suffix):
"""An FP8 export carries a calibrated activation scale next to the weight; the
whole-state loader installs it just as the streaming loader does."""
model = TinyDiT()
load_quantized_state_dict(
model,
int8_tensors(
weight_dtype=torch.float8_e4m3fn,
extra={f"q{suffix}": torch.tensor(0.5)},
),
)
assert model.q.input_scale.item() == pytest.approx(0.5)
assert "q.input_scale" not in model.state_dict()
assert model.q(_bf16_x()).dtype == torch.bfloat16
@pytest.mark.parametrize("disabler", ["checkpoint", "layer"])
def test_full_precision_fp8_export_keeps_its_activation_scale_unused(disabler):
"""A full-precision-matmul export flags itself checkpoint-wide or per layer, and
then the stored scale is stale by construction."""
extra = (
{"scaled_fp8": torch.zeros(2)}
if disabler == "checkpoint"
else {"q.comfy_quant": _fp8_marker(full_precision_matrix_mult=True)}
)
model = TinyDiT()
load_quantized_state_dict(
model,
int8_tensors(
weight_dtype=torch.float8_e4m3fn,
marker=_fp8_marker() if disabler == "checkpoint" else None,
extra={"q.scale_input": torch.tensor(0.5), **extra},
),
)
assert model.q._quantized is True
assert model.q.input_scale is None
@pytest.mark.parametrize("suffix", [".scale_input", ".input_scale"])
def test_load_quantized_state_dict_ignores_a_placeholder_activation_scale(suffix):
"""An exporter that calibrated nothing writes exactly 1.0, which records no
scale; the layer keeps its weight and runs with BF16 activations."""
model = TinyDiT()
load_quantized_state_dict(
model,
int8_tensors(
weight_dtype=torch.float8_e4m3fn,
extra={f"q{suffix}": torch.tensor(1.0)},
),
)
assert model.q._quantized is True
assert model.q.input_scale is None
def test_load_quantized_state_dict_tolerates_an_orphan_placeholder_input_scale():
sd = int8_tensors(extra={"plain.scale_input": torch.tensor(1.0)})
load_quantized_state_dict(TinyDiT(), sd)
def test_load_quantized_state_dict_refuses_an_input_scale_on_an_int8_weight():
sd = int8_tensors(extra={"q.scale_input": torch.tensor(0.5)})
with pytest.raises(RuntimeError, match="FP8 input scale on non-FP8 weight"):
load_quantized_state_dict(TinyDiT(), sd)
@pytest.mark.parametrize(
"scale",
[torch.tensor(0.0), torch.tensor(-1.0), torch.tensor(float("nan")),
torch.tensor([0.5, 0.6])],
ids=["zero", "negative", "nan", "two-values"],
)
def test_load_quantized_state_dict_refuses_an_unusable_input_scale(scale):
sd = int8_tensors(weight_dtype=torch.float8_e4m3fn, extra={"q.scale_input": scale})
with pytest.raises(RuntimeError, match="invalid FP8 input scale"):
load_quantized_state_dict(TinyDiT(), sd)
def test_load_quantized_state_dict_orphan_input_scale_raises():
"""An activation scale for a layer that is not quantized cannot be honoured."""
sd = int8_tensors(extra={"plain.scale_input": torch.tensor(0.5)})
with pytest.raises(RuntimeError, match="orphan .scale_input"):
load_quantized_state_dict(TinyDiT(), sd)
# --------------------------------------------------------------- load_dit
def test_load_dit_bf16(tmp_path):
path = write_safetensors(tmp_path / "bf16.safetensors", bf16_tensors())
model = load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16)
assert model.q._quantized is False
assert model.q.weight.dtype == torch.bfloat16
assert model.plain.weight.dtype == torch.bfloat16
@pytest.mark.parametrize(
"kwargs", [{}, {"prefix": "model.diffusion_model."}], ids=["raw-keys", "wrapped-keys"]
)
def test_load_dit_int8_and_fp8(tmp_path, kwargs):
"""Both quantized formats load, and the wrapper prefix is stripped."""
for weight_dtype in (torch.int8, torch.float8_e4m3fn):
path, _ = int8_checkpoint(
tmp_path / f"dit-{weight_dtype}.safetensors", weight_dtype=weight_dtype, **kwargs
)
model = load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16)
assert model.q._quantized is True
assert model.q.weight._qdata.dtype == weight_dtype
assert model.plain.weight.dtype == torch.bfloat16
assert model.q(_bf16_x()).shape == (4, OUT_F)
def test_load_dit_installs_the_fp8_activation_scale(tmp_path):
"""An FP8 image checkpoint carries ``.scale_input``; the whole-state path used to
stop on the key instead of loading, so no image model ever ran with it."""
path, _ = int8_checkpoint(
tmp_path / "fp8.safetensors",
weight_dtype=torch.float8_e4m3fn,
extra={"q.scale_input": torch.tensor(0.5)},
)
model = load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16)
assert model.q.weight._qdata.dtype == torch.float8_e4m3fn
assert model.q.input_scale.item() == pytest.approx(0.5)
@pytest.mark.parametrize("prefix", ["", "net."])
@pytest.mark.parametrize("quantized", [False, True], ids=["bf16", "int8"])
def test_load_dit_drop_keys_applies_on_both_paths(tmp_path, quantized, prefix):
"""Unexpected leftover keys (e.g. Krea2's unused ``last.*``) are dropped, matched
against the wrapper-stripped name.
"""
extra = {
"last.down.residual": torch.randn(16, dtype=torch.bfloat16),
"last.up.residual": torch.randn(16, dtype=torch.bfloat16),
}
tensors = (
int8_tensors(extra=extra, prefix=prefix) if quantized
else bf16_tensors(extra=extra, prefix=prefix)
)
path = write_safetensors(tmp_path / "dit.safetensors", tensors)
model = TinyDiT()
# Without drop_keys the strict load would fail on the unexpected keys.
load_dit(model, path, device="cpu", dtype=torch.bfloat16, drop_keys=("last.down", "last.up"))
assert model.q._quantized is quantized
assert model.plain.weight.dtype == torch.bfloat16
@pytest.mark.parametrize("quantized", [False, True], ids=["bf16", "int8"])
@pytest.mark.parametrize(
"prefix", ["", "model.diffusion_model."], ids=["raw-keys", "wrapped-keys"]
)
def test_load_dit_drops_checkpoint_markers_for_every_model(tmp_path, quantized, prefix):
"""Checkpoint metadata is dropped centrally, so no model has to name it.
``TinyDiT`` knows nothing about ``__index_timestep_zero__`` and no ``drop_keys``
is passed, yet the strict load survives: markers are registry knowledge
(``thenoise.utils.checkpoint``), read off the header and stripped here. Without
the central drop the BF16 path fails on an unexpected key and the quantized
path on an unrecognized one.
"""
marker = "__index_timestep_zero__"
tensors = (int8_tensors if quantized else bf16_tensors)(
prefix=prefix, extra={f"{prefix}{marker}": torch.zeros(1)}
)
path = write_safetensors(tmp_path / "dit.safetensors", tensors)
model = load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16)
assert model.q._quantized is quantized
assert model.plain.weight.dtype == torch.bfloat16
assert not hasattr(model, marker)
class _ScaleNorm(torch.nn.Module):
def __init__(self, dim):
super().__init__()
self.scale = torch.nn.Parameter(torch.ones(dim))
class _ScaleModel(torch.nn.Module):
"""A model whose norm parameter is called ``scale``, not ``weight``."""
def __init__(self):
super().__init__()
self.q = QuantizedLinear(IN_F, OUT_F)
self.norm = _ScaleNorm(OUT_F)
def test_load_dit_key_map(tmp_path):
"""ComfyUI's INT8 exporter stores norm ``scale`` params under ``weight``."""
path, _ = int8_checkpoint(
tmp_path / "int8.safetensors",
extra={"norm.weight": torch.randn(OUT_F, dtype=torch.bfloat16)},
drop=["plain.weight", "plain.bias"],
)
key_map = lambda k: k[: -len(".weight")] + ".scale" if k.endswith("norm.weight") else k
model = load_dit(_ScaleModel(), path, device="cpu", dtype=torch.bfloat16, key_map=key_map)
assert model.q._quantized is True
assert model.norm.scale.dtype == torch.bfloat16
class _WeightNorm(torch.nn.Module):
"""A norm whose parameter is called ``weight`` (the shared RMSNorm layout)."""
def __init__(self, dim):
super().__init__()
self.weight = torch.nn.Parameter(torch.ones(dim))
class _WeightModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.norm = _WeightNorm(OUT_F)
def test_load_dit_value_map_on_bf16(tmp_path):
"""value_map renames a zero-centered ``scale`` to ``weight`` and shifts by one.
Mirrors Krea2's reconciliation: the checkpoint stores ``scale`` (effective
``weight = scale + 1``); the loader must rename and shift so the runtime
``weight`` param is correct. Runs on the BF16 path.
"""
path = write_safetensors(
tmp_path / "bf16.safetensors",
{"norm.scale": torch.full((OUT_F,), 2.0, dtype=torch.bfloat16)},
)
def value_map(key, tensor):
if key.endswith(".scale"):
return key[: -len(".scale")] + ".weight", tensor + 1.0
return key, tensor
model = load_dit(_WeightModel(), path, device="cpu", dtype=torch.bfloat16, value_map=value_map)
assert torch.equal(model.norm.weight, torch.full((OUT_F,), 3.0, dtype=torch.bfloat16))
@pytest.mark.parametrize("quantized", [False, True], ids=["bf16", "int8"])
def test_load_dit_state_map_stacks_several_tensors_into_one_parameter(tmp_path, quantized):
"""``state_map`` is the hook for N checkpoint keys -> 1 parameter.
Neither per-key map can express it (a ``key_map`` sees one name at a time and a
``value_map`` one tensor), and it has to run BEFORE the quantized/BF16 branch:
this checkpoint names its fused projection ``qkv``, so the fold has to move the
``.weight_scale`` and ``.comfy_quant`` siblings along with the weight or the
quantized path would fail to see a quantized layer at all.
"""
tensors = int8_tensors() if quantized else bf16_tensors()
tensors = {
(k.replace("q.", "qkv.", 1) if k.startswith("q.") else k): v
for k, v in tensors.items()
}
path = write_safetensors(tmp_path / "dit.safetensors", tensors)
def state_map(sd):
return {k.replace("qkv.", "q.", 1) if k.startswith("qkv.") else k: v for k, v in sd.items()}
model = load_dit(TinyDiT(), path, device="cpu", dtype=torch.bfloat16, state_map=state_map)
assert model.q._quantized is quantized
if quantized:
# The scale/marker siblings followed the weight, so the layer is still a
# real quantized one carrying the checkpoint's own codes.
assert torch.equal(model.q.weight._qdata, tensors["qkv.weight"])
assert torch.equal(model.q.weight.params.scale, tensors["qkv.weight_scale"])
else:
assert torch.equal(model.q.weight, tensors["qkv.weight"])
class _BufModel(torch.nn.Module):
"""Model with an internal buffer that is deliberately not in the checkpoint."""
def __init__(self):
super().__init__()
self.plain = torch.nn.Linear(IN_F, OUT_F, bias=True)
self.register_buffer("rope_seq", torch.zeros(128))
def test_load_dit_expected_missing_keeps_the_buffer(tmp_path):
path = write_safetensors(
tmp_path / "bf16.safetensors",
{
"plain.weight": torch.randn(OUT_F, IN_F, dtype=torch.bfloat16),
"plain.bias": torch.randn(OUT_F, dtype=torch.bfloat16),
},
)
model = load_dit(
_BufModel(), path, device="cpu", dtype=torch.bfloat16, expected_missing=("rope_seq",)
)
assert model.plain.weight.dtype == torch.bfloat16
assert model.rope_seq.dtype == torch.float32 # kept, not taken from the checkpoint
def test_load_dit_unexpected_missing_raises(tmp_path):
path = write_safetensors(
tmp_path / "bf16.safetensors",
{"plain.weight": torch.randn(OUT_F, IN_F, dtype=torch.bfloat16)}, # plain.bias missing
)
with pytest.raises(RuntimeError, match="missing"):
load_dit(
_BufModel(), path, device="cpu", dtype=torch.bfloat16,
expected_missing=("rope_seq",), # does not cover plain.bias
)