"""Tail file export and loading: the release file drops the unused proj_out, stores Linear weights in bf16 and the attention RMSNorm weights in fp32, carries clean metadata, and loads to the same tail as the fp32 file.""" import json import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(HERE), "src")) sys.path.insert(0, HERE) import pytest # noqa: E402 import torch # noqa: E402 pytest.importorskip("diffusers") pytest.importorskip("safetensors") from tiny import K, tiny_tail_state, tiny_transformer # noqa: E402 def _legacy(tmp_path): from safetensors.torch import save_file sd = tiny_tail_state(tiny_transformer(0)) p = str(tmp_path / "legacy.safetensors") save_file(sd, p, metadata={"base_model": "Qwen/Qwen-Image-2.1-Turbo", "k": str(K), "weights": "ema", "step": "1"}) return p, sd def test_export_layout_and_metadata(tmp_path): from safetensors import safe_open from pq_image_dwd.weights import FORMAT, export_tail, load_tail_file legacy, sd = _legacy(tmp_path) out = str(tmp_path / "dwd_tail.safetensors") meta = export_tail(legacy, out) with safe_open(out, framework="pt") as f: stored = f.metadata() keys = set(f.keys()) dt = {k: f.get_tensor(k).dtype for k in keys} assert stored == meta assert set(stored) == {"format", "format_version", "base_repo", "k", "steps", "head_sigma", "patch", "head_layout", "color", "oklab_mean", "oklab_std", "weights", "dtype", "compute"} assert stored["format"] == FORMAT and stored["k"] == str(K) and stored["steps"] == "8" assert stored["base_repo"] == "Qwen/Qwen-Image-2.1-Turbo" and stored["dtype"] == "bfloat16" assert json.loads(stored["oklab_mean"]) == [0.56, 0.0, 0.01] and float(stored["head_sigma"]) == 0.414568 assert keys == set(sd) - {"proj_out.weight"} for k, d in dt.items(): assert d == (torch.float32 if k.endswith(("norm_q.weight", "norm_k.weight")) else torch.bfloat16), k a, ma = load_tail_file(out) b, mb = load_tail_file(legacy) assert "proj_out.weight" not in b and set(a) == set(b) assert ma["k"] == mb["k"] == K and mb["format"] == FORMAT # bf16 storage is the round-to-nearest of the fp32 weights (what bf16 autocast computes with) for k in a: want = b[k] if k.endswith(("norm_q.weight", "norm_k.weight")) else b[k].to(torch.bfloat16) assert torch.equal(a[k], want), k def test_fp32_export_and_rejections(tmp_path): from safetensors.torch import save_file from pq_image_dwd.weights import export_tail, load_tail, load_tail_file legacy, sd = _legacy(tmp_path) out = str(tmp_path / "fp32.safetensors") meta = export_tail(legacy, out, dtype=torch.float32) assert meta["dtype"] == "float32" assert all(v.dtype == torch.float32 for v in load_tail_file(out)[0].values()) # a directory holding dwd_tail.safetensors d = tmp_path / "repo" d.mkdir() export_tail(legacy, str(d / "dwd_tail.safetensors")) assert load_tail(str(d))[1]["k"] == K with pytest.raises(FileNotFoundError): load_tail(str(tmp_path / "missing.safetensors")) # wrong format, wrong head layout, stray tensors bad = str(tmp_path / "bad.safetensors") save_file({"x": torch.zeros(1)}, bad, metadata={"format": "dwd-klein-tail"}) with pytest.raises(ValueError): load_tail_file(bad) save_file({**sd, "extra.weight": torch.zeros(1)}, bad) with pytest.raises(ValueError): load_tail_file(bad) m = dict(meta) m["head_layout"] = "(p1,p2,c)" save_file({k: v for k, v in sd.items() if k != "proj_out.weight"}, bad, metadata=m) with pytest.raises(ValueError): load_tail_file(bad) def test_tail_rejects_mismatched_weights(): from pq_image_dwd.model import DWDTail tr = tiny_transformer(0) sd = {k: v for k, v in tiny_tail_state(tr).items() if k != "proj_out.weight"} t = DWDTail.for_transformer(tr, K) with pytest.raises(KeyError): t.load_weights({k: v for k, v in sd.items() if k != "head.bias"}, tr.time_text_embed.time_proj.freqs) t = DWDTail.for_transformer(tr, K + 1) with pytest.raises(KeyError): t.load_weights(sd, tr.time_text_embed.time_proj.freqs)