"""Export round trip on a tiny CPU model: a training checkpoint becomes a safetensors file with only the student tail + head (EMA overlaid by default), the expected dtype and metadata, and nothing from the optimizer, discriminator, RNG or config.""" import importlib.util 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") K = 2 def _fake_checkpoint(path: str, seed: int = 0, k: int = K, with_ema: bool = True) -> dict: """A training checkpoint with the trainer's top-level entries; student and EMA differ.""" from tiny import tiny_base from dwd_klein.model import DWDKlein model = DWDKlein(tiny_base(seed), k=k) g = torch.Generator().manual_seed(seed + 1) with torch.no_grad(): for p in model.student.parameters(): p.add_(0.01 * torch.randn(p.shape, generator=g)) student = {n: v.detach().clone() for n, v in model.student.state_dict().items()} ema = {n: (p.detach() + 0.003 * torch.randn(p.shape, generator=g)).clone() for n, p in model.student.named_parameters()} ck = {"it": 1500, "world": 1, "cfg": {"run": "my-run", "k": k, "ckpt_root": "./checkpoints", "data_root": "./data"}, "student": student, "opt": {"state": {0: {"exp_avg": torch.zeros(3)}}, "param_groups": []}, "disc": {"heads.0.weight": torch.ones(2, 2)}, "opt_d": {"state": {}, "param_groups": []}, "rank_states": [{"data": None, "rng": {"torch": torch.get_rng_state()}}]} if with_ema: ck["ema"] = ema torch.save(ck, path) return ck def test_export_keys_dtype_metadata(tmp_path): from safetensors import safe_open from dwd_klein.color import OKLAB_MEAN, OKLAB_STD from dwd_klein.export import BASE_REPO, TAIL_PREFIXES, export_checkpoint, load_tail_file ckp, out = str(tmp_path / "ckpt_001500.pt"), str(tmp_path / "tail.safetensors") ck = _fake_checkpoint(ckp) meta = export_checkpoint(ckp, out) sd, parsed = load_tail_file(out) assert set(sd) == set(ck["student"]) assert all(k.startswith(TAIL_PREFIXES) for k in sd) assert any(k.startswith("head.") for k in sd) and any(k.startswith("blocks.1.") for k in sd) assert not any(k.startswith("blocks.2.") for k in sd) assert all(v.dtype == torch.bfloat16 for v in sd.values()) for n, v in sd.items(): # EMA overlay: every student tensor is a parameter, so every value comes from the EMA assert torch.equal(v, ck["ema"][n].to(torch.bfloat16)), n with safe_open(out, framework="pt") as f: raw_meta = f.metadata() assert raw_meta == meta assert meta["format"] == "dwd-klein-tail" and meta["format_version"] == "1" assert meta["base_repo"] == BASE_REPO == "black-forest-labs/FLUX.2-klein-4B" assert meta["k"] == str(K) and meta["steps"] == "4" and meta["patch"] == "16" assert meta["head_layout"] == "(c,p1,p2)" and meta["weights"] == "ema" and meta["dtype"] == "bfloat16" assert json.loads(meta["oklab_mean"]) == list(OKLAB_MEAN) and float(meta["oklab_std"]) == OKLAB_STD assert meta["train_iteration"] == "1500" assert parsed["k"] == K and parsed["steps"] == 4 def test_export_has_nothing_else(tmp_path): from dwd_klein.export import export_checkpoint, load_tail_file ckp, out = str(tmp_path / "ck.pt"), str(tmp_path / "tail.safetensors") _fake_checkpoint(ckp) meta = export_checkpoint(ckp, out) sd, _ = load_tail_file(out) for bad in ("opt", "disc", "rng", "rank_states", "cfg", "exp_avg", "heads."): assert not any(k.startswith(bad) or bad in k.split(".")[0] for k in sd), bad blob = json.dumps(meta) for bad in ("./checkpoints", "./data", "my-run", "ckpt_root", "data_root"): assert bad not in blob, bad # file size: only the tail + head (no optimizer moments) n_bytes = sum(v.numel() * v.element_size() for v in sd.values()) assert os.path.getsize(out) < n_bytes + 64 * 1024 def test_export_raw_and_fp32(tmp_path): from dwd_klein.export import export_checkpoint, load_tail_file ckp = str(tmp_path / "ck.pt") ck = _fake_checkpoint(ckp) raw = str(tmp_path / "raw.safetensors") assert export_checkpoint(ckp, raw, use_ema=False)["weights"] == "raw" sd, _ = load_tail_file(raw) assert all(torch.equal(v, ck["student"][n].to(torch.bfloat16)) for n, v in sd.items()) f32 = str(tmp_path / "f32.safetensors") assert export_checkpoint(ckp, f32, dtype=torch.float32)["dtype"] == "float32" sd, _ = load_tail_file(f32) assert all(v.dtype == torch.float32 and torch.equal(v, ck["ema"][n]) for n, v in sd.items()) def test_export_errors(tmp_path): from safetensors.torch import save_file from dwd_klein.export import build_metadata, check_metadata, export_checkpoint, load_tail_file ckp = str(tmp_path / "noema.pt") _fake_checkpoint(ckp, with_ema=False) with pytest.raises(KeyError): export_checkpoint(ckp, str(tmp_path / "x.safetensors")) export_checkpoint(ckp, str(tmp_path / "x.safetensors"), use_ema=False) with pytest.raises(ValueError): check_metadata({"format": "something-else"}) meta = build_metadata(K, True, torch.bfloat16) with pytest.raises(ValueError): check_metadata({**meta, "oklab_std": "0.2"}) with pytest.raises(ValueError): check_metadata({**meta, "head_layout": "(p1,p2,c)"}) bad = str(tmp_path / "bad_k.safetensors") save_file({"blocks.0.w": torch.zeros(1), "head.weight": torch.zeros(1)}, bad, metadata=meta) # k=2 claimed with pytest.raises(ValueError): load_tail_file(bad) def test_export_cli_run_dir(tmp_path): spec = importlib.util.spec_from_file_location( "export_checkpoint_cli", os.path.join(os.path.dirname(HERE), "scripts", "export_checkpoint.py")) cli = importlib.util.module_from_spec(spec) spec.loader.exec_module(cli) from dwd_klein.export import load_tail_file run = tmp_path / "run" run.mkdir() _fake_checkpoint(str(run / "ckpt_001500.pt")) (run / "latest").write_text("ckpt_001500.pt") out = str(tmp_path / "cli.safetensors") assert cli.main(["--ckpt", str(run), "--out", out, "--raw", "--fp32"]) == 0 sd, meta = load_tail_file(out) assert meta["weights"] == "raw" and meta["dtype"] == "float32" and meta["k"] == K