"""Architecture constants of the dflow_2b denoiser and their ``config.json`` form. The denoiser has one fixed architecture. ``DFlowConfig`` holds its constants; ``DFLOW_2B_CONFIG`` is the released model. ``config.json`` carries the same values under the ``"denoiser"`` key, and loading compares them field by field, so a file for a different architecture fails before any weight is read. Other top-level keys of ``config.json`` belong to other components (the text adapter) and are validated by their own loaders. The ``"inference"`` key holds the release's ``InferencePolicy``. """ from __future__ import annotations import json from dataclasses import asdict, dataclass from pathlib import Path DENOISER_CONFIG_KEY = "denoiser" INFERENCE_CONFIG_KEY = "inference" EMPTY_PROMPT_ERROR = ( 'Please enter a prompt. Empty prompts are off: set "allow_empty_prompt": ' 'true under "inference" in config.json to allow them.' ) @dataclass(frozen=True) class DFlowConfig: """Constants of the single-stream denoiser. Attributes: latent_channels: Channels of the (whitened dinac3_96) latent. patch_size: Latent pixels per image token side (a 1x1 patch embed). width: Residual stream width of every block. heads: Attention heads; ``width / heads`` must equal the RoPE head width ``sum(rope_axes_dims)``. mlp_ratio: MLP hidden width as a multiple of ``width``. text_refiner_depth: Unmodulated text-only blocks run once per prompt. prefix_depth: Image layers before the routable middle. middle_depth: Routable middle layers (skipped by path drop). suffix_depth: Image layers after the tail join. time_frequency_width: Sinusoidal timestep features. time_hidden_width: Hidden width of the timestep MLP. time_embed_width: Width of the timestep vector every AdaLN reads. time_scale: Multiplier on ``t`` before the sinusoid. time_max_period: Longest sinusoid period. rope_theta: RoPE frequency base. rope_axes_dims: Head channels of the three RoPE axes (text/frame, y, x). rope_axes_lens: Position capacity of the three RoPE axes. norm_eps: RMSNorm epsilon. """ latent_channels: int patch_size: int width: int heads: int mlp_ratio: int text_refiner_depth: int prefix_depth: int middle_depth: int suffix_depth: int time_frequency_width: int time_hidden_width: int time_embed_width: int time_scale: float time_max_period: float rope_theta: float rope_axes_dims: tuple[int, int, int] rope_axes_lens: tuple[int, int, int] norm_eps: float def __post_init__(self) -> None: """Check the constants are mutually consistent. Raises: ValueError: If the head width differs from the RoPE head width, a width does not split into heads, or a size is not positive. """ for name, value in asdict(self).items(): numbers = value if isinstance(value, tuple) else (value,) if any(number <= 0 for number in numbers): raise ValueError(f"DFlowConfig.{name} must be positive") if self.width % self.heads != 0: raise ValueError("DFlowConfig.width must be divisible by heads") if self.head_width != sum(self.rope_axes_dims): raise ValueError( f"DFlowConfig head width {self.head_width} must equal the RoPE " f"head width {sum(self.rope_axes_dims)}" ) if any(dim % 2 for dim in self.rope_axes_dims): raise ValueError("DFlowConfig.rope_axes_dims entries must be even") if self.patch_size != 1: raise ValueError("DFlowConfig supports a 1x1 patch embed only") @property def head_width(self) -> int: """Channels per attention head.""" return self.width // self.heads @property def mlp_hidden_width(self) -> int: """Hidden channels of every block MLP.""" return self.width * self.mlp_ratio @property def image_layer_count(self) -> int: """Modulated image layers (prefix, middle and suffix).""" return self.prefix_depth + self.middle_depth + self.suffix_depth def to_json_dict(self) -> dict[str, int | float | list[int]]: """The ``config.json`` ``"denoiser"`` mapping (tuples as lists).""" return { key: list(value) if isinstance(value, tuple) else value for key, value in asdict(self).items() } DFLOW_2B_CONFIG = DFlowConfig( latent_channels=96, patch_size=1, width=2304, heads=18, mlp_ratio=4, text_refiner_depth=2, prefix_depth=6, middle_depth=18, suffix_depth=6, time_frequency_width=256, time_hidden_width=1024, time_embed_width=256, time_scale=1000.0, time_max_period=10000.0, rope_theta=10000.0, rope_axes_dims=(32, 48, 48), rope_axes_lens=(8192, 512, 512), norm_eps=1e-6, ) def validate_denoiser_config(payload: dict[str, object], expected: DFlowConfig) -> None: """Compare a ``config.json`` ``"denoiser"`` mapping with ``expected``. Raises: ValueError: If a key is missing or unknown, or a value differs. """ reference = expected.to_json_dict() missing = sorted(set(reference) - set(payload)) unknown = sorted(set(payload) - set(reference)) if missing or unknown: raise ValueError( f"config.json denoiser keys differ from this package: missing={missing}, " f"unknown={unknown}" ) mismatched = { key: (payload[key], value) for key, value in reference.items() if payload[key] != value or type(payload[key]) is not type(value) } if mismatched: details = ", ".join( f"{key}: file {found!r}, expected {want!r}" for key, (found, want) in sorted(mismatched.items()) ) raise ValueError( f"config.json describes a different denoiser architecture ({details})" ) def read_denoiser_config(path: Path, expected: DFlowConfig) -> DFlowConfig: """Read ``config.json`` and return ``expected`` once its denoiser matches. Args: path: The release's ``config.json``. expected: The architecture this package builds. Returns: ``expected``. Raises: FileNotFoundError: If ``path`` does not exist. ValueError: If the file is not a JSON object with a matching ``"denoiser"`` mapping. """ if not path.is_file(): raise FileNotFoundError(f"Missing denoiser config: {path}") payload = json.loads(path.read_text(encoding="utf-8")) match payload: case {"denoiser": dict() as denoiser}: validate_denoiser_config(denoiser, expected) return expected case dict(): raise ValueError(f"{path} has no {DENOISER_CONFIG_KEY!r} mapping") case _: raise ValueError(f"{path} must hold a JSON object") @dataclass(frozen=True) class InferencePolicy: """Inference rules a release sets in ``config.json`` ``"inference"``. Attributes: allow_empty_prompt: Whether a blank prompt may sample (from the learned unconditional text). Off in the release, so a public interface does not generate freely when the prompt is forgotten; set it to true locally to allow it. """ allow_empty_prompt: bool def to_json_dict(self) -> dict[str, object]: """The ``"inference"`` mapping of ``config.json``.""" return {"allow_empty_prompt": self.allow_empty_prompt} # The policy the release ships. RELEASE_INFERENCE_POLICY = InferencePolicy(allow_empty_prompt=False) def read_inference_policy(path: Path) -> InferencePolicy: """Read the ``"inference"`` mapping of ``config.json``. Raises: FileNotFoundError: If ``path`` does not exist. ValueError: If the mapping is missing, has other keys, or ``allow_empty_prompt`` is not a boolean. """ if not path.is_file(): raise FileNotFoundError(f"Missing config: {path}") payload = json.loads(path.read_text(encoding="utf-8")) match payload: case {"inference": {"allow_empty_prompt": bool() as allow} as policy} if ( len(policy) == 1 ): return InferencePolicy(allow_empty_prompt=allow) case _: raise ValueError( f'{path} needs "{INFERENCE_CONFIG_KEY}": {{"allow_empty_prompt": ' "true or false} and no other keys under it." )