"""The tail file: reading, checking and writing `dwd_tail.safetensors`. The released file holds the trained tail and head (EMA weights): 4 transformer blocks, the copies of the time embedding and the shared modulation, norm_out, and head. Linear weights are bf16; the 8 attention RMSNorm weights (128 values each) are fp32, because the tail runs under bf16 autocast, where those weights are used as stored (see model.FP32_SUFFIXES). This is the same computation as running fp32 weights under bf16 autocast. The safetensors metadata (all strings) describes how to run the head: format "pq-image-dwd-tail" format_version "1" base_repo the base model the tail was trained on k number of transformer blocks in the tail steps sampler steps; the head replaces the last one head_sigma the sigma of that last step patch pixels per token side (16) head_layout order of the 768 head outputs per token: "(c,p1,p2)" color "oklab_norm": head outputs are normalized Oklab oklab_mean JSON list, normalization mean oklab_std normalization std weights "ema" dtype storage dtype of the Linear weights ("bfloat16" or "float32") compute "bf16-autocast" `load_tail_file` also reads the earlier fp32 export of the same weights (no `format` key, plus an unused proj_out), which gives the identical tail. """ from __future__ import annotations import json import os import re import torch from .color import OKLAB_MEAN, OKLAB_STD, PATCH from .model import keeps_fp32 from .schedule import HEAD_SIGMA, STEPS FORMAT = "pq-image-dwd-tail" FORMAT_VERSION = 1 BASE_REPO = "Qwen/Qwen-Image-2.1-Turbo" HEAD_LAYOUT = "(c,p1,p2)" TAIL_FILENAME = "dwd_tail.safetensors" TAIL_PREFIXES = ("blocks.", "time_text_embed.", "modulation.", "norm_out.", "head.") UNUSED_KEYS = ("proj_out.weight",) # trained-tail velocity output: present in the fp32 export, never used _DTYPES = {"bfloat16": torch.bfloat16, "float32": torch.float32} def count_blocks(sd: dict) -> int: """Number of tail blocks in a state dict (keys blocks..*).""" idx = {int(m.group(1)) for k in sd if (m := re.match(r"blocks\.(\d+)\.", k))} if idx != set(range(len(idx))): raise ValueError(f"tail block indices are not contiguous from 0: {sorted(idx)}") return len(idx) def clean_state_dict(sd: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: """Drop the unused keys and check that only tail and head tensors are left.""" out = {k: v for k, v in sd.items() if k not in UNUSED_KEYS} bad = [k for k in out if not k.startswith(TAIL_PREFIXES)] if bad: raise ValueError(f"unexpected keys in the tail state: {bad[:5]}") if "head.weight" not in out: raise ValueError("the state has no DWD head") return out def build_metadata(k: int, dtype: torch.dtype, base_repo: str = BASE_REPO) -> dict[str, str]: return {"format": FORMAT, "format_version": str(FORMAT_VERSION), "base_repo": base_repo, "k": str(k), "steps": str(STEPS), "head_sigma": repr(float(HEAD_SIGMA)), "patch": str(PATCH), "head_layout": HEAD_LAYOUT, "color": "oklab_norm", "oklab_mean": json.dumps(list(OKLAB_MEAN)), "oklab_std": repr(float(OKLAB_STD)), "weights": "ema", "dtype": str(dtype).replace("torch.", ""), "compute": "bf16-autocast"} def check_metadata(meta: dict | None, sd: dict | None = None) -> dict: """Validate the metadata of a tail file. Returns it parsed: {k, steps, base_repo, ...}. A file without a `format` key is accepted as the earlier export of the same weights when its tensors are a DWD tail (sd given); its metadata is then rebuilt from the tensors.""" meta = dict(meta or {}) if "format" not in meta and sd is not None and "head.weight" in sd and any(k.startswith("blocks.") for k in sd): dtype = sd["head.weight"].dtype meta = build_metadata(count_blocks(sd), dtype, meta.get("base_model", BASE_REPO)) if meta.get("format") != FORMAT: raise ValueError(f"not a DWD tail file for this package (format={meta.get('format')!r})") if int(meta.get("format_version", -1)) > FORMAT_VERSION: raise ValueError(f"tail format_version {meta['format_version']} is newer than this code ({FORMAT_VERSION})") if int(meta["patch"]) != PATCH or meta["head_layout"] != HEAD_LAYOUT or meta.get("color") != "oklab_norm": raise ValueError(f"unsupported head layout: patch {meta['patch']}, {meta['head_layout']}, {meta.get('color')}") mean, std = json.loads(meta["oklab_mean"]), float(meta["oklab_std"]) if any(abs(a - b) > 1e-9 for a, b in zip(mean, OKLAB_MEAN)) or abs(std - OKLAB_STD) > 1e-9: raise ValueError(f"tail was trained with Oklab mean {mean} / std {std}; this code uses " f"{list(OKLAB_MEAN)} / {OKLAB_STD}") return {**meta, "k": int(meta["k"]), "steps": int(meta["steps"])} def load_tail_file(path: str) -> tuple[dict[str, torch.Tensor], dict]: """Read a tail file: (tensors on CPU, unused keys dropped; parsed metadata).""" from safetensors import safe_open from safetensors.torch import load_file with safe_open(path, framework="pt") as f: raw_meta = f.metadata() sd = clean_state_dict(load_file(path)) meta = check_metadata(raw_meta, sd) if count_blocks(sd) != meta["k"]: raise ValueError(f"metadata says k={meta['k']} but the file has {count_blocks(sd)} blocks") return sd, meta def load_tail(tail: str, filename: str = TAIL_FILENAME) -> tuple[dict[str, torch.Tensor], dict]: """A .safetensors file, a directory holding `filename`, or a Hugging Face repo id -> (tensors, metadata).""" if os.path.isdir(tail): tail = os.path.join(tail, filename) elif tail.endswith(".safetensors") and not os.path.isfile(tail): raise FileNotFoundError(tail) elif not os.path.isfile(tail): from huggingface_hub import hf_hub_download tail = hf_hub_download(tail, filename) return load_tail_file(tail) def release_state_dict(sd: dict[str, torch.Tensor], dtype: torch.dtype = torch.bfloat16) -> dict[str, torch.Tensor]: """Tail tensors in the released layout: unused keys dropped, Linear weights in `dtype`, the RMSNorm weights fp32.""" if dtype not in _DTYPES.values(): raise ValueError(f"dtype must be bfloat16 or float32, got {dtype}") return {n: v.detach().to(torch.float32 if keeps_fp32(n) else dtype).contiguous().clone() for n, v in sorted(clean_state_dict(sd).items())} def export_tail(src: str, out_path: str, dtype: torch.dtype = torch.bfloat16, base_repo: str = BASE_REPO) -> dict[str, str]: """Re-write a tail file (e.g. the fp32 export) as a release file with clean metadata. Returns the metadata.""" from safetensors.torch import save_file sd, _ = load_tail_file(src) out = release_state_dict(sd, dtype) meta = build_metadata(count_blocks(out), dtype, base_repo) os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) save_file(out, out_path, metadata=meta) return meta