"""DWDPipeline on a tiny CPU model (random weights, no downloads): - steps 1-7 (and the optional stock last step + VAE) are exactly the stock QwenImage21Pipeline denoising loop, with and without its prefix KV cache, for text-to-image and editing; - the prefix at the last step is exactly the stock forward's hidden states entering the tail's first block; - the tail loaded from the bf16 release file gives exactly the head output of the fp32 weights under bf16 autocast (the evaluated computation), and the earlier fp32 file gives the same image. """ 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 C_LAT, K, TinyText, TinyVAE, sched, tiny_tail_state, tiny_transformer # noqa: E402 W, H = 64, 32 # pixels -> 4 x 2 tokens def _legacy_file(tmp_path, tr, name="legacy.safetensors"): """The earlier export's layout: fp32 tensors incl. an unused proj_out, metadata without a `format` key.""" from safetensors.torch import save_file sd = tiny_tail_state(tr) path = str(tmp_path / name) save_file(sd, path, metadata={"base_model": "Qwen/Qwen-Image-2.1-Turbo", "k": str(K), "weights": "ema"}) return path, sd def _release_file(tmp_path, legacy): from pq_image_dwd.weights import export_tail out = str(tmp_path / "dwd_tail.safetensors") export_tail(legacy, out) return out def _pipe(tail, vae=None): from pq_image_dwd.pipeline import DWDPipeline return DWDPipeline.from_components(tiny_transformer(0), tail, TinyText(), sched(), vae=vae or TinyVAE(), device="cpu") def _stock_loop(tr, cond, h, w, seed, steps, kv: bool): """QwenImage21Pipeline.__call__ steps 3-5 re-typed: prepare_latents, retrieve_timesteps with the turbo sigmas, timestep cast, transformer call (prefix KV cache extract / cached), scheduler.step. Runs `steps` steps.""" from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21KVCache from diffusers.utils.torch_utils import randn_tensor from pq_image_dwd import schedule as S sch = sched() gen = torch.Generator("cpu").manual_seed(seed) lat = randn_tensor((1, 1, C_LAT, h, w), generator=gen, device=torch.device("cpu"), dtype=torch.bfloat16) lat = lat.view(1, C_LAT, h * w).transpose(1, 2) sch.set_timesteps(sigmas=S.SIGMAS, device="cpu", mu=0.9) sch.set_begin_index(0) img_mask = torch.cat([cond.img_mask, cond.img_mask.new_ones(1, h * w // 4)], 1) shapes = [[*cond.cond_shapes, (1, h, w)]] cache = QwenImage21KVCache(len(tr.transformer_blocks)) if kv else None with torch.no_grad(): for i, t in enumerate(sch.timesteps[:steps]): inp = lat if cond.cond_lat is None else torch.cat([cond.cond_lat, lat], 1) timestep = t.expand(1).to(lat.dtype) v = tr(hidden_states=inp, timestep=timestep / 1000, encoder_hidden_states=cond.embeds, encoder_hidden_states_mask=cond.mask, img_shapes=shapes, img_mask=img_mask, kv_cache=cache, kv_cache_mode=None if cache is None else ("extract" if i == 0 else "cached"), return_dict=False)[0][:, -h * w:] lat = sch.step(v, t, lat, return_dict=False)[0] return lat def _captured_prefix(tr, lat, cond, h, w, n_prefix): """Run the stock forward (no cache) at the last sigma and capture the hidden states entering block n_prefix.""" from pq_image_dwd import schedule as S cap = {} def hook(mod, args, kwargs): cap["hs"] = kwargs["hidden_states"].clone() hk = tr.transformer_blocks[n_prefix].register_forward_pre_hook(hook, with_kwargs=True) t = torch.tensor([S.SIGMAS[-1] * 1000], dtype=torch.float32).to(torch.bfloat16) / 1000 inp = lat if cond.cond_lat is None else torch.cat([cond.cond_lat, lat], 1) with torch.no_grad(): tr(hidden_states=inp, timestep=t, encoder_hidden_states=cond.embeds, encoder_hidden_states_mask=cond.mask, img_shapes=[[*cond.cond_shapes, (1, h, w)]], img_mask=torch.cat([cond.img_mask, cond.img_mask.new_ones(1, h * w // 4)], 1), return_dict=False) hk.remove() return cap["hs"], t def _edit_image(seed=3, size=(64, 32)): import numpy as np from PIL import Image rng = np.random.default_rng(seed) return Image.fromarray(rng.integers(0, 255, (size[1], size[0], 3), dtype=np.uint8)) @pytest.mark.parametrize("edit", [False, True]) def test_steps_are_the_stock_pipeline(tmp_path, edit): from pq_image_dwd.color import to_uint8 legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) cond = pipe.encode("a cat on a mat", [_edit_image()] if edit else None, output_resolution=48) if edit: assert cond.cond_lat is not None and cond.cond_shapes == ((1, 2, 4),) h, w = H // 16, W // 16 o = pipe.generate(cond, h, w, seed=5, dwd=False, vae=True) tr = tiny_transformer(0) for kv in (True, False): assert torch.equal(_stock_loop(tr, cond, h, w, 5, 7, kv), o["lat_last"]) ref = _stock_loop(tr, cond, h, w, 5, 8, kv) assert torch.equal(to_uint8(TinyVAE().decode(ref, h, w)), o["vae"]) o2 = pipe.generate(cond, h, w, seed=5, dwd=False, vae=True, use_kv_cache=False) assert torch.equal(o2["vae"], o["vae"]) if edit: # the condition image matters other = pipe.encode("a cat on a mat", [_edit_image(seed=4)], output_resolution=48) assert not torch.equal(pipe.generate(other, h, w, seed=5, dwd=False)["lat_last"], o["lat_last"]) @pytest.mark.parametrize("edit", [False, True]) def test_prefix_is_the_stock_forward(tmp_path, edit): from pq_image_dwd.model import prefix_forward legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) cond = pipe.encode("a dog", [_edit_image()] if edit else None, output_resolution=48) h, w = H // 16, W // 16 lat = pipe.generate(cond, h, w, seed=2, dwd=False)["lat_last"] ref, t = _captured_prefix(tiny_transformer(0), lat, cond, h, w, pipe.n_prefix) hs, ctx = prefix_forward(pipe.transformer, pipe.n_prefix, lat, cond, t, h, w) assert torch.equal(hs, ref) assert ctx.n_txt == hs.shape[1] - h * w @pytest.mark.parametrize("edit", [False, True]) def test_head_is_the_fp32_autocast_path(tmp_path, edit): """The pipeline image == stock steps 1-7, captured stock prefix, the fp32 tail under bf16 autocast (the evaluated computation), Oklab -> sRGB -> uint8. Holds for the bf16 release file and for the fp32 file.""" from pq_image_dwd.color import head_to_srgb, to_uint8 from pq_image_dwd.model import DWDTail from pq_image_dwd.pipeline import fp32_time_freqs tr = tiny_transformer(0) legacy, sd = _legacy_file(tmp_path, tr) release = _release_file(tmp_path, legacy) pipe = _pipe(release) image = [_edit_image()] if edit else None img = pipe("a cat", image=image, width=W, height=H, seed=3, output_resolution=48, output_type="pt") assert img.shape == (H, W, 3) and img.dtype == torch.uint8 cond = pipe.encode("a cat", image, output_resolution=48) h, w = H // 16, W // 16 lat = _stock_loop(tr, cond, h, w, 3, 7, kv=True) hs, t = _captured_prefix(tr, lat, cond, h, w, pipe.n_prefix) ref_tail = DWDTail.for_transformer(tr, K, device="cpu") ref_tail.load_state_dict({n: v for n, v in sd.items() if n != "proj_out.weight"}) # fp32 weights ref_tail.time_text_embed.time_proj.freqs = fp32_time_freqs(tr) assert all(p.dtype == torch.float32 for p in ref_tail.parameters()) from pq_image_dwd.model import build_ctx ctx = build_ctx(tr, cond, h, w, "cpu")[0] with torch.no_grad(): y = ref_tail(hs, t, ctx) assert torch.equal(to_uint8(head_to_srgb(y, h, w))[0], img) # the fp32 file gives the same image assert torch.equal(_pipe(legacy)("a cat", image=image, width=W, height=H, seed=3, output_resolution=48, output_type="pt"), img) # and the return_vae image is the stock pipeline's d, v = pipe("a cat", image=image, width=W, height=H, seed=3, output_resolution=48, output_type="pt", return_vae=True) assert torch.equal(d, img) assert torch.equal(v, to_uint8(TinyVAE().decode(_stock_loop(tr, cond, h, w, 3, 8, kv=True), h, w))[0]) def test_tail_dtypes_and_stock_model_untouched(tmp_path): tr0 = tiny_transformer(0) legacy, _ = _legacy_file(tmp_path, tr0) pipe = _pipe(_release_file(tmp_path, legacy)) assert pipe.k == K and pipe.n_prefix == len(tr0.transformer_blocks) - K assert len(pipe.transformer.transformer_blocks) == len(tr0.transformer_blocks) assert pipe.transformer.norm_out is not None and pipe.transformer.proj_out is not None for (n, a), (_, b) in zip(pipe.transformer.state_dict().items(), tr0.state_dict().items()): assert torch.equal(a, b), n for n, p in pipe.tail.named_parameters(): want = torch.float32 if n.endswith(("norm_q.weight", "norm_k.weight")) else torch.bfloat16 assert p.dtype == want and not p.requires_grad and not p.is_meta, n assert pipe.tail.time_text_embed.time_proj.freqs.dtype == torch.float32 assert not hasattr(pipe.tail, "proj_out") def test_inputs_and_outputs(tmp_path): import numpy as np from PIL import Image legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) a = pipe("a cat", width=W, height=H, seed=0) assert isinstance(a, Image.Image) and a.size == (W, H) b = pipe(["a cat", "a dog"], width=W, height=H, seed=0, output_type="np") assert len(b) == 2 and b[0].shape == (H, W, 3) and b[0].dtype == np.uint8 assert np.array_equal(b[0], np.asarray(a)) # first prompt uses seed 0 c = pipe("a dog", width=W, height=H, seed=1, output_type="np") assert np.array_equal(b[1], c) # second prompt uses seed + 1 assert not np.array_equal(pipe("a cat", width=W, height=H, seed=1, output_type="np"), b[0]) for bad in ((48, 32), (64, 16), (-32, 32)): with pytest.raises(ValueError): pipe("a cat", width=bad[0], height=bad[1]) with pytest.raises(ValueError): pipe("a cat", width=W, height=H, output_type="latent") # editing: the output size defaults to about output_resolution^2 at the condition image's aspect e = pipe("make it snowy", image=_edit_image(size=(128, 64)), seed=0, output_resolution=48) assert e.size == (64, 32) # a file of another format, and a tail with a different block count than its metadata says, are rejected from safetensors.torch import save_file from pq_image_dwd.weights import build_metadata, check_metadata, load_tail_file with pytest.raises(ValueError): check_metadata({"format": "something-else"}) sd = {k: v for k, v in tiny_tail_state(tiny_transformer(0)).items() if k != "proj_out.weight"} bad = str(tmp_path / "k_mismatch.safetensors") save_file(sd, bad, metadata=build_metadata(K + 1, torch.float32)) with pytest.raises(ValueError, match="blocks"): load_tail_file(bad) def test_compile_flag_does_not_change_the_image(tmp_path): pytest.importorskip("torch._dynamo") legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) ref = pipe("a cat", width=W, height=H, seed=0, output_type="pt") try: pipe.enable_compile() out = pipe("a cat", width=W, height=H, seed=0, output_type="pt") except Exception as e: # no compiler toolchain on this machine pytest.skip(f"torch.compile unavailable: {type(e).__name__}") assert (out.int() - ref.int()).abs().max() <= 2