File size: 8,652 Bytes
6daffc2
 
 
 
 
 
 
9fe1cfd
 
6daffc2
 
 
 
 
 
 
 
 
9fe1cfd
 
 
 
 
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fe1cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""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."
            )