multimodalart HF Staff commited on
Commit
00ff9d7
·
verified ·
1 Parent(s): daff47b

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,13 +1,40 @@
1
  ---
2
- title: Dflow 2b
3
- emoji: 👁
4
- colorFrom: green
5
  colorTo: green
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: dflow_2b
3
+ emoji: 🖼️
4
+ colorFrom: purple
5
  colorTo: green
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ short_description: Text-to-image with the 2B dflow flow-matching model
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 1h
12
  ---
13
 
14
+ # dflow_2b — text-to-image
15
+
16
+ Interactive demo of **[data-archetype/dflow_2b](https://huggingface.co/data-archetype/dflow_2b)**,
17
+ a 2B-parameter flow-matching text-to-image model (preview, version 0.2).
18
+
19
+ - **Sampling:** 50-step ER-SDE solver on a Beta(1.25, 1.25) log-SNR-shifted
20
+ schedule (resolution-shifted).
21
+ - **Guidance:** path-drop guidance (PDG, full path drop, constant scale 2.5,
22
+ suffix caption bias −4) with self-attention gain −0.03; classifier-free
23
+ guidance is off by default but can be enabled in the UI.
24
+ - **Prompts:** plain text — `(phrase:weight)` emphasis markup, `"quoted text"`
25
+ tokenized letter-by-letter — or a **stored JSON layout** (summary / frame /
26
+ items with 0–1000 `box_2d` boxes) compiled to the chosen image size
27
+ automatically.
28
+ - **Autoencoder:** [dinac3_96](https://huggingface.co/data-archetype/dinac3_96)
29
+ (DINOv3-based semantic autoencoder), downloaded automatically.
30
+ - **torch.compile is disabled** (ZeroGPU does not support JIT compilation);
31
+ the pipeline runs eagerly, which trades a little speed for compatibility.
32
+
33
+ Examples are the prompts, seeds and sizes the authors showcase in the model's
34
+ gallery.
35
+
36
+ ## License
37
+
38
+ - Model weights: MG-BY-NC-2.0 (non-commercial).
39
+ - Text encoder: Gemma terms of use.
40
+ - `dflow` package code: Apache-2.0 (bundled verbatim from the model release).
app.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive text-to-image demo for data-archetype/dflow_2b."""
2
+
3
+ import spaces # ZeroGPU: must be imported before torch.
4
+
5
+ import json
6
+ import random
7
+ import time
8
+
9
+ import gradio as gr
10
+
11
+ from dflow.guidance import (
12
+ CfgGuidance,
13
+ ConstantPdgScale,
14
+ GuidanceSettings,
15
+ PdgGuidance,
16
+ PdgMode,
17
+ )
18
+ from dflow.inference import GenerationSettings, SamplingSettings
19
+ from dflow.pipeline import DFlowPipeline
20
+ from dflow.schedules import ScheduleKind, TimeSchedule
21
+ from dflow.solvers import Solver
22
+
23
+ MAX_SEED = 2**63 - 1
24
+
25
+ # Size presets: (width, height) in pixels. Layout JSON compiles to the chosen
26
+ # size; plain prompts work at any of these sizes.
27
+ SIZE_PRESETS = {
28
+ "832 × 1216 (2:3 portrait)": (832, 1216),
29
+ "1216 × 832 (3:2 landscape)": (1216, 832),
30
+ "1120 × 1664 (2:3 portrait, 1.4 MP)": (1120, 1664),
31
+ "1664 × 1120 (3:2 landscape, 1.4 MP)": (1664, 1120),
32
+ "1216 × 1088 (10:9)": (1216, 1088),
33
+ "1024 × 1024 (square)": (1024, 1024),
34
+ }
35
+
36
+ pipe = DFlowPipeline.from_pretrained("data-archetype/dflow_2b", compile=False)
37
+
38
+
39
+ @spaces.GPU(duration=180)
40
+ def generate(
41
+ prompt: str,
42
+ size_choice: str,
43
+ seed: int,
44
+ steps: int,
45
+ noise_scale: float,
46
+ pdg_scale: float,
47
+ suffix_caption_bias: float,
48
+ self_attention_gain: float,
49
+ use_cfg: bool,
50
+ cfg_scale: float,
51
+ negative_prompt: str,
52
+ randomize_seed: bool,
53
+ progress: gr.Progress = gr.Progress(track_tqdm=True),
54
+ ) -> tuple:
55
+ """Generate an image from a text prompt with dflow_2b.
56
+
57
+ Args:
58
+ prompt: Text prompt, or a stored JSON layout (summary/frame/items
59
+ with 0-1000 boxes) which the pipeline compiles to the size.
60
+ size_choice: One of the size preset labels.
61
+ seed: Seed of the random draws, in [0, 2**63 - 1].
62
+ steps: Number of ER-SDE solver updates (50 in the reference).
63
+ noise_scale: Noise multiplier of the stochastic solver.
64
+ pdg_scale: Constant path-drop guidance scale (2.5 in the reference).
65
+ suffix_caption_bias: PDG reference caption-logit bias (-4 in the
66
+ reference; more negative reads the prompt less).
67
+ self_attention_gain: Self-attention gain (-0.03 by default).
68
+ use_cfg: Enable classifier-free guidance against the negative
69
+ prompt (off in the reference; PDG replaces it).
70
+ cfg_scale: CFG scale, used only when use_cfg is True.
71
+ negative_prompt: Text of the CFG negative branch; empty selects the
72
+ learned null text.
73
+ randomize_seed: Draw and return a fresh seed instead of using the
74
+ given one.
75
+
76
+ Returns:
77
+ (image, seed_used, seconds): the generated PIL image, the seed it
78
+ was generated with, and the wall-clock seconds spent generating.
79
+ """
80
+
81
+ if randomize_seed:
82
+ seed = random.randint(0, MAX_SEED)
83
+ seed = int(seed) % (MAX_SEED + 1)
84
+
85
+ width, height = SIZE_PRESETS.get(size_choice, (832, 1216))
86
+
87
+ settings = GenerationSettings(
88
+ width=width,
89
+ height=height,
90
+ seed=seed,
91
+ sampling=SamplingSettings(
92
+ solver=Solver.ER_SDE,
93
+ noise_scale=float(noise_scale),
94
+ schedule=TimeSchedule(
95
+ kind=ScheduleKind.BETA_1_25,
96
+ steps=int(steps),
97
+ beta_mean=0.5,
98
+ beta_concentration=0.6,
99
+ ),
100
+ ),
101
+ guidance=GuidanceSettings(
102
+ pdg=PdgGuidance(
103
+ mode=PdgMode.FULL,
104
+ scale=ConstantPdgScale(scale=float(pdg_scale)),
105
+ suffix_caption_bias=float(suffix_caption_bias),
106
+ ),
107
+ cfg=CfgGuidance(
108
+ enabled=bool(use_cfg),
109
+ scale=float(cfg_scale) if use_cfg else None,
110
+ ),
111
+ self_attention_gain=float(self_attention_gain),
112
+ ),
113
+ negative_prompt=str(negative_prompt),
114
+ )
115
+
116
+ started = time.perf_counter()
117
+ output = pipe(prompt, settings)
118
+ elapsed = time.perf_counter() - started
119
+
120
+ return output.images[0], seed, round(elapsed, 1)
121
+
122
+
123
+ _JAZZ_LAYOUT = json.dumps(
124
+ {
125
+ "summary": {
126
+ "meta": ["concert_poster", "flat_illustration", "mid_century_modern"],
127
+ "canvas": "single",
128
+ "caption": (
129
+ "A mid-century style jazz festival poster shows a saxophonist in "
130
+ "silhouette against a large orange sun on a deep teal background. "
131
+ 'The title "BLUE HARBOR JAZZ" runs across the top in cream capitals '
132
+ 'and the line "JULY 12 – 14, 1996" sits at the bottom.'
133
+ ),
134
+ },
135
+ "frame": {
136
+ "caption": (
137
+ "The saxophonist stands in the centre, cut off at the knees, with "
138
+ "the sun behind his shoulders. The title fills the top fifth and "
139
+ "the date line sits in a band along the bottom edge. Flat colour "
140
+ "shapes with a light paper grain."
141
+ ),
142
+ "tags": ["flat_color", "centered_composition", "paper_grain"],
143
+ "palette": ["#0F4C5C", "#F28C28", "#F5E9D0", "#1B1B1B"],
144
+ },
145
+ "items": [
146
+ {
147
+ "label": "object",
148
+ "caption": "A large flat orange circle, the sun, behind the musician.",
149
+ "tags": ["sun", "circle"],
150
+ "palette": ["#F28C28"],
151
+ "box_2d": [230, 170, 720, 830],
152
+ },
153
+ {
154
+ "label": "character",
155
+ "caption": (
156
+ "A black silhouette of a man in a hat playing a tenor saxophone, "
157
+ "facing right, leaning back slightly."
158
+ ),
159
+ "tags": ["saxophonist", "silhouette", "hat"],
160
+ "palette": ["#1B1B1B"],
161
+ "box_2d": [260, 250, 880, 760],
162
+ },
163
+ {
164
+ "label": "text",
165
+ "caption": (
166
+ 'The title "BLUE HARBOR JAZZ" in bold condensed cream capitals '
167
+ "on one line."
168
+ ),
169
+ "text": "BLUE HARBOR JAZZ",
170
+ "tags": ["title", "condensed_sans", "uppercase"],
171
+ "palette": ["#F5E9D0"],
172
+ "box_2d": [60, 70, 180, 930],
173
+ },
174
+ {
175
+ "label": "text",
176
+ "caption": (
177
+ 'The date line "JULY 12 – 14, 1996" in small spaced cream capitals.'
178
+ ),
179
+ "text": "JULY 12 – 14, 1996",
180
+ "tags": ["date", "small_caps"],
181
+ "palette": ["#F5E9D0"],
182
+ "box_2d": [905, 300, 950, 700],
183
+ },
184
+ ],
185
+ }
186
+ )
187
+
188
+ # Each row: the authors' gallery prompt with the seed and size it was shown at
189
+ # (self-attention gain as the authors used for that image; CFG off everywhere).
190
+ _EXAMPLE_ROWS = [
191
+ [
192
+ "A bright orange and black rooster standing on a damp garden path, "
193
+ "surrounded by lush green tropical plants and trees, its red comb upright "
194
+ "and long dark tail feathers curving down over the wet concrete.",
195
+ "832 × 1216 (2:3 portrait)",
196
+ 42,
197
+ 50,
198
+ 1.0,
199
+ 2.5,
200
+ -4.0,
201
+ -0.03,
202
+ False,
203
+ 4.0,
204
+ "",
205
+ False,
206
+ ],
207
+ [
208
+ "Leopard lying down in a tree at night.",
209
+ "1216 × 832 (3:2 landscape)",
210
+ 43,
211
+ 50,
212
+ 1.0,
213
+ 2.5,
214
+ -4.0,
215
+ -0.03,
216
+ False,
217
+ 4.0,
218
+ "",
219
+ False,
220
+ ],
221
+ [
222
+ 'A traditional japanese woodblock print, "the great wave off kanagawa" by '
223
+ "hokusai, depicts a massive blue and white wave crashing towards the viewer "
224
+ "against a pale blue sky.",
225
+ "1024 × 1024 (square)",
226
+ 424,
227
+ 50,
228
+ 1.0,
229
+ 2.5,
230
+ -4.0,
231
+ -0.03,
232
+ False,
233
+ 4.0,
234
+ "",
235
+ False,
236
+ ],
237
+ [
238
+ "An oil painting of a landscape with sheep and farmers near a mill by John "
239
+ "Constable",
240
+ "1216 × 1088 (10:9)",
241
+ 44,
242
+ 50,
243
+ 1.0,
244
+ 2.5,
245
+ -4.0,
246
+ -0.02,
247
+ False,
248
+ 4.0,
249
+ "",
250
+ False,
251
+ ],
252
+ [
253
+ _JAZZ_LAYOUT,
254
+ "832 × 1216 (2:3 portrait)",
255
+ 42,
256
+ 50,
257
+ 1.0,
258
+ 2.5,
259
+ -4.0,
260
+ -0.03,
261
+ False,
262
+ 4.0,
263
+ "",
264
+ False,
265
+ ],
266
+ ]
267
+
268
+ css = """
269
+ #col-container { margin: 0 auto; max-width: 1100px; }
270
+ """
271
+
272
+ with gr.Blocks(theme=gr.themes.Citrus(), css=css) as demo:
273
+ gr.Markdown(
274
+ """
275
+ # dflow_2b — text-to-image
276
+
277
+ **dflow_2b** is a 2B-parameter flow-matching text-to-image model from
278
+ [data-archetype](https://huggingface.co/data-archetype/dflow_2b)
279
+ (preview, version 0.2). It samples with a 50-step ER-SDE solver on a
280
+ Beta(1.25, 1.25) schedule and uses **path-drop guidance** (PDG) instead
281
+ of classifier-free guidance by default.
282
+
283
+ Prompts may be plain text — with `(phrase:weight)` emphasis markup and
284
+ `"quoted text"` tokenized letter-by-letter — **or a stored JSON layout**
285
+ (summary / frame / items with 0–1000 `box_2d` coordinates) which the
286
+ pipeline compiles to the chosen image size automatically. Try the
287
+ examples below.
288
+
289
+ *Weights: MG-BY-NC-2.0 (non-commercial); text encoder under Gemma
290
+ terms. Preview model — some seeds are uneven.*
291
+ """
292
+ )
293
+
294
+ with gr.Column(elem_id="col-container"):
295
+ with gr.Row():
296
+ with gr.Column(scale=1):
297
+ prompt = gr.Textbox(
298
+ label="Prompt (text or JSON layout)",
299
+ placeholder=(
300
+ "A bright orange and black rooster standing on a damp "
301
+ "garden path…"
302
+ ),
303
+ lines=5,
304
+ max_lines=14,
305
+ )
306
+ with gr.Row():
307
+ size_choice = gr.Dropdown(
308
+ choices=list(SIZE_PRESETS.keys()),
309
+ value="832 × 1216 (2:3 portrait)",
310
+ label="Image size",
311
+ filterable=False,
312
+ )
313
+ seed = gr.Number(
314
+ value=0,
315
+ minimum=0,
316
+ maximum=MAX_SEED,
317
+ label="Seed",
318
+ precision=0,
319
+ )
320
+ randomize_seed = gr.Checkbox(
321
+ value=True, label="Randomize seed on every run"
322
+ )
323
+ with gr.Accordion("Guidance", open=True):
324
+ pdg_scale = gr.Slider(
325
+ 0.0, 6.0, value=2.5, step=0.1, label="PDG scale"
326
+ )
327
+ suffix_caption_bias = gr.Slider(
328
+ -12.0, 0.0, value=-4.0, step=0.5, label="Suffix caption bias"
329
+ )
330
+ self_attention_gain = gr.Slider(
331
+ -0.10,
332
+ 0.0,
333
+ value=-0.03,
334
+ step=0.01,
335
+ label="Self-attention gain",
336
+ )
337
+ use_cfg = gr.Checkbox(
338
+ value=False,
339
+ label="Enable CFG (uses the negative prompt)",
340
+ )
341
+ negative_prompt = gr.Textbox(
342
+ label="Negative prompt (CFG only)",
343
+ value="",
344
+ lines=2,
345
+ placeholder="blurry, watermark…",
346
+ )
347
+ cfg_scale = gr.Slider(
348
+ 1.0, 12.0, value=4.0, step=0.1, label="CFG scale"
349
+ )
350
+ with gr.Accordion("Sampler", open=False):
351
+ steps = gr.Slider(1, 100, value=50, step=1, label="Steps")
352
+ noise_scale = gr.Slider(
353
+ 0.0, 2.0, value=1.0, step=0.05, label="Noise scale"
354
+ )
355
+ run = gr.Button("Generate", variant="primary")
356
+ with gr.Column(scale=1):
357
+ image = gr.Image(label="Generated image", type="pil")
358
+ seed_used = gr.Number(label="Seed used", precision=0)
359
+ elapsed = gr.Number(label="Seconds", precision=1)
360
+
361
+ run.click(
362
+ fn=generate,
363
+ inputs=[
364
+ prompt,
365
+ size_choice,
366
+ seed,
367
+ steps,
368
+ noise_scale,
369
+ pdg_scale,
370
+ suffix_caption_bias,
371
+ self_attention_gain,
372
+ use_cfg,
373
+ cfg_scale,
374
+ negative_prompt,
375
+ randomize_seed,
376
+ ],
377
+ outputs=[image, seed_used, elapsed],
378
+ api_name="generate",
379
+ show_progress=True,
380
+ )
381
+
382
+ gr.Examples(
383
+ examples=_EXAMPLE_ROWS,
384
+ inputs=[
385
+ prompt,
386
+ size_choice,
387
+ seed,
388
+ steps,
389
+ noise_scale,
390
+ pdg_scale,
391
+ suffix_caption_bias,
392
+ self_attention_gain,
393
+ use_cfg,
394
+ cfg_scale,
395
+ negative_prompt,
396
+ randomize_seed,
397
+ ],
398
+ fn=generate,
399
+ outputs=[image, seed_used, elapsed],
400
+ cache_examples=True,
401
+ cache_mode="lazy",
402
+ label="Examples from the model's gallery (authors' prompts, seeds and sizes)",
403
+ )
404
+
405
+ demo.launch(mcp_server=True)
dflow/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """dflow: inference package for the dflow_2b text-to-image model."""
2
+
3
+ from .version import MODEL_VERSION, __version__
4
+
5
+ __all__ = ["MODEL_VERSION", "__version__"]
dflow/blocks.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The transformer block of the dflow denoiser: dense joint self-attention.
2
+
3
+ One block class serves the text refiner (unmodulated) and the prefix, middle
4
+ and suffix image layers (scale-and-gate AdaLN from the timestep). Every block
5
+ is a sandwich-norm residual block::
6
+
7
+ h = norm2(attention(modulate(norm1(x), s_a)))
8
+ x = x + tanh(g_a) * h
9
+ h = norm2'(mlp(modulate(norm1'(x), s_m)))
10
+ x = x + tanh(g_m) * h
11
+
12
+ with ``modulate(n, s) = n * (1 + s)`` (no shift); the refiner adds ``h``
13
+ directly. Attention is fused-QKV multi-head attention with RMSNorm on queries
14
+ and keys, adjacent-pair 3-axis RoPE, and dense scaled-dot-product attention.
15
+
16
+ Extra attention inputs, all built once per forward outside the blocks:
17
+
18
+ - ``query_scale``: a 0-dim float32 tensor multiplying the queries after RoPE,
19
+ ``exp(self-attention logit gain)``; a tensor so a new value reuses the
20
+ compiled graph. None leaves the queries unchanged (the text refiner).
21
+ - ``key_bias``: an additive ``[B, 1, 1, S]`` attention-logit bias on every
22
+ key (prompt emphasis on text keys, zero elsewhere), or None for the
23
+ mask-free (flash) path.
24
+ - ``value_scale``: a ``[B, 1, S, 1]`` multiplier on every value, or None.
25
+
26
+ Blocks hold no validation: shapes are checked where the model builds inputs.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from typing import TYPE_CHECKING, Protocol
32
+
33
+ import torch
34
+ import torch.nn.functional as F
35
+ from torch import Tensor, nn
36
+
37
+ if TYPE_CHECKING:
38
+ from .configuration import DFlowConfig
39
+
40
+
41
+ class BlockCall(Protocol):
42
+ """The eager or compiled block implementation."""
43
+
44
+ def __call__(
45
+ self,
46
+ x: Tensor,
47
+ *,
48
+ rope_sin: Tensor,
49
+ rope_cos: Tensor,
50
+ modulation: Tensor | None,
51
+ query_scale: Tensor | None,
52
+ key_bias: Tensor | None,
53
+ value_scale: Tensor | None,
54
+ ) -> Tensor:
55
+ """Run the block."""
56
+ ...
57
+
58
+
59
+ class RMSNorm(nn.Module):
60
+ """RMSNorm with an affine weight cast to the input dtype at use.
61
+
62
+ The output keeps the input dtype (autocast computes the norm in float32
63
+ and the result is cast back).
64
+ """
65
+
66
+ weight: nn.Parameter
67
+ width: int
68
+ eps: float
69
+
70
+ def __init__(self, width: int, *, eps: float) -> None:
71
+ """Build a unit-initialised ``[width]`` weight."""
72
+
73
+ super().__init__()
74
+ self.width = width
75
+ self.eps = eps
76
+ self.weight = nn.Parameter(torch.ones(width))
77
+
78
+ def forward(self, x: Tensor) -> Tensor:
79
+ """Normalise the last dimension of ``x``."""
80
+
81
+ out = F.rms_norm(x, (self.width,), self.weight.to(dtype=x.dtype), self.eps)
82
+ return out if out.dtype == x.dtype else out.to(dtype=x.dtype)
83
+
84
+
85
+ def _rotate_adjacent_pairs(x: Tensor) -> Tensor:
86
+ """Rotate channel pairs ``(x0, x1) -> (-x1, x0)`` along the last dim."""
87
+
88
+ pairs = x.reshape(*x.shape[:-1], x.shape[-1] // 2, 2)
89
+ return torch.stack((-pairs[..., 1], pairs[..., 0]), dim=-1).reshape_as(x)
90
+
91
+
92
+ def _apply_rope(x: Tensor, sin: Tensor, cos: Tensor) -> Tensor:
93
+ """Rotate ``x`` ``[B, S, H, D]`` by float32 ``sin``/``cos`` ``[B, S, 1, D]``
94
+ in float32, returning ``x``'s dtype."""
95
+
96
+ rotated = x.to(dtype=sin.dtype)
97
+ return (rotated * cos + _rotate_adjacent_pairs(rotated) * sin).to(dtype=x.dtype)
98
+
99
+
100
+ class JointSelfAttention(nn.Module):
101
+ """Fused-QKV multi-head self-attention with QK RMSNorm and 3-axis RoPE."""
102
+
103
+ qkv: nn.Linear
104
+ q_norm: RMSNorm
105
+ k_norm: RMSNorm
106
+ proj_out: nn.Linear
107
+ heads: int
108
+ head_width: int
109
+
110
+ def __init__(self, config: DFlowConfig) -> None:
111
+ """Build the bias-free projections and the per-head norms."""
112
+
113
+ super().__init__()
114
+ self.heads = config.heads
115
+ self.head_width = config.head_width
116
+ self.qkv = nn.Linear(config.width, 3 * config.width, bias=False)
117
+ self.q_norm = RMSNorm(config.head_width, eps=config.norm_eps)
118
+ self.k_norm = RMSNorm(config.head_width, eps=config.norm_eps)
119
+ self.proj_out = nn.Linear(config.width, config.width, bias=False)
120
+
121
+ def forward(
122
+ self,
123
+ x: Tensor,
124
+ *,
125
+ rope_sin: Tensor,
126
+ rope_cos: Tensor,
127
+ query_scale: Tensor | None,
128
+ key_bias: Tensor | None,
129
+ value_scale: Tensor | None,
130
+ ) -> Tensor:
131
+ """Attend over ``x`` ``[B, S, width]``.
132
+
133
+ Args:
134
+ x: Normalised (and modulated) tokens.
135
+ rope_sin: ``[B, S, head_width]`` float32.
136
+ rope_cos: ``[B, S, head_width]`` float32.
137
+ query_scale: 0-dim float32 query multiplier, or None.
138
+ key_bias: ``[B, 1, 1, S]`` additive logit bias (query dtype), or None.
139
+ value_scale: ``[B, 1, S, 1]`` value multiplier (value dtype), or None.
140
+
141
+ Returns:
142
+ ``[B, S, width]`` attention output after the output projection.
143
+ """
144
+
145
+ batch, length, width = x.shape
146
+ qkv = self.qkv(x).view(batch, length, 3, self.heads, self.head_width)
147
+ q, k, v = qkv.unbind(2)
148
+ sin = rope_sin.unsqueeze(2)
149
+ cos = rope_cos.unsqueeze(2)
150
+ q = _apply_rope(self.q_norm(q), sin, cos)
151
+ k = _apply_rope(self.k_norm(k), sin, cos)
152
+ if query_scale is not None:
153
+ q = (q.to(dtype=torch.float32) * query_scale).to(dtype=k.dtype)
154
+ v = v.transpose(1, 2)
155
+ if value_scale is not None:
156
+ v = v * value_scale
157
+ out = F.scaled_dot_product_attention(
158
+ q.transpose(1, 2), k.transpose(1, 2), v, attn_mask=key_bias
159
+ )
160
+ return self.proj_out(out.transpose(1, 2).reshape(batch, length, width))
161
+
162
+
163
+ class GeluMlp(nn.Module):
164
+ """``down(gelu(up(x)))`` with biases and the exact (erf) GELU."""
165
+
166
+ up: nn.Linear
167
+ down: nn.Linear
168
+
169
+ def __init__(self, config: DFlowConfig) -> None:
170
+ """Build the two biased projections."""
171
+
172
+ super().__init__()
173
+ self.up = nn.Linear(config.width, config.mlp_hidden_width, bias=True)
174
+ self.down = nn.Linear(config.mlp_hidden_width, config.width, bias=True)
175
+
176
+ def forward(self, x: Tensor) -> Tensor:
177
+ """Apply the MLP to ``[..., width]`` tokens."""
178
+
179
+ return self.down(F.gelu(self.up(x)))
180
+
181
+
182
+ def _modulate(normed: Tensor, scale: Tensor) -> Tensor:
183
+ """``normed * (1 + scale)`` in float32 with per-sample ``scale`` ``[B, D]``,
184
+ returned in ``normed``'s dtype."""
185
+
186
+ out = normed.to(dtype=torch.float32) * (1.0 + scale.unsqueeze(1))
187
+ return out.to(dtype=normed.dtype)
188
+
189
+
190
+ def _gate(gate: Tensor, values: Tensor) -> Tensor:
191
+ """``tanh(gate) * values`` in float32 with per-sample ``gate`` ``[B, D]``,
192
+ returned in ``values``' dtype."""
193
+
194
+ out = torch.tanh(gate).unsqueeze(1) * values.to(dtype=torch.float32)
195
+ return out.to(dtype=values.dtype)
196
+
197
+
198
+ class DFlowBlock(nn.Module):
199
+ """One sandwich-norm transformer block (refiner or image layer)."""
200
+
201
+ attn_norm1: RMSNorm
202
+ attn_norm2: RMSNorm
203
+ mlp_norm1: RMSNorm
204
+ mlp_norm2: RMSNorm
205
+ attn: JointSelfAttention
206
+ mlp: GeluMlp
207
+ _implementation: BlockCall
208
+ _compiled: bool
209
+
210
+ def __init__(self, config: DFlowConfig) -> None:
211
+ """Build the four norms, the attention and the MLP."""
212
+
213
+ super().__init__()
214
+ self.attn_norm1 = RMSNorm(config.width, eps=config.norm_eps)
215
+ self.attn_norm2 = RMSNorm(config.width, eps=config.norm_eps)
216
+ self.mlp_norm1 = RMSNorm(config.width, eps=config.norm_eps)
217
+ self.mlp_norm2 = RMSNorm(config.width, eps=config.norm_eps)
218
+ self.attn = JointSelfAttention(config)
219
+ self.mlp = GeluMlp(config)
220
+ self._implementation = self._forward_impl
221
+ self._compiled = False
222
+
223
+ def forward(
224
+ self,
225
+ x: Tensor,
226
+ *,
227
+ rope_sin: Tensor,
228
+ rope_cos: Tensor,
229
+ modulation: Tensor | None,
230
+ query_scale: Tensor | None,
231
+ key_bias: Tensor | None,
232
+ value_scale: Tensor | None,
233
+ ) -> Tensor:
234
+ """Run the block, compiled once ``compile_block`` was called.
235
+
236
+ Args:
237
+ x: Residual stream ``[B, S, width]``.
238
+ rope_sin: ``[B, S, head_width]`` float32 RoPE sines.
239
+ rope_cos: ``[B, S, head_width]`` float32 RoPE cosines.
240
+ modulation: Float32 ``[B, 4 * width]`` AdaLN projection, chunked as
241
+ (attention scale, attention gate, MLP scale, MLP gate); None for
242
+ the unmodulated refiner.
243
+ query_scale: See the module docstring.
244
+ key_bias: See the module docstring.
245
+ value_scale: See the module docstring.
246
+
247
+ Returns:
248
+ The updated residual stream, in ``x``'s dtype.
249
+ """
250
+
251
+ return self._implementation(
252
+ x,
253
+ rope_sin=rope_sin,
254
+ rope_cos=rope_cos,
255
+ modulation=modulation,
256
+ query_scale=query_scale,
257
+ key_bias=key_bias,
258
+ value_scale=value_scale,
259
+ )
260
+
261
+ def compile_block(self, *, dynamic: bool) -> None:
262
+ """Replace the eager implementation by ``torch.compile(fullgraph=True)``.
263
+
264
+ Compilation happens on the first call; a graph break or compiler
265
+ error raises there.
266
+
267
+ Raises:
268
+ RuntimeError: If the block is already compiled.
269
+ """
270
+
271
+ if self._compiled:
272
+ raise RuntimeError("DFlowBlock is already compiled")
273
+ self._implementation = torch.compile(
274
+ self._forward_impl, fullgraph=True, dynamic=dynamic
275
+ )
276
+ self._compiled = True
277
+
278
+ def _forward_impl(
279
+ self,
280
+ x: Tensor,
281
+ *,
282
+ rope_sin: Tensor,
283
+ rope_cos: Tensor,
284
+ modulation: Tensor | None,
285
+ query_scale: Tensor | None,
286
+ key_bias: Tensor | None,
287
+ value_scale: Tensor | None,
288
+ ) -> Tensor:
289
+ """The block math (see ``forward``)."""
290
+
291
+ if modulation is None:
292
+ h = self.attn(
293
+ self.attn_norm1(x),
294
+ rope_sin=rope_sin,
295
+ rope_cos=rope_cos,
296
+ query_scale=query_scale,
297
+ key_bias=key_bias,
298
+ value_scale=value_scale,
299
+ )
300
+ x = x + self.attn_norm2(h)
301
+ return x + self.mlp_norm2(self.mlp(self.mlp_norm1(x)))
302
+ scale_a, gate_a, scale_m, gate_m = modulation.chunk(4, dim=-1)
303
+ h = self.attn(
304
+ _modulate(self.attn_norm1(x), scale_a),
305
+ rope_sin=rope_sin,
306
+ rope_cos=rope_cos,
307
+ query_scale=query_scale,
308
+ key_bias=key_bias,
309
+ value_scale=value_scale,
310
+ )
311
+ x = x + _gate(gate_a, self.attn_norm2(h))
312
+ h = self.mlp(_modulate(self.mlp_norm1(x), scale_m))
313
+ return x + _gate(gate_m, self.mlp_norm2(h))
dflow/brownian_noise.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-step standard normals and Brownian-tree increments for the SDE solvers.
2
+
3
+ Both draw from one explicit ``torch.Generator``. A CPU generator (the
4
+ recommended source) draws float32 values on the host and copies them to the
5
+ state's device without a host sync, so one seed gives the same noise on every
6
+ GPU model. A CUDA generator draws on the state's device; its numbers depend on
7
+ the GPU model.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+
14
+ import torch
15
+ from torch import Tensor
16
+ from torchsde import BrownianTree
17
+
18
+ BROWNIAN_RELATIVE_TOLERANCE = 1.0e-10
19
+ _ENTROPY_HIGH = 2**31 - 1
20
+
21
+
22
+ def _require_generator_device(generator: torch.Generator, device: torch.device) -> None:
23
+ """Fail fast when a non-CPU generator is not on the state's device.
24
+
25
+ Raises:
26
+ ValueError: On a CUDA generator for a state on another device.
27
+ """
28
+
29
+ generator_device = torch.device(generator.device)
30
+ if generator_device.type == "cpu":
31
+ return
32
+ matches = generator_device.type == device.type and (
33
+ generator_device.index is None
34
+ or device.index is None
35
+ or generator_device.index == device.index
36
+ )
37
+ if not matches:
38
+ raise ValueError(
39
+ f"The noise generator is on {generator_device} but the state is on "
40
+ f"{device}; use a CPU generator or one on the state's device."
41
+ )
42
+
43
+
44
+ def _to_device(host: Tensor, device: torch.device) -> Tensor:
45
+ """Copy a host tensor to ``device`` through pinned memory without a sync."""
46
+
47
+ if device.type == "cpu":
48
+ return host
49
+ return host.pin_memory().to(device=device, non_blocking=True)
50
+
51
+
52
+ def standard_normal(
53
+ shape: tuple[int, ...], *, generator: torch.Generator, device: torch.device
54
+ ) -> Tensor:
55
+ """Draw one float32 ``N(0, 1)`` tensor of ``shape`` on ``device``.
56
+
57
+ A CPU generator fills a host buffer (``Tensor.normal_``) and copies it over;
58
+ a device generator calls ``torch.randn`` on the device.
59
+
60
+ Raises:
61
+ ValueError: If a device generator is on another device.
62
+ """
63
+
64
+ _require_generator_device(generator, device)
65
+ if torch.device(generator.device).type == "cpu":
66
+ host = torch.empty(shape, dtype=torch.float32, device="cpu")
67
+ host.normal_(generator=generator)
68
+ return _to_device(host, device)
69
+ return torch.randn(shape, device=device, dtype=torch.float32, generator=generator)
70
+
71
+
72
+ class BrownianIntervalNormal:
73
+ """Normalized Brownian increments on a fixed time domain, one tree per sample.
74
+
75
+ ``sample(start, end)`` returns ``(W(end) - W(start)) / sqrt(|end - start|)``
76
+ in normalized domain units, so increments over adjacent intervals are
77
+ consistent whatever the schedule. Trees live on the generator's device
78
+ (the host for a CPU generator).
79
+ """
80
+
81
+ def __init__(
82
+ self, *, state: Tensor, start: float, end: float, generator: torch.Generator
83
+ ) -> None:
84
+ """Draw one tree entropy per batch item from ``generator``.
85
+
86
+ Raises:
87
+ ValueError: For a non-finite or empty domain, or a generator on
88
+ another device than the state.
89
+ """
90
+
91
+ if not (math.isfinite(start) and math.isfinite(end)) or start >= end:
92
+ raise ValueError(
93
+ f"The Brownian domain must be finite with start < end; got "
94
+ f"[{start}, {end}]."
95
+ )
96
+ _require_generator_device(generator, state.device)
97
+ tree_device = torch.device(generator.device)
98
+ if tree_device.type != "cpu":
99
+ tree_device = state.device
100
+ entropies = torch.randint(
101
+ low=0,
102
+ high=_ENTROPY_HIGH,
103
+ size=(int(state.shape[0]),),
104
+ device=torch.device(generator.device),
105
+ dtype=torch.int64,
106
+ generator=generator,
107
+ )
108
+ origin = torch.zeros(
109
+ tuple(state.shape[1:]), device=tree_device, dtype=torch.float32
110
+ )
111
+ self._trees = tuple(
112
+ BrownianTree(
113
+ t0=0.0,
114
+ w0=origin,
115
+ t1=1.0,
116
+ entropy=int(entropy),
117
+ tol=BROWNIAN_RELATIVE_TOLERANCE,
118
+ )
119
+ for entropy in entropies.cpu().tolist()
120
+ )
121
+ self._start = start
122
+ self._span = end - start
123
+ self._end = end
124
+
125
+ def sample(self, *, state: Tensor, start: float, end: float) -> Tensor:
126
+ """Return the normalized increment from ``start`` to ``end`` like ``state``.
127
+
128
+ Raises:
129
+ ValueError: For equal endpoints or a query outside the domain.
130
+ """
131
+
132
+ low, high = min(start, end), max(start, end)
133
+ if low == high or low < self._start or high > self._end:
134
+ raise ValueError(
135
+ f"Brownian query [{start}, {end}] is empty or outside "
136
+ f"[{self._start}, {self._end}]."
137
+ )
138
+ normalized_low = (low - self._start) / self._span
139
+ normalized_high = (high - self._start) / self._span
140
+ sign = 1.0 if end > start else -1.0
141
+ scale = sign / math.sqrt(normalized_high - normalized_low)
142
+ increments = torch.stack(
143
+ tuple(tree(normalized_low, normalized_high) for tree in self._trees), dim=0
144
+ )
145
+ scaled = increments * scale
146
+ if scaled.device.type == "cpu":
147
+ return _to_device(scaled, state.device).to(dtype=state.dtype)
148
+ return scaled.to(device=state.device, dtype=state.dtype)
dflow/configuration.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Architecture constants of the dflow_2b denoiser and their ``config.json`` form.
2
+
3
+ The denoiser has one fixed architecture. ``DFlowConfig`` holds its constants;
4
+ ``DFLOW_2B_CONFIG`` is the released model. ``config.json`` carries the same
5
+ values under the ``"denoiser"`` key, and loading compares them field by field,
6
+ so a file for a different architecture fails before any weight is read.
7
+ Other top-level keys of ``config.json`` belong to other components (the text
8
+ adapter) and are validated by their own loaders. The ``"inference"`` key holds
9
+ the release's ``InferencePolicy``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from dataclasses import asdict, dataclass
16
+ from pathlib import Path
17
+
18
+ DENOISER_CONFIG_KEY = "denoiser"
19
+ INFERENCE_CONFIG_KEY = "inference"
20
+ EMPTY_PROMPT_ERROR = (
21
+ 'Please enter a prompt. Empty prompts are off: set "allow_empty_prompt": '
22
+ 'true under "inference" in config.json to allow them.'
23
+ )
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class DFlowConfig:
28
+ """Constants of the single-stream denoiser.
29
+
30
+ Attributes:
31
+ latent_channels: Channels of the (whitened dinac3_96) latent.
32
+ patch_size: Latent pixels per image token side (a 1x1 patch embed).
33
+ width: Residual stream width of every block.
34
+ heads: Attention heads; ``width / heads`` must equal the RoPE head
35
+ width ``sum(rope_axes_dims)``.
36
+ mlp_ratio: MLP hidden width as a multiple of ``width``.
37
+ text_refiner_depth: Unmodulated text-only blocks run once per prompt.
38
+ prefix_depth: Image layers before the routable middle.
39
+ middle_depth: Routable middle layers (skipped by path drop).
40
+ suffix_depth: Image layers after the tail join.
41
+ time_frequency_width: Sinusoidal timestep features.
42
+ time_hidden_width: Hidden width of the timestep MLP.
43
+ time_embed_width: Width of the timestep vector every AdaLN reads.
44
+ time_scale: Multiplier on ``t`` before the sinusoid.
45
+ time_max_period: Longest sinusoid period.
46
+ rope_theta: RoPE frequency base.
47
+ rope_axes_dims: Head channels of the three RoPE axes (text/frame, y, x).
48
+ rope_axes_lens: Position capacity of the three RoPE axes.
49
+ norm_eps: RMSNorm epsilon.
50
+ """
51
+
52
+ latent_channels: int
53
+ patch_size: int
54
+ width: int
55
+ heads: int
56
+ mlp_ratio: int
57
+ text_refiner_depth: int
58
+ prefix_depth: int
59
+ middle_depth: int
60
+ suffix_depth: int
61
+ time_frequency_width: int
62
+ time_hidden_width: int
63
+ time_embed_width: int
64
+ time_scale: float
65
+ time_max_period: float
66
+ rope_theta: float
67
+ rope_axes_dims: tuple[int, int, int]
68
+ rope_axes_lens: tuple[int, int, int]
69
+ norm_eps: float
70
+
71
+ def __post_init__(self) -> None:
72
+ """Check the constants are mutually consistent.
73
+
74
+ Raises:
75
+ ValueError: If the head width differs from the RoPE head width, a
76
+ width does not split into heads, or a size is not positive.
77
+ """
78
+
79
+ for name, value in asdict(self).items():
80
+ numbers = value if isinstance(value, tuple) else (value,)
81
+ if any(number <= 0 for number in numbers):
82
+ raise ValueError(f"DFlowConfig.{name} must be positive")
83
+ if self.width % self.heads != 0:
84
+ raise ValueError("DFlowConfig.width must be divisible by heads")
85
+ if self.head_width != sum(self.rope_axes_dims):
86
+ raise ValueError(
87
+ f"DFlowConfig head width {self.head_width} must equal the RoPE "
88
+ f"head width {sum(self.rope_axes_dims)}"
89
+ )
90
+ if any(dim % 2 for dim in self.rope_axes_dims):
91
+ raise ValueError("DFlowConfig.rope_axes_dims entries must be even")
92
+ if self.patch_size != 1:
93
+ raise ValueError("DFlowConfig supports a 1x1 patch embed only")
94
+
95
+ @property
96
+ def head_width(self) -> int:
97
+ """Channels per attention head."""
98
+
99
+ return self.width // self.heads
100
+
101
+ @property
102
+ def mlp_hidden_width(self) -> int:
103
+ """Hidden channels of every block MLP."""
104
+
105
+ return self.width * self.mlp_ratio
106
+
107
+ @property
108
+ def image_layer_count(self) -> int:
109
+ """Modulated image layers (prefix, middle and suffix)."""
110
+
111
+ return self.prefix_depth + self.middle_depth + self.suffix_depth
112
+
113
+ def to_json_dict(self) -> dict[str, int | float | list[int]]:
114
+ """The ``config.json`` ``"denoiser"`` mapping (tuples as lists)."""
115
+
116
+ return {
117
+ key: list(value) if isinstance(value, tuple) else value
118
+ for key, value in asdict(self).items()
119
+ }
120
+
121
+
122
+ DFLOW_2B_CONFIG = DFlowConfig(
123
+ latent_channels=96,
124
+ patch_size=1,
125
+ width=2304,
126
+ heads=18,
127
+ mlp_ratio=4,
128
+ text_refiner_depth=2,
129
+ prefix_depth=6,
130
+ middle_depth=18,
131
+ suffix_depth=6,
132
+ time_frequency_width=256,
133
+ time_hidden_width=1024,
134
+ time_embed_width=256,
135
+ time_scale=1000.0,
136
+ time_max_period=10000.0,
137
+ rope_theta=10000.0,
138
+ rope_axes_dims=(32, 48, 48),
139
+ rope_axes_lens=(8192, 512, 512),
140
+ norm_eps=1e-6,
141
+ )
142
+
143
+
144
+ def validate_denoiser_config(payload: dict[str, object], expected: DFlowConfig) -> None:
145
+ """Compare a ``config.json`` ``"denoiser"`` mapping with ``expected``.
146
+
147
+ Raises:
148
+ ValueError: If a key is missing or unknown, or a value differs.
149
+ """
150
+
151
+ reference = expected.to_json_dict()
152
+ missing = sorted(set(reference) - set(payload))
153
+ unknown = sorted(set(payload) - set(reference))
154
+ if missing or unknown:
155
+ raise ValueError(
156
+ f"config.json denoiser keys differ from this package: missing={missing}, "
157
+ f"unknown={unknown}"
158
+ )
159
+ mismatched = {
160
+ key: (payload[key], value)
161
+ for key, value in reference.items()
162
+ if payload[key] != value or type(payload[key]) is not type(value)
163
+ }
164
+ if mismatched:
165
+ details = ", ".join(
166
+ f"{key}: file {found!r}, expected {want!r}"
167
+ for key, (found, want) in sorted(mismatched.items())
168
+ )
169
+ raise ValueError(
170
+ f"config.json describes a different denoiser architecture ({details})"
171
+ )
172
+
173
+
174
+ def read_denoiser_config(path: Path, expected: DFlowConfig) -> DFlowConfig:
175
+ """Read ``config.json`` and return ``expected`` once its denoiser matches.
176
+
177
+ Args:
178
+ path: The release's ``config.json``.
179
+ expected: The architecture this package builds.
180
+
181
+ Returns:
182
+ ``expected``.
183
+
184
+ Raises:
185
+ FileNotFoundError: If ``path`` does not exist.
186
+ ValueError: If the file is not a JSON object with a matching
187
+ ``"denoiser"`` mapping.
188
+ """
189
+
190
+ if not path.is_file():
191
+ raise FileNotFoundError(f"Missing denoiser config: {path}")
192
+ payload = json.loads(path.read_text(encoding="utf-8"))
193
+ match payload:
194
+ case {"denoiser": dict() as denoiser}:
195
+ validate_denoiser_config(denoiser, expected)
196
+ return expected
197
+ case dict():
198
+ raise ValueError(f"{path} has no {DENOISER_CONFIG_KEY!r} mapping")
199
+ case _:
200
+ raise ValueError(f"{path} must hold a JSON object")
201
+
202
+
203
+ @dataclass(frozen=True)
204
+ class InferencePolicy:
205
+ """Inference rules a release sets in ``config.json`` ``"inference"``.
206
+
207
+ Attributes:
208
+ allow_empty_prompt: Whether a blank prompt may sample (from the learned
209
+ unconditional text). Off in the release, so a public interface does
210
+ not generate freely when the prompt is forgotten; set it to true
211
+ locally to allow it.
212
+ """
213
+
214
+ allow_empty_prompt: bool
215
+
216
+ def to_json_dict(self) -> dict[str, object]:
217
+ """The ``"inference"`` mapping of ``config.json``."""
218
+
219
+ return {"allow_empty_prompt": self.allow_empty_prompt}
220
+
221
+
222
+ # The policy the release ships.
223
+ RELEASE_INFERENCE_POLICY = InferencePolicy(allow_empty_prompt=False)
224
+
225
+
226
+ def read_inference_policy(path: Path) -> InferencePolicy:
227
+ """Read the ``"inference"`` mapping of ``config.json``.
228
+
229
+ Raises:
230
+ FileNotFoundError: If ``path`` does not exist.
231
+ ValueError: If the mapping is missing, has other keys, or
232
+ ``allow_empty_prompt`` is not a boolean.
233
+ """
234
+
235
+ if not path.is_file():
236
+ raise FileNotFoundError(f"Missing config: {path}")
237
+ payload = json.loads(path.read_text(encoding="utf-8"))
238
+ match payload:
239
+ case {"inference": {"allow_empty_prompt": bool() as allow} as policy} if (
240
+ len(policy) == 1
241
+ ):
242
+ return InferencePolicy(allow_empty_prompt=allow)
243
+ case _:
244
+ raise ValueError(
245
+ f'{path} needs "{INFERENCE_CONFIG_KEY}": {{"allow_empty_prompt": '
246
+ "true or false} and no other keys under it."
247
+ )
dflow/diffusers_pipeline.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An optional 🤗 diffusers wrapper around ``DFlowPipeline``.
2
+
3
+ ``diffusers`` is not a dependency of dflow; importing this module without it
4
+ raises ImportError. The wrapper gives the familiar ``DiffusionPipeline`` call
5
+ signature and output type; the model, sampler and guidance are dflow's own.
6
+ It does not support ``save_pretrained`` or loading through
7
+ ``DiffusionPipeline.from_pretrained``.
8
+
9
+ Example::
10
+
11
+ from dflow.diffusers_pipeline import DFlowDiffusersPipeline
12
+
13
+ pipe = DFlowDiffusersPipeline.from_pretrained("data-archetype/dflow_2b")
14
+ image = pipe("A lighthouse on a cliff at dusk.", generator_seed=7).images[0]
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import replace
20
+ from pathlib import Path
21
+
22
+ import torch
23
+ from diffusers import DiffusionPipeline
24
+ from diffusers.pipelines.pipeline_utils import ImagePipelineOutput
25
+
26
+ from .guidance import CfgGuidance, ConstantPdgScale, GuidanceSettings, PdgGuidance
27
+ from .inference import GenerationSettings, SamplingSettings
28
+ from .pipeline import REPOSITORY, DFlowPipeline, OutputType
29
+ from .schedules import TimeSchedule
30
+
31
+
32
+ class DFlowDiffusersPipeline(DiffusionPipeline):
33
+ """``DiffusionPipeline``-style access to dflow_2b.
34
+
35
+ Args:
36
+ pipeline: A loaded ``DFlowPipeline``.
37
+ """
38
+
39
+ def __init__(self, pipeline: DFlowPipeline) -> None:
40
+ super().__init__()
41
+ self.dflow = pipeline
42
+
43
+ @classmethod
44
+ def from_pretrained( # type: ignore[override]
45
+ cls,
46
+ pretrained_model_name_or_path: str | Path = REPOSITORY,
47
+ *,
48
+ device: torch.device | str = "cuda",
49
+ compile: bool = True,
50
+ revision: str | None = None,
51
+ ) -> DFlowDiffusersPipeline:
52
+ """Load dflow_2b (see ``DFlowPipeline.from_pretrained``)."""
53
+
54
+ return cls(
55
+ DFlowPipeline.from_pretrained(
56
+ pretrained_model_name_or_path,
57
+ device=device,
58
+ compile=compile,
59
+ revision=revision,
60
+ )
61
+ )
62
+
63
+ @torch.inference_mode()
64
+ def __call__(
65
+ self,
66
+ prompt: str,
67
+ negative_prompt: str = "",
68
+ *,
69
+ height: int = 1216,
70
+ width: int = 832,
71
+ num_inference_steps: int = 50,
72
+ guidance_scale: float = 2.5,
73
+ num_images_per_prompt: int = 1,
74
+ generator_seed: int = 0,
75
+ settings: GenerationSettings | None = None,
76
+ ) -> ImagePipelineOutput:
77
+ """Generate images.
78
+
79
+ ``guidance_scale`` is the path-drop guidance (PDG) scale of the
80
+ default preset. A negative prompt needs a guidance mode that reads
81
+ one (CFG or contrastive PDG), so it is accepted only together with
82
+ ``settings`` whose guidance reads it; it then replaces the settings'
83
+ negative prompt. Pass ``settings`` to control everything else; it then
84
+ overrides every other argument except the prompt, the negative prompt
85
+ and the image count.
86
+
87
+ Raises:
88
+ ValueError: For a negative prompt without ``settings``, or with
89
+ settings whose guidance never reads it.
90
+ """
91
+
92
+ chosen = settings
93
+ if chosen is not None and negative_prompt:
94
+ if not chosen.guidance.uses_negative:
95
+ raise ValueError(
96
+ "negative_prompt is set but the settings' guidance never reads "
97
+ "it; enable CFG or a contrastive PDG mode."
98
+ )
99
+ chosen = replace(chosen, negative_prompt=negative_prompt)
100
+ if chosen is None:
101
+ if negative_prompt:
102
+ raise ValueError(
103
+ "The default preset uses no negative prompt; pass settings "
104
+ "with CFG or contrastive PDG and set negative_prompt there."
105
+ )
106
+ defaults = GenerationSettings()
107
+ chosen = replace(
108
+ defaults,
109
+ width=width,
110
+ height=height,
111
+ seed=generator_seed,
112
+ sampling=replace(
113
+ SamplingSettings(),
114
+ schedule=TimeSchedule(steps=num_inference_steps),
115
+ ),
116
+ guidance=GuidanceSettings(
117
+ pdg=PdgGuidance(scale=ConstantPdgScale(guidance_scale)),
118
+ cfg=CfgGuidance(),
119
+ ),
120
+ )
121
+ output = self.dflow(
122
+ prompt,
123
+ chosen,
124
+ num_images=num_images_per_prompt,
125
+ output_type=OutputType.PIL,
126
+ )
127
+ return ImagePipelineOutput(images=output.images)
dflow/guidance.py ADDED
@@ -0,0 +1,1267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CFG and path-drop guidance (PDG): which forwards each step runs and how
2
+ their velocities combine.
3
+
4
+ Every denoiser forward is a ``BranchCall``: a text branch (the prompt, or the
5
+ negative prompt / learned null text), a routing path (``DFlowPath``) and the
6
+ image self-attention logit gain of that forward. ``GuidanceSettings`` is
7
+ validated once; ``build_guidance_plan`` resolves it against the run's schedule
8
+ into one ``GuidanceStep`` per schedule point (``0 .. steps``), so the per-step
9
+ code is a table lookup plus tensor arithmetic. ``GuidancePlan.guided_velocity``
10
+ takes a callable ``evaluate(call) -> velocity`` and returns the guided velocity.
11
+
12
+ The main forward always uses the prompt; its gain is
13
+ ``GuidanceSettings.self_attention_gain`` (0 on the CFG steps of the alternating
14
+ modes). Guidance forwards use ``guidance_self_attention_gain``. PDG reference
15
+ forwards also carry ``PdgGuidance.suffix_caption_bias``: an additive
16
+ attention-logit bias on the prompt's keys in the suffix layers (0: none).
17
+
18
+ Single-reference steps return ``v_ref + s (v_main - v_ref)`` (or its APG
19
+ projection); the combined modes return
20
+ ``v_main + 0.5 (s_cfg (v_main - v_cfg) + s_pdg (v_main - v_pdg))``, where the
21
+ scales are extra strengths (a quantile-ramp PDG scale has 1 subtracted). A
22
+ PDG scale of 1 (0 in the combined modes) skips the PDG forward. Guidance
23
+ rescale pulls the guided norm toward the main norm.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import itertools
29
+ import math
30
+ from bisect import bisect_right
31
+ from collections.abc import Callable, Sequence
32
+ from dataclasses import dataclass, field
33
+ from enum import StrEnum
34
+
35
+ import numpy as np
36
+ import torch
37
+ from torch import Tensor
38
+
39
+ from .schedules import ScheduleCdf, TimeSchedule, build_timesteps
40
+ from .types import DFlowPath
41
+
42
+ SELF_ATTENTION_GAIN_MIN = -0.5
43
+ SELF_ATTENTION_GAIN_MAX = 0.1
44
+ DEFAULT_SELF_ATTENTION_GAIN = -0.03
45
+ DEFAULT_PDG_SCALE = 2.5
46
+ # Release default: the PDG reference reads the prompt less in its suffix layers.
47
+ DEFAULT_SUFFIX_CAPTION_BIAS = -4.0
48
+ SUFFIX_CAPTION_BIAS_MIN = -10.0
49
+ SUFFIX_CAPTION_BIAS_MAX = 0.0
50
+ # A PDG scale within this distance of its neutral value skips the PDG forward.
51
+ _NEUTRAL_SCALE_TOLERANCE = 1.0e-6
52
+ # The LINEAR_LOGSNR curve interpolates between these logSNR anchors.
53
+ _CURVE_LOGSNR_NOISY = -15.0
54
+ _CURVE_LOGSNR_CLEAN = 15.0
55
+ _BEZIER_SAMPLES = 4096
56
+ # Radial APG band edges in cycles per latent pixel: DC, (0, 1/32], (1/32, 1/8],
57
+ # (1/8, 1/4] and above 1/4.
58
+ PROJECTION_BAND_EDGES: tuple[float, ...] = (0.0, 1 / 32, 1 / 8, 1 / 4)
59
+ PROJECTION_BAND_COUNT = len(PROJECTION_BAND_EDGES) + 1
60
+
61
+
62
+ class BranchText(StrEnum):
63
+ """Text a forward is conditioned on.
64
+
65
+ POSITIVE: the prompt.
66
+ NEGATIVE: the negative prompt, or the learned null text when there is none.
67
+ """
68
+
69
+ POSITIVE = "positive"
70
+ NEGATIVE = "negative"
71
+
72
+
73
+ class GuidanceBranch(StrEnum):
74
+ """A denoiser forward a guidance step may need: text branch and path."""
75
+
76
+ POSITIVE_FULL = "positive_full"
77
+ POSITIVE_PATH_DROP = "positive_path_drop"
78
+ POSITIVE_THREE_QUARTER = "positive_three_quarter"
79
+ NEGATIVE_FULL = "negative_full"
80
+ NEGATIVE_PATH_DROP = "negative_path_drop"
81
+ NEGATIVE_THREE_QUARTER = "negative_three_quarter"
82
+
83
+ @staticmethod
84
+ def of(text: BranchText, path: DFlowPath) -> GuidanceBranch:
85
+ """Return the branch of a text branch and a path."""
86
+
87
+ return GuidanceBranch(f"{text.value}_{path.value}")
88
+
89
+ @property
90
+ def text(self) -> BranchText:
91
+ """The text branch of this forward."""
92
+
93
+ return BranchText(self.value.split("_", 1)[0])
94
+
95
+ @property
96
+ def path(self) -> DFlowPath:
97
+ """The routing path of this forward."""
98
+
99
+ return DFlowPath(self.value.split("_", 1)[1])
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class BranchCall:
104
+ """One denoiser forward: branch, image self-attention logit gain and the
105
+ suffix layers' prompt-key logit bias (0: none)."""
106
+
107
+ branch: GuidanceBranch
108
+ self_attention_gain: float
109
+ suffix_caption_bias: float
110
+
111
+
112
+ class PdgMode(StrEnum):
113
+ """Path-drop guidance policies (the reference is the same network with its
114
+ middle layers skipped).
115
+
116
+ FULL: middle dropped, prompt text.
117
+ FULL_CONTRASTIVE: middle dropped, negative text.
118
+ THREE_QUARTER: one image token per 2x2 group through the middle, prompt.
119
+ ALTERNATE_CONTRASTIVE_POSITIVE: FULL_CONTRASTIVE on even steps, FULL on odd.
120
+ ALTERNATE_PDG_FIRST / ALTERNATE_CFG_FIRST: contrastive full PDG and CFG on
121
+ alternate steps of the PDG window, starting with PDG / CFG.
122
+ ALTERNATE_POSITIVE_PDG_FIRST / ALTERNATE_POSITIVE_CFG_FIRST: the same with
123
+ prompt-text PDG.
124
+ COMBINED_CFG_PDG: CFG and contrastive PDG every step, differentials averaged.
125
+ PDG_WITH_ALTERNATING_CFG: contrastive PDG every step, plus CFG (averaged) on
126
+ odd steps.
127
+ CFG_TO_PDG: CFG before the PDG window, prompt-text full PDG inside it.
128
+ """
129
+
130
+ FULL = "full"
131
+ FULL_CONTRASTIVE = "full_contrastive"
132
+ THREE_QUARTER = "three_quarter"
133
+ ALTERNATE_CONTRASTIVE_POSITIVE = "alternate_contrastive_positive"
134
+ ALTERNATE_PDG_FIRST = "alternate_pdg_first"
135
+ ALTERNATE_CFG_FIRST = "alternate_cfg_first"
136
+ ALTERNATE_POSITIVE_PDG_FIRST = "alternate_positive_pdg_first"
137
+ ALTERNATE_POSITIVE_CFG_FIRST = "alternate_positive_cfg_first"
138
+ COMBINED_CFG_PDG = "combined_cfg_pdg"
139
+ PDG_WITH_ALTERNATING_CFG = "pdg_with_alternating_cfg"
140
+ CFG_TO_PDG = "cfg_to_pdg"
141
+
142
+ @property
143
+ def uses_cfg(self) -> bool:
144
+ """Whether the mode runs CFG forwards (and needs a CFG scale)."""
145
+
146
+ match self:
147
+ case (
148
+ PdgMode.ALTERNATE_PDG_FIRST
149
+ | PdgMode.ALTERNATE_CFG_FIRST
150
+ | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST
151
+ | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST
152
+ | PdgMode.COMBINED_CFG_PDG
153
+ | PdgMode.PDG_WITH_ALTERNATING_CFG
154
+ | PdgMode.CFG_TO_PDG
155
+ ):
156
+ return True
157
+ case (
158
+ PdgMode.FULL
159
+ | PdgMode.FULL_CONTRASTIVE
160
+ | PdgMode.THREE_QUARTER
161
+ | PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE
162
+ ):
163
+ return False
164
+ case _ as unreachable:
165
+ raise ValueError(f"Unsupported PDG mode: {unreachable}")
166
+
167
+ @property
168
+ def alternates_with_cfg(self) -> bool:
169
+ """Whether PDG and CFG alternate inside the PDG window."""
170
+
171
+ return self in _ALTERNATING_MODES
172
+
173
+ @property
174
+ def averages_cfg(self) -> bool:
175
+ """Whether CFG and PDG differentials are averaged on shared steps."""
176
+
177
+ return self in (PdgMode.COMBINED_CFG_PDG, PdgMode.PDG_WITH_ALTERNATING_CFG)
178
+
179
+ def text_at(self, step: int) -> BranchText:
180
+ """Text of this mode's PDG reference on ``step``."""
181
+
182
+ match self:
183
+ case PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE:
184
+ return BranchText.NEGATIVE if step % 2 == 0 else BranchText.POSITIVE
185
+ case (
186
+ PdgMode.FULL_CONTRASTIVE
187
+ | PdgMode.ALTERNATE_PDG_FIRST
188
+ | PdgMode.ALTERNATE_CFG_FIRST
189
+ | PdgMode.COMBINED_CFG_PDG
190
+ | PdgMode.PDG_WITH_ALTERNATING_CFG
191
+ ):
192
+ return BranchText.NEGATIVE
193
+ case (
194
+ PdgMode.FULL
195
+ | PdgMode.THREE_QUARTER
196
+ | PdgMode.CFG_TO_PDG
197
+ | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST
198
+ | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST
199
+ ):
200
+ return BranchText.POSITIVE
201
+ case _ as unreachable:
202
+ raise ValueError(f"Unsupported PDG mode: {unreachable}")
203
+
204
+ @property
205
+ def uses_negative(self) -> bool:
206
+ """Whether any step of this mode conditions on the negative text."""
207
+
208
+ return self.uses_cfg or BranchText.NEGATIVE in (
209
+ self.text_at(0),
210
+ self.text_at(1),
211
+ )
212
+
213
+
214
+ _ALTERNATING_MODES = frozenset(
215
+ {
216
+ PdgMode.ALTERNATE_PDG_FIRST,
217
+ PdgMode.ALTERNATE_CFG_FIRST,
218
+ PdgMode.ALTERNATE_POSITIVE_PDG_FIRST,
219
+ PdgMode.ALTERNATE_POSITIVE_CFG_FIRST,
220
+ }
221
+ )
222
+
223
+
224
+ def _alternation_uses_pdg(mode: PdgMode, step: int) -> bool:
225
+ """Whether an alternating mode runs PDG (not CFG) on ``step``."""
226
+
227
+ match mode:
228
+ case PdgMode.ALTERNATE_PDG_FIRST | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST:
229
+ return step % 2 == 0
230
+ case PdgMode.ALTERNATE_CFG_FIRST | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST:
231
+ return step % 2 == 1
232
+ case _ as unsupported:
233
+ raise ValueError(f"{unsupported} does not alternate PDG and CFG.")
234
+
235
+
236
+ def _validate_scale(value: float, name: str) -> None:
237
+ """Require a finite, non-negative guidance value.
238
+
239
+ Raises:
240
+ ValueError: Otherwise.
241
+ """
242
+
243
+ if not math.isfinite(value) or value < 0.0:
244
+ raise ValueError(f"{name} must be finite and >= 0, got {value}.")
245
+
246
+
247
+ def _validate_gain(value: float, name: str) -> None:
248
+ """Require a self-attention gain in [-0.5, 0.1].
249
+
250
+ Raises:
251
+ ValueError: Otherwise.
252
+ """
253
+
254
+ if not (
255
+ math.isfinite(value)
256
+ and SELF_ATTENTION_GAIN_MIN <= value <= SELF_ATTENTION_GAIN_MAX
257
+ ):
258
+ raise ValueError(
259
+ f"{name} must lie in [{SELF_ATTENTION_GAIN_MIN}, "
260
+ f"{SELF_ATTENTION_GAIN_MAX}], got {value}."
261
+ )
262
+
263
+
264
+ @dataclass(frozen=True)
265
+ class StepWindow:
266
+ """Inclusive solver-step window; ``stop_step`` None is the last step.
267
+
268
+ Raises:
269
+ ValueError: For a negative start or a stop before the start.
270
+ """
271
+
272
+ start_step: int = 0
273
+ stop_step: int | None = None
274
+
275
+ def __post_init__(self) -> None:
276
+ """Validate the bounds that do not depend on the step count."""
277
+
278
+ if self.start_step < 0:
279
+ raise ValueError(f"start_step must be >= 0, got {self.start_step}.")
280
+ if self.stop_step is not None and self.stop_step < self.start_step:
281
+ raise ValueError(
282
+ f"stop_step {self.stop_step} is before start_step {self.start_step}."
283
+ )
284
+
285
+ def resolve(self, steps: int, name: str) -> tuple[int, int]:
286
+ """Return (start, stop) for a run of ``steps`` updates.
287
+
288
+ Raises:
289
+ ValueError: If the window does not fit inside the run.
290
+ """
291
+
292
+ stop = steps - 1 if self.stop_step is None else self.stop_step
293
+ if stop >= steps or self.start_step > stop:
294
+ raise ValueError(
295
+ f"The {name} window [{self.start_step}, {stop}] does not fit in "
296
+ f"{steps} steps (indices 0 to {steps - 1})."
297
+ )
298
+ return self.start_step, stop
299
+
300
+
301
+ @dataclass(frozen=True)
302
+ class CfgGuidance:
303
+ """Classifier-free guidance against the negative text.
304
+
305
+ Attributes:
306
+ enabled: Run CFG inside ``window``. The alternating, combined and
307
+ CFG-to-PDG PDG modes run CFG forwards of their own and need
308
+ ``scale`` even when this is False.
309
+ scale: Guidance scale (1 is no guidance); None when unused.
310
+ window: Steps where plain CFG applies.
311
+
312
+ Raises:
313
+ ValueError: For a negative scale or CFG enabled without a scale.
314
+ """
315
+
316
+ enabled: bool = False
317
+ scale: float | None = None
318
+ window: StepWindow = field(default_factory=StepWindow)
319
+
320
+ def __post_init__(self) -> None:
321
+ """Validate the scale."""
322
+
323
+ if self.scale is not None:
324
+ _validate_scale(self.scale, "CfgGuidance.scale")
325
+ if self.enabled and self.scale is None:
326
+ raise ValueError("CfgGuidance.scale is required when CFG is enabled.")
327
+
328
+
329
+ @dataclass(frozen=True)
330
+ class ConstantPdgScale:
331
+ """The same PDG scale at every step."""
332
+
333
+ scale: float = DEFAULT_PDG_SCALE
334
+
335
+ def __post_init__(self) -> None:
336
+ """Validate the scale."""
337
+
338
+ _validate_scale(self.scale, "ConstantPdgScale.scale")
339
+
340
+
341
+ @dataclass(frozen=True)
342
+ class RampPdgScale:
343
+ """PDG scale linear in the schedule's CDF quantile from ``start_scale`` at the
344
+ noisy end to ``end_scale`` after ``length`` of the distribution, then held.
345
+
346
+ On the standard schedules step ``i`` of ``N`` sits at quantile ``1 - i/N``,
347
+ so ``length`` is the fraction of the steps (0.3: until step 15 of 50). The
348
+ scale is read at every evaluation's actual time.
349
+ """
350
+
351
+ start_scale: float = 4.5
352
+ end_scale: float = DEFAULT_PDG_SCALE
353
+ length: float = 0.3
354
+
355
+ def __post_init__(self) -> None:
356
+ """Validate scales and length.
357
+
358
+ Raises:
359
+ ValueError: For negative scales or a length outside (0, 1].
360
+ """
361
+
362
+ _validate_scale(self.start_scale, "RampPdgScale.start_scale")
363
+ _validate_scale(self.end_scale, "RampPdgScale.end_scale")
364
+ if not (math.isfinite(self.length) and 0.0 < self.length <= 1.0):
365
+ raise ValueError(
366
+ f"RampPdgScale.length must lie in (0, 1], got {self.length}."
367
+ )
368
+
369
+ def scale_at_quantile(self, quantile: float) -> float:
370
+ """Interpolate the two knots (1, start) and (1 - length, end)."""
371
+
372
+ knots = ((1.0, self.start_scale), (1.0 - self.length, self.end_scale))
373
+ q = min(1.0, max(knots[-1][0], quantile))
374
+ index = min(bisect_right(knots, -q, key=lambda knot: -knot[0]), len(knots) - 1)
375
+ high, low = knots[max(index - 1, 0)], knots[index]
376
+ fraction = (high[0] - q) / (high[0] - low[0])
377
+ return high[1] + fraction * (low[1] - high[1])
378
+
379
+
380
+ class EndpointCurveKind(StrEnum):
381
+ """Shape of a per-step PDG curve from the noisy-end scale to the clean-end one.
382
+
383
+ LINEAR: linear in the step index.
384
+ LINEAR_LOGSNR: linear in the step's log-SNR between -15 and +15.
385
+ POWER: (step / steps) ** power.
386
+ S_CURVE: logistic in the step position, normalised to the endpoints.
387
+ """
388
+
389
+ LINEAR = "linear"
390
+ LINEAR_LOGSNR = "linear_logsnr"
391
+ POWER = "power"
392
+ S_CURVE = "s_curve"
393
+
394
+
395
+ @dataclass(frozen=True)
396
+ class EndpointPdgCurve:
397
+ """A per-step PDG scale from ``noisy_scale`` (first point) to ``clean_scale``
398
+ (last point).
399
+
400
+ Raises:
401
+ ValueError: For negative scales, a non-positive power or sharpness, or
402
+ a knee outside [0, 1].
403
+ """
404
+
405
+ kind: EndpointCurveKind = EndpointCurveKind.POWER
406
+ noisy_scale: float = 2.0
407
+ clean_scale: float = DEFAULT_PDG_SCALE
408
+ power: float = 3.0
409
+ s_curve_knee: float = 0.5
410
+ s_curve_sharpness: float = 8.0
411
+
412
+ def __post_init__(self) -> None:
413
+ """Validate every parameter."""
414
+
415
+ _validate_scale(self.noisy_scale, "EndpointPdgCurve.noisy_scale")
416
+ _validate_scale(self.clean_scale, "EndpointPdgCurve.clean_scale")
417
+ for name, value in (
418
+ ("power", self.power),
419
+ ("s_curve_sharpness", self.s_curve_sharpness),
420
+ ):
421
+ if not (math.isfinite(value) and value > 0.0):
422
+ raise ValueError(f"EndpointPdgCurve.{name} must be > 0, got {value}.")
423
+ if not (math.isfinite(self.s_curve_knee) and 0.0 <= self.s_curve_knee <= 1.0):
424
+ raise ValueError(
425
+ f"EndpointPdgCurve.s_curve_knee must lie in [0, 1], got "
426
+ f"{self.s_curve_knee}."
427
+ )
428
+
429
+
430
+ @dataclass(frozen=True)
431
+ class BezierPdgCurve:
432
+ """A per-step PDG scale ``1 + multiplier * y(t)`` with ``y`` a cubic Bezier
433
+ over flow time from ``(edge, clean_y)`` to ``(1 - edge, noisy_y)``.
434
+
435
+ Raises:
436
+ ValueError: For negative values, an edge outside (0, 0.5), handles
437
+ outside [edge, 1 - edge] or a clean handle after the noisy one.
438
+ """
439
+
440
+ multiplier: float = 3.0
441
+ clean_y: float = 0.205
442
+ clean_handle_t: float = 0.010
443
+ clean_handle_y: float = 0.408
444
+ noisy_handle_t: float = 0.995
445
+ noisy_handle_y: float = 0.275
446
+ noisy_y: float = 0.523
447
+ edge: float = 0.005
448
+
449
+ def __post_init__(self) -> None:
450
+ """Validate every control point."""
451
+
452
+ for name, value in (
453
+ ("multiplier", self.multiplier),
454
+ ("clean_y", self.clean_y),
455
+ ("clean_handle_y", self.clean_handle_y),
456
+ ("noisy_handle_y", self.noisy_handle_y),
457
+ ("noisy_y", self.noisy_y),
458
+ ):
459
+ _validate_scale(value, f"BezierPdgCurve.{name}")
460
+ if not (math.isfinite(self.edge) and 0.0 < self.edge < 0.5):
461
+ raise ValueError(
462
+ f"BezierPdgCurve.edge must lie in (0, 0.5), got {self.edge}."
463
+ )
464
+ for name, value in (
465
+ ("clean_handle_t", self.clean_handle_t),
466
+ ("noisy_handle_t", self.noisy_handle_t),
467
+ ):
468
+ if not (math.isfinite(value) and self.edge <= value <= 1.0 - self.edge):
469
+ raise ValueError(
470
+ f"BezierPdgCurve.{name} must lie in [edge, 1 - edge], got {value}."
471
+ )
472
+ if self.clean_handle_t > self.noisy_handle_t:
473
+ raise ValueError("BezierPdgCurve.clean_handle_t must be <= noisy_handle_t.")
474
+
475
+
476
+ type PdgScaleSchedule = (
477
+ ConstantPdgScale | RampPdgScale | EndpointPdgCurve | BezierPdgCurve
478
+ )
479
+
480
+
481
+ @dataclass(frozen=True)
482
+ class PdgGuidance:
483
+ """Path-drop guidance: policy, scale schedule, step window and the
484
+ reference's suffix caption bias.
485
+
486
+ Attributes:
487
+ suffix_caption_bias: Additive attention-logit bias on the prompt's
488
+ token keys (the learned suffix tokens excluded) in the six suffix
489
+ layers of every PDG reference forward; negative values make the
490
+ reference read the prompt less. 0 turns it off; the supported
491
+ range is ``[SUFFIX_CAPTION_BIAS_MIN, SUFFIX_CAPTION_BIAS_MAX]``.
492
+
493
+ Raises:
494
+ ValueError: For a quantile ramp with CFG_TO_PDG, or a suffix caption
495
+ bias outside the supported range.
496
+ """
497
+
498
+ mode: PdgMode = PdgMode.FULL
499
+ scale: PdgScaleSchedule = field(default_factory=ConstantPdgScale)
500
+ window: StepWindow = field(default_factory=StepWindow)
501
+ suffix_caption_bias: float = DEFAULT_SUFFIX_CAPTION_BIAS
502
+
503
+ def __post_init__(self) -> None:
504
+ """Reject the ramp with the step-window crossover mode and a bias
505
+ outside the supported range."""
506
+
507
+ if not (
508
+ math.isfinite(self.suffix_caption_bias)
509
+ and SUFFIX_CAPTION_BIAS_MIN
510
+ <= self.suffix_caption_bias
511
+ <= SUFFIX_CAPTION_BIAS_MAX
512
+ ):
513
+ raise ValueError(
514
+ "suffix_caption_bias must lie in "
515
+ f"[{SUFFIX_CAPTION_BIAS_MIN}, {SUFFIX_CAPTION_BIAS_MAX}], got "
516
+ f"{self.suffix_caption_bias}."
517
+ )
518
+ if self.mode is PdgMode.CFG_TO_PDG and isinstance(self.scale, RampPdgScale):
519
+ raise ValueError(
520
+ "CFG_TO_PDG switches on the step window; use a constant or "
521
+ "per-step PDG scale with it, not a quantile ramp."
522
+ )
523
+
524
+
525
+ class ProjectionMode(StrEnum):
526
+ """Adaptive projected guidance (APG) on the x0-space guidance update.
527
+
528
+ OFF: plain guidance.
529
+ GLOBAL: one projection per sample.
530
+ PER_BAND: one projection per sample and radial frequency band.
531
+ """
532
+
533
+ OFF = "off"
534
+ GLOBAL = "global"
535
+ PER_BAND = "per_band"
536
+
537
+
538
+ @dataclass(frozen=True)
539
+ class ProjectedGuidance:
540
+ """APG: the guided x0 is ``x0_main + (w - 1)(D_perp + parallel_weight D_par)``
541
+ with ``D = x0_main - x0_reference`` split against ``x0_main``.
542
+
543
+ Attributes:
544
+ mode: OFF, GLOBAL or PER_BAND.
545
+ parallel_weight: Weight kept on the parallel part (1 is plain guidance).
546
+ first_band: PER_BAND only: bands below it stay unprojected (0 is the
547
+ mean colour, 1 the coarsest structure).
548
+
549
+ Raises:
550
+ ValueError: For a weight outside [0, 1] or an invalid first band.
551
+ """
552
+
553
+ mode: ProjectionMode = ProjectionMode.OFF
554
+ parallel_weight: float = 1.0
555
+ first_band: int = 0
556
+
557
+ def __post_init__(self) -> None:
558
+ """Validate weight and band."""
559
+
560
+ if not (
561
+ math.isfinite(self.parallel_weight) and 0.0 <= self.parallel_weight <= 1.0
562
+ ):
563
+ raise ValueError(
564
+ "ProjectedGuidance.parallel_weight must lie in [0, 1], got "
565
+ f"{self.parallel_weight}."
566
+ )
567
+ if not 0 <= self.first_band < PROJECTION_BAND_COUNT:
568
+ raise ValueError(
569
+ f"ProjectedGuidance.first_band must lie in [0, "
570
+ f"{PROJECTION_BAND_COUNT - 1}], got {self.first_band}."
571
+ )
572
+ if self.mode is not ProjectionMode.PER_BAND and self.first_band != 0:
573
+ raise ValueError("ProjectedGuidance.first_band needs PER_BAND mode.")
574
+
575
+
576
+ class SparseStepSchedule(StrEnum):
577
+ """Which steps run the main and CFG forwards on the three-quarter path.
578
+
579
+ PREFIX: the first ``percent`` of the steps.
580
+ CYCLIC: ``percent`` of the steps spread evenly (50: every other step).
581
+ """
582
+
583
+ PREFIX = "prefix"
584
+ CYCLIC = "cyclic"
585
+
586
+
587
+ @dataclass(frozen=True)
588
+ class SparseMiddleSteps:
589
+ """Speed option: run the main (and CFG) forwards with one image token per
590
+ 2x2 group through the middle on some steps; PDG then drops the full middle.
591
+
592
+ Raises:
593
+ ValueError: For a percent outside [0, 100].
594
+ """
595
+
596
+ percent: float = 0.0
597
+ schedule: SparseStepSchedule = SparseStepSchedule.PREFIX
598
+
599
+ def __post_init__(self) -> None:
600
+ """Validate the percent."""
601
+
602
+ if not (math.isfinite(self.percent) and 0.0 <= self.percent <= 100.0):
603
+ raise ValueError(
604
+ f"SparseMiddleSteps.percent must lie in [0, 100], got {self.percent}."
605
+ )
606
+
607
+ def active(self, step: int, steps: int) -> bool:
608
+ """Whether ``step`` (0-based, of ``steps``) is sparse."""
609
+
610
+ if self.percent <= 0.0:
611
+ return False
612
+ match self.schedule:
613
+ case SparseStepSchedule.PREFIX:
614
+ count = math.ceil((self.percent / 100.0) * float(steps))
615
+ return step < max(0, min(steps, count))
616
+ case SparseStepSchedule.CYCLIC:
617
+ before = math.floor((float(step) * self.percent) / 100.0)
618
+ after = math.floor((float(step + 1) * self.percent) / 100.0)
619
+ return after > before
620
+ case _ as unreachable:
621
+ raise ValueError(f"Unsupported sparse step schedule: {unreachable}")
622
+
623
+
624
+ @dataclass(frozen=True)
625
+ class GuidanceSettings:
626
+ """Complete guidance configuration (defaults: the release's default preset).
627
+
628
+ Attributes:
629
+ pdg: Path-drop guidance, or None for none.
630
+ cfg: Classifier-free guidance.
631
+ self_attention_gain: Image self-attention logit gain of the main forward.
632
+ guidance_self_attention_gain: Gain of the guidance forwards.
633
+ projection: APG on single-reference steps.
634
+ rescale: Guidance rescale in [0, 1] (0 off); exclusive with APG.
635
+ sparse_middle: Sparse middle steps on the main and CFG forwards.
636
+
637
+ Raises:
638
+ ValueError: On inconsistent or out-of-range settings.
639
+ """
640
+
641
+ pdg: PdgGuidance | None = field(default_factory=PdgGuidance)
642
+ cfg: CfgGuidance = field(default_factory=CfgGuidance)
643
+ self_attention_gain: float = DEFAULT_SELF_ATTENTION_GAIN
644
+ guidance_self_attention_gain: float = 0.0
645
+ projection: ProjectedGuidance = field(default_factory=ProjectedGuidance)
646
+ rescale: float = 0.0
647
+ sparse_middle: SparseMiddleSteps = field(default_factory=SparseMiddleSteps)
648
+
649
+ def __post_init__(self) -> None:
650
+ """Validate gains, CFG needs, APG and rescale."""
651
+
652
+ _validate_gain(self.self_attention_gain, "self_attention_gain")
653
+ _validate_gain(
654
+ self.guidance_self_attention_gain, "guidance_self_attention_gain"
655
+ )
656
+ if self.pdg is not None and self.pdg.mode.uses_cfg and self.cfg.scale is None:
657
+ raise ValueError(f"PDG mode {self.pdg.mode.value} needs cfg.scale.")
658
+ if (
659
+ self.cfg.scale is not None
660
+ and not self.cfg.enabled
661
+ and not (self.pdg is not None and self.pdg.mode.uses_cfg)
662
+ ):
663
+ raise ValueError(
664
+ "cfg.scale is set but neither CFG nor a CFG-using PDG mode is on."
665
+ )
666
+ if not (math.isfinite(self.rescale) and 0.0 <= self.rescale <= 1.0):
667
+ raise ValueError(f"rescale must lie in [0, 1], got {self.rescale}.")
668
+ if self.projection.mode is not ProjectionMode.OFF:
669
+ self._validate_projection()
670
+
671
+ def _validate_projection(self) -> None:
672
+ """APG needs guidance, excludes rescale and the averaged modes.
673
+
674
+ Raises:
675
+ ValueError: Otherwise.
676
+ """
677
+
678
+ if self.pdg is None and not self.cfg.enabled:
679
+ raise ValueError("Projected guidance needs CFG or PDG on.")
680
+ if self.rescale > 0.0:
681
+ raise ValueError("Projected guidance and guidance rescale are exclusive.")
682
+ if self.pdg is not None and self.pdg.mode.averages_cfg:
683
+ raise ValueError(
684
+ f"Projected guidance needs a single reference; {self.pdg.mode.value} "
685
+ "averages two."
686
+ )
687
+
688
+ @property
689
+ def uses_negative(self) -> bool:
690
+ """Whether any forward conditions on the negative (or null) text."""
691
+
692
+ return self.cfg.enabled or (
693
+ self.pdg is not None and self.pdg.mode.uses_negative
694
+ )
695
+
696
+
697
+ @dataclass(frozen=True)
698
+ class UnguidedStep:
699
+ """Only the main forward."""
700
+
701
+ main: BranchCall
702
+
703
+
704
+ @dataclass(frozen=True)
705
+ class SingleReferenceStep:
706
+ """``v_ref + scale (v_main - v_ref)`` (or its APG projection)."""
707
+
708
+ main: BranchCall
709
+ reference: BranchCall
710
+ scale: float
711
+
712
+
713
+ @dataclass(frozen=True)
714
+ class AveragedStep:
715
+ """``v_main + 0.5 (cfg_scale (v_main - v_cfg) + pdg_scale (v_main - v_pdg))``;
716
+ ``pdg`` None (neutral PDG scale) uses ``v_pdg = v_main``."""
717
+
718
+ main: BranchCall
719
+ cfg: BranchCall
720
+ pdg: BranchCall | None
721
+ cfg_scale: float
722
+ pdg_scale: float
723
+
724
+
725
+ type GuidanceStep = UnguidedStep | SingleReferenceStep | AveragedStep
726
+
727
+
728
+ def _sigmoid(value: float) -> float:
729
+ """Numerically stable logistic function."""
730
+
731
+ if value >= 0.0:
732
+ return 1.0 / (1.0 + math.exp(-value))
733
+ exp_value = math.exp(value)
734
+ return exp_value / (1.0 + exp_value)
735
+
736
+
737
+ def _positions(count: int) -> list[float]:
738
+ """Evenly spaced positions in [0, 1] (``[0.0]`` for one point)."""
739
+
740
+ if count == 1:
741
+ return [0.0]
742
+ return [float(index) / float(count - 1) for index in range(count)]
743
+
744
+
745
+ def _endpoint_weights(
746
+ curve: EndpointPdgCurve, count: int, times: Sequence[float]
747
+ ) -> list[float]:
748
+ """Interpolation weights (0 noisy, 1 clean) of an endpoint curve.
749
+
750
+ Raises:
751
+ ValueError: For fewer than two points or a degenerate S-curve.
752
+ """
753
+
754
+ if count < 2:
755
+ raise ValueError(f"A {curve.kind.value} PDG curve needs at least two points.")
756
+ positions = _positions(count)
757
+ match curve.kind:
758
+ case EndpointCurveKind.LINEAR:
759
+ return positions
760
+ case EndpointCurveKind.POWER:
761
+ return [position**curve.power for position in positions]
762
+ case EndpointCurveKind.LINEAR_LOGSNR:
763
+ span = _CURVE_LOGSNR_CLEAN - _CURVE_LOGSNR_NOISY
764
+ weights = []
765
+ for time in times:
766
+ clamped = min(max(time, 1e-12), 1.0 - 1e-12)
767
+ log_snr = -2.0 * (math.log(clamped) - math.log1p(-clamped))
768
+ weights.append(
769
+ min(max((log_snr - _CURVE_LOGSNR_NOISY) / span, 0.0), 1.0)
770
+ )
771
+ return weights
772
+ case EndpointCurveKind.S_CURVE:
773
+ raw = [
774
+ _sigmoid((position - curve.s_curve_knee) * curve.s_curve_sharpness)
775
+ for position in positions
776
+ ]
777
+ if raw[-1] - raw[0] <= 1e-12:
778
+ raise ValueError("s_curve_sharpness is too small to normalise.")
779
+ return [(value - raw[0]) / (raw[-1] - raw[0]) for value in raw]
780
+ case _ as unreachable:
781
+ raise ValueError(f"Unsupported endpoint curve: {unreachable}")
782
+
783
+
784
+ def _bezier_values(curve: BezierPdgCurve, count: int) -> list[float]:
785
+ """Per-point ``1 + multiplier * y`` of a Bezier curve, noisy point first."""
786
+
787
+ u = np.linspace(0.0, 1.0, _BEZIER_SAMPLES, dtype=np.float64)
788
+ v = 1.0 - u
789
+ basis = (v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u)
790
+ xs = (curve.edge, curve.clean_handle_t, curve.noisy_handle_t, 1.0 - curve.edge)
791
+ ys = (curve.clean_y, curve.clean_handle_y, curve.noisy_handle_y, curve.noisy_y)
792
+ x_values = basis[0] * xs[0] + basis[1] * xs[1] + basis[2] * xs[2] + basis[3] * xs[3]
793
+ y_values = basis[0] * ys[0] + basis[1] * ys[1] + basis[2] * ys[2] + basis[3] * ys[3]
794
+ order = np.argsort(x_values)
795
+ query = np.asarray([1.0 - position for position in _positions(count)])
796
+ interpolated = np.interp(query, x_values[order], y_values[order])
797
+ return [1.0 + curve.multiplier * float(value) for value in interpolated.tolist()]
798
+
799
+
800
+ def per_step_pdg_scales(
801
+ curve: EndpointPdgCurve | BezierPdgCurve,
802
+ *,
803
+ schedule: TimeSchedule,
804
+ log_snr_shift: float,
805
+ ) -> tuple[float, ...]:
806
+ """Return a per-step curve's PDG scale at each of the ``steps + 1`` points,
807
+ rounded to float32 (as the training code stores them).
808
+
809
+ LINEAR_LOGSNR reads the shifted schedule's times without the noisy-endpoint
810
+ cap.
811
+ """
812
+
813
+ count = schedule.steps + 1
814
+ match curve:
815
+ case BezierPdgCurve():
816
+ values = _bezier_values(curve, count)
817
+ case EndpointPdgCurve():
818
+ times = build_timesteps(
819
+ schedule,
820
+ log_snr_shift=log_snr_shift,
821
+ finite_noisy_endpoint=False,
822
+ device=torch.device("cpu"),
823
+ ).tolist()
824
+ weights = _endpoint_weights(curve, count, times)
825
+ noisy, clean = curve.noisy_scale, curve.clean_scale
826
+ values = [noisy + (clean - noisy) * weight for weight in weights]
827
+ case _ as unreachable:
828
+ raise ValueError(f"Unsupported PDG curve: {unreachable}")
829
+ return tuple(torch.tensor(values, dtype=torch.float32, device="cpu").tolist())
830
+
831
+
832
+ @dataclass(frozen=True)
833
+ class _PlanInputs:
834
+ """Run-level values the per-step resolution reads."""
835
+
836
+ settings: GuidanceSettings
837
+ steps: int
838
+ times: tuple[float, ...]
839
+ cdf: ScheduleCdf
840
+ pdg_values: tuple[float, ...] | None
841
+ cfg_window: tuple[int, int] | None
842
+ pdg_window: tuple[int, int] | None
843
+
844
+
845
+ @dataclass(frozen=True)
846
+ class _Activity:
847
+ """Which guidance runs on one step and the PDG reference path."""
848
+
849
+ cfg: bool
850
+ pdg: bool
851
+ pdg_path: DFlowPath
852
+
853
+
854
+ def _concrete_pdg_path(mode: PdgMode) -> DFlowPath:
855
+ """The reference path of a single-reference PDG mode."""
856
+
857
+ return (
858
+ DFlowPath.THREE_QUARTER
859
+ if mode is PdgMode.THREE_QUARTER
860
+ else DFlowPath.PATH_DROP
861
+ )
862
+
863
+
864
+ def _inside(step: int, window: tuple[int, int] | None) -> bool:
865
+ """Whether ``step`` lies in an inclusive window (None: never)."""
866
+
867
+ return window is not None and window[0] <= step <= window[1]
868
+
869
+
870
+ def _resolve_activity(inputs: _PlanInputs, step: int) -> _Activity:
871
+ """Resolve which of CFG and PDG run on ``step`` (clamped step index)."""
872
+
873
+ cfg_window = _inside(step, inputs.cfg_window)
874
+ pdg_window = _inside(step, inputs.pdg_window)
875
+ pdg = inputs.settings.pdg
876
+ if pdg is None:
877
+ return _Activity(cfg_window, False, DFlowPath.PATH_DROP)
878
+ mode = pdg.mode
879
+ if pdg_window and mode.alternates_with_cfg:
880
+ uses_pdg = _alternation_uses_pdg(mode, step)
881
+ return _Activity(not uses_pdg, uses_pdg, DFlowPath.PATH_DROP)
882
+ if mode is PdgMode.CFG_TO_PDG:
883
+ if pdg_window:
884
+ return _Activity(False, True, DFlowPath.PATH_DROP)
885
+ start = inputs.pdg_window[0] if inputs.pdg_window is not None else 0
886
+ return _Activity(step < start, False, DFlowPath.PATH_DROP)
887
+ if pdg_window and mode is PdgMode.PDG_WITH_ALTERNATING_CFG:
888
+ return _Activity(step % 2 == 1, True, DFlowPath.PATH_DROP)
889
+ if pdg_window and mode is PdgMode.COMBINED_CFG_PDG:
890
+ return _Activity(True, True, DFlowPath.PATH_DROP)
891
+ return _Activity(cfg_window, pdg_window, _concrete_pdg_path(mode))
892
+
893
+
894
+ def _pdg_scale(inputs: _PlanInputs, index: int) -> float:
895
+ """The absolute PDG scale at schedule point ``index``."""
896
+
897
+ pdg = inputs.settings.pdg
898
+ if pdg is None:
899
+ raise ValueError("PDG scale requested without PDG.")
900
+ match pdg.scale:
901
+ case ConstantPdgScale(scale=scale):
902
+ return scale
903
+ case RampPdgScale() as ramp:
904
+ return ramp.scale_at_quantile(
905
+ inputs.cdf.quantile_at_time(inputs.times[index])
906
+ )
907
+ case EndpointPdgCurve() | BezierPdgCurve():
908
+ if inputs.pdg_values is None:
909
+ raise ValueError("Per-step PDG values were not prepared.")
910
+ return inputs.pdg_values[index]
911
+ case _ as unreachable:
912
+ raise ValueError(f"Unsupported PDG scale: {unreachable}")
913
+
914
+
915
+ def _cfg_scale(settings: GuidanceSettings) -> float:
916
+ """The CFG scale of an active CFG forward."""
917
+
918
+ if settings.cfg.scale is None:
919
+ raise ValueError("A CFG forward is active but cfg.scale is None.")
920
+ return settings.cfg.scale
921
+
922
+
923
+ def _resolve_step(inputs: _PlanInputs, index: int) -> GuidanceStep:
924
+ """Resolve the forwards and combination of schedule point ``index``."""
925
+
926
+ settings = inputs.settings
927
+ step = min(index, inputs.steps - 1)
928
+ activity = _resolve_activity(inputs, step)
929
+ cfg_on, pdg_on = activity.cfg, activity.pdg
930
+ mode = settings.pdg.mode if settings.pdg is not None else None
931
+ averaged = cfg_on and pdg_on and mode is not None and mode.averages_cfg
932
+ ramp = settings.pdg is not None and isinstance(settings.pdg.scale, RampPdgScale)
933
+ pdg_scale = _pdg_scale(inputs, index) if pdg_on else 0.0
934
+ neutral = 0.0 if averaged and not ramp else 1.0
935
+ if pdg_on and math.isclose(
936
+ pdg_scale, neutral, rel_tol=0.0, abs_tol=_NEUTRAL_SCALE_TOLERANCE
937
+ ):
938
+ pdg_on = False
939
+ alternating_cfg = (
940
+ cfg_on and not pdg_on and mode is not None and mode.alternates_with_cfg
941
+ )
942
+ main_gain = 0.0 if alternating_cfg else settings.self_attention_gain
943
+ guidance_gain = 0.0 if alternating_cfg else settings.guidance_self_attention_gain
944
+ sparse = settings.sparse_middle.active(step, inputs.steps)
945
+ dense_path = DFlowPath.THREE_QUARTER if sparse else DFlowPath.FULL
946
+ pdg_path = DFlowPath.PATH_DROP if sparse else activity.pdg_path
947
+ caption_bias = settings.pdg.suffix_caption_bias if settings.pdg is not None else 0.0
948
+ main = BranchCall(
949
+ GuidanceBranch.of(BranchText.POSITIVE, dense_path), main_gain, 0.0
950
+ )
951
+ if not (cfg_on or pdg_on):
952
+ return UnguidedStep(main)
953
+ cfg_call = BranchCall(
954
+ GuidanceBranch.of(BranchText.NEGATIVE, dense_path), guidance_gain, 0.0
955
+ )
956
+ if averaged:
957
+ pdg_call = (
958
+ BranchCall(
959
+ GuidanceBranch.of(BranchText.NEGATIVE, pdg_path),
960
+ guidance_gain,
961
+ caption_bias,
962
+ )
963
+ if pdg_on
964
+ else None
965
+ )
966
+ pdg_extra = _pdg_scale(inputs, index) - (1.0 if ramp else 0.0)
967
+ return AveragedStep(main, cfg_call, pdg_call, _cfg_scale(settings), pdg_extra)
968
+ if not pdg_on or mode is None:
969
+ return SingleReferenceStep(main, cfg_call, _cfg_scale(settings))
970
+ text = mode.text_at(step)
971
+ reference = BranchCall(
972
+ GuidanceBranch.of(text, pdg_path), guidance_gain, caption_bias
973
+ )
974
+ return SingleReferenceStep(main, reference, pdg_scale)
975
+
976
+
977
+ def _band_masks(height: int, width: int, device: torch.device) -> Tensor:
978
+ """Radial ``[bands, H, W]`` FFT masks of ``PROJECTION_BAND_EDGES``."""
979
+
980
+ fy = torch.fft.fftfreq(height, device=device)
981
+ fx = torch.fft.fftfreq(width, device=device)
982
+ radius = torch.sqrt(fy[:, None].square() + fx[None, :].square())
983
+ masks = [radius == 0.0]
984
+ for low, high in itertools.pairwise(PROJECTION_BAND_EDGES):
985
+ masks.append((radius > low) & (radius <= high))
986
+ masks.append(radius > PROJECTION_BAND_EDGES[-1])
987
+ return torch.stack(masks).to(dtype=torch.float32)
988
+
989
+
990
+ def _parallel_part(
991
+ delta: Tensor, reference: Tensor, projection: ProjectedGuidance
992
+ ) -> Tensor:
993
+ """The part of ``delta`` parallel to ``reference`` (float32 ``[B, C, H, W]``),
994
+ per sample or per sample and band from ``first_band`` on."""
995
+
996
+ eps = torch.finfo(torch.float32).eps
997
+ match projection.mode:
998
+ case ProjectionMode.GLOBAL:
999
+ dims = (1, 2, 3)
1000
+ coefficient = (delta * reference).sum(dims, keepdim=True) / (
1001
+ reference.square().sum(dims, keepdim=True) + eps
1002
+ )
1003
+ return coefficient * reference
1004
+ case ProjectionMode.PER_BAND:
1005
+ masks = _band_masks(
1006
+ int(delta.shape[-2]), int(delta.shape[-1]), delta.device
1007
+ )
1008
+ fd = torch.fft.fft2(delta, norm="ortho")
1009
+ fr = torch.fft.fft2(reference, norm="ortho")
1010
+ parallel = torch.zeros_like(fr)
1011
+ for mask in masks[projection.first_band :]:
1012
+ band = fr * mask
1013
+ coefficient = (fd * band.conj()).real.sum((1, 2, 3), keepdim=True) / (
1014
+ band.abs().square().sum((1, 2, 3), keepdim=True) + eps
1015
+ )
1016
+ parallel = parallel + coefficient * band
1017
+ return torch.fft.ifft2(parallel, norm="ortho").real
1018
+ case ProjectionMode.OFF:
1019
+ raise ValueError("An OFF projection has no parallel part.")
1020
+ case _ as unreachable:
1021
+ raise ValueError(f"Unsupported projection mode: {unreachable}")
1022
+
1023
+
1024
+ def projected_guidance_velocity(
1025
+ *,
1026
+ main: Tensor,
1027
+ reference: Tensor,
1028
+ state: Tensor,
1029
+ time: Tensor,
1030
+ scale: float,
1031
+ projection: ProjectedGuidance,
1032
+ ) -> Tensor:
1033
+ """APG in velocity units: ``v_main + (w - 1)(dv - (1 - parallel_weight)
1034
+ dv_par)``, ``dv = v_main - v_ref`` and ``dv_par`` its part parallel to
1035
+ ``x0_main = x_t - t v_main``."""
1036
+
1037
+ t_view = time.to(device=main.device, dtype=torch.float32).view(
1038
+ (-1,) + (1,) * (main.dim() - 1)
1039
+ )
1040
+ x0_main = state.to(dtype=torch.float32) - t_view * main.to(dtype=torch.float32)
1041
+ delta = (main - reference).to(dtype=torch.float32)
1042
+ parallel = _parallel_part(delta, x0_main, projection)
1043
+ update = (scale - 1.0) * (delta - (1.0 - projection.parallel_weight) * parallel)
1044
+ return (main.to(dtype=torch.float32) + update).to(dtype=main.dtype)
1045
+
1046
+
1047
+ def rescale_guided_velocity(
1048
+ *, guided: Tensor, reference: Tensor, rescale: float
1049
+ ) -> Tensor:
1050
+ """Interpolate ``guided`` toward its per-sample rescale to ``reference``'s norm."""
1051
+
1052
+ if rescale == 0.0:
1053
+ return guided
1054
+ flat = (int(guided.shape[0]), -1)
1055
+ guided32 = guided.to(dtype=torch.float32)
1056
+ guided_norm = guided32.reshape(flat).norm(dim=1, keepdim=True)
1057
+ reference_norm = (
1058
+ reference.to(dtype=torch.float32).reshape(flat).norm(dim=1, keepdim=True)
1059
+ )
1060
+ view = (int(guided.shape[0]),) + (1,) * (guided.dim() - 1)
1061
+ eps = torch.finfo(torch.float32).eps
1062
+ rescaled = guided32 * (
1063
+ reference_norm.view(view) / guided_norm.clamp_min(eps).view(view)
1064
+ )
1065
+ return torch.lerp(guided32, rescaled, rescale).to(dtype=guided.dtype)
1066
+
1067
+
1068
+ type BranchEvaluator = Callable[[BranchCall], Tensor]
1069
+
1070
+
1071
+ @dataclass(frozen=True)
1072
+ class GuidancePlan:
1073
+ """Per-schedule-point guidance of one run (``build_guidance_plan``).
1074
+
1075
+ Attributes:
1076
+ steps: One ``GuidanceStep`` per schedule point, index 0 the noisy end.
1077
+ projection: APG of the single-reference steps.
1078
+ rescale: Guidance rescale.
1079
+ """
1080
+
1081
+ steps: tuple[GuidanceStep, ...]
1082
+ projection: ProjectedGuidance
1083
+ rescale: float
1084
+
1085
+ def calls(self, index: int) -> tuple[BranchCall, ...]:
1086
+ """The forwards point ``index`` runs, in evaluation order."""
1087
+
1088
+ match self.steps[index]:
1089
+ case UnguidedStep(main=main):
1090
+ return (main,)
1091
+ case SingleReferenceStep(main=main, reference=reference):
1092
+ return (main, reference)
1093
+ case AveragedStep(main=main, cfg=cfg, pdg=None):
1094
+ return (main, cfg)
1095
+ case AveragedStep(main=main, cfg=cfg, pdg=BranchCall() as pdg):
1096
+ return (main, cfg, pdg)
1097
+ case _ as unreachable:
1098
+ raise ValueError(f"Unsupported guidance step: {unreachable}")
1099
+
1100
+ def guided_velocity(
1101
+ self, index: int, state: Tensor, time: Tensor, evaluate: BranchEvaluator
1102
+ ) -> Tensor:
1103
+ """Run point ``index``'s forwards through ``evaluate`` (main first) and
1104
+ return the guided velocity in ``state``'s dtype.
1105
+
1106
+ Args:
1107
+ index: Schedule point (the solver's ``step_index``).
1108
+ state: The solver state ``x_t`` (APG reads it).
1109
+ time: Float32 ``[B]`` times of the point.
1110
+ evaluate: Runs one forward at ``(state, time)``.
1111
+ """
1112
+
1113
+ step = self.steps[index]
1114
+ main = evaluate(step.main)
1115
+ match step:
1116
+ case UnguidedStep():
1117
+ return main.to(dtype=state.dtype)
1118
+ case SingleReferenceStep(reference=reference, scale=scale):
1119
+ guided = self._single(main, evaluate(reference), state, time, scale)
1120
+ case AveragedStep() as averaged:
1121
+ cfg = evaluate(averaged.cfg)
1122
+ pdg = main if averaged.pdg is None else evaluate(averaged.pdg)
1123
+ guided = main + 0.5 * (
1124
+ averaged.cfg_scale * (main - cfg)
1125
+ + averaged.pdg_scale * (main - pdg)
1126
+ )
1127
+ case _ as unreachable:
1128
+ raise ValueError(f"Unsupported guidance step: {unreachable}")
1129
+ if self.rescale > 0.0:
1130
+ guided = rescale_guided_velocity(
1131
+ guided=guided, reference=main, rescale=self.rescale
1132
+ )
1133
+ return guided.to(dtype=state.dtype)
1134
+
1135
+ def _single(
1136
+ self, main: Tensor, reference: Tensor, state: Tensor, time: Tensor, scale: float
1137
+ ) -> Tensor:
1138
+ """Combine one reference with the main velocity (plain or APG)."""
1139
+
1140
+ if self.projection.mode is ProjectionMode.OFF:
1141
+ return reference + scale * (main - reference)
1142
+ return projected_guidance_velocity(
1143
+ main=main,
1144
+ reference=reference,
1145
+ state=state,
1146
+ time=time,
1147
+ scale=scale,
1148
+ projection=self.projection,
1149
+ )
1150
+
1151
+
1152
+ def build_guidance_plan(
1153
+ settings: GuidanceSettings,
1154
+ *,
1155
+ schedule: TimeSchedule,
1156
+ log_snr_shift: float,
1157
+ timesteps: Sequence[float],
1158
+ ) -> GuidancePlan:
1159
+ """Resolve ``settings`` for one run.
1160
+
1161
+ Args:
1162
+ settings: Validated guidance settings.
1163
+ schedule: The run's schedule family and step count.
1164
+ log_snr_shift: The effective shift the schedule was built with.
1165
+ timesteps: Host copy of the solver's schedule (``steps + 1`` floats,
1166
+ with the noisy-endpoint cap if the solver uses it); the ramp reads
1167
+ its quantiles at these times.
1168
+
1169
+ Returns:
1170
+ One ``GuidanceStep`` per schedule point.
1171
+
1172
+ Raises:
1173
+ ValueError: If a window does not fit, ``timesteps`` has the wrong
1174
+ length, or CFG is on with a PDG mode that has no CFG steps and the
1175
+ two windows overlap (PDG would silently take those steps).
1176
+ """
1177
+
1178
+ steps = schedule.steps
1179
+ if len(timesteps) != steps + 1:
1180
+ raise ValueError(
1181
+ f"timesteps has {len(timesteps)} points; the schedule has {steps + 1}."
1182
+ )
1183
+ pdg = settings.pdg
1184
+ pdg_values = None
1185
+ if pdg is not None:
1186
+ match pdg.scale:
1187
+ case EndpointPdgCurve() | BezierPdgCurve() as curve:
1188
+ pdg_values = per_step_pdg_scales(
1189
+ curve, schedule=schedule, log_snr_shift=log_snr_shift
1190
+ )
1191
+ case ConstantPdgScale() | RampPdgScale():
1192
+ pass
1193
+ case _ as unreachable:
1194
+ raise ValueError(f"Unsupported PDG scale: {unreachable}")
1195
+ cfg_window = (
1196
+ settings.cfg.window.resolve(steps, "CFG") if settings.cfg.enabled else None
1197
+ )
1198
+ pdg_window = pdg.window.resolve(steps, "PDG") if pdg is not None else None
1199
+ _reject_shadowed_cfg(settings, cfg_window, pdg_window)
1200
+ inputs = _PlanInputs(
1201
+ settings=settings,
1202
+ steps=steps,
1203
+ times=tuple(float(time) for time in timesteps),
1204
+ cdf=ScheduleCdf(schedule, log_snr_shift),
1205
+ pdg_values=pdg_values,
1206
+ cfg_window=cfg_window,
1207
+ pdg_window=pdg_window,
1208
+ )
1209
+ return GuidancePlan(
1210
+ steps=tuple(_resolve_step(inputs, index) for index in range(steps + 1)),
1211
+ projection=settings.projection,
1212
+ rescale=settings.rescale,
1213
+ )
1214
+
1215
+
1216
+ def _reject_shadowed_cfg(
1217
+ settings: GuidanceSettings,
1218
+ cfg_window: tuple[int, int] | None,
1219
+ pdg_window: tuple[int, int] | None,
1220
+ ) -> None:
1221
+ """Reject CFG that a PDG mode without CFG steps would silently replace.
1222
+
1223
+ Raises:
1224
+ ValueError: If CFG is on, the PDG mode runs no CFG forwards and the
1225
+ CFG and PDG windows share a step.
1226
+ """
1227
+
1228
+ pdg = settings.pdg
1229
+ if cfg_window is None or pdg_window is None or pdg is None or pdg.mode.uses_cfg:
1230
+ return
1231
+ first = max(cfg_window[0], pdg_window[0])
1232
+ last = min(cfg_window[1], pdg_window[1])
1233
+ if first <= last:
1234
+ raise ValueError(
1235
+ f"CFG and PDG mode {pdg.mode.value} are both active on steps "
1236
+ f"{first}-{last}; PDG would take those steps. Use a PDG mode that "
1237
+ "includes CFG (combined_cfg_pdg, alternate_*, pdg_with_alternating_cfg, "
1238
+ "cfg_to_pdg) or make the step windows disjoint."
1239
+ )
1240
+
1241
+
1242
+ # The three-quarter routing keeps one token of each 2x2 latent group, so the
1243
+ # token grid needs even sides: image sides that are multiples of this.
1244
+ THREE_QUARTER_SIZE_MULTIPLE = 32
1245
+
1246
+
1247
+ def check_three_quarter_size(
1248
+ settings: GuidanceSettings, width: int, height: int
1249
+ ) -> None:
1250
+ """Reject an image size the three-quarter routing cannot run at.
1251
+
1252
+ Raises:
1253
+ ValueError: If PDG mode ``three_quarter`` or sparse middle steps are
1254
+ on and a side is not a multiple of ``THREE_QUARTER_SIZE_MULTIPLE``.
1255
+ """
1256
+
1257
+ three_quarter = settings.pdg is not None and (
1258
+ settings.pdg.mode is PdgMode.THREE_QUARTER
1259
+ )
1260
+ if not (three_quarter or settings.sparse_middle.percent > 0.0):
1261
+ return
1262
+ if width % THREE_QUARTER_SIZE_MULTIPLE or height % THREE_QUARTER_SIZE_MULTIPLE:
1263
+ raise ValueError(
1264
+ "PDG mode three_quarter and sparse middle steps need a width and "
1265
+ f"height that are multiples of {THREE_QUARTER_SIZE_MULTIPLE}; got "
1266
+ f"{width}x{height}."
1267
+ )
dflow/inference.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sampling dflow latents: settings, noise and the guided solver loop.
2
+
3
+ The engine joins the pieces: prompts are encoded and refined once per call,
4
+ the guidance plan decides which forwards each schedule point runs, and the
5
+ solver integrates from noise (``t = 1``) to the image (``t = 0``).
6
+
7
+ Seeds. One integer seed fixes everything random in a call:
8
+
9
+ - the initial noise is ``torch.randn`` of the latent shape from a CPU
10
+ generator seeded with the seed (the same noise on every GPU);
11
+ - stochastic solvers draw from a second CPU generator with the same seed;
12
+ - the three-quarter routing draws its kept tokens from a CUDA generator with
13
+ the same seed.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from collections.abc import Callable, Sequence
20
+ from dataclasses import dataclass, field
21
+ from typing import TYPE_CHECKING
22
+
23
+ import torch
24
+ from torch import Tensor
25
+
26
+ from .configuration import EMPTY_PROMPT_ERROR, InferencePolicy
27
+ from .guidance import (
28
+ BranchCall,
29
+ BranchText,
30
+ GuidanceSettings,
31
+ build_guidance_plan,
32
+ check_three_quarter_size,
33
+ )
34
+ from .layout import compile_layout, is_compiled_layout
35
+ from .modeling import DFlowModel, PreparedText, self_attention_gain_tensor
36
+ from .prompt_emphasis import EmphasisSettings
37
+ from .schedules import (
38
+ TRAINING_BASE_LOG_SNR_SHIFT,
39
+ TimeSchedule,
40
+ build_timesteps,
41
+ resolution_log_snr_shift,
42
+ )
43
+ from .solvers import (
44
+ DEFAULT_SDE_NOISE_SCALE,
45
+ Solver,
46
+ solve,
47
+ solver_is_stochastic,
48
+ solver_requires_finite_noisy_endpoint,
49
+ )
50
+ from .types import DFlowPath
51
+ from .vae import LATENT_CHANNELS, LATENT_STRIDE
52
+
53
+ if TYPE_CHECKING:
54
+ from .text_conditioning import DFlowTextEncoder
55
+
56
+ DEFAULT_WIDTH = 832
57
+ DEFAULT_HEIGHT = 1216
58
+ MAX_SEED = 2**63 - 1
59
+
60
+ LatentCallback = Callable[[Tensor, int, int], None]
61
+ """Receives the predicted clean latents ``[B, 96, h, w]``, the number of
62
+ completed updates and the total after each solver update."""
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class SamplingSettings:
67
+ """Solver, schedule and timestep shift.
68
+
69
+ The log-SNR shift moves every schedule point towards the noisy end
70
+ (negative values). By default it is the shift the model was trained with
71
+ at the image size: ``base_log_snr_shift - ln(width * height / 256^2)``,
72
+ capped at 0 (-2.99 at 832 x 1216).
73
+
74
+ Attributes:
75
+ solver: Numerical method.
76
+ noise_scale: Noise multiplier of stochastic solvers (ignored by
77
+ deterministic ones).
78
+ schedule: Spacing and number of solver updates.
79
+ base_log_snr_shift: Size-independent part of the shift.
80
+ resolution_shift: Add the image-size term to the shift.
81
+
82
+ Raises:
83
+ ValueError: For a negative or non-finite noise scale or shift.
84
+ """
85
+
86
+ solver: Solver = Solver.ER_SDE
87
+ noise_scale: float = DEFAULT_SDE_NOISE_SCALE
88
+ schedule: TimeSchedule = field(default_factory=TimeSchedule)
89
+ base_log_snr_shift: float = TRAINING_BASE_LOG_SNR_SHIFT
90
+ resolution_shift: bool = True
91
+
92
+ def __post_init__(self) -> None:
93
+ """Validate the noise scale and the base shift."""
94
+
95
+ if not math.isfinite(self.noise_scale) or self.noise_scale < 0.0:
96
+ raise ValueError(f"noise_scale must be >= 0, got {self.noise_scale}.")
97
+ if not math.isfinite(self.base_log_snr_shift):
98
+ raise ValueError("base_log_snr_shift must be finite.")
99
+
100
+ def log_snr_shift(self, width: int, height: int) -> float:
101
+ """The effective shift at an image size."""
102
+
103
+ if self.resolution_shift:
104
+ return resolution_log_snr_shift(width, height, base=self.base_log_snr_shift)
105
+ return self.base_log_snr_shift
106
+
107
+ def timesteps(self, width: int, height: int, device: torch.device) -> Tensor:
108
+ """The descending float32 schedule at an image size."""
109
+
110
+ return build_timesteps(
111
+ self.schedule,
112
+ log_snr_shift=self.log_snr_shift(width, height),
113
+ finite_noisy_endpoint=solver_requires_finite_noisy_endpoint(self.solver),
114
+ device=device,
115
+ )
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class GenerationSettings:
120
+ """Everything except the prompt that fixes one generation.
121
+
122
+ Attributes:
123
+ width: Image width in pixels, a multiple of 16.
124
+ height: Image height in pixels, a multiple of 16.
125
+ seed: Seed of every random draw (see the module docstring).
126
+ sampling: Solver, schedule and shift.
127
+ guidance: Guidance and self-attention gains.
128
+ emphasis: Prompt-emphasis settings for ``(phrase:weight)`` markup, or
129
+ None to read prompts verbatim. Layout prompts are always verbatim.
130
+ negative_prompt: Text of the negative branch used by CFG and the
131
+ contrastive guidance modes; empty selects the learned null text.
132
+
133
+ Raises:
134
+ ValueError: For a size that is not a positive multiple of 16 or a
135
+ seed outside ``[0, 2**63 - 1]``.
136
+ """
137
+
138
+ width: int = DEFAULT_WIDTH
139
+ height: int = DEFAULT_HEIGHT
140
+ seed: int = 0
141
+ sampling: SamplingSettings = field(default_factory=SamplingSettings)
142
+ guidance: GuidanceSettings = field(default_factory=GuidanceSettings)
143
+ emphasis: EmphasisSettings | None = field(default_factory=EmphasisSettings)
144
+ negative_prompt: str = ""
145
+
146
+ def __post_init__(self) -> None:
147
+ """Validate the size and seed."""
148
+
149
+ for name, value in (("width", self.width), ("height", self.height)):
150
+ if value <= 0 or value % LATENT_STRIDE:
151
+ raise ValueError(
152
+ f"{name} must be a positive multiple of {LATENT_STRIDE}, "
153
+ f"got {value}."
154
+ )
155
+ if not 0 <= self.seed <= MAX_SEED:
156
+ raise ValueError(f"seed must lie in [0, {MAX_SEED}], got {self.seed}.")
157
+
158
+ @property
159
+ def latent_shape(self) -> tuple[int, int, int]:
160
+ """``(channels, height / 16, width / 16)`` of one latent."""
161
+
162
+ return (
163
+ LATENT_CHANNELS,
164
+ self.height // LATENT_STRIDE,
165
+ self.width // LATENT_STRIDE,
166
+ )
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class ImageToImage:
171
+ """Start from existing latents instead of pure noise.
172
+
173
+ The schedule is built at its full step count and sampling starts at
174
+ ``start_step``: the start latents are noised to that point's time with
175
+ the seed's noise, and the remaining ``steps - start_step`` updates run.
176
+ Guidance step windows count from the start step.
177
+
178
+ Attributes:
179
+ latents: ``[B or 1, 96, h, w]`` float32 whitened latents of the
180
+ generation size.
181
+ start_step: Index of the first schedule point, in ``[0, steps)``.
182
+ """
183
+
184
+ latents: Tensor
185
+ start_step: int
186
+
187
+
188
+ def resolve_prompt(prompt: str, width: int, height: int) -> str:
189
+ """Return the text the encoder reads for a prompt at an image size.
190
+
191
+ A stored layout (the ``summary``/``frame``/``items`` JSON with 0-1000
192
+ boxes) is compiled to the pixel layout the model was trained on at that
193
+ size; an already compiled layout is returned unchanged after its panel
194
+ box is checked against the size. Plain prompts are returned unchanged.
195
+
196
+ Raises:
197
+ dflow.layout.LayoutSizeMismatchError: For a layout compiled for
198
+ another size.
199
+ dflow.layout.LayoutError: For an invalid layout.
200
+ """
201
+
202
+ if is_compiled_layout(prompt):
203
+ return compile_layout(prompt, width, height)
204
+ return prompt
205
+
206
+
207
+ class DFlowEngine:
208
+ """Samples latents with a loaded denoiser and text encoder.
209
+
210
+ Args:
211
+ model: The denoiser on a CUDA device.
212
+ text_encoder: The prompt encoder on the same device.
213
+ policy: The release's inference rules (``config.json`` ``"inference"``).
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ model: DFlowModel,
219
+ text_encoder: DFlowTextEncoder,
220
+ *,
221
+ policy: InferencePolicy,
222
+ ) -> None:
223
+ self.model = model
224
+ self.text_encoder = text_encoder
225
+ self.policy = policy
226
+ self.device = next(model.parameters()).device
227
+
228
+ def check_prompts(self, prompts: Sequence[str]) -> None:
229
+ """Reject blank prompts unless the policy allows them.
230
+
231
+ Raises:
232
+ ValueError: ``EMPTY_PROMPT_ERROR`` for a blank prompt.
233
+ """
234
+
235
+ if not self.policy.allow_empty_prompt and any(
236
+ not prompt.strip() for prompt in prompts
237
+ ):
238
+ raise ValueError(EMPTY_PROMPT_ERROR)
239
+
240
+ def prepare_texts(
241
+ self,
242
+ prompts: Sequence[str],
243
+ settings: GenerationSettings,
244
+ ) -> dict[BranchText, PreparedText]:
245
+ """Encode and refine the positive prompts and, when the guidance uses
246
+ it, the negative prompt repeated over the batch.
247
+
248
+ The negative branch never takes prompt emphasis.
249
+
250
+ Raises:
251
+ ValueError: If a prompt is blank while the policy forbids it, or the
252
+ positive prompts do not share one token count.
253
+ """
254
+
255
+ self.check_prompts(prompts)
256
+ positives = [
257
+ resolve_prompt(prompt, settings.width, settings.height)
258
+ for prompt in prompts
259
+ ]
260
+ texts = {
261
+ BranchText.POSITIVE: self.model.prepare_text(
262
+ self.text_encoder.encode(positives, emphasis=settings.emphasis)
263
+ )
264
+ }
265
+ if settings.guidance.uses_negative:
266
+ negative = resolve_prompt(
267
+ settings.negative_prompt, settings.width, settings.height
268
+ )
269
+ texts[BranchText.NEGATIVE] = self.model.prepare_text(
270
+ self.text_encoder.encode([negative] * len(prompts), emphasis=None)
271
+ )
272
+ return texts
273
+
274
+ @torch.inference_mode()
275
+ def sample(
276
+ self,
277
+ prompts: Sequence[str],
278
+ settings: GenerationSettings,
279
+ *,
280
+ image_to_image: ImageToImage | None = None,
281
+ callback: LatentCallback | None = None,
282
+ ) -> Tensor:
283
+ """Sample one latent per prompt.
284
+
285
+ Args:
286
+ prompts: Plain prompts, stored or compiled layouts, all with the
287
+ same token count (repeat one prompt for several images).
288
+ settings: Size, seed, sampling and guidance.
289
+ image_to_image: Start latents and start step, or None to start
290
+ from noise.
291
+ callback: Called after each solver update with the predicted
292
+ clean latents.
293
+
294
+ Returns:
295
+ Float32 whitened latents ``[B, 96, height / 16, width / 16]``.
296
+
297
+ Raises:
298
+ ValueError: On an empty prompt list, unequal prompt lengths, start
299
+ latents of the wrong shape, or a size the three-quarter routing
300
+ cannot run at.
301
+ """
302
+
303
+ if not prompts:
304
+ raise ValueError("At least one prompt is required.")
305
+ check_three_quarter_size(settings.guidance, settings.width, settings.height)
306
+ batch = len(prompts)
307
+ texts = self.prepare_texts(prompts, settings)
308
+ sampling = settings.sampling
309
+ full = sampling.timesteps(settings.width, settings.height, self.device)
310
+ noise = self._initial_noise(batch, settings)
311
+ match image_to_image:
312
+ case None:
313
+ timesteps = full
314
+ state = noise
315
+ case ImageToImage(latents=latents, start_step=start):
316
+ timesteps = _slice_schedule(full, start)
317
+ state = _noised_start(latents, noise, timesteps[0], batch)
318
+ case _ as unreachable:
319
+ raise ValueError(f"Unsupported image_to_image: {unreachable}")
320
+ host_times = timesteps.tolist()
321
+ plan = build_guidance_plan(
322
+ settings.guidance,
323
+ schedule=TimeSchedule(
324
+ kind=sampling.schedule.kind,
325
+ steps=len(host_times) - 1,
326
+ beta_mean=sampling.schedule.beta_mean,
327
+ beta_concentration=sampling.schedule.beta_concentration,
328
+ ),
329
+ log_snr_shift=sampling.log_snr_shift(settings.width, settings.height),
330
+ timesteps=host_times,
331
+ )
332
+ routing = torch.Generator(device=self.device).manual_seed(settings.seed)
333
+ gains: dict[float, Tensor] = {}
334
+
335
+ def evaluate_at(state: Tensor, time: Tensor) -> Callable[[BranchCall], Tensor]:
336
+ def evaluate(call: BranchCall) -> Tensor:
337
+ path = call.branch.path
338
+ if call.self_attention_gain not in gains:
339
+ gains[call.self_attention_gain] = self_attention_gain_tensor(
340
+ call.self_attention_gain, device=self.device
341
+ )
342
+ return self.model(
343
+ state,
344
+ time,
345
+ texts[call.branch.text],
346
+ path=path,
347
+ self_attention_gain=gains[call.self_attention_gain],
348
+ suffix_caption_bias=call.suffix_caption_bias,
349
+ generator=routing if path is DFlowPath.THREE_QUARTER else None,
350
+ )
351
+
352
+ return evaluate
353
+
354
+ def velocity(state: Tensor, time: Tensor, index: int) -> Tensor:
355
+ return plan.guided_velocity(index, state, time, evaluate_at(state, time))
356
+
357
+ return solve(
358
+ velocity,
359
+ state,
360
+ timesteps,
361
+ solver=sampling.solver,
362
+ noise_scale=sampling.noise_scale,
363
+ generator=(
364
+ torch.Generator(device="cpu").manual_seed(settings.seed)
365
+ if solver_is_stochastic(sampling.solver)
366
+ else None
367
+ ),
368
+ callback=callback,
369
+ )
370
+
371
+ def _initial_noise(self, batch: int, settings: GenerationSettings) -> Tensor:
372
+ """The seed's standard normal latents on the device, channels-last."""
373
+
374
+ generator = torch.Generator(device="cpu").manual_seed(settings.seed)
375
+ noise = torch.randn(
376
+ (batch, *settings.latent_shape),
377
+ generator=generator,
378
+ dtype=torch.float32,
379
+ device="cpu",
380
+ )
381
+ return noise.to(device=self.device).contiguous(
382
+ memory_format=torch.channels_last
383
+ )
384
+
385
+
386
+ def _slice_schedule(timesteps: Tensor, start_step: int) -> Tensor:
387
+ """The schedule from ``start_step`` on.
388
+
389
+ Raises:
390
+ ValueError: If ``start_step`` leaves no update.
391
+ """
392
+
393
+ steps = int(timesteps.shape[0]) - 1
394
+ if not 0 <= start_step < steps:
395
+ raise ValueError(f"start_step must lie in [0, {steps}), got {start_step}.")
396
+ return timesteps[start_step:].contiguous()
397
+
398
+
399
+ def _noised_start(latents: Tensor, noise: Tensor, time: Tensor, batch: int) -> Tensor:
400
+ """``(1 - t) x0 + t noise`` at the first point of a sliced schedule.
401
+
402
+ Raises:
403
+ ValueError: If the latents do not match the noise's shape (a batch of
404
+ one is repeated over the prompts).
405
+ """
406
+
407
+ if latents.ndim != 4 or tuple(latents.shape[1:]) != tuple(noise.shape[1:]):
408
+ raise ValueError(
409
+ f"Start latents must have shape [B, {', '.join(map(str, noise.shape[1:]))}]"
410
+ f", got {tuple(latents.shape)}."
411
+ )
412
+ if int(latents.shape[0]) not in (1, batch):
413
+ raise ValueError(
414
+ f"Start latents hold {latents.shape[0]} images for {batch} prompts."
415
+ )
416
+ clean = latents.to(device=noise.device, dtype=torch.float32).expand_as(noise)
417
+ return ((1.0 - time) * clean + time * noise).contiguous(
418
+ memory_format=torch.channels_last
419
+ )
dflow/layout.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layout prompts: compile a stored layout into the prompt the model reads.
2
+
3
+ A stored layout is JSON with three parts:
4
+
5
+ - ``summary``: ``meta`` tags, ``canvas`` and a ``caption`` of the whole image;
6
+ - ``frame``: ``caption``, ``tags`` and ``palette`` of the whole canvas;
7
+ - ``items``: boxes, each with a ``label`` (character, object, text), optional
8
+ ``caption``, ``tags`` and ``palette``, a ``box_2d`` ``[y0, x0, y1, x1]`` on a
9
+ 0-1000 scale and, for text items, the exact ``text``.
10
+
11
+ The model was trained on the compiled form, which depends on the image size:
12
+ the frame becomes a full-canvas ``panel`` item and every box becomes integer
13
+ pixels centred on the image centre (``abs_centralized``, ``yxyx``). Optional
14
+ fields may be left out; training dropped them at random.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import math
21
+ from collections.abc import Mapping
22
+ from enum import StrEnum
23
+
24
+ __all__ = [
25
+ "LAYOUT_BOX_SCALE",
26
+ "LayoutError",
27
+ "LayoutLabel",
28
+ "LayoutSizeMismatchError",
29
+ "compile_layout",
30
+ "is_compiled_layout",
31
+ "is_stored_layout",
32
+ "panel_box",
33
+ ]
34
+
35
+ # Normalized box scale of stored layouts.
36
+ LAYOUT_BOX_SCALE = 1000
37
+ # Rounding applied before flooring/ceiling box edges (keeps exact edges exact).
38
+ _BOX_EDGE_DECIMALS = 9
39
+ # Optional descriptive fields of the frame and of every item, in compiled order.
40
+ _ENTRY_FIELDS = ("caption", "tags", "palette")
41
+ _SUMMARY_KEYS = frozenset({"meta", "canvas", "caption"})
42
+ _STORED_KEYS = frozenset({"summary", "frame", "items"})
43
+ _ITEM_KEYS = frozenset({"label", "box_2d", "text", *_ENTRY_FIELDS})
44
+ _COORD_SPACE = "abs_centralized"
45
+ _BOX_FORMAT = "yxyx"
46
+ _COMPILED_KEYS = frozenset({"summary", "items", "bbox_coord_space", "bbox_format"})
47
+ # Top-level keys every JSON prompt has; the text encoder tokenizes such prompts
48
+ # as structured JSON (character tokens for visible text only).
49
+ _JSON_PROMPT_KEYS = frozenset({"summary", "items"})
50
+
51
+
52
+ class LayoutLabel(StrEnum):
53
+ """Item labels of a layout."""
54
+
55
+ CHARACTER = "character"
56
+ OBJECT = "object"
57
+ TEXT = "text"
58
+ PANEL = "panel"
59
+
60
+
61
+ class LayoutError(ValueError):
62
+ """A layout is malformed."""
63
+
64
+
65
+ class LayoutSizeMismatchError(LayoutError):
66
+ """A compiled layout prompt was compiled for another image size."""
67
+
68
+
69
+ def _json_object(text: str) -> dict[str, object] | None:
70
+ """Return ``text`` parsed as a JSON object, or None if it is not one."""
71
+
72
+ if not text.lstrip().startswith("{"):
73
+ return None
74
+ try:
75
+ parsed = json.loads(text)
76
+ except json.JSONDecodeError:
77
+ return None
78
+ match parsed:
79
+ case dict():
80
+ return parsed
81
+ case _:
82
+ return None
83
+
84
+
85
+ def is_compiled_layout(text: str) -> bool:
86
+ """Whether ``text`` is a JSON layout prompt (an object with ``summary`` and
87
+ ``items``).
88
+
89
+ The text encoder tokenizes such prompts as structured JSON and never parses
90
+ them for emphasis markup, exactly as in training. A stored (uncompiled)
91
+ layout also passes this test; ``is_stored_layout`` tells them apart.
92
+ """
93
+
94
+ parsed = _json_object(text)
95
+ return parsed is not None and set(parsed) >= _JSON_PROMPT_KEYS
96
+
97
+
98
+ def is_stored_layout(text: str) -> bool:
99
+ """Whether ``text`` is a stored layout (``summary``, ``frame``, ``items``)
100
+ that still needs ``compile_layout`` before it can be encoded."""
101
+
102
+ parsed = _json_object(text)
103
+ return parsed is not None and set(parsed) == _STORED_KEYS
104
+
105
+
106
+ def panel_box(width: int, height: int) -> list[int]:
107
+ """Return the compiled full-canvas ``panel`` box ``[y0, x0, y1, x1]``.
108
+
109
+ Raises:
110
+ LayoutError: If the size is not positive.
111
+ """
112
+
113
+ if width <= 0 or height <= 0:
114
+ raise LayoutError(f"Layout size must be positive, got {width}x{height}.")
115
+ return [-(height // 2), -(width // 2), height - height // 2, width - width // 2]
116
+
117
+
118
+ def _four_ints(value: object, *, where: str) -> tuple[int, int, int, int]:
119
+ """Return ``value`` as four integers (booleans excluded).
120
+
121
+ Raises:
122
+ LayoutError: If it is not a list of four integers.
123
+ """
124
+
125
+ match value:
126
+ case list() if len(value) == 4 and all(
127
+ isinstance(item, int) and not isinstance(item, bool) for item in value
128
+ ):
129
+ a, b, c, d = (int(item) for item in value)
130
+ return a, b, c, d
131
+ case _:
132
+ raise LayoutError(f"{where} must be four integers, got {value!r}.")
133
+
134
+
135
+ def _box_pixels(box: object, *, width: int, height: int, where: str) -> list[int]:
136
+ """Return a 0-1000 ``yxyx`` box as centred integer pixels.
137
+
138
+ Min edges are floored and max edges ceiled after rounding to 9 decimals,
139
+ then shifted by ``height // 2`` / ``width // 2``.
140
+
141
+ Raises:
142
+ LayoutError: If ``box`` is not four ordered integers in 0..1000.
143
+ """
144
+
145
+ y0, x0, y1, x1 = _four_ints(box, where=f"{where}.box_2d")
146
+ if not (0 <= y0 < y1 <= LAYOUT_BOX_SCALE and 0 <= x0 < x1 <= LAYOUT_BOX_SCALE):
147
+ raise LayoutError(
148
+ f"{where}.box_2d {box!r} must be [y0, x0, y1, x1] with "
149
+ f"0 <= y0 < y1 <= {LAYOUT_BOX_SCALE} and 0 <= x0 < x1 <= "
150
+ f"{LAYOUT_BOX_SCALE}."
151
+ )
152
+
153
+ def edge(value: int, size: int) -> float:
154
+ return round(value * size / LAYOUT_BOX_SCALE, _BOX_EDGE_DECIMALS)
155
+
156
+ return [
157
+ math.floor(edge(y0, height)) - height // 2,
158
+ math.floor(edge(x0, width)) - width // 2,
159
+ math.ceil(edge(y1, height)) - height // 2,
160
+ math.ceil(edge(x1, width)) - width // 2,
161
+ ]
162
+
163
+
164
+ def _require_object(value: object, *, where: str) -> Mapping[str, object]:
165
+ """Return ``value`` as a JSON object.
166
+
167
+ Raises:
168
+ LayoutError: If it is not one.
169
+ """
170
+
171
+ match value:
172
+ case Mapping():
173
+ return value
174
+ case _:
175
+ raise LayoutError(f"{where} must be a JSON object.")
176
+
177
+
178
+ def _require_keys(
179
+ entry: Mapping[str, object], *, allowed: frozenset[str], where: str
180
+ ) -> None:
181
+ """Raise unless every key of ``entry`` is in ``allowed``."""
182
+
183
+ unknown = sorted(set(entry) - allowed)
184
+ if unknown:
185
+ raise LayoutError(
186
+ f"{where} has unknown keys {unknown}; allowed: {sorted(allowed)}."
187
+ )
188
+
189
+
190
+ def _require_string_list(value: object, *, where: str) -> None:
191
+ """Raise unless ``value`` is a list of strings."""
192
+
193
+ match value:
194
+ case list() if all(isinstance(item, str) for item in value):
195
+ return
196
+ case _:
197
+ raise LayoutError(f"{where} must be a list of strings.")
198
+
199
+
200
+ def _require_string(value: object, *, where: str) -> None:
201
+ """Raise unless ``value`` is a string."""
202
+
203
+ if not isinstance(value, str):
204
+ raise LayoutError(f"{where} must be a string.")
205
+
206
+
207
+ def _validated_entry_fields(entry: Mapping[str, object], *, where: str) -> None:
208
+ """Check the optional ``caption``, ``tags`` and ``palette`` fields."""
209
+
210
+ if "caption" in entry:
211
+ _require_string(entry["caption"], where=f"{where}.caption")
212
+ for key in ("tags", "palette"):
213
+ if key in entry:
214
+ _require_string_list(entry[key], where=f"{where}.{key}")
215
+
216
+
217
+ def _validated_summary(value: object) -> Mapping[str, object]:
218
+ """Return the checked ``summary`` object."""
219
+
220
+ summary = _require_object(value, where="summary")
221
+ _require_keys(summary, allowed=_SUMMARY_KEYS, where="summary")
222
+ if "meta" in summary:
223
+ _require_string_list(summary["meta"], where="summary.meta")
224
+ for key in ("canvas", "caption"):
225
+ if key in summary:
226
+ _require_string(summary[key], where=f"summary.{key}")
227
+ return summary
228
+
229
+
230
+ def _validated_items(value: object) -> list[Mapping[str, object]]:
231
+ """Return the checked ``items`` list."""
232
+
233
+ match value:
234
+ case list():
235
+ raw_items: list[object] = value
236
+ case _:
237
+ raise LayoutError("items must be a JSON list.")
238
+ items: list[Mapping[str, object]] = []
239
+ for pos, raw in enumerate(raw_items):
240
+ where = f"items[{pos}]"
241
+ item = _require_object(raw, where=where)
242
+ _require_keys(item, allowed=_ITEM_KEYS, where=where)
243
+ label = item.get("label")
244
+ if label not in {member.value for member in LayoutLabel}:
245
+ raise LayoutError(
246
+ f"{where}.label must be one of {[m.value for m in LayoutLabel]}, "
247
+ f"got {label!r}."
248
+ )
249
+ if "box_2d" not in item:
250
+ raise LayoutError(f"{where} needs a box_2d [y0, x0, y1, x1] on 0-1000.")
251
+ if label == LayoutLabel.TEXT and "text" not in item:
252
+ raise LayoutError(f"{where} is a text item and needs its exact 'text'.")
253
+ if "text" in item:
254
+ _require_string(item["text"], where=f"{where}.text")
255
+ _validated_entry_fields(item, where=where)
256
+ items.append(item)
257
+ return items
258
+
259
+
260
+ def _compile_stored(layout: Mapping[str, object], *, width: int, height: int) -> str:
261
+ """Compile a stored layout at ``width`` x ``height``.
262
+
263
+ Raises:
264
+ LayoutError: If the layout is malformed.
265
+ """
266
+
267
+ if set(layout) != _STORED_KEYS:
268
+ raise LayoutError(
269
+ "A stored layout needs exactly the keys summary, frame and items; got "
270
+ f"{sorted(layout)}."
271
+ )
272
+ summary = _validated_summary(layout["summary"])
273
+ frame = _require_object(layout["frame"], where="frame")
274
+ _require_keys(frame, allowed=frozenset(_ENTRY_FIELDS), where="frame")
275
+ _validated_entry_fields(frame, where="frame")
276
+ items = _validated_items(layout["items"])
277
+ panel: dict[str, object] = {"label": LayoutLabel.PANEL.value}
278
+ panel.update({key: frame[key] for key in _ENTRY_FIELDS if key in frame})
279
+ panel["bbox"] = panel_box(width, height)
280
+ compiled_items: list[dict[str, object]] = [panel]
281
+ for pos, item in enumerate(items):
282
+ out: dict[str, object] = {"label": item["label"]}
283
+ out.update({key: item[key] for key in _ENTRY_FIELDS if key in item})
284
+ out["bbox"] = _box_pixels(
285
+ item["box_2d"], width=width, height=height, where=f"items[{pos}]"
286
+ )
287
+ if "text" in item:
288
+ out["text"] = item["text"]
289
+ compiled_items.append(out)
290
+ prompt = {
291
+ "summary": dict(summary),
292
+ "items": compiled_items,
293
+ "bbox_coord_space": _COORD_SPACE,
294
+ "bbox_format": _BOX_FORMAT,
295
+ }
296
+ return json.dumps(prompt, ensure_ascii=False, separators=(",", ":"))
297
+
298
+
299
+ def _compiled_size(items: object) -> tuple[int, int] | None:
300
+ """Return the ``(width, height)`` a compiled prompt's panel encodes, or None."""
301
+
302
+ match items:
303
+ case [{"label": "panel", "bbox": list() as box}, *_]:
304
+ try:
305
+ y0, x0, y1, x1 = _four_ints(box, where="panel bbox")
306
+ except LayoutError:
307
+ return None
308
+ width, height = x1 - x0, y1 - y0
309
+ if width <= 0 or height <= 0 or box != panel_box(width, height):
310
+ return None
311
+ return width, height
312
+ case _:
313
+ return None
314
+
315
+
316
+ def _check_compiled(parsed: Mapping[str, object], *, width: int, height: int) -> None:
317
+ """Check a compiled prompt's format and that its panel matches the size.
318
+
319
+ Raises:
320
+ LayoutSizeMismatchError: If the panel box is for another size.
321
+ LayoutError: If the prompt is not a compiled layout.
322
+ """
323
+
324
+ if set(parsed) != _COMPILED_KEYS:
325
+ raise LayoutError(
326
+ "A compiled layout needs exactly the keys summary, items, "
327
+ f"bbox_coord_space and bbox_format; got {sorted(parsed)}."
328
+ )
329
+ if (
330
+ parsed["bbox_coord_space"] != _COORD_SPACE
331
+ or parsed["bbox_format"] != _BOX_FORMAT
332
+ ):
333
+ raise LayoutError(
334
+ f"A compiled layout must use bbox_coord_space={_COORD_SPACE!r} and "
335
+ f"bbox_format={_BOX_FORMAT!r}."
336
+ )
337
+ size = _compiled_size(parsed["items"])
338
+ if size is None:
339
+ raise LayoutError(
340
+ "A compiled layout's first item must be the full-canvas panel with an "
341
+ "integer bbox."
342
+ )
343
+ if size != (width, height):
344
+ raise LayoutSizeMismatchError(
345
+ f"This layout prompt was compiled for {size[0]}x{size[1]} "
346
+ f"(width x height); the image is {width}x{height}. Compile the "
347
+ "stored layout again at the image size."
348
+ )
349
+
350
+
351
+ def compile_layout(
352
+ layout_json: str | Mapping[str, object], width: int, height: int
353
+ ) -> str:
354
+ """Return the layout prompt the model reads for a ``width`` x ``height`` image.
355
+
356
+ Args:
357
+ layout_json: A stored layout (JSON text or a parsed mapping), or an
358
+ already compiled prompt (JSON text only), which is returned
359
+ verbatim after its panel box is checked against the size.
360
+ width: Image width in pixels.
361
+ height: Image height in pixels.
362
+
363
+ Returns:
364
+ The compiled prompt: one-line JSON, byte-identical to the training-time
365
+ compile of the same stored layout at this size.
366
+
367
+ Raises:
368
+ LayoutSizeMismatchError: If a compiled prompt is for another size.
369
+ LayoutError: If the layout is malformed or the size is not positive.
370
+ """
371
+
372
+ panel_box(width, height)
373
+ match layout_json:
374
+ case str() as text:
375
+ parsed = _json_object(text)
376
+ if parsed is None:
377
+ raise LayoutError("The layout is not a JSON object.")
378
+ # Only compiled prompts carry a coordinate space; anything else is
379
+ # read as a stored layout, whose own checks name a bad key.
380
+ if "bbox_coord_space" not in parsed:
381
+ return _compile_stored(parsed, width=width, height=height)
382
+ _check_compiled(parsed, width=width, height=height)
383
+ return text
384
+ case Mapping() as layout:
385
+ return _compile_stored(layout, width=width, height=height)
386
+ case _:
387
+ raise TypeError("layout_json must be JSON text or a mapping.")
dflow/loading.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load the dflow_2b denoiser and text adapter weights from a release directory.
2
+
3
+ A release directory holds ``model.safetensors`` (every weight, public names,
4
+ see ``precision``), ``config.json`` (architecture constants) and
5
+ ``release.json`` (version and counts). Loading checks, before any weight
6
+ reaches a module: the config against this package's architecture, the
7
+ version, the tensor and parameter counts, every name (none missing, none
8
+ extra), every shape and every storage dtype. The denoiser then loads with
9
+ ``strict=True``.
10
+
11
+ Public names: ``denoiser.<module path>`` for the denoiser (``DFlowModel``'s
12
+ own ``state_dict`` names, e.g. ``denoiser.prefix_layers.0.attn.qkv.weight``)
13
+ and ``text_adapter.<key>`` for the text adapter (its keys come from the text
14
+ adapter module, ``text_conditioning.TEXT_ADAPTER_KEY_MAP``).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import torch
23
+ from safetensors.torch import load_file
24
+ from torch import Tensor
25
+
26
+ from .configuration import DFLOW_2B_CONFIG, DFlowConfig, read_denoiser_config
27
+ from .modeling import DFlowModel
28
+ from .precision import (
29
+ DENOISER_PREFIX,
30
+ TEXT_ADAPTER_PREFIX,
31
+ StoredDType,
32
+ denoiser_storage_dtype,
33
+ text_adapter_storage_dtypes,
34
+ )
35
+ from .version import MODEL_VERSION
36
+
37
+ MODEL_FILENAME = "model.safetensors"
38
+ CONFIG_FILENAME = "config.json"
39
+ RELEASE_FILENAME = "release.json"
40
+
41
+
42
+ def expected_denoiser_shapes(config: DFlowConfig) -> dict[str, tuple[int, ...]]:
43
+ """Public name -> shape of every denoiser tensor of ``config``."""
44
+
45
+ with torch.device("meta"):
46
+ model = DFlowModel(config)
47
+ return {
48
+ DENOISER_PREFIX + name: tuple(tensor.shape)
49
+ for name, tensor in model.state_dict().items()
50
+ }
51
+
52
+
53
+ def expected_storage(config: DFlowConfig) -> dict[str, StoredDType]:
54
+ """Public name -> storage dtype of every tensor in ``model.safetensors``."""
55
+
56
+ storage = {
57
+ name: denoiser_storage_dtype(name) for name in expected_denoiser_shapes(config)
58
+ }
59
+ storage.update(text_adapter_storage_dtypes())
60
+ return storage
61
+
62
+
63
+ def validate_public_tensors(tensors: dict[str, Tensor], config: DFlowConfig) -> None:
64
+ """Check names, denoiser shapes and storage dtypes of a public weight file.
65
+
66
+ Raises:
67
+ ValueError: If a name is missing or unexpected, a denoiser shape
68
+ differs from ``config``'s, or a dtype differs from the policy.
69
+ """
70
+
71
+ storage = expected_storage(config)
72
+ missing = sorted(set(storage) - set(tensors))
73
+ unexpected = sorted(set(tensors) - set(storage))
74
+ if missing or unexpected:
75
+ raise ValueError(
76
+ f"{MODEL_FILENAME} does not match this package: missing={missing}, "
77
+ f"unexpected={unexpected}"
78
+ )
79
+ for name, shape in expected_denoiser_shapes(config).items():
80
+ if tuple(tensors[name].shape) != shape:
81
+ raise ValueError(
82
+ f"{name} has shape {tuple(tensors[name].shape)}; expected {shape}"
83
+ )
84
+ for name, stored in storage.items():
85
+ if tensors[name].dtype != stored.torch_dtype:
86
+ raise ValueError(
87
+ f"{name} is stored as {tensors[name].dtype}; the storage policy "
88
+ f"requires {stored.torch_dtype}"
89
+ )
90
+
91
+
92
+ def _validate_release_metadata(path: Path, tensors: dict[str, Tensor]) -> None:
93
+ """Check ``release.json``'s version and counts against the weight file.
94
+
95
+ Raises:
96
+ FileNotFoundError: If ``release.json`` is missing.
97
+ ValueError: If the version or a count differs.
98
+ """
99
+
100
+ if not path.is_file():
101
+ raise FileNotFoundError(f"Missing release metadata: {path}")
102
+ match json.loads(path.read_text(encoding="utf-8")):
103
+ case {
104
+ "version": str() as version,
105
+ "tensor_count": int() as tensor_count,
106
+ "parameter_count": int() as parameter_count,
107
+ }:
108
+ pass
109
+ case _:
110
+ raise ValueError(
111
+ f"{path} must hold version, tensor_count and parameter_count"
112
+ )
113
+ if version != MODEL_VERSION:
114
+ raise ValueError(
115
+ f"{path} is release {version}; this package loads {MODEL_VERSION}"
116
+ )
117
+ found_parameters = sum(tensor.numel() for tensor in tensors.values())
118
+ if (tensor_count, parameter_count) != (len(tensors), found_parameters):
119
+ raise ValueError(
120
+ f"{MODEL_FILENAME} holds {len(tensors)} tensors and {found_parameters} "
121
+ f"parameters; {RELEASE_FILENAME} declares {tensor_count} and "
122
+ f"{parameter_count}"
123
+ )
124
+
125
+
126
+ def read_release_tensors(directory: Path, config: DFlowConfig) -> dict[str, Tensor]:
127
+ """Read and validate every tensor of a release directory (on the CPU).
128
+
129
+ Raises:
130
+ FileNotFoundError: If a release file is missing.
131
+ ValueError: If the config, metadata or tensors do not match.
132
+ """
133
+
134
+ read_denoiser_config(directory / CONFIG_FILENAME, config)
135
+ weights = directory / MODEL_FILENAME
136
+ if not weights.is_file():
137
+ raise FileNotFoundError(f"Missing weights: {weights}")
138
+ tensors = load_file(weights, device="cpu")
139
+ _validate_release_metadata(directory / RELEASE_FILENAME, tensors)
140
+ validate_public_tensors(tensors, config)
141
+ return tensors
142
+
143
+
144
+ def _with_prefix(tensors: dict[str, Tensor], prefix: str) -> dict[str, Tensor]:
145
+ """The entries of ``tensors`` under ``prefix``, with the prefix removed."""
146
+
147
+ return {
148
+ name.removeprefix(prefix): tensor
149
+ for name, tensor in tensors.items()
150
+ if name.startswith(prefix)
151
+ }
152
+
153
+
154
+ def load_dflow_denoiser(
155
+ directory: Path,
156
+ *,
157
+ device: torch.device,
158
+ compile_model: bool,
159
+ config: DFlowConfig = DFLOW_2B_CONFIG,
160
+ ) -> DFlowModel:
161
+ """Build the denoiser and load a release directory's weights.
162
+
163
+ Weights keep their storage dtypes on the device (bfloat16 with FP32
164
+ islands). With ``compile_model`` every block is compiled
165
+ (``DFlowModel.compile_blocks(dynamic=True)``); graphs build on first use.
166
+
167
+ Args:
168
+ directory: Release directory (``model.safetensors``, ``config.json``,
169
+ ``release.json``).
170
+ device: CUDA device for the model.
171
+ compile_model: Compile the blocks, or run eagerly.
172
+ config: The architecture to expect (the released model's by default).
173
+
174
+ Returns:
175
+ The eval-mode denoiser without gradients.
176
+
177
+ Raises:
178
+ FileNotFoundError: If a release file is missing.
179
+ ValueError: If ``device`` is not CUDA or the release does not match.
180
+ """
181
+
182
+ if device.type != "cuda":
183
+ raise ValueError(f"dflow runs on CUDA (bfloat16 autocast), got {device}")
184
+ tensors = read_release_tensors(directory, config)
185
+ with torch.device("meta"):
186
+ model = DFlowModel(config)
187
+ model.load_state_dict(
188
+ _with_prefix(tensors, DENOISER_PREFIX), strict=True, assign=True
189
+ )
190
+ model.to(device=device)
191
+ model.eval()
192
+ model.requires_grad_(False)
193
+ if compile_model:
194
+ model.compile_blocks(dynamic=True)
195
+ return model
196
+
197
+
198
+ def load_text_adapter_tensors(
199
+ directory: Path, *, config: DFlowConfig = DFLOW_2B_CONFIG
200
+ ) -> dict[str, Tensor]:
201
+ """The text adapter's validated tensors, keyed relative to the adapter
202
+ module (the ``text_adapter.`` prefix removed), on the CPU.
203
+
204
+ Raises:
205
+ FileNotFoundError: If a release file is missing.
206
+ ValueError: If the release does not match.
207
+ """
208
+
209
+ return _with_prefix(read_release_tensors(directory, config), TEXT_ADAPTER_PREFIX)
dflow/modeling.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The dflow_2b denoiser: a single-stream text-image flow-matching transformer.
2
+
3
+ Time and velocity convention
4
+ ----------------------------
5
+ The model is trained on the linear path
6
+
7
+ x_t = (1 - t) * x_0 + t * eps, eps ~ N(0, I), t in [0, 1],
8
+
9
+ where ``x_0`` is a whitened dinac3_96 latent: ``t = 1`` is pure noise and
10
+ ``t = 0`` is data. ``forward`` returns the velocity
11
+
12
+ v = dx_t / dt = eps - x_0,
13
+
14
+ so an Euler step towards data is ``x_{t - h} = x_t - h * v``. The timestep
15
+ enters as a float32 ``t`` in ``[0, 1]``; the time embedding reads
16
+ ``sin``/``cos`` of ``1000 * t * f_k`` (128 log-spaced frequencies ``f_k``
17
+ from 1 to 1/10000). Log-SNR shifts and schedules are the sampler's business:
18
+ the model takes the plain ``t`` of the path above.
19
+
20
+ Stream and routing
21
+ ------------------
22
+ Each sample is one sequence ``[image tokens, text tokens]`` (row-major
23
+ ``H x W`` latent grid, then the ``L`` refined prompt tokens) with joint
24
+ self-attention in every layer. The text goes through two unmodulated refiner
25
+ blocks once per prompt (``prepare_text``); it does not depend on the image
26
+ size or the timestep, so one ``PreparedText`` serves every sampling step and
27
+ size. Image layers: 6 prefix, 18 middle, a tail join, 6 suffix. ``DFlowPath``
28
+ picks what the middle sees (``DFlowPath`` docstring); the tail join
29
+ concatenates the prefix output ``p`` with the middle output ``m`` (the learned
30
+ mask token where the middle did not run), scales both halves by ``1 + s(t)``,
31
+ projects back to the width, and adds a separate projection of the scaled
32
+ prefix at the rows the middle skipped.
33
+
34
+ Precision
35
+ ---------
36
+ Weights are bfloat16 with float32 norm weights and velocity head. Both entry
37
+ points run under CUDA bfloat16 autocast and ``torch.no_grad``. The text
38
+ refiner keeps a float32 residual stream (its input is float32); the joint
39
+ stream is bfloat16. Norm weights and the velocity head are cast to their
40
+ input's dtype at use, as in training under autocast. AdaLN scales and gates,
41
+ RoPE and the returned velocity are float32.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import math
47
+ from dataclasses import dataclass, replace
48
+ from typing import TYPE_CHECKING
49
+
50
+ import torch
51
+ import torch.nn.functional as F
52
+ from torch import Tensor, nn
53
+
54
+ from .blocks import DFlowBlock, RMSNorm
55
+ from .rope3d import joint_rope_rows, text_rope_rows, validate_rope_capacity
56
+ from .types import SUFFIX_TOKEN_COUNT, DFlowPath, TextConditioning
57
+
58
+ if TYPE_CHECKING:
59
+ from .configuration import DFlowConfig
60
+
61
+ AUTOCAST_DTYPE = torch.bfloat16
62
+ SELF_ATTENTION_GAIN_RANGE = (-0.5, 0.1)
63
+ """Supported self-attention logit gains (inclusive)."""
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class PreparedText:
68
+ """A prompt batch after the text refiner, reusable across steps and sizes.
69
+
70
+ Attributes:
71
+ tokens: ``[B, L, width]`` refined tokens (float32).
72
+ key_bias: ``[B, L]`` float32 prompt-emphasis key bias, or None.
73
+ value_scale: ``[B, L]`` float32 prompt-emphasis value scale, or None.
74
+ """
75
+
76
+ tokens: Tensor
77
+ key_bias: Tensor | None
78
+ value_scale: Tensor | None
79
+
80
+ @property
81
+ def length(self) -> int:
82
+ """Tokens per prompt ``L``."""
83
+
84
+ return int(self.tokens.shape[1])
85
+
86
+
87
+ def self_attention_gain_tensor(gain: float, *, device: torch.device) -> Tensor:
88
+ """The 0-dim float32 tensor ``forward`` takes as ``self_attention_gain``.
89
+
90
+ The gain ``g`` multiplies the image layers' queries by ``exp(g)`` (an
91
+ attention-logit temperature); 0 leaves the model unchanged.
92
+
93
+ Raises:
94
+ ValueError: If ``gain`` is not finite or outside
95
+ ``SELF_ATTENTION_GAIN_RANGE``.
96
+ """
97
+
98
+ low, high = SELF_ATTENTION_GAIN_RANGE
99
+ if not math.isfinite(gain) or not low <= gain <= high:
100
+ raise ValueError(
101
+ f"self-attention gain must be finite and within [{low}, {high}], got {gain}"
102
+ )
103
+ return torch.tensor(gain, dtype=torch.float32, device=device)
104
+
105
+
106
+ class TimeEmbedding(nn.Module):
107
+ """Sinusoidal timestep features through a SiLU MLP to the AdaLN width."""
108
+
109
+ proj_in: nn.Linear
110
+ proj_out: nn.Linear
111
+ frequency_width: int
112
+ time_scale: float
113
+ max_period: float
114
+
115
+ def __init__(self, config: DFlowConfig) -> None:
116
+ """Build the two projections."""
117
+
118
+ super().__init__()
119
+ self.frequency_width = config.time_frequency_width
120
+ self.time_scale = config.time_scale
121
+ self.max_period = config.time_max_period
122
+ self.proj_in = nn.Linear(config.time_frequency_width, config.time_hidden_width)
123
+ self.proj_out = nn.Linear(config.time_hidden_width, config.time_embed_width)
124
+
125
+ def forward(self, t: Tensor) -> Tensor:
126
+ """Embed float32 ``t`` ``[B]`` into ``[B, time_embed_width]``."""
127
+
128
+ half = self.frequency_width // 2
129
+ freqs = torch.exp(
130
+ -math.log(self.max_period)
131
+ * torch.arange(half, device=t.device, dtype=torch.float32)
132
+ / max(float(half - 1), 1.0)
133
+ )
134
+ angles = (t.to(dtype=torch.float32) * self.time_scale)[:, None] * freqs[None]
135
+ features = torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1)
136
+ hidden = F.silu(self.proj_in(features.to(dtype=self.proj_in.weight.dtype)))
137
+ return self.proj_out(hidden.to(dtype=self.proj_out.weight.dtype))
138
+
139
+
140
+ class TailJoin(nn.Module):
141
+ """Concat join of the prefix and middle streams with time-dependent gains."""
142
+
143
+ mask_token: nn.Parameter
144
+ adascale: nn.Linear
145
+ proj: nn.Linear
146
+ dropped_skip_proj: nn.Linear
147
+
148
+ def __init__(self, config: DFlowConfig) -> None:
149
+ """Build the mask token and the three projections."""
150
+
151
+ super().__init__()
152
+ self.mask_token = nn.Parameter(torch.zeros(1, config.width))
153
+ self.adascale = nn.Linear(config.time_embed_width, 2 * config.width)
154
+ self.proj = nn.Linear(2 * config.width, config.width)
155
+ self.dropped_skip_proj = nn.Linear(config.width, config.width, bias=False)
156
+
157
+ def forward(
158
+ self,
159
+ prefix: Tensor,
160
+ middle: Tensor,
161
+ dropped: Tensor | None,
162
+ time_act: Tensor,
163
+ ) -> Tensor:
164
+ """Fuse ``[B, S, D]`` streams: ``W [g_p p ; g_m m] + b`` with
165
+ ``g = 1 + s(t)``, plus ``dropped * dropped_skip_proj(g_p p)``.
166
+
167
+ Args:
168
+ prefix: Prefix output.
169
+ middle: Middle output, the mask token where the middle did not run.
170
+ dropped: ``[B, S, 1]`` 1 at rows the middle skipped and 0 elsewhere;
171
+ None when the middle ran on every row.
172
+ time_act: SiLU of the timestep vector ``[B, time_embed_width]``.
173
+ """
174
+
175
+ batch, length, width = prefix.shape
176
+ concat = torch.cat([prefix, middle], dim=-1)
177
+ scale = self.adascale(time_act).to(dtype=torch.float32)
178
+ scaled = concat.to(dtype=torch.float32) * (1.0 + scale[:, None, :])
179
+ # Row-major [B * S, 2D] matrices: the projections see the token rows
180
+ # exactly as the trained model's packed stream does.
181
+ rows = scaled.to(dtype=concat.dtype).reshape(batch * length, 2 * width)
182
+ fused = self.proj(rows)
183
+ if dropped is not None:
184
+ fused = fused + dropped.reshape(batch * length, 1) * self.dropped_skip_proj(
185
+ rows[:, :width]
186
+ )
187
+ return fused.reshape(batch, length, width)
188
+
189
+
190
+ @dataclass(frozen=True)
191
+ class _StreamInputs:
192
+ """Per-forward inputs shared by every image layer."""
193
+
194
+ rope_sin: Tensor
195
+ rope_cos: Tensor
196
+ query_scale: Tensor
197
+ key_bias: Tensor | None
198
+ value_scale: Tensor | None
199
+ time_act: Tensor
200
+
201
+
202
+ class DFlowModel(nn.Module):
203
+ """The denoiser (see the module docstring for conventions)."""
204
+
205
+ config: DFlowConfig
206
+ patch_embed: nn.Conv2d
207
+ time_embed: TimeEmbedding
208
+ text_refiner_layers: nn.ModuleList
209
+ prefix_layers: nn.ModuleList
210
+ middle_layers: nn.ModuleList
211
+ suffix_layers: nn.ModuleList
212
+ prefix_adaln: nn.ModuleList
213
+ middle_adaln: nn.ModuleList
214
+ suffix_adaln: nn.ModuleList
215
+ tail_join: TailJoin
216
+ final_norm: RMSNorm
217
+ final_modulation: nn.Linear
218
+ velocity_head: nn.Linear
219
+
220
+ def __init__(self, config: DFlowConfig) -> None:
221
+ """Build every module of ``config`` (weights are loaded separately)."""
222
+
223
+ super().__init__()
224
+ self.config = config
225
+ self.patch_embed = nn.Conv2d(config.latent_channels, config.width, 1)
226
+ self.time_embed = TimeEmbedding(config)
227
+ self.text_refiner_layers = _blocks(config, config.text_refiner_depth)
228
+ self.prefix_layers = _blocks(config, config.prefix_depth)
229
+ self.middle_layers = _blocks(config, config.middle_depth)
230
+ self.suffix_layers = _blocks(config, config.suffix_depth)
231
+ self.prefix_adaln = _adaln(config, config.prefix_depth)
232
+ self.middle_adaln = _adaln(config, config.middle_depth)
233
+ self.suffix_adaln = _adaln(config, config.suffix_depth)
234
+ self.tail_join = TailJoin(config)
235
+ self.final_norm = RMSNorm(config.width, eps=config.norm_eps)
236
+ self.final_modulation = nn.Linear(config.time_embed_width, 2 * config.width)
237
+ self.velocity_head = nn.Linear(config.width, config.latent_channels)
238
+
239
+ def compile_blocks(self, *, dynamic: bool) -> None:
240
+ """Compile every transformer block with ``torch.compile(fullgraph=True)``.
241
+
242
+ Graphs build on first use; a graph break or compiler error raises
243
+ then. Path, gain value and emphasis tensors stay outside the graphs.
244
+
245
+ Raises:
246
+ RuntimeError: If Dynamo is set to suppress errors, or a block is
247
+ already compiled.
248
+ """
249
+
250
+ if torch._dynamo.config.suppress_errors:
251
+ raise RuntimeError(
252
+ "torch._dynamo.config.suppress_errors is set: dflow compiles with "
253
+ "errors raised, never with an eager fallback"
254
+ )
255
+ for layers in (
256
+ self.text_refiner_layers,
257
+ self.prefix_layers,
258
+ self.middle_layers,
259
+ self.suffix_layers,
260
+ ):
261
+ for block in _block_list(layers):
262
+ block.compile_block(dynamic=dynamic)
263
+
264
+ @torch.no_grad()
265
+ def prepare_text(self, text: TextConditioning) -> PreparedText:
266
+ """Run the text refiner once for a prompt batch.
267
+
268
+ Args:
269
+ text: Encoder tokens ``[B, L, width]`` float32 and optional
270
+ emphasis tensors ``[B, L]`` float32, on the model's device.
271
+
272
+ Returns:
273
+ The refined tokens with the emphasis tensors carried along.
274
+
275
+ Raises:
276
+ ValueError: For wrong shapes, dtypes or devices, or a prompt too
277
+ long for the RoPE capacity.
278
+ """
279
+
280
+ self._validate_text(text)
281
+ batch, length, _ = text.tokens.shape
282
+ validate_rope_capacity(
283
+ self.config, text_length=length, grid_height=1, grid_width=1
284
+ )
285
+ device = text.tokens.device
286
+ sin, cos = text_rope_rows(self.config, length, device=device)
287
+ key_bias = _key_bias(text.key_bias, dtype=AUTOCAST_DTYPE)
288
+ value_scale = _value_scale(text.value_scale, dtype=AUTOCAST_DTYPE)
289
+ rope_sin = _batched(sin, batch)
290
+ rope_cos = _batched(cos, batch)
291
+ x = _owned(text.tokens)
292
+ with torch.autocast(device_type=device.type, dtype=AUTOCAST_DTYPE):
293
+ for block in _block_list(self.text_refiner_layers):
294
+ x = block(
295
+ x,
296
+ rope_sin=rope_sin,
297
+ rope_cos=rope_cos,
298
+ modulation=None,
299
+ query_scale=None,
300
+ key_bias=key_bias,
301
+ value_scale=value_scale,
302
+ )
303
+ return PreparedText(
304
+ tokens=x, key_bias=text.key_bias, value_scale=text.value_scale
305
+ )
306
+
307
+ @torch.no_grad()
308
+ def forward(
309
+ self,
310
+ latents: Tensor,
311
+ timestep: Tensor,
312
+ prepared: PreparedText,
313
+ *,
314
+ path: DFlowPath,
315
+ self_attention_gain: Tensor,
316
+ suffix_caption_bias: float,
317
+ generator: torch.Generator | None,
318
+ ) -> Tensor:
319
+ """Predict the velocity ``eps - x_0`` at ``(x_t, t)``.
320
+
321
+ Args:
322
+ latents: ``x_t`` ``[B, 96, H, W]`` float32 (whitened latent grid).
323
+ timestep: ``t`` ``[B]`` float32 in ``[0, 1]`` (1 = noise).
324
+ prepared: ``prepare_text`` output with batch ``B``.
325
+ path: Middle routing (``DFlowPath``).
326
+ self_attention_gain: 0-dim float32 tensor on the latents' device
327
+ (``self_attention_gain_tensor``); scales the image layers'
328
+ queries by ``exp(gain)``, never the refiner's.
329
+ suffix_caption_bias: Additive attention-logit bias on the prompt's
330
+ token keys (every text row but the learned suffix) in the six
331
+ suffix layers, for every query; 0 for none. The PDG reference
332
+ forward uses it (``PdgGuidance.suffix_caption_bias``).
333
+ generator: For ``THREE_QUARTER``, the CUDA generator that picks the
334
+ one kept token of each 2x2 group (uniformly, per sample and
335
+ step); it draws exactly what the training code
336
+ draws, so a generator seeded alike keeps the same tokens.
337
+ None for the other paths.
338
+
339
+ Returns:
340
+ Velocity ``[B, 96, H, W]`` float32.
341
+
342
+ Raises:
343
+ ValueError: For inconsistent shapes, dtypes or devices, a grid
344
+ beyond the RoPE capacity, an odd grid side with
345
+ ``THREE_QUARTER``, a generator given or missing for the
346
+ path, or a non-finite suffix caption bias.
347
+ """
348
+
349
+ self._validate_forward(
350
+ latents,
351
+ timestep,
352
+ prepared,
353
+ path=path,
354
+ self_attention_gain=self_attention_gain,
355
+ suffix_caption_bias=suffix_caption_bias,
356
+ generator=generator,
357
+ )
358
+ with torch.autocast(device_type=latents.device.type, dtype=AUTOCAST_DTYPE):
359
+ return self._velocity(
360
+ latents,
361
+ timestep,
362
+ prepared,
363
+ path=path,
364
+ self_attention_gain=self_attention_gain,
365
+ suffix_caption_bias=suffix_caption_bias,
366
+ generator=generator,
367
+ )
368
+
369
+ def _velocity(
370
+ self,
371
+ latents: Tensor,
372
+ timestep: Tensor,
373
+ prepared: PreparedText,
374
+ *,
375
+ path: DFlowPath,
376
+ self_attention_gain: Tensor,
377
+ suffix_caption_bias: float,
378
+ generator: torch.Generator | None,
379
+ ) -> Tensor:
380
+ """``forward`` after validation, inside autocast."""
381
+
382
+ batch, _, grid_height, grid_width = latents.shape
383
+ image = self.patch_embed(latents).flatten(2).transpose(1, 2)
384
+ image_count = int(image.shape[1])
385
+ x = torch.cat([image, prepared.tokens.to(dtype=image.dtype)], dim=1)
386
+ sin, cos = joint_rope_rows(
387
+ self.config,
388
+ text_length=prepared.length,
389
+ grid_height=grid_height,
390
+ grid_width=grid_width,
391
+ device=latents.device,
392
+ )
393
+ time_act = F.silu(self.time_embed(timestep))
394
+ stream = _StreamInputs(
395
+ rope_sin=_batched(sin, batch),
396
+ rope_cos=_batched(cos, batch),
397
+ query_scale=torch.exp(self_attention_gain.to(dtype=torch.float64)).to(
398
+ dtype=torch.float32
399
+ ),
400
+ key_bias=_key_bias(
401
+ _pad_image_rows(prepared.key_bias, image_count, fill=0.0),
402
+ dtype=x.dtype,
403
+ ),
404
+ value_scale=_value_scale(
405
+ _pad_image_rows(prepared.value_scale, image_count, fill=1.0),
406
+ dtype=x.dtype,
407
+ ),
408
+ time_act=time_act,
409
+ )
410
+ x = self._run_layers(x, self.prefix_layers, self.prefix_adaln, stream)
411
+ x = self._middle_and_join(
412
+ x,
413
+ stream,
414
+ path=path,
415
+ grid=(grid_height, grid_width),
416
+ image_count=image_count,
417
+ generator=generator,
418
+ )
419
+ suffix_stream = (
420
+ stream
421
+ if suffix_caption_bias == 0.0
422
+ else _with_caption_key_bias(
423
+ stream,
424
+ bias=suffix_caption_bias,
425
+ image_count=image_count,
426
+ text_length=prepared.length,
427
+ batch=batch,
428
+ dtype=x.dtype,
429
+ )
430
+ )
431
+ x = self._run_layers(x, self.suffix_layers, self.suffix_adaln, suffix_stream)
432
+ return self._final_layer(x[:, :image_count], time_act, grid_height, grid_width)
433
+
434
+ def _middle_and_join(
435
+ self,
436
+ prefix: Tensor,
437
+ stream: _StreamInputs,
438
+ *,
439
+ path: DFlowPath,
440
+ grid: tuple[int, int],
441
+ image_count: int,
442
+ generator: torch.Generator | None,
443
+ ) -> Tensor:
444
+ """Run ``path``'s middle on the prefix output and fuse it in the tail join."""
445
+
446
+ mask = self.tail_join.mask_token.to(dtype=prefix.dtype).expand_as(prefix)
447
+ match path:
448
+ case DFlowPath.FULL:
449
+ middle = self._run_layers(
450
+ prefix, self.middle_layers, self.middle_adaln, stream
451
+ )
452
+ return self.tail_join(prefix, middle, None, stream.time_act)
453
+ case DFlowPath.PATH_DROP:
454
+ dropped = prefix.new_ones(prefix.shape[0], prefix.shape[1], 1)
455
+ return self.tail_join(prefix, mask, dropped, stream.time_act)
456
+ case DFlowPath.THREE_QUARTER:
457
+ if generator is None:
458
+ raise ValueError("THREE_QUARTER needs a generator")
459
+ rows = three_quarter_middle_rows(
460
+ grid=grid,
461
+ image_count=image_count,
462
+ text_length=prefix.shape[1] - image_count,
463
+ batch=prefix.shape[0],
464
+ generator=generator,
465
+ device=prefix.device,
466
+ )
467
+ kept = self._run_layers(
468
+ _gather_rows(prefix, rows),
469
+ self.middle_layers,
470
+ self.middle_adaln,
471
+ _gather_stream(stream, rows),
472
+ )
473
+ middle = mask.contiguous().scatter(
474
+ 1, _row_index(rows, prefix.shape[-1]), kept
475
+ )
476
+ dropped = prefix.new_ones(prefix.shape[0], prefix.shape[1], 1).scatter(
477
+ 1, rows.unsqueeze(-1), prefix.new_zeros((*rows.shape, 1))
478
+ )
479
+ return self.tail_join(prefix, middle, dropped, stream.time_act)
480
+ case _ as unsupported:
481
+ raise ValueError(f"Unsupported DFlowPath: {unsupported}")
482
+
483
+ @staticmethod
484
+ def _run_layers(
485
+ x: Tensor, layers: nn.ModuleList, adaln: nn.ModuleList, stream: _StreamInputs
486
+ ) -> Tensor:
487
+ """Run modulated image ``layers`` with their AdaLN projections."""
488
+
489
+ for block, projection in zip(
490
+ _block_list(layers), _linear_list(adaln), strict=True
491
+ ):
492
+ x = block(
493
+ x,
494
+ rope_sin=stream.rope_sin,
495
+ rope_cos=stream.rope_cos,
496
+ modulation=projection(stream.time_act).to(dtype=torch.float32),
497
+ query_scale=stream.query_scale,
498
+ key_bias=stream.key_bias,
499
+ value_scale=stream.value_scale,
500
+ )
501
+ return x
502
+
503
+ def _final_layer(
504
+ self, image: Tensor, time_act: Tensor, grid_height: int, grid_width: int
505
+ ) -> Tensor:
506
+ """Final norm, timestep shift/scale and the velocity head, as a
507
+ float32 ``[B, C, H, W]`` grid."""
508
+
509
+ normed = self.final_norm(image)
510
+ shift, scale = (
511
+ self.final_modulation(time_act).to(dtype=torch.float32).chunk(2, dim=-1)
512
+ )
513
+ out = normed.to(dtype=torch.float32) * (1.0 + scale.unsqueeze(1))
514
+ out = (out + shift.unsqueeze(1)).to(dtype=normed.dtype)
515
+ velocity = F.linear(
516
+ out,
517
+ self.velocity_head.weight.to(dtype=out.dtype),
518
+ self.velocity_head.bias.to(dtype=out.dtype),
519
+ ).to(dtype=torch.float32)
520
+ batch = velocity.shape[0]
521
+ return velocity.transpose(1, 2).reshape(
522
+ batch, self.config.latent_channels, grid_height, grid_width
523
+ )
524
+
525
+ def _validate_text(self, text: TextConditioning) -> None:
526
+ """Check ``TextConditioning`` shapes, dtypes and device.
527
+
528
+ Raises:
529
+ ValueError: On any mismatch.
530
+ """
531
+
532
+ tokens = text.tokens
533
+ if tokens.dim() != 3 or tokens.shape[2] != self.config.width:
534
+ raise ValueError(
535
+ f"text tokens must be [B, L, {self.config.width}], got "
536
+ f"{tuple(tokens.shape)}"
537
+ )
538
+ if tokens.dtype != torch.float32:
539
+ raise ValueError(f"text tokens must be float32, got {tokens.dtype}")
540
+ if tokens.device != self.patch_embed.weight.device:
541
+ raise ValueError(
542
+ f"text tokens are on {tokens.device}; the model is on "
543
+ f"{self.patch_embed.weight.device}"
544
+ )
545
+ for name, values in (
546
+ ("key_bias", text.key_bias),
547
+ ("value_scale", text.value_scale),
548
+ ):
549
+ if values is None:
550
+ continue
551
+ if values.shape != tokens.shape[:2] or values.dtype != torch.float32:
552
+ raise ValueError(
553
+ f"text {name} must be float32 {tuple(tokens.shape[:2])}, got "
554
+ f"{values.dtype} {tuple(values.shape)}"
555
+ )
556
+ if values.device != tokens.device:
557
+ raise ValueError(f"text {name} must be on the tokens' device")
558
+
559
+ def _validate_forward(
560
+ self,
561
+ latents: Tensor,
562
+ timestep: Tensor,
563
+ prepared: PreparedText,
564
+ *,
565
+ path: DFlowPath,
566
+ self_attention_gain: Tensor,
567
+ suffix_caption_bias: float,
568
+ generator: torch.Generator | None,
569
+ ) -> None:
570
+ """Check ``forward``'s inputs (host-side metadata only, no device reads).
571
+
572
+ Raises:
573
+ ValueError: On any mismatch (see ``forward``).
574
+ """
575
+
576
+ config = self.config
577
+ if not math.isfinite(suffix_caption_bias):
578
+ raise ValueError(
579
+ f"suffix_caption_bias must be finite, got {suffix_caption_bias}"
580
+ )
581
+ if latents.dim() != 4 or latents.shape[1] != config.latent_channels:
582
+ raise ValueError(
583
+ f"latents must be [B, {config.latent_channels}, H, W], got "
584
+ f"{tuple(latents.shape)}"
585
+ )
586
+ batch, _, grid_height, grid_width = latents.shape
587
+ device = self.patch_embed.weight.device
588
+ expected = {
589
+ "latents": (
590
+ latents,
591
+ (batch, config.latent_channels, grid_height, grid_width),
592
+ ),
593
+ "timestep": (timestep, (batch,)),
594
+ "prepared tokens": (
595
+ prepared.tokens,
596
+ (batch, prepared.length, config.width),
597
+ ),
598
+ "self_attention_gain": (self_attention_gain, ()),
599
+ }
600
+ for name, (tensor, shape) in expected.items():
601
+ if tuple(tensor.shape) != shape or tensor.dtype != torch.float32:
602
+ raise ValueError(
603
+ f"{name} must be float32 {shape}, got {tensor.dtype} "
604
+ f"{tuple(tensor.shape)}"
605
+ )
606
+ if tensor.device != device:
607
+ raise ValueError(
608
+ f"{name} is on {tensor.device}; the model is on {device}"
609
+ )
610
+ validate_rope_capacity(
611
+ config,
612
+ text_length=prepared.length,
613
+ grid_height=grid_height,
614
+ grid_width=grid_width,
615
+ )
616
+ match path:
617
+ case DFlowPath.THREE_QUARTER:
618
+ if generator is None or not _generator_on(generator, device):
619
+ raise ValueError(
620
+ f"THREE_QUARTER needs a torch.Generator on {device}"
621
+ )
622
+ if grid_height % 2 or grid_width % 2:
623
+ raise ValueError(
624
+ "THREE_QUARTER needs even token-grid sides, got "
625
+ f"{grid_height}x{grid_width}"
626
+ )
627
+ case DFlowPath.FULL | DFlowPath.PATH_DROP:
628
+ if generator is not None:
629
+ raise ValueError(f"{path} draws nothing: pass generator=None")
630
+ case _ as unsupported:
631
+ raise ValueError(f"Unsupported DFlowPath: {unsupported}")
632
+
633
+
634
+ def three_quarter_middle_rows(
635
+ *,
636
+ grid: tuple[int, int],
637
+ image_count: int,
638
+ text_length: int,
639
+ batch: int,
640
+ generator: torch.Generator,
641
+ device: torch.device,
642
+ ) -> Tensor:
643
+ """Stream rows ``[B, H * W / 4 + L]`` the THREE_QUARTER middle runs on.
644
+
645
+ One uniformly drawn token of every 2x2 group of the row-major ``H x W``
646
+ grid (groups in raster order), then every text row. After the group
647
+ choice it draws (and discards) one float64 uniform per text token, as the
648
+ training code does for its all-kept text subset, so a shared
649
+ generator advances identically.
650
+ """
651
+
652
+ grid_height, grid_width = grid
653
+ group_y = torch.arange(grid_height // 2, device=device, dtype=torch.int64)
654
+ group_x = torch.arange(grid_width // 2, device=device, dtype=torch.int64)
655
+ base = (2 * group_y.view(-1, 1) * grid_width + 2 * group_x.view(1, -1)).reshape(
656
+ -1, 1
657
+ )
658
+ slot = torch.arange(4, device=device, dtype=torch.int64)
659
+ groups = base + (slot % 2 + (slot // 2) * grid_width).view(1, 4)
660
+ choice = torch.randint(
661
+ 0, 4, (batch, groups.shape[0]), device=device, generator=generator
662
+ )
663
+ kept = groups.unsqueeze(0).expand(batch, -1, -1).gather(2, choice.unsqueeze(-1))
664
+ torch.rand(
665
+ (batch * text_length,), device=device, dtype=torch.float64, generator=generator
666
+ )
667
+ text = image_count + torch.arange(text_length, device=device, dtype=torch.int64)
668
+ return torch.cat([kept.squeeze(-1), text.expand(batch, -1)], dim=1)
669
+
670
+
671
+ def _generator_on(generator: torch.Generator, device: torch.device) -> bool:
672
+ """Whether ``generator`` draws on ``device`` (an index-less generator
673
+ device means the current device of its type)."""
674
+
675
+ found = generator.device
676
+ if found.type != device.type:
677
+ return False
678
+ if found.index is None or device.index is None:
679
+ return found.index is None and (
680
+ device.index is None or device.index == torch.cuda.current_device()
681
+ )
682
+ return found.index == device.index
683
+
684
+
685
+ def _row_index(rows: Tensor, width: int) -> Tensor:
686
+ """``rows`` ``[B, K]`` expanded to gather/scatter ``[B, K, width]``."""
687
+
688
+ return rows.unsqueeze(-1).expand(-1, -1, width)
689
+
690
+
691
+ def _gather_rows(values: Tensor, rows: Tensor) -> Tensor:
692
+ """Rows ``[B, K, D]`` of ``values`` ``[B, S, D]``."""
693
+
694
+ return values.gather(1, _row_index(rows, values.shape[-1]))
695
+
696
+
697
+ def _gather_stream(stream: _StreamInputs, rows: Tensor) -> _StreamInputs:
698
+ """``stream`` restricted to ``rows`` ``[B, K]``."""
699
+
700
+ batch, count = rows.shape
701
+ return _StreamInputs(
702
+ rope_sin=_gather_rows(stream.rope_sin, rows),
703
+ rope_cos=_gather_rows(stream.rope_cos, rows),
704
+ query_scale=stream.query_scale,
705
+ key_bias=None
706
+ if stream.key_bias is None
707
+ else stream.key_bias.gather(3, rows.view(batch, 1, 1, count)),
708
+ value_scale=None
709
+ if stream.value_scale is None
710
+ else stream.value_scale.gather(2, rows.view(batch, 1, count, 1)),
711
+ time_act=stream.time_act,
712
+ )
713
+
714
+
715
+ def _with_caption_key_bias(
716
+ stream: _StreamInputs,
717
+ *,
718
+ bias: float,
719
+ image_count: int,
720
+ text_length: int,
721
+ batch: int,
722
+ dtype: torch.dtype,
723
+ ) -> _StreamInputs:
724
+ """``stream`` with ``bias`` added to the key bias of the prompt's token
725
+ rows: the ``text_length - SUFFIX_TOKEN_COUNT`` rows after the image rows
726
+ (the learned suffix rows keep their bias)."""
727
+
728
+ caption = torch.zeros(
729
+ (batch, image_count + text_length), dtype=dtype, device=stream.time_act.device
730
+ )
731
+ caption[:, image_count : image_count + text_length - SUFFIX_TOKEN_COUNT] = bias
732
+ added = caption[:, None, None, :]
733
+ key_bias = added if stream.key_bias is None else stream.key_bias + added
734
+ return replace(stream, key_bias=_owned(key_bias))
735
+
736
+
737
+ def _pad_image_rows(
738
+ values: Tensor | None, image_count: int, *, fill: float
739
+ ) -> Tensor | None:
740
+ """``[B, L]`` text values prefixed by ``fill`` for ``image_count`` image rows."""
741
+
742
+ if values is None:
743
+ return None
744
+ pad = values.new_full((values.shape[0], image_count), fill)
745
+ return torch.cat([pad, values], dim=1)
746
+
747
+
748
+ def _key_bias(values: Tensor | None, *, dtype: torch.dtype) -> Tensor | None:
749
+ """``[B, S]`` key bias as an additive SDPA mask ``[B, 1, 1, S]``."""
750
+
751
+ if values is None:
752
+ return None
753
+ return _owned(values.to(dtype=dtype)[:, None, None, :])
754
+
755
+
756
+ def _value_scale(values: Tensor | None, *, dtype: torch.dtype) -> Tensor | None:
757
+ """``[B, S]`` value scale as ``[B, 1, S, 1]``."""
758
+
759
+ if values is None:
760
+ return None
761
+ return _owned(values.to(dtype=dtype)[:, None, :, None])
762
+
763
+
764
+ def _owned(values: Tensor) -> Tensor:
765
+ """A contiguous copy of ``values`` that is not a view.
766
+
767
+ Compiled blocks guard on whether an input is a view, so every block input
768
+ is built as an owned tensor: one graph serves every call site.
769
+ """
770
+
771
+ return values.clone(memory_format=torch.contiguous_format)
772
+
773
+
774
+ def _batched(rows: Tensor, batch: int) -> Tensor:
775
+ """``[N, D]`` rows repeated over a batch as an owned ``[B, N, D]`` tensor."""
776
+
777
+ return _owned(rows.unsqueeze(0).expand(batch, -1, -1))
778
+
779
+
780
+ def _blocks(config: DFlowConfig, count: int) -> nn.ModuleList:
781
+ """``count`` transformer blocks."""
782
+
783
+ return nn.ModuleList(DFlowBlock(config) for _ in range(count))
784
+
785
+
786
+ def _adaln(config: DFlowConfig, count: int) -> nn.ModuleList:
787
+ """``count`` AdaLN projections ``time_embed_width -> 4 * width``."""
788
+
789
+ return nn.ModuleList(
790
+ nn.Linear(config.time_embed_width, 4 * config.width) for _ in range(count)
791
+ )
792
+
793
+
794
+ def _block_list(layers: nn.ModuleList) -> list[DFlowBlock]:
795
+ """The blocks of ``layers``, typed.
796
+
797
+ Raises:
798
+ TypeError: If an entry is not a DFlowBlock.
799
+ """
800
+
801
+ blocks: list[DFlowBlock] = []
802
+ for layer in layers:
803
+ match layer:
804
+ case DFlowBlock() as block:
805
+ blocks.append(block)
806
+ case _ as other:
807
+ raise TypeError(f"expected DFlowBlock, got {type(other).__name__}")
808
+ return blocks
809
+
810
+
811
+ def _linear_list(layers: nn.ModuleList) -> list[nn.Linear]:
812
+ """The linears of ``layers``, typed.
813
+
814
+ Raises:
815
+ TypeError: If an entry is not an nn.Linear.
816
+ """
817
+
818
+ linears: list[nn.Linear] = []
819
+ for layer in layers:
820
+ match layer:
821
+ case nn.Linear() as linear:
822
+ linears.append(linear)
823
+ case _ as other:
824
+ raise TypeError(f"expected nn.Linear, got {type(other).__name__}")
825
+ return linears
dflow/pipeline.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompt-to-image pipeline: loading, sampling, decoding and PNG metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Sequence
7
+ from dataclasses import asdict, dataclass, field
8
+ from enum import Enum
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ from huggingface_hub import snapshot_download
13
+ from PIL import Image, PngImagePlugin
14
+ from torch import Tensor
15
+
16
+ from .configuration import read_inference_policy
17
+ from .inference import (
18
+ DFlowEngine,
19
+ GenerationSettings,
20
+ ImageToImage,
21
+ LatentCallback,
22
+ )
23
+ from .loading import CONFIG_FILENAME, load_dflow_denoiser, load_text_adapter_tensors
24
+ from .preview import preview_images
25
+ from .text_conditioning import DFlowTextEncoder, TextAdapter
26
+ from .vae import DFlowVae
27
+ from .version import MODEL_VERSION, __version__
28
+
29
+ REPOSITORY = "data-archetype/dflow_2b"
30
+ TEXT_ENCODER_DIRNAME = "text_encoder"
31
+ PNG_METADATA_KEY = "dflow"
32
+ _RELEASE_PATTERNS = (
33
+ "model.safetensors",
34
+ "config.json",
35
+ "release.json",
36
+ f"{TEXT_ENCODER_DIRNAME}/*",
37
+ )
38
+
39
+
40
+ def resolve_release_directory(
41
+ path_or_repository: str | Path,
42
+ *,
43
+ revision: str | None,
44
+ cache_dir: Path | None,
45
+ ) -> Path:
46
+ """Return a local release directory.
47
+
48
+ A ``Path`` or an existing directory is used as it is; any other string
49
+ with a ``/`` is a Hub repository id whose weights and text encoder are
50
+ downloaded.
51
+
52
+ Raises:
53
+ FileNotFoundError: If a ``Path`` names no directory, or a string is
54
+ neither a directory nor a Hub id.
55
+ """
56
+
57
+ if isinstance(path_or_repository, Path):
58
+ if not path_or_repository.is_dir():
59
+ raise FileNotFoundError(f"No release directory at {path_or_repository}.")
60
+ return path_or_repository
61
+ local = Path(path_or_repository).expanduser()
62
+ if local.is_dir():
63
+ return local
64
+ if "/" not in path_or_repository:
65
+ raise FileNotFoundError(
66
+ f"No release folder {path_or_repository!r} here; pass its path or the "
67
+ "Hub id data-archetype/dflow_2b."
68
+ )
69
+ return Path(
70
+ snapshot_download(
71
+ path_or_repository,
72
+ revision=revision,
73
+ allow_patterns=list(_RELEASE_PATTERNS),
74
+ cache_dir=None if cache_dir is None else str(cache_dir),
75
+ )
76
+ )
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class DFlowComponents:
81
+ """The loaded parts of the model.
82
+
83
+ Attributes:
84
+ engine: Denoiser and text encoder.
85
+ vae: The dinac3_96 autoencoder.
86
+ compiled: Whether the blocks were compiled.
87
+ """
88
+
89
+ engine: DFlowEngine
90
+ vae: DFlowVae
91
+ compiled: bool
92
+
93
+ @classmethod
94
+ def from_pretrained(
95
+ cls,
96
+ path_or_repository: str | Path = REPOSITORY,
97
+ *,
98
+ device: torch.device | str = "cuda",
99
+ compile: bool = True,
100
+ revision: str | None = None,
101
+ cache_dir: Path | None = None,
102
+ vae_dir: Path | None = None,
103
+ ) -> DFlowComponents:
104
+ """Load the denoiser, text encoder and autoencoder.
105
+
106
+ Args:
107
+ path_or_repository: A local release directory or Hub repository.
108
+ device: CUDA device.
109
+ compile: ``torch.compile`` the denoiser blocks, encoder layers and
110
+ autoencoder. Graphs build on first use (30 to 45 seconds);
111
+ False runs eagerly.
112
+ revision: Hub revision of the release (a repository id only).
113
+ cache_dir: Hugging Face cache directory, or None for the default.
114
+ vae_dir: A local copy of ``data-archetype/dinac3_96``, or None to
115
+ download its pinned commit.
116
+
117
+ Raises:
118
+ FileNotFoundError: If release files are missing.
119
+ ValueError: On a non-CUDA device or a release that does not match
120
+ this code.
121
+ """
122
+
123
+ target = torch.device(device)
124
+ directory = resolve_release_directory(
125
+ path_or_repository, revision=revision, cache_dir=cache_dir
126
+ )
127
+ model = load_dflow_denoiser(directory, device=target, compile_model=compile)
128
+ adapter = TextAdapter()
129
+ adapter.load_state_dict(load_text_adapter_tensors(directory), strict=True)
130
+ text_encoder = DFlowTextEncoder.from_directory(
131
+ directory / TEXT_ENCODER_DIRNAME, adapter=adapter, device=target
132
+ )
133
+ if compile:
134
+ text_encoder.compile_layers()
135
+ vae = DFlowVae.from_pretrained(
136
+ device=target, compile=compile, local_dir=vae_dir, cache_dir=cache_dir
137
+ )
138
+ policy = read_inference_policy(directory / CONFIG_FILENAME)
139
+ return cls(
140
+ engine=DFlowEngine(model, text_encoder, policy=policy),
141
+ vae=vae,
142
+ compiled=compile,
143
+ )
144
+
145
+
146
+ class OutputType(Enum):
147
+ """What ``DFlowPipeline.__call__`` returns."""
148
+
149
+ PIL = "pil"
150
+ TENSOR = "tensor"
151
+ LATENT = "latent"
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class DFlowOutput:
156
+ """Images of one call.
157
+
158
+ Attributes:
159
+ images: PIL images with their settings in the PNG text chunk (PIL
160
+ output), else empty.
161
+ tensors: ``[B, 3, H, W]`` float32 RGB in ``[-1, 1]`` (TENSOR output),
162
+ or ``[B, 96, h, w]`` latents (LATENT output), else None.
163
+ settings: The settings of the call.
164
+ """
165
+
166
+ images: list[Image.Image]
167
+ tensors: Tensor | None
168
+ settings: GenerationSettings
169
+
170
+
171
+ @dataclass
172
+ class DFlowPipeline:
173
+ """Text to image with dflow_2b.
174
+
175
+ Example::
176
+
177
+ pipe = DFlowPipeline.from_pretrained("data-archetype/dflow_2b")
178
+ image = pipe("A lighthouse on a cliff at dusk.").images[0]
179
+ image.save("lighthouse.png", pnginfo=pipe.png_info(image))
180
+ """
181
+
182
+ components: DFlowComponents
183
+ default_settings: GenerationSettings = field(default_factory=GenerationSettings)
184
+
185
+ @classmethod
186
+ def from_pretrained(
187
+ cls,
188
+ path_or_repository: str | Path = REPOSITORY,
189
+ *,
190
+ device: torch.device | str = "cuda",
191
+ compile: bool = True,
192
+ revision: str | None = None,
193
+ cache_dir: Path | None = None,
194
+ vae_dir: Path | None = None,
195
+ ) -> DFlowPipeline:
196
+ """Load a pipeline (see ``DFlowComponents.from_pretrained``)."""
197
+
198
+ return cls(
199
+ DFlowComponents.from_pretrained(
200
+ path_or_repository,
201
+ device=device,
202
+ compile=compile,
203
+ revision=revision,
204
+ cache_dir=cache_dir,
205
+ vae_dir=vae_dir,
206
+ )
207
+ )
208
+
209
+ def __call__(
210
+ self,
211
+ prompt: str | Sequence[str],
212
+ settings: GenerationSettings | None = None,
213
+ *,
214
+ num_images: int = 1,
215
+ output_type: OutputType = OutputType.PIL,
216
+ image_to_image: ImageToImage | None = None,
217
+ callback: LatentCallback | None = None,
218
+ ) -> DFlowOutput:
219
+ """Generate images.
220
+
221
+ Args:
222
+ prompt: One prompt (repeated ``num_images`` times) or a list of
223
+ prompts with the same token count.
224
+ settings: Size, seed, sampling and guidance; the pipeline's
225
+ ``default_settings`` when None.
226
+ num_images: Images per prompt string (a single prompt only).
227
+ output_type: PIL images, RGB tensors or latents.
228
+ image_to_image: Start latents and start step, or None.
229
+ callback: Receives the predicted clean latents after each update
230
+ (``dflow.preview.LatentRgbPreview`` turns them into previews).
231
+
232
+ Raises:
233
+ ValueError: For ``num_images`` < 1 or with a prompt list.
234
+ """
235
+
236
+ chosen = self.default_settings if settings is None else settings
237
+ prompts = _prompt_list(prompt, num_images)
238
+ latents = self.components.engine.sample(
239
+ prompts, chosen, image_to_image=image_to_image, callback=callback
240
+ )
241
+ match output_type:
242
+ case OutputType.LATENT:
243
+ return DFlowOutput(images=[], tensors=latents, settings=chosen)
244
+ case OutputType.TENSOR:
245
+ rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0)
246
+ return DFlowOutput(images=[], tensors=rgb, settings=chosen)
247
+ case OutputType.PIL:
248
+ rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0)
249
+ images = preview_images(rgb)
250
+ for index, image in enumerate(images):
251
+ image.info[PNG_METADATA_KEY] = generation_metadata(
252
+ prompts[index], chosen, batch_index=index
253
+ )
254
+ return DFlowOutput(images=images, tensors=None, settings=chosen)
255
+ case _ as unreachable:
256
+ raise ValueError(f"Unsupported output type: {unreachable}")
257
+
258
+ @staticmethod
259
+ def png_info(image: Image.Image) -> PngImagePlugin.PngInfo:
260
+ """A ``PngInfo`` carrying the image's generation metadata, for
261
+ ``image.save(path, pnginfo=...)``.
262
+
263
+ Raises:
264
+ KeyError: If the image did not come from this pipeline.
265
+ """
266
+
267
+ info = PngImagePlugin.PngInfo()
268
+ info.add_text(PNG_METADATA_KEY, str(image.info[PNG_METADATA_KEY]))
269
+ return info
270
+
271
+
272
+ def generation_metadata(
273
+ prompt: str, settings: GenerationSettings, *, batch_index: int
274
+ ) -> str:
275
+ """JSON text describing one generated image."""
276
+
277
+ payload = {
278
+ "model": f"dflow_2b {MODEL_VERSION}",
279
+ "package": __version__,
280
+ "prompt": prompt,
281
+ "batch_index": batch_index,
282
+ "settings": asdict(settings),
283
+ }
284
+ return json.dumps(payload, default=_json_value, sort_keys=True)
285
+
286
+
287
+ def _json_value(value: object) -> object:
288
+ """JSON form of enums in the settings."""
289
+
290
+ match value:
291
+ case Enum():
292
+ return value.value
293
+ case _:
294
+ raise TypeError(f"Cannot serialize {type(value).__name__} to JSON.")
295
+
296
+
297
+ def _prompt_list(prompt: str | Sequence[str], num_images: int) -> list[str]:
298
+ """The batch's prompts.
299
+
300
+ Raises:
301
+ ValueError: For ``num_images`` < 1, or ``num_images`` > 1 with a list.
302
+ """
303
+
304
+ if num_images < 1:
305
+ raise ValueError(f"num_images must be >= 1, got {num_images}.")
306
+ if isinstance(prompt, str):
307
+ return [prompt] * num_images
308
+ if num_images != 1:
309
+ raise ValueError("num_images applies to a single prompt string only.")
310
+ return list(prompt)
dflow/precision.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Storage dtypes of the public ``model.safetensors``: bfloat16 with FP32 islands.
2
+
3
+ Every tensor name in the file matches exactly one rule. The FP32 islands are
4
+ the tensors whose rounding would change results: norm affine weights (some
5
+ see a float32 residual stream), the velocity head, the text adapter's learned
6
+ tokens and tap statistics. The rest is bfloat16. The same
7
+ policy writes the file (``export_release.py``) and checks it on load; a
8
+ tensor stored in another dtype fails loading.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from enum import Enum
15
+
16
+ import torch
17
+
18
+ from .text_conditioning import TEXT_ADAPTER_KEY_MAP
19
+
20
+ DENOISER_PREFIX = "denoiser."
21
+ TEXT_ADAPTER_PREFIX = "text_adapter."
22
+
23
+
24
+ class StoredDType(Enum):
25
+ """The dtype one public tensor is stored in."""
26
+
27
+ BFLOAT16 = "bfloat16"
28
+ FLOAT32 = "float32"
29
+
30
+ @property
31
+ def torch_dtype(self) -> torch.dtype:
32
+ """The matching torch dtype."""
33
+
34
+ match self:
35
+ case StoredDType.BFLOAT16:
36
+ return torch.bfloat16
37
+ case StoredDType.FLOAT32:
38
+ return torch.float32
39
+ case _ as unreachable:
40
+ raise RuntimeError(f"Unsupported stored dtype: {unreachable}")
41
+
42
+
43
+ _LAYER = r"denoiser\.(?:text_refiner|prefix|middle|suffix)_layers\.\d+\."
44
+ _NORMS = r"(?:attn_norm1|attn_norm2|mlp_norm1|mlp_norm2|attn\.q_norm|attn\.k_norm)"
45
+
46
+ _STORAGE_RULES: tuple[tuple[re.Pattern[str], StoredDType], ...] = (
47
+ (re.compile(_LAYER + _NORMS + r"\.weight"), StoredDType.FLOAT32),
48
+ (
49
+ re.compile(
50
+ _LAYER
51
+ + r"(?:attn\.(?:qkv|proj_out)\.weight|mlp\.(?:up|down)\.(?:weight|bias))"
52
+ ),
53
+ StoredDType.BFLOAT16,
54
+ ),
55
+ (
56
+ re.compile(r"denoiser\.(?:prefix|middle|suffix)_adaln\.\d+\.(?:weight|bias)"),
57
+ StoredDType.BFLOAT16,
58
+ ),
59
+ (
60
+ re.compile(
61
+ r"denoiser\.(?:patch_embed|time_embed\.proj_in|time_embed\.proj_out"
62
+ r"|tail_join\.adascale|tail_join\.proj|final_modulation)"
63
+ r"\.(?:weight|bias)"
64
+ ),
65
+ StoredDType.BFLOAT16,
66
+ ),
67
+ (
68
+ re.compile(r"denoiser\.tail_join\.(?:mask_token|dropped_skip_proj\.weight)"),
69
+ StoredDType.BFLOAT16,
70
+ ),
71
+ (
72
+ re.compile(r"denoiser\.(?:final_norm\.weight|velocity_head\.(?:weight|bias))"),
73
+ StoredDType.FLOAT32,
74
+ ),
75
+ )
76
+
77
+
78
+ def denoiser_storage_dtype(name: str) -> StoredDType:
79
+ """Storage dtype of one public ``denoiser.*`` tensor.
80
+
81
+ Raises:
82
+ RuntimeError: If ``name`` matches no rule or several.
83
+ """
84
+
85
+ matches = {
86
+ storage for pattern, storage in _STORAGE_RULES if pattern.fullmatch(name)
87
+ }
88
+ if len(matches) != 1:
89
+ raise RuntimeError(
90
+ f"Public tensor {name!r} matches storage rules "
91
+ f"{sorted(storage.value for storage in matches)}; it needs exactly one"
92
+ )
93
+ return matches.pop()
94
+
95
+
96
+ # Storage of each training text adapter tensor; the public key of each is
97
+ # ``text_adapter.`` + ``TEXT_ADAPTER_KEY_MAP[training key]`` (text_conditioning).
98
+ _TEXT_ADAPTER_STORAGE: dict[str, StoredDType] = {
99
+ "conditioning._encoder._proj_lo.weight": StoredDType.BFLOAT16,
100
+ "conditioning._encoder._proj_mid.weight": StoredDType.BFLOAT16,
101
+ "conditioning._encoder._proj_hi.weight": StoredDType.BFLOAT16,
102
+ "conditioning._encoder._tap_statistics.mean": StoredDType.FLOAT32,
103
+ "conditioning._encoder._tap_statistics.std": StoredDType.FLOAT32,
104
+ "conditioning.learned_padding_tokens": StoredDType.FLOAT32,
105
+ "conditioning.uncond_token": StoredDType.FLOAT32,
106
+ }
107
+
108
+
109
+ def text_adapter_storage_dtypes() -> dict[str, StoredDType]:
110
+ """Storage dtype of every public text adapter tensor, keyed by its full
111
+ public name (``text_adapter.<key>``).
112
+
113
+ Raises:
114
+ RuntimeError: If the adapter's key map and the storage rules differ.
115
+ """
116
+
117
+ if set(TEXT_ADAPTER_KEY_MAP) != set(_TEXT_ADAPTER_STORAGE):
118
+ raise RuntimeError(
119
+ "Text adapter keys and storage rules differ: "
120
+ f"{sorted(set(TEXT_ADAPTER_KEY_MAP) ^ set(_TEXT_ADAPTER_STORAGE))}"
121
+ )
122
+ return {
123
+ TEXT_ADAPTER_PREFIX + public: _TEXT_ADAPTER_STORAGE[internal]
124
+ for internal, public in TEXT_ADAPTER_KEY_MAP.items()
125
+ }
dflow/preview.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast latent-to-RGB previews for dinac3_96 latents.
2
+
3
+ A fitted linear readout: a 3x3 convolution from the 96 whitened latent
4
+ channels to a 2x2 cell of RGB values per latent token, pixel-shuffled to 1/8
5
+ of the image resolution. It is meant for live previews during sampling; the
6
+ final image always comes from the VAE decoder.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from PIL import Image
18
+ from safetensors import safe_open
19
+ from safetensors.torch import load_file
20
+ from torch import Tensor
21
+
22
+ LATENT_RGB_PREVIEW_FILENAME = "latent_rgb_preview.safetensors"
23
+ _METADATA_KEY = "dflow"
24
+ _FORMAT = "dflow.latent_rgb_preview.v1"
25
+ _WEIGHT_KEY = "projection.weight"
26
+ _BIAS_KEY = "projection.bias"
27
+ _LATENT_CHANNELS = 96
28
+ _RGB_CHANNELS = 3
29
+ _EXPANSION = 2
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class LatentRgbPreview:
34
+ """The fitted projection, as float32 tensors on one device.
35
+
36
+ Attributes:
37
+ weight: ``[12, 96, k, k]`` convolution weight (k odd).
38
+ bias: ``[12]`` bias.
39
+ """
40
+
41
+ weight: Tensor
42
+ bias: Tensor
43
+
44
+ @classmethod
45
+ def from_file(cls, path: Path) -> LatentRgbPreview:
46
+ """Load a projection file and check its metadata and shapes.
47
+
48
+ Raises:
49
+ ValueError: If the metadata, tensor names, shapes or dtypes do not
50
+ match the dinac3_96 preview format.
51
+ """
52
+
53
+ _check_metadata(path)
54
+ tensors = load_file(str(path), device="cpu")
55
+ if set(tensors) != {_WEIGHT_KEY, _BIAS_KEY}:
56
+ raise ValueError(
57
+ f"{path} must hold exactly {_WEIGHT_KEY} and {_BIAS_KEY}, "
58
+ f"got {sorted(tensors)}."
59
+ )
60
+ weight = tensors[_WEIGHT_KEY]
61
+ bias = tensors[_BIAS_KEY]
62
+ cells = _RGB_CHANNELS * _EXPANSION**2
63
+ kernel = int(weight.shape[-1])
64
+ if (
65
+ weight.ndim != 4
66
+ or tuple(weight.shape[:2]) != (cells, _LATENT_CHANNELS)
67
+ or int(weight.shape[2]) != kernel
68
+ or kernel % 2 != 1
69
+ or tuple(bias.shape) != (cells,)
70
+ ):
71
+ raise ValueError(
72
+ f"{path}: expected weight [{cells}, {_LATENT_CHANNELS}, k, k] with "
73
+ f"odd k and bias [{cells}], got {tuple(weight.shape)} and "
74
+ f"{tuple(bias.shape)}."
75
+ )
76
+ if weight.dtype != torch.float32 or bias.dtype != torch.float32:
77
+ raise ValueError(f"{path}: the projection must be stored in float32.")
78
+ return cls(weight=weight.contiguous(), bias=bias.contiguous())
79
+
80
+ @classmethod
81
+ def bundled(cls) -> LatentRgbPreview:
82
+ """Load the projection shipped with the package."""
83
+
84
+ return cls.from_file(Path(__file__).with_name(LATENT_RGB_PREVIEW_FILENAME))
85
+
86
+ def to(self, device: torch.device) -> LatentRgbPreview:
87
+ """Return a copy on ``device``."""
88
+
89
+ return LatentRgbPreview(self.weight.to(device), self.bias.to(device))
90
+
91
+ def project(self, latents: Tensor) -> Tensor:
92
+ """Project whitened latents ``[B, 96, h, w]`` to RGB ``[B, 3, 2h, 2w]``
93
+ in ``[-1, 1]`` (float32, on the latents' device).
94
+
95
+ The latents are padded by replication so the output keeps the latent
96
+ grid's size.
97
+ """
98
+
99
+ pad = int(self.weight.shape[-1]) // 2
100
+ with torch.autocast(device_type=latents.device.type, enabled=False):
101
+ padded = F.pad(latents.float(), (pad, pad, pad, pad), mode="replicate")
102
+ cells = F.conv2d(padded, self.weight, self.bias)
103
+ return F.pixel_shuffle(cells, _EXPANSION).clamp(-1.0, 1.0)
104
+
105
+
106
+ def preview_images(rgb: Tensor) -> list[Image.Image]:
107
+ """Convert ``[B, 3, H, W]`` RGB in ``[-1, 1]`` to PIL images."""
108
+
109
+ pixels = (
110
+ rgb.detach()
111
+ .float()
112
+ .add(1.0)
113
+ .mul(127.5)
114
+ .round()
115
+ .clamp(0.0, 255.0)
116
+ .to(torch.uint8)
117
+ .permute(0, 2, 3, 1)
118
+ .cpu()
119
+ .numpy()
120
+ )
121
+ return [Image.fromarray(image, mode="RGB") for image in pixels]
122
+
123
+
124
+ def _check_metadata(path: Path) -> None:
125
+ """Require the dflow preview format in the file's metadata.
126
+
127
+ Raises:
128
+ ValueError: If the metadata is missing or describes another format.
129
+ """
130
+
131
+ with safe_open(str(path), framework="pt", device="cpu") as handle:
132
+ header = handle.metadata()
133
+ if header is None or _METADATA_KEY not in header:
134
+ raise ValueError(f"{path} has no '{_METADATA_KEY}' metadata.")
135
+ metadata: dict[str, str] = json.loads(header[_METADATA_KEY])
136
+ expected = {
137
+ "format": _FORMAT,
138
+ "latent_channels": str(_LATENT_CHANNELS),
139
+ "rgb_channels": str(_RGB_CHANNELS),
140
+ "spatial_expansion_factor": str(_EXPANSION),
141
+ }
142
+ wrong = {
143
+ key: (metadata.get(key), value)
144
+ for key, value in expected.items()
145
+ if metadata.get(key) != value
146
+ }
147
+ if wrong:
148
+ raise ValueError(f"{path}: incompatible preview metadata {wrong}.")
dflow/prompt_emphasis.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Prompt emphasis: ``(phrase:weight)`` markup applied through attention.
2
+
3
+ Markup (the grammar of the ComfyUI ``MOSSImagePromptWeight`` node):
4
+
5
+ - the prompt is NFC-normalized first;
6
+ - a balanced ``(...)`` group whose text after its last colon is a number
7
+ (``2``, ``.5``, ``-1``) weights the phrase before that colon; the phrase may
8
+ hold colons, and groups nest (an inner weight overrides its outer group);
9
+ - any other group, and an unmatched parenthesis, stays literal text;
10
+ - ``\(`` and ``\)`` are literal parentheses.
11
+
12
+ Weights reach the model per token: a token takes the weight of the last group
13
+ whose phrase its characters overlap; weight 1 changes nothing.
14
+
15
+ - Weight > 0: an additive bias on the token's attention key logits,
16
+ ``strength * log(w)`` (``LOG``: the token's share of attention is
17
+ multiplied by ``w``) or ``strength * 2 * (w - 1)`` (``LINEAR``).
18
+ - Weight <= 0: the token's attention value is scaled by
19
+ ``1 + strength * (w - 1)`` (0 mutes it, -1 subtracts it).
20
+
21
+ The bias and scale act in every joint attention of the weighted prompt's
22
+ forward passes and, with ``EmphasisSettings.encoder``, inside the text
23
+ encoder's self-attention too. JSON layout prompts are never parsed.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ import re
30
+ import unicodedata
31
+ from collections.abc import Sequence
32
+ from dataclasses import dataclass
33
+ from enum import StrEnum
34
+
35
+ __all__ = [
36
+ "EmphasisMapping",
37
+ "EmphasisSettings",
38
+ "ParsedPrompt",
39
+ "TokenEmphasis",
40
+ "WeightedTerm",
41
+ "parse_prompt_weights",
42
+ "token_emphasis",
43
+ "token_weights",
44
+ ]
45
+
46
+ # A group's weight: the text after its last colon, matched in full.
47
+ _WEIGHT = re.compile(r"-?\d*\.?\d+")
48
+ # One-character stand-ins for escaped parentheses (positions do not move).
49
+ _ESCAPED = {"(": "\x01", ")": "\x02"}
50
+ _UNESCAPED = {value: key for key, value in _ESCAPED.items()}
51
+ _NEUTRAL_WEIGHT = 1.0
52
+ _NEUTRAL_BIAS = 0.0
53
+ _NEUTRAL_SCALE = 1.0
54
+
55
+
56
+ class EmphasisMapping(StrEnum):
57
+ """How a positive weight becomes an attention-logit bias.
58
+
59
+ LOG: ``log(w)``; ``(x:2)`` gets exactly twice the attention mass.
60
+ LINEAR: ``2 * (w - 1)``; ``(x:2)`` gets about 7 times the mass.
61
+ """
62
+
63
+ LOG = "log"
64
+ LINEAR = "linear"
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class EmphasisSettings:
69
+ """Prompt-emphasis settings.
70
+
71
+ The defaults are the ComfyUI ``MOSSImagePromptWeight`` node's: ``LINEAR``
72
+ mapping, strength 1, encoder weighting on.
73
+
74
+ Attributes:
75
+ mapping: Positive-weight to logit-bias mapping.
76
+ strength: Multiplier on every bias and value-scale offset.
77
+ encoder: Also apply the weights inside the text encoder.
78
+
79
+ Raises:
80
+ ValueError: If ``strength`` is negative or not finite.
81
+ """
82
+
83
+ mapping: EmphasisMapping = EmphasisMapping.LINEAR
84
+ strength: float = 1.0
85
+ encoder: bool = True
86
+
87
+ def __post_init__(self) -> None:
88
+ """Validate the strength."""
89
+
90
+ if not math.isfinite(self.strength) or self.strength < 0.0:
91
+ raise ValueError(f"strength must be finite and >= 0, got {self.strength}.")
92
+
93
+ def key_bias(self, weight: float) -> float:
94
+ """Return the key-logit bias of a token with weight > 0."""
95
+
96
+ match self.mapping:
97
+ case EmphasisMapping.LOG:
98
+ return self.strength * math.log(weight)
99
+ case EmphasisMapping.LINEAR:
100
+ return self.strength * 2.0 * (weight - 1.0)
101
+ case _ as unreachable:
102
+ raise ValueError(f"Unsupported emphasis mapping: {unreachable}")
103
+
104
+ def value_scale(self, weight: float) -> float:
105
+ """Return the value multiplier of a token with weight <= 0."""
106
+
107
+ return 1.0 + self.strength * (weight - 1.0)
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class WeightedTerm:
112
+ """One weighted group of a prompt.
113
+
114
+ Attributes:
115
+ start, end: The phrase in the clean text, surrounding spaces excluded.
116
+ weight: Its weight (any real number; 1 changes nothing).
117
+ raw_start, raw_end: The whole ``(...:w)`` group in the NFC-normalized
118
+ prompt as typed (for highlighting it).
119
+ """
120
+
121
+ start: int
122
+ end: int
123
+ weight: float
124
+ raw_start: int
125
+ raw_end: int
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class ParsedPrompt:
130
+ """A prompt with its emphasis markup removed.
131
+
132
+ Attributes:
133
+ clean_text: What the text encoder reads.
134
+ terms: Weighted groups, each outer group before the groups nested in
135
+ it (a later term overrides an earlier one on shared tokens).
136
+ """
137
+
138
+ clean_text: str
139
+ terms: tuple[WeightedTerm, ...]
140
+
141
+
142
+ def parse_prompt_weights(text: str) -> ParsedPrompt:
143
+ """Parse ``(phrase:weight)`` markup (grammar in the module docstring)."""
144
+
145
+ normalized = unicodedata.normalize("NFC", text)
146
+ escaped, raw_at = _escape(normalized)
147
+ terms: list[WeightedTerm | None] = []
148
+ clean = _strip_weights(escaped, 0, len(escaped), terms=terms, base=0, raw_at=raw_at)
149
+ return ParsedPrompt(
150
+ clean_text="".join(_UNESCAPED.get(char, char) for char in clean),
151
+ terms=tuple(term for term in terms if term is not None),
152
+ )
153
+
154
+
155
+ def _escape(text: str) -> tuple[str, list[int]]:
156
+ """Replace ``\\(`` / ``\\)`` by one-character stand-ins; return the raw
157
+ index of each character (plus the end)."""
158
+
159
+ out: list[str] = []
160
+ raw_at: list[int] = []
161
+ pos = 0
162
+ while pos < len(text):
163
+ pair = text[pos : pos + 2]
164
+ if len(pair) == 2 and pair[0] == "\\" and pair[1] in _ESCAPED:
165
+ out.append(_ESCAPED[pair[1]])
166
+ raw_at.append(pos)
167
+ pos += 2
168
+ else:
169
+ out.append(text[pos])
170
+ raw_at.append(pos)
171
+ pos += 1
172
+ raw_at.append(len(text))
173
+ return "".join(out), raw_at
174
+
175
+
176
+ def _groups(text: str, lo: int, hi: int) -> list[tuple[int, int]]:
177
+ """Split ``text[lo:hi]`` into text runs and balanced ``(...)`` groups."""
178
+
179
+ out: list[tuple[int, int]] = []
180
+ depth, start = 0, lo
181
+ for pos in range(lo, hi):
182
+ if text[pos] == "(":
183
+ if depth == 0:
184
+ out.append((start, pos))
185
+ start = pos
186
+ depth += 1
187
+ elif text[pos] == ")" and depth:
188
+ depth -= 1
189
+ if depth == 0:
190
+ out.append((start, pos + 1))
191
+ start = pos + 1
192
+ if depth:
193
+ # An unmatched "(" stays text; what follows it is split again.
194
+ return [*out, (start, start + 1), *_groups(text, start + 1, hi)]
195
+ return [*out, (start, hi)]
196
+
197
+
198
+ def _strip_weights(
199
+ text: str,
200
+ lo: int,
201
+ hi: int,
202
+ *,
203
+ terms: list[WeightedTerm | None],
204
+ base: int,
205
+ raw_at: Sequence[int],
206
+ ) -> str:
207
+ """Return ``text[lo:hi]`` without weight markup, recording the terms.
208
+
209
+ ``base`` is where the returned text starts in the whole clean text.
210
+ """
211
+
212
+ out = ""
213
+ for a, b in _groups(text, lo, hi):
214
+ if b - a < 2 or text[a] != "(" or text[b - 1] != ")":
215
+ out += text[a:b]
216
+ continue
217
+ colon = text.rfind(":", a + 1, b - 1)
218
+ weight = text[colon + 1 : b - 1].strip() if colon >= 0 else ""
219
+ if (
220
+ colon < 0
221
+ or text[a + 1 : colon].strip() == ""
222
+ or _WEIGHT.fullmatch(weight) is None
223
+ ):
224
+ inner = _strip_weights(
225
+ text, a + 1, b - 1, terms=terms, base=base + len(out) + 1, raw_at=raw_at
226
+ )
227
+ out += "(" + inner + ")"
228
+ continue
229
+ index = len(terms)
230
+ terms.append(None) # the outer group first, so nested groups override it
231
+ start = base + len(out)
232
+ phrase = _strip_weights(
233
+ text, a + 1, colon, terms=terms, base=start, raw_at=raw_at
234
+ )
235
+ terms[index] = WeightedTerm(
236
+ start=start + len(phrase) - len(phrase.lstrip()),
237
+ end=start + len(phrase.rstrip()),
238
+ weight=float(weight),
239
+ raw_start=raw_at[a],
240
+ raw_end=raw_at[b - 1] + 1,
241
+ )
242
+ out += phrase
243
+ return out
244
+
245
+
246
+ def token_weights(
247
+ terms: Sequence[WeightedTerm], offsets: Sequence[tuple[int, int]]
248
+ ) -> list[float]:
249
+ """Return each token's weight: that of the last term its span overlaps.
250
+
251
+ Args:
252
+ terms: The prompt's weighted terms, outer groups first.
253
+ offsets: Per token, its ``(start, end)`` span in the clean text
254
+ (``(0, 0)`` for special tokens, which never overlap a term).
255
+ """
256
+
257
+ weights = [_NEUTRAL_WEIGHT] * len(offsets)
258
+ for term in terms:
259
+ for pos, (lo, hi) in enumerate(offsets):
260
+ if lo < term.end and hi > term.start:
261
+ weights[pos] = term.weight
262
+ return weights
263
+
264
+
265
+ @dataclass(frozen=True)
266
+ class TokenEmphasis:
267
+ """Per-token attention bias and value scale of one prompt.
268
+
269
+ Attributes:
270
+ key_bias: Additive key-logit bias per token (0: unchanged).
271
+ value_scale: Value multiplier per token (1: unchanged).
272
+ """
273
+
274
+ key_bias: tuple[float, ...]
275
+ value_scale: tuple[float, ...]
276
+
277
+ def has_key_bias(self) -> bool:
278
+ """Whether any token's key bias differs from 0."""
279
+
280
+ return any(value != _NEUTRAL_BIAS for value in self.key_bias)
281
+
282
+ def has_value_scale(self) -> bool:
283
+ """Whether any token's value scale differs from 1."""
284
+
285
+ return any(value != _NEUTRAL_SCALE for value in self.value_scale)
286
+
287
+
288
+ def token_emphasis(
289
+ parsed: ParsedPrompt,
290
+ offsets: Sequence[tuple[int, int]],
291
+ settings: EmphasisSettings,
292
+ ) -> TokenEmphasis | None:
293
+ """Map a parsed prompt's weights onto its tokens.
294
+
295
+ Args:
296
+ parsed: The parsed prompt.
297
+ offsets: Per token of ``parsed.clean_text``, its character span.
298
+ settings: The mapping and strength.
299
+
300
+ Returns:
301
+ The token bias and scale, or None when no token is weighted.
302
+ """
303
+
304
+ if not parsed.terms:
305
+ return None
306
+ weights = token_weights(parsed.terms, offsets)
307
+ if all(weight == _NEUTRAL_WEIGHT for weight in weights):
308
+ return None
309
+ return TokenEmphasis(
310
+ key_bias=tuple(
311
+ settings.key_bias(w) if w > 0.0 and w != _NEUTRAL_WEIGHT else _NEUTRAL_BIAS
312
+ for w in weights
313
+ ),
314
+ value_scale=tuple(
315
+ settings.value_scale(w) if w <= 0.0 else _NEUTRAL_SCALE for w in weights
316
+ ),
317
+ )
dflow/rope3d.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Centred three-axis rotary position embedding of the joint text-image stream.
2
+
3
+ Every token has a 3-axis position ``(a, y, x)``; each axis rotates its own
4
+ channel pairs of every attention head (``rope_axes_dims`` channels, adjacent
5
+ pairs). Text token ``i`` (1-based) of an ``L``-token prompt sits at
6
+ ``(i, 0, 0)``. Image token ``(row, col)`` of an ``H x W`` grid sits at
7
+ ``(L + 1, row - (H - 1) / 2, col - (W - 1) / 2)``: the grid is centred on the
8
+ text, so its spatial positions are half-integers on even sides. Angles are
9
+ ``position * theta^(-2k / dim)`` computed in float64 and rounded to float32
10
+ before the sine and cosine; nothing in this module passes through bfloat16.
11
+
12
+ Two evaluation paths reproduce the trained model bit for bit:
13
+
14
+ - the text refiner reads rows of a per-axis table built on the CPU with
15
+ ``torch.polar`` (``text_rope_rows``);
16
+ - the joint stream evaluates its real-valued positions directly on the
17
+ positions' device (``joint_rope_rows``).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from functools import lru_cache
23
+ from typing import TYPE_CHECKING
24
+
25
+ import torch
26
+ from torch import Tensor
27
+
28
+ if TYPE_CHECKING:
29
+ from .configuration import DFlowConfig
30
+
31
+ RopeRows = tuple[Tensor, Tensor]
32
+ """``(sin, cos)``, each ``[N, head_width]`` float32, adjacent-pair layout."""
33
+
34
+
35
+ def validate_rope_capacity(
36
+ config: DFlowConfig, *, text_length: int, grid_height: int, grid_width: int
37
+ ) -> None:
38
+ """Check a prompt length and token grid fit the RoPE capacity.
39
+
40
+ Raises:
41
+ ValueError: If the text or image axis-0 position (``L + 1``) reaches
42
+ ``rope_axes_lens[0]``, a grid side exceeds its axis capacity, or a
43
+ size is not positive.
44
+ """
45
+
46
+ axis0, axis1, axis2 = config.rope_axes_lens
47
+ if text_length <= 0 or grid_height <= 0 or grid_width <= 0:
48
+ raise ValueError(
49
+ "text length and token grid must be positive, got "
50
+ f"L={text_length}, grid={grid_height}x{grid_width}"
51
+ )
52
+ if text_length + 1 >= axis0:
53
+ raise ValueError(
54
+ f"A {text_length}-token prompt exceeds the RoPE text capacity: the "
55
+ f"image sits at axis-0 position {text_length + 1}, which must stay "
56
+ f"below {axis0}"
57
+ )
58
+ if grid_height > axis1 or grid_width > axis2:
59
+ raise ValueError(
60
+ f"Token grid {grid_height}x{grid_width} exceeds the RoPE spatial "
61
+ f"capacity {axis1}x{axis2}"
62
+ )
63
+
64
+
65
+ def _axis_frequencies(*, dim: int, theta: float, device: torch.device) -> Tensor:
66
+ """One axis's float64 rotation frequencies ``theta^(-2k / dim)``."""
67
+
68
+ exponents = torch.arange(0, dim, 2, dtype=torch.float64, device=device)
69
+ return 1.0 / (theta ** (exponents / float(dim)))
70
+
71
+
72
+ def text_position_ids(length: int, *, device: torch.device) -> Tensor:
73
+ """Int64 positions ``(1..L, 0, 0)`` ``[L, 3]`` of an ``L``-token prompt."""
74
+
75
+ axis0 = torch.arange(1, length + 1, dtype=torch.int64, device=device)
76
+ zeros = torch.zeros_like(axis0)
77
+ return torch.stack((axis0, zeros, zeros), dim=-1)
78
+
79
+
80
+ def image_position_ids(
81
+ *, text_length: int, grid_height: int, grid_width: int, device: torch.device
82
+ ) -> Tensor:
83
+ """Float64 centred positions ``[H * W, 3]`` of a row-major token grid after
84
+ an ``L``-token prompt: ``(L + 1, row - (H - 1) / 2, col - (W - 1) / 2)``."""
85
+
86
+ local = torch.arange(grid_height * grid_width, dtype=torch.int64, device=device)
87
+ row = local // grid_width
88
+ col = local - row * grid_width
89
+ ids = torch.stack((torch.full_like(local, text_length + 1), row, col), dim=-1)
90
+ centred = ids.to(torch.float64)
91
+ centred[:, 1] -= (grid_height - 1) / 2
92
+ centred[:, 2] -= (grid_width - 1) / 2
93
+ return centred
94
+
95
+
96
+ def rope_rows_at(config: DFlowConfig, positions: Tensor) -> RopeRows:
97
+ """RoPE rows of real-valued positions ``[N, 3]`` on their own device.
98
+
99
+ Angles are ``position * frequency`` in float64, then float32; sine and
100
+ cosine run in float32 and repeat over each adjacent channel pair.
101
+ """
102
+
103
+ sins: list[Tensor] = []
104
+ coses: list[Tensor] = []
105
+ for axis, dim in enumerate(config.rope_axes_dims):
106
+ freqs = _axis_frequencies(
107
+ dim=dim, theta=config.rope_theta, device=positions.device
108
+ )
109
+ angles = torch.outer(positions[:, axis].to(torch.float64), freqs).float()
110
+ sins.append(torch.sin(angles).repeat_interleave(2, dim=-1))
111
+ coses.append(torch.cos(angles).repeat_interleave(2, dim=-1))
112
+ return torch.cat(sins, dim=-1), torch.cat(coses, dim=-1)
113
+
114
+
115
+ @lru_cache(maxsize=4)
116
+ def _axis_tables(config: DFlowConfig) -> tuple[RopeRows, ...]:
117
+ """Per-axis CPU tables ``(sin, cos)`` ``[axis_len, dim]`` of integer
118
+ positions, from ``torch.polar`` of the float32-rounded float64 angles."""
119
+
120
+ cpu = torch.device("cpu")
121
+ tables: list[RopeRows] = []
122
+ for dim, length in zip(config.rope_axes_dims, config.rope_axes_lens, strict=True):
123
+ timestep = torch.arange(length, dtype=torch.float64, device=cpu)
124
+ freqs = _axis_frequencies(dim=dim, theta=config.rope_theta, device=cpu)
125
+ angles = torch.outer(timestep, freqs).float()
126
+ rotation = torch.polar(torch.ones_like(angles), angles)
127
+ tables.append(
128
+ (
129
+ rotation.imag.repeat_interleave(2, dim=-1).float(),
130
+ rotation.real.repeat_interleave(2, dim=-1).float(),
131
+ )
132
+ )
133
+ return tuple(tables)
134
+
135
+
136
+ def text_rope_rows(
137
+ config: DFlowConfig, length: int, *, device: torch.device
138
+ ) -> RopeRows:
139
+ """RoPE rows ``[L, head_width]`` of an ``L``-token prompt for the text
140
+ refiner: rows of the CPU integer-position tables, moved to ``device``."""
141
+
142
+ ids = text_position_ids(length, device=torch.device("cpu"))
143
+ sins: list[Tensor] = []
144
+ coses: list[Tensor] = []
145
+ for axis, (sin_table, cos_table) in enumerate(_axis_tables(config)):
146
+ sins.append(sin_table.index_select(0, ids[:, axis]))
147
+ coses.append(cos_table.index_select(0, ids[:, axis]))
148
+ return torch.cat(sins, dim=-1).to(device), torch.cat(coses, dim=-1).to(device)
149
+
150
+
151
+ def joint_rope_rows(
152
+ config: DFlowConfig,
153
+ *,
154
+ text_length: int,
155
+ grid_height: int,
156
+ grid_width: int,
157
+ device: torch.device,
158
+ ) -> RopeRows:
159
+ """RoPE rows ``[H * W + L, head_width]`` of the joint stream
160
+ ``[image tokens, text tokens]``, evaluated on ``device``."""
161
+
162
+ positions = torch.cat(
163
+ (
164
+ image_position_ids(
165
+ text_length=text_length,
166
+ grid_height=grid_height,
167
+ grid_width=grid_width,
168
+ device=device,
169
+ ),
170
+ text_position_ids(text_length, device=device).to(torch.float64),
171
+ ),
172
+ dim=0,
173
+ )
174
+ return rope_rows_at(config, positions)
dflow/schedules.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flow-matching timestep schedules, the log-SNR shift and the schedule CDF.
2
+
3
+ Time convention (shared with ``solvers`` and ``guidance``): the flow path is
4
+ ``x_t = (1 - t) x_0 + t noise`` with ``t = 1`` pure noise and ``t = 0`` clean.
5
+ A schedule is a strictly descending float32 tensor of ``steps + 1`` times,
6
+ noisy end first. The model predicts the velocity ``v = dx_t/dt = noise - x_0``,
7
+ so the clean estimate at time ``t`` is ``x_0 = x_t - t v``.
8
+
9
+ The log-SNR of time ``t`` is ``-2 logit(t)``. An additive log-SNR shift ``s``
10
+ moves every interior time to ``sigmoid(logit(t) - s / 2)``; a negative shift
11
+ spends more steps near the noisy end. The model was trained with
12
+ ``s = min(0, -0.25 - ln(width * height / 256^2))``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from enum import StrEnum
20
+
21
+ import numpy as np
22
+ import torch
23
+ from scipy import special, stats
24
+ from torch import Tensor
25
+
26
+ # Resolution-shift constants: base shift and reference side in pixels.
27
+ TRAINING_BASE_LOG_SNR_SHIFT = -0.25
28
+ RESOLUTION_SHIFT_REFERENCE = 256
29
+ # Shifts at or below this magnitude leave the schedule unchanged.
30
+ _SHIFT_NO_OP_TOLERANCE = 1.0e-9
31
+ # The noisy endpoint t = 1 becomes 1 - this for solvers that evaluate log-SNR.
32
+ FINITE_NOISY_ENDPOINT_EPSILON = 1.0e-4
33
+ BETA_0_6_SHAPE = 0.6
34
+ BETA_1_25_SHAPE = 1.25
35
+ DEFAULT_CUSTOM_BETA_MEAN = 0.5
36
+ DEFAULT_CUSTOM_BETA_CONCENTRATION = 0.6
37
+
38
+
39
+ class ScheduleKind(StrEnum):
40
+ """Spacing of the schedule's points before the log-SNR shift.
41
+
42
+ LINEAR: evenly spaced times.
43
+ BETA_0_6: equal-probability quantiles of Beta(0.6, 0.6) (dense at both ends).
44
+ BETA_1_25: quantiles of Beta(1.25, 1.25) (slightly dense in the middle).
45
+ CUSTOM_BETA: quantiles of Beta(mean * concentration,
46
+ (1 - mean) * concentration).
47
+ """
48
+
49
+ LINEAR = "linear"
50
+ BETA_0_6 = "beta_0_6"
51
+ BETA_1_25 = "beta_1_25"
52
+ CUSTOM_BETA = "custom_beta"
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class TimeSchedule:
57
+ """A schedule family and its step count.
58
+
59
+ Attributes:
60
+ kind: Point spacing.
61
+ steps: Solver updates; the schedule has ``steps + 1`` points.
62
+ beta_mean: Mean of the CUSTOM_BETA distribution, in (0, 1).
63
+ beta_concentration: Concentration (alpha + beta) of CUSTOM_BETA, > 0.
64
+
65
+ Raises:
66
+ TypeError: For a non-int step count.
67
+ ValueError: For a non-positive step count or invalid beta parameters.
68
+ """
69
+
70
+ kind: ScheduleKind = ScheduleKind.BETA_1_25
71
+ steps: int = 50
72
+ beta_mean: float = DEFAULT_CUSTOM_BETA_MEAN
73
+ beta_concentration: float = DEFAULT_CUSTOM_BETA_CONCENTRATION
74
+
75
+ def __post_init__(self) -> None:
76
+ """Validate the step count and the custom beta parameters."""
77
+
78
+ if isinstance(self.steps, bool) or not isinstance(self.steps, int):
79
+ raise TypeError("TimeSchedule.steps must be an int.")
80
+ if self.steps < 1:
81
+ raise ValueError(f"TimeSchedule.steps must be >= 1, got {self.steps}.")
82
+ if not (math.isfinite(self.beta_mean) and 0.0 < self.beta_mean < 1.0):
83
+ raise ValueError(
84
+ f"TimeSchedule.beta_mean must lie in (0, 1), got {self.beta_mean}."
85
+ )
86
+ if not (math.isfinite(self.beta_concentration) and self.beta_concentration > 0):
87
+ raise ValueError(
88
+ "TimeSchedule.beta_concentration must be finite and > 0, got "
89
+ f"{self.beta_concentration}."
90
+ )
91
+
92
+ @property
93
+ def beta_parameters(self) -> tuple[float, float] | None:
94
+ """Return (alpha, beta) of a beta spacing, or None for LINEAR."""
95
+
96
+ match self.kind:
97
+ case ScheduleKind.LINEAR:
98
+ return None
99
+ case ScheduleKind.BETA_0_6:
100
+ return BETA_0_6_SHAPE, BETA_0_6_SHAPE
101
+ case ScheduleKind.BETA_1_25:
102
+ return BETA_1_25_SHAPE, BETA_1_25_SHAPE
103
+ case ScheduleKind.CUSTOM_BETA:
104
+ return (
105
+ self.beta_mean * self.beta_concentration,
106
+ (1.0 - self.beta_mean) * self.beta_concentration,
107
+ )
108
+ case _ as unreachable:
109
+ raise ValueError(f"Unsupported schedule kind: {unreachable}")
110
+
111
+
112
+ def resolution_log_snr_shift(
113
+ width: int,
114
+ height: int,
115
+ *,
116
+ base: float = TRAINING_BASE_LOG_SNR_SHIFT,
117
+ reference: int = RESOLUTION_SHIFT_REFERENCE,
118
+ ) -> float:
119
+ """Return ``min(0, base - ln(width * height / reference^2))``.
120
+
121
+ This is the timestep shift the model was trained with at a given image
122
+ size (-2.99 at 832 x 1216 with the defaults).
123
+
124
+ Args:
125
+ width: Image width in pixels.
126
+ height: Image height in pixels.
127
+ base: Size-independent part of the shift.
128
+ reference: Side in pixels of the square whose area has no size term.
129
+
130
+ Raises:
131
+ ValueError: For a non-positive size or reference, or a non-finite base.
132
+ """
133
+
134
+ if width <= 0 or height <= 0 or reference <= 0:
135
+ raise ValueError(
136
+ "width, height and reference must be positive, got "
137
+ f"{width} x {height}, reference {reference}."
138
+ )
139
+ if not math.isfinite(base):
140
+ raise ValueError(f"base must be finite, got {base}.")
141
+ resolution_term = -math.log((width * height) / float(reference * reference))
142
+ return min(0.0, float(base) + resolution_term)
143
+
144
+
145
+ def apply_log_snr_shift(timesteps: Tensor, shift: float) -> Tensor:
146
+ """Shift interior times by ``shift`` in log-SNR; keep exact 0 and 1.
147
+
148
+ Args:
149
+ timesteps: Float tensor of times in [0, 1].
150
+ shift: Additive log-SNR shift; |shift| <= 1e-9 returns the input.
151
+
152
+ Raises:
153
+ ValueError: For a non-finite shift.
154
+ """
155
+
156
+ if not math.isfinite(shift):
157
+ raise ValueError(f"log_snr_shift must be finite, got {shift}.")
158
+ if abs(shift) <= _SHIFT_NO_OP_TOLERANCE:
159
+ return timesteps
160
+ finfo = torch.finfo(timesteps.dtype)
161
+ clamped = timesteps.clamp(max(float(finfo.tiny), 1.0e-12), 1.0 - float(finfo.eps))
162
+ shifted = torch.sigmoid(torch.logit(clamped) - 0.5 * shift)
163
+ shifted = torch.where(timesteps == 0.0, torch.zeros_like(shifted), shifted)
164
+ return torch.where(timesteps == 1.0, torch.ones_like(shifted), shifted)
165
+
166
+
167
+ def _beta_quantiles(points: int, *, alpha: float, beta: float) -> Tensor:
168
+ """Return Beta(alpha, beta) quantiles of a float32 probability grid, in float32.
169
+
170
+ Raises:
171
+ RuntimeError: If SciPy returns non-finite quantiles.
172
+ """
173
+
174
+ probabilities = torch.linspace(0.0, 1.0, points, dtype=torch.float32, device="cpu")
175
+ values = np.asarray(
176
+ stats.beta.ppf(probabilities.to(torch.float64).numpy(), alpha, beta),
177
+ dtype=np.float32,
178
+ )
179
+ if not bool(np.isfinite(values).all()):
180
+ raise RuntimeError(f"Beta({alpha}, {beta}) quantiles are not finite.")
181
+ return torch.from_numpy(values)
182
+
183
+
184
+ def _ascending_base(schedule: TimeSchedule) -> Tensor:
185
+ """Return the unshifted ascending float32 CPU grid of ``steps + 1`` points."""
186
+
187
+ points = schedule.steps + 1
188
+ parameters = schedule.beta_parameters
189
+ if parameters is None:
190
+ return torch.linspace(0.0, 1.0, points, dtype=torch.float32, device="cpu")
191
+ alpha, beta = parameters
192
+ return _beta_quantiles(points, alpha=alpha, beta=beta)
193
+
194
+
195
+ def _cap_noisy_endpoint(descending: Tensor) -> Tensor:
196
+ """Replace an exact ``t = 1`` first point by ``1 - 1e-4`` (or the next float
197
+ above its neighbour when that neighbour is already closer to 1).
198
+
199
+ Raises:
200
+ ValueError: If no float32 lies strictly between the neighbour and 1.
201
+ """
202
+
203
+ if float(descending[0]) != 1.0:
204
+ return descending
205
+ one = torch.ones((), dtype=descending.dtype, device=descending.device)
206
+ candidate = torch.tensor(
207
+ 1.0 - FINITE_NOISY_ENDPOINT_EPSILON,
208
+ dtype=descending.dtype,
209
+ device=descending.device,
210
+ )
211
+ neighbour = descending[1]
212
+ if float(neighbour) >= float(candidate):
213
+ candidate = torch.nextafter(neighbour, one)
214
+ if float(candidate) >= 1.0:
215
+ raise ValueError(
216
+ "No finite noisy endpoint fits between the second schedule point "
217
+ "and t = 1; lower the step count or the log-SNR shift magnitude."
218
+ )
219
+ capped = descending.clone()
220
+ capped[0] = candidate
221
+ return capped
222
+
223
+
224
+ def build_timesteps(
225
+ schedule: TimeSchedule,
226
+ *,
227
+ log_snr_shift: float,
228
+ finite_noisy_endpoint: bool,
229
+ device: torch.device,
230
+ ) -> Tensor:
231
+ """Build the descending float32 schedule the solver integrates over.
232
+
233
+ Order of operations (as the training code): unshifted ascending grid,
234
+ moved to ``device``, log-SNR shift there, flip to descending, then, when
235
+ ``finite_noisy_endpoint``, replace the exact ``t = 1`` start by
236
+ ``1 - 1e-4``. Log-SNR solvers
237
+ (``solvers.solver_requires_finite_noisy_endpoint``) need that finite start.
238
+ The shift runs on ``device`` because CPU and CUDA ``logit``/``sigmoid`` can
239
+ differ in the last bit.
240
+
241
+ Args:
242
+ schedule: Spacing and step count.
243
+ log_snr_shift: Effective shift (e.g. ``resolution_log_snr_shift``).
244
+ finite_noisy_endpoint: Whether to cap the noisy endpoint below 1.
245
+ device: Device of the returned tensor.
246
+
247
+ Returns:
248
+ Float32 tensor ``[steps + 1]``, strictly descending, ending at 0.
249
+
250
+ Raises:
251
+ ValueError: For a non-finite shift or an impossible endpoint cap.
252
+ """
253
+
254
+ base = _ascending_base(schedule).to(device=device)
255
+ descending = torch.flip(apply_log_snr_shift(base, log_snr_shift), dims=(0,))
256
+ if finite_noisy_endpoint:
257
+ descending = _cap_noisy_endpoint(descending)
258
+ return descending.contiguous()
259
+
260
+
261
+ @dataclass(frozen=True)
262
+ class ScheduleCdf:
263
+ """CDF of a shifted schedule's time distribution: 1 at the noisy end, 0 clean.
264
+
265
+ Step ``i`` of an ``N``-step standard schedule sits at quantile ``1 - i / N``
266
+ before the endpoint cap; the guidance ramp is defined in this coordinate.
267
+ Evaluated on the host from Python floats (no device work).
268
+ """
269
+
270
+ schedule: TimeSchedule
271
+ log_snr_shift: float
272
+
273
+ def quantile_at_time(self, time: float) -> float:
274
+ """Return the CDF value of the unshifted distribution at a solver time."""
275
+
276
+ if time <= 0.0:
277
+ return 0.0
278
+ if time >= 1.0:
279
+ return 1.0
280
+ logit = math.log(time) - math.log1p(-time)
281
+ base_time = float(special.expit(logit + 0.5 * self.log_snr_shift))
282
+ parameters = self.schedule.beta_parameters
283
+ if parameters is None:
284
+ return base_time
285
+ alpha, beta = parameters
286
+ return float(special.betainc(alpha, beta, base_time))
dflow/solvers.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Float32 solvers for the linear flow-matching path.
2
+
3
+ Conventions (see ``schedules``): ``x_t = (1 - t) x_0 + t noise``, times run
4
+ from the noisy end (``t`` near 1) to ``t = 0``, and the velocity callable
5
+ returns ``v = noise - x_0`` at ``(x_t, t)``, so ``x_0 = x_t - t v`` and an Euler
6
+ step is ``x + (t_next - t) v``. The solver state is float32.
7
+
8
+ Every solver calls ``velocity(state, time, step_index)`` where ``time`` is a
9
+ float32 ``[B]`` tensor holding ``timesteps[step_index]``: each evaluation sits
10
+ exactly on a schedule point, and ``step_index`` is that point's index
11
+ (``0 .. steps``; ABM2 also evaluates the last point). Guidance uses the index to
12
+ look up its per-step plan.
13
+
14
+ The schedule is read to the host once before the loop; the per-step code has
15
+ no host synchronisation.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import itertools
21
+ import math
22
+ from dataclasses import dataclass
23
+ from enum import StrEnum
24
+ from typing import Protocol
25
+
26
+ import numpy as np
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import Tensor
30
+
31
+ from .brownian_noise import BrownianIntervalNormal, standard_normal
32
+
33
+ DEFAULT_SDE_NOISE_SCALE = 1.0
34
+ DEFAULT_DPMPP_2M_SDE_ETA = 0.5
35
+ # Floor of t in Euler-Maruyama's velocity-to-score conversion.
36
+ _SCORE_TIME_FLOOR = 1.0e-4
37
+ _ER_MAX_STAGE = 3
38
+ _ER_QUADRATURE_POINTS = 16
39
+ _ER_NOISE_EXPONENT = 0.3
40
+ _ER_NOISE_OFFSET = 10.0
41
+
42
+
43
+ class Solver(StrEnum):
44
+ """Numerical solvers.
45
+
46
+ EULER: first-order ODE.
47
+ EULER_MARUYAMA: first-order reverse SDE (noise scale 1 is the SDE's own).
48
+ ER_SDE: third-stage extended reverse-time SDE with independent normals.
49
+ ER_SDE_BT: ER_SDE with Brownian-tree noise (schedule-consistent paths).
50
+ DPMPP_2M: second-order multistep ODE in half-log-SNR.
51
+ DPMPP_2M_SDE: DPM++ 2M SDE midpoint method (noise scale is eta).
52
+ ABM2: Adams-Bashforth-Moulton predictor-corrector (two evaluations a step).
53
+ """
54
+
55
+ EULER = "euler"
56
+ EULER_MARUYAMA = "euler_maruyama"
57
+ ER_SDE = "er_sde"
58
+ ER_SDE_BT = "er_sde_bt"
59
+ DPMPP_2M = "dpmpp_2m"
60
+ DPMPP_2M_SDE = "dpmpp_2m_sde"
61
+ ABM2 = "abm2"
62
+
63
+
64
+ def default_noise_scale(solver: Solver) -> float:
65
+ """Return the recommended noise scale (eta for DPM++ 2M SDE) of a solver."""
66
+
67
+ match solver:
68
+ case Solver.DPMPP_2M_SDE:
69
+ return DEFAULT_DPMPP_2M_SDE_ETA
70
+ case (
71
+ Solver.EULER
72
+ | Solver.EULER_MARUYAMA
73
+ | Solver.ER_SDE
74
+ | Solver.ER_SDE_BT
75
+ | Solver.DPMPP_2M
76
+ | Solver.ABM2
77
+ ):
78
+ return DEFAULT_SDE_NOISE_SCALE
79
+ case _ as unreachable:
80
+ raise ValueError(f"Unsupported solver: {unreachable}")
81
+
82
+
83
+ def solver_is_stochastic(solver: Solver) -> bool:
84
+ """Return whether a solver injects noise (and needs a generator)."""
85
+
86
+ match solver:
87
+ case (
88
+ Solver.EULER_MARUYAMA
89
+ | Solver.ER_SDE
90
+ | Solver.ER_SDE_BT
91
+ | Solver.DPMPP_2M_SDE
92
+ ):
93
+ return True
94
+ case Solver.EULER | Solver.DPMPP_2M | Solver.ABM2:
95
+ return False
96
+ case _ as unreachable:
97
+ raise ValueError(f"Unsupported solver: {unreachable}")
98
+
99
+
100
+ def solver_requires_finite_noisy_endpoint(solver: Solver) -> bool:
101
+ """Return whether a solver evaluates log-SNR at the first point (needs t < 1)."""
102
+
103
+ match solver:
104
+ case Solver.ER_SDE | Solver.ER_SDE_BT | Solver.DPMPP_2M | Solver.DPMPP_2M_SDE:
105
+ return True
106
+ case Solver.EULER | Solver.EULER_MARUYAMA | Solver.ABM2:
107
+ return False
108
+ case _ as unreachable:
109
+ raise ValueError(f"Unsupported solver: {unreachable}")
110
+
111
+
112
+ class VelocityFunction(Protocol):
113
+ """The velocity at one schedule point."""
114
+
115
+ def __call__(self, state: Tensor, time: Tensor, step_index: int, /) -> Tensor:
116
+ """Return ``v`` like ``state`` for float32 times ``[B]`` at ``step_index``."""
117
+
118
+ ...
119
+
120
+
121
+ class SolverCallback(Protocol):
122
+ """Observer of each completed solver update."""
123
+
124
+ def __call__(self, predicted_x0: Tensor, completed: int, total: int, /) -> None:
125
+ """Receive the latest clean estimate after ``completed`` of ``total``."""
126
+
127
+ ...
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class _Run:
132
+ """Validated per-solve inputs shared by every solver loop."""
133
+
134
+ velocity: VelocityFunction
135
+ times: Tensor
136
+ host_times: tuple[float, ...]
137
+ callback: SolverCallback | None
138
+
139
+ @property
140
+ def intervals(self) -> int:
141
+ """Number of solver updates."""
142
+
143
+ return len(self.host_times) - 1
144
+
145
+ def time_batch(self, index: int, batch: int) -> Tensor:
146
+ """Return ``times[index]`` as a float32 ``[batch]`` vector."""
147
+
148
+ return self.times[index].expand(batch)
149
+
150
+ def evaluate(self, state: Tensor, index: int) -> Tensor:
151
+ """Evaluate the velocity at schedule point ``index``, cast like ``state``."""
152
+
153
+ time = self.time_batch(index, int(state.shape[0]))
154
+ return self.velocity(state, time, index).to(dtype=state.dtype)
155
+
156
+ def report(self, state: Tensor, velocity: Tensor, index: int, done: int) -> None:
157
+ """Send ``state - t_index v`` to the callback when one is set."""
158
+
159
+ if self.callback is not None:
160
+ self.callback(state - self.times[index] * velocity, done, self.intervals)
161
+
162
+
163
+ def _validate(state: Tensor, timesteps: Tensor) -> tuple[float, ...]:
164
+ """Check state and schedule invariants once; return the host times.
165
+
166
+ Raises:
167
+ ValueError: For a non-float32 or non-4D state, or a schedule that is not
168
+ a strictly descending finite float32 vector in [0, 1] of length >= 2.
169
+ """
170
+
171
+ if state.dim() != 4 or state.dtype != torch.float32:
172
+ raise ValueError(
173
+ f"The solver state must be float32 [B, C, H, W]; got {state.dtype} "
174
+ f"with shape {tuple(state.shape)}."
175
+ )
176
+ if timesteps.dim() != 1 or timesteps.dtype != torch.float32:
177
+ raise ValueError("timesteps must be a float32 vector.")
178
+ if timesteps.device != state.device:
179
+ raise ValueError(
180
+ f"timesteps are on {timesteps.device} but the state is on {state.device}."
181
+ )
182
+ host = tuple(float(value) for value in timesteps.cpu().tolist())
183
+ if len(host) < 2 or not all(math.isfinite(value) for value in host):
184
+ raise ValueError("timesteps need at least two finite points.")
185
+ if any(value < 0.0 or value > 1.0 for value in host):
186
+ raise ValueError("timesteps must lie in [0, 1].")
187
+ if any(a <= b for a, b in itertools.pairwise(host)):
188
+ raise ValueError("timesteps must be strictly descending.")
189
+ return host
190
+
191
+
192
+ def _require_finite_log_snr(host_times: tuple[float, ...], solver: Solver) -> None:
193
+ """Require evaluation times in (0, 1) for a log-SNR solver.
194
+
195
+ Raises:
196
+ ValueError: If a model-evaluation time is 0 or 1.
197
+ """
198
+
199
+ if any(value <= 0.0 or value >= 1.0 for value in host_times[:-1]):
200
+ raise ValueError(
201
+ f"{solver.value} evaluates log-SNR: every point but the last must lie "
202
+ "in (0, 1). Build the schedule with finite_noisy_endpoint=True."
203
+ )
204
+
205
+
206
+ def _euler(run: _Run, state: Tensor) -> Tensor:
207
+ """First-order Euler; the step is the float32 difference of the points."""
208
+
209
+ deltas = (run.times[1:] - run.times[:-1]).cpu().tolist()
210
+ for index in range(run.intervals):
211
+ velocity = run.evaluate(state, index)
212
+ run.report(state, velocity, index, index + 1)
213
+ state = state + float(deltas[index]) * velocity
214
+ return state
215
+
216
+
217
+ def _euler_maruyama(
218
+ run: _Run, state: Tensor, *, noise_scale: float, generator: torch.Generator
219
+ ) -> Tensor:
220
+ """Reverse-SDE Euler-Maruyama: drift ``v - t score``, diffusion ``2 t``.
221
+
222
+ The score is ``-((1 - t) v + x) / max(t, 1e-4)``. A final step to t = 0
223
+ returns ``x - t v``.
224
+ """
225
+
226
+ deltas = (run.times[1:] - run.times[:-1]).cpu().tolist()
227
+ batch = int(state.shape[0])
228
+ for index in range(run.intervals):
229
+ t0 = run.host_times[index]
230
+ dt = float(deltas[index])
231
+ time = torch.full((batch,), t0, device=state.device, dtype=torch.float32)
232
+ velocity = run.velocity(state, time, index).to(dtype=state.dtype)
233
+ run.report(state, velocity, index, index + 1)
234
+ if index == run.intervals - 1 and run.host_times[index + 1] == 0.0:
235
+ state = state - t0 * velocity
236
+ continue
237
+ noise = standard_normal(
238
+ tuple(state.shape), generator=generator, device=state.device
239
+ )
240
+ time_view = time.view(batch, 1, 1, 1)
241
+ safe_time = time_view.clamp(min=_SCORE_TIME_FLOOR)
242
+ score = -(((1.0 - safe_time) * velocity) + state) / safe_time
243
+ drift = velocity - time_view * score
244
+ scale = noise_scale * math.sqrt(2.0 * t0) * math.sqrt(abs(dt))
245
+ state = state + dt * drift + scale * noise
246
+ return state
247
+
248
+
249
+ def _half_log_snr_float64(times: Tensor) -> Tensor:
250
+ """Return ``log((1 - t) / t)`` in float64 (t clamped above 0)."""
251
+
252
+ times64 = times.clamp(min=torch.finfo(times.dtype).tiny).to(dtype=torch.float64)
253
+ return torch.log1p(-times64) - torch.log(times64)
254
+
255
+
256
+ def _require_increasing(lambdas: Tensor, host_times: tuple[float, ...]) -> None:
257
+ """Require half-log-SNR to rise over every step that does not end at 0.
258
+
259
+ Raises:
260
+ ValueError: Otherwise.
261
+ """
262
+
263
+ values = lambdas.cpu().tolist()
264
+ for index, (current, following) in enumerate(itertools.pairwise(values)):
265
+ if host_times[index + 1] != 0.0 and following - current <= 0.0:
266
+ raise ValueError("The schedule must raise half-log-SNR over every step.")
267
+
268
+
269
+ def _dpmpp_2m_update(
270
+ state: Tensor,
271
+ denoised: Tensor,
272
+ previous: tuple[Tensor, Tensor] | None,
273
+ current_lambda: Tensor,
274
+ next_lambda: Tensor,
275
+ ) -> Tensor:
276
+ """One DPM++ 2M update; ``previous`` is (denoised, lambda) of the last step."""
277
+
278
+ step = next_lambda - current_lambda
279
+ if previous is None:
280
+ extrapolated = denoised
281
+ else:
282
+ previous_denoised, previous_lambda = previous
283
+ ratio = (current_lambda - previous_lambda) / step
284
+ extrapolated = (1.0 + 1.0 / (2.0 * ratio)) * denoised - (
285
+ 1.0 / (2.0 * ratio)
286
+ ) * previous_denoised
287
+ log_sigma_ratio = F.logsigmoid(-next_lambda) - F.logsigmoid(-current_lambda)
288
+ sigma_ratio = torch.exp(log_sigma_ratio).to(dtype=state.dtype)
289
+ alpha_next = torch.sigmoid(next_lambda).to(dtype=state.dtype)
290
+ coefficient = (alpha_next * (-torch.expm1(-step))).to(dtype=state.dtype)
291
+ return sigma_ratio * state + coefficient * extrapolated
292
+
293
+
294
+ def _dpmpp_2m(run: _Run, state: Tensor) -> Tensor:
295
+ """DPM++ 2M in half-log-SNR; a final step to t = 0 returns ``x - t v``."""
296
+
297
+ lambdas = _half_log_snr_float64(run.times)
298
+ _require_increasing(lambdas, run.host_times)
299
+ previous: tuple[Tensor, Tensor] | None = None
300
+ for index in range(run.intervals):
301
+ velocity = run.evaluate(state, index)
302
+ denoised = state - run.times[index] * velocity
303
+ run.report(state, velocity, index, index + 1)
304
+ if run.host_times[index + 1] == 0.0:
305
+ state = denoised
306
+ else:
307
+ state = _dpmpp_2m_update(
308
+ state, denoised, previous, lambdas[index], lambdas[index + 1]
309
+ )
310
+ previous = (denoised, lambdas[index])
311
+ return state
312
+
313
+
314
+ @dataclass(frozen=True)
315
+ class _SdeStep:
316
+ """One DPM++ 2M SDE interval: times, half-log-SNR step and eta."""
317
+
318
+ current_time: Tensor
319
+ next_time: Tensor
320
+ step: Tensor
321
+ eta: float
322
+
323
+
324
+ def _dpmpp_2m_sde_update(
325
+ state: Tensor,
326
+ denoised: Tensor,
327
+ previous: tuple[Tensor, Tensor] | None,
328
+ interval: _SdeStep,
329
+ generator: torch.Generator,
330
+ ) -> Tensor:
331
+ """One DPM++ 2M SDE midpoint update; ``previous`` is (denoised, step)."""
332
+
333
+ eta = interval.eta
334
+ stochastic_step = interval.step * (1.0 + eta)
335
+ sigma_ratio = (interval.next_time / interval.current_time) * torch.exp(
336
+ -interval.step * eta
337
+ )
338
+ coefficient = (1.0 - interval.next_time) * (-torch.expm1(-stochastic_step))
339
+ result = sigma_ratio.to(state.dtype) * state
340
+ result = result + coefficient.to(state.dtype) * denoised
341
+ if previous is not None:
342
+ previous_denoised, previous_step = previous
343
+ ratio = previous_step / interval.step
344
+ result = result + (
345
+ 0.5
346
+ * coefficient.to(state.dtype)
347
+ / ratio.to(state.dtype)
348
+ * (denoised - previous_denoised)
349
+ )
350
+ if eta == 0.0:
351
+ return result
352
+ normal = standard_normal(
353
+ tuple(state.shape), generator=generator, device=state.device
354
+ )
355
+ noise_scale = interval.next_time * torch.sqrt(
356
+ -torch.expm1(-2.0 * interval.step * eta)
357
+ )
358
+ return result + noise_scale.to(state.dtype) * normal
359
+
360
+
361
+ def _dpmpp_2m_sde(
362
+ run: _Run, state: Tensor, *, eta: float, generator: torch.Generator
363
+ ) -> Tensor:
364
+ """DPM++ 2M SDE (eta 0 is the deterministic midpoint method)."""
365
+
366
+ lambdas = _half_log_snr_float64(run.times)
367
+ _require_increasing(lambdas, run.host_times)
368
+ previous_denoised: Tensor | None = None
369
+ previous_step: Tensor | None = None
370
+ for index in range(run.intervals):
371
+ velocity = run.evaluate(state, index)
372
+ denoised = state - run.times[index] * velocity
373
+ run.report(state, velocity, index, index + 1)
374
+ if run.host_times[index + 1] == 0.0:
375
+ state = denoised
376
+ else:
377
+ step = lambdas[index + 1] - lambdas[index]
378
+ previous = (
379
+ None
380
+ if previous_denoised is None or previous_step is None
381
+ else (previous_denoised, previous_step)
382
+ )
383
+ interval = _SdeStep(run.times[index], run.times[index + 1], step, eta)
384
+ state = _dpmpp_2m_sde_update(state, denoised, previous, interval, generator)
385
+ previous_step = step
386
+ previous_denoised = denoised
387
+ return state
388
+
389
+
390
+ def _er_noise_scaler(er_lambda: Tensor) -> Tensor:
391
+ """ER-SDE noise-scaling function ``l (exp(l^0.3) + 10)``."""
392
+
393
+ return er_lambda * (torch.exp(er_lambda.pow(_ER_NOISE_EXPONENT)) + _ER_NOISE_OFFSET)
394
+
395
+
396
+ def _er_stochastic_time(er_lambda: Tensor) -> Tensor:
397
+ """ER Brownian clock ``1 / (exp(l^0.3) + 10)^2``."""
398
+
399
+ denominator = torch.exp(er_lambda.pow(_ER_NOISE_EXPONENT)) + _ER_NOISE_OFFSET
400
+ return denominator.square().reciprocal()
401
+
402
+
403
+ @dataclass(frozen=True)
404
+ class _ErSdeContext:
405
+ """Per-solve ER-SDE constants: lambdas, quadrature rule and noise source."""
406
+
407
+ times: Tensor
408
+ er_lambdas: Tensor
409
+ nodes: Tensor
410
+ weights: Tensor
411
+ noise_scale: float
412
+ generator: torch.Generator
413
+ tree: BrownianIntervalNormal | None
414
+ # Host Brownian-clock time per point (read once; BT only).
415
+ clock: tuple[float, ...]
416
+
417
+
418
+ def _er_context(
419
+ run: _Run,
420
+ state: Tensor,
421
+ *,
422
+ noise_scale: float,
423
+ generator: torch.Generator,
424
+ brownian: bool,
425
+ ) -> _ErSdeContext:
426
+ """Prepare ER-SDE constants (and the Brownian tree) before the loop."""
427
+
428
+ times = run.times
429
+ half_log_snr = torch.log1p(-times) - torch.log(times)
430
+ er_lambdas = torch.exp(-half_log_snr)
431
+ nodes_np, weights_np = np.polynomial.legendre.leggauss(_ER_QUADRATURE_POINTS)
432
+ nodes = torch.as_tensor(nodes_np, device=times.device, dtype=torch.float32)
433
+ weights = torch.as_tensor(weights_np, device=times.device, dtype=torch.float32)
434
+ tree: BrownianIntervalNormal | None = None
435
+ clock: tuple[float, ...] = ()
436
+ if brownian and noise_scale > 0.0:
437
+ tree = BrownianIntervalNormal(
438
+ state=state,
439
+ start=0.0,
440
+ end=1.0 / (1.0 + _ER_NOISE_OFFSET) ** 2,
441
+ generator=generator,
442
+ )
443
+ clock = tuple(
444
+ float(_er_stochastic_time(er_lambdas[index]).item())
445
+ for index in range(len(run.host_times))
446
+ )
447
+ return _ErSdeContext(
448
+ times, er_lambdas, nodes, weights, noise_scale, generator, tree, clock
449
+ )
450
+
451
+
452
+ def _er_quadrature(
453
+ context: _ErSdeContext, lambda_s: Tensor, lambda_t: Tensor
454
+ ) -> tuple[Tensor, Tensor]:
455
+ """Gauss-Legendre ER-SDE correction integrals over one interval."""
456
+
457
+ midpoint = (lambda_s + lambda_t) / 2.0
458
+ half_span = (lambda_s - lambda_t) / 2.0
459
+ positions = midpoint + half_span * context.nodes
460
+ scaled = _er_noise_scaler(positions)
461
+ second = half_span * torch.sum(context.weights / scaled)
462
+ third = half_span * torch.sum(context.weights * (positions - lambda_s) / scaled)
463
+ return second, third
464
+
465
+
466
+ @dataclass(frozen=True)
467
+ class _ErHistory:
468
+ """Clean estimate and its first divided difference from the last step."""
469
+
470
+ denoised: Tensor
471
+ derivative: Tensor | None
472
+
473
+
474
+ def _er_sde_step(
475
+ context: _ErSdeContext,
476
+ state: Tensor,
477
+ denoised: Tensor,
478
+ history: _ErHistory | None,
479
+ index: int,
480
+ ) -> tuple[Tensor, Tensor | None]:
481
+ """One non-terminal ER-SDE update; returns the state and the derivative."""
482
+
483
+ lambdas = context.er_lambdas
484
+ lambda_s, lambda_t = lambdas[index], lambdas[index + 1]
485
+ alpha_s = context.times[index] / lambda_s
486
+ alpha_t = context.times[index + 1] / lambda_t
487
+ noise_t = _er_noise_scaler(lambda_t)
488
+ ratio = noise_t / _er_noise_scaler(lambda_s)
489
+ next_state = (alpha_t / alpha_s) * ratio * state
490
+ next_state = next_state + alpha_t * (1.0 - ratio) * denoised
491
+ derivative: Tensor | None = None
492
+ stage = min(_ER_MAX_STAGE, index + 1)
493
+ if stage >= 2 and history is not None:
494
+ second, third = _er_quadrature(context, lambda_s, lambda_t)
495
+ delta = lambda_t - lambda_s
496
+ derivative = (denoised - history.denoised) / (lambda_s - lambdas[index - 1])
497
+ next_state = next_state + alpha_t * (delta + second * noise_t) * derivative
498
+ if stage >= 3 and history.derivative is not None:
499
+ span = (lambda_s - lambdas[index - 2]) / 2.0
500
+ second_derivative = (derivative - history.derivative) / span
501
+ next_state = (
502
+ next_state
503
+ + alpha_t * (delta.square() / 2.0 + third * noise_t) * second_derivative
504
+ )
505
+ if context.noise_scale > 0.0:
506
+ if context.tree is None:
507
+ noise = standard_normal(
508
+ tuple(state.shape), generator=context.generator, device=state.device
509
+ )
510
+ else:
511
+ noise = context.tree.sample(
512
+ state=state,
513
+ start=context.clock[index],
514
+ end=context.clock[index + 1],
515
+ )
516
+ variance = lambda_t.square() - lambda_s.square() * ratio.square()
517
+ stochastic = alpha_t * torch.sqrt(torch.clamp(variance, min=0.0))
518
+ next_state = next_state + context.noise_scale * stochastic * noise
519
+ return next_state.to(dtype=state.dtype), derivative
520
+
521
+
522
+ def _er_sde(run: _Run, state: Tensor, context: _ErSdeContext) -> Tensor:
523
+ """Third-stage VP ER-SDE; a final step to t = 0 returns ``x - t v``."""
524
+
525
+ history: _ErHistory | None = None
526
+ for index in range(run.intervals):
527
+ velocity = run.evaluate(state, index)
528
+ denoised = state - run.times[index] * velocity
529
+ run.report(state, velocity, index, index + 1)
530
+ derivative: Tensor | None = None
531
+ if run.host_times[index + 1] == 0.0:
532
+ state = denoised
533
+ else:
534
+ state, derivative = _er_sde_step(context, state, denoised, history, index)
535
+ history = _ErHistory(denoised, derivative)
536
+ return state
537
+
538
+
539
+ def _abm2(run: _Run, state: Tensor) -> Tensor:
540
+ """ABM2: Euler bootstrap, then AB2 predictor and trapezoidal corrector,
541
+ re-evaluating the velocity at the corrected state."""
542
+
543
+ times = run.times
544
+ previous_velocity = run.evaluate(state, 0)
545
+ state = state + (times[1] - times[0]) * previous_velocity
546
+ current_velocity = run.evaluate(state, 1)
547
+ run.report(state, current_velocity, 1, 1)
548
+ for index in range(1, run.intervals):
549
+ previous_step = times[index] - times[index - 1]
550
+ current_step = times[index + 1] - times[index]
551
+ ratio = current_step / previous_step
552
+ predicted = state + current_step * (
553
+ (1.0 + 0.5 * ratio) * current_velocity + (-0.5 * ratio) * previous_velocity
554
+ )
555
+ predicted_velocity = run.evaluate(predicted, index + 1)
556
+ state = state + 0.5 * current_step * (current_velocity + predicted_velocity)
557
+ previous_velocity = current_velocity
558
+ current_velocity = run.evaluate(state, index + 1)
559
+ run.report(state, current_velocity, index + 1, index + 1)
560
+ return state
561
+
562
+
563
+ def _validate_noise(solver: Solver, noise_scale: float, generator: object) -> None:
564
+ """Check the noise scale, and that stochastic solvers have a generator.
565
+
566
+ Raises:
567
+ ValueError: For a negative or non-finite scale, or a missing generator.
568
+ """
569
+
570
+ if not math.isfinite(noise_scale) or noise_scale < 0.0:
571
+ raise ValueError(f"noise_scale must be finite and >= 0, got {noise_scale}.")
572
+ if solver_is_stochastic(solver) and generator is None:
573
+ raise ValueError(f"{solver.value} injects noise: pass a torch.Generator.")
574
+
575
+
576
+ def solve(
577
+ velocity: VelocityFunction,
578
+ initial_state: Tensor,
579
+ timesteps: Tensor,
580
+ *,
581
+ solver: Solver,
582
+ noise_scale: float,
583
+ generator: torch.Generator | None,
584
+ callback: SolverCallback | None = None,
585
+ ) -> Tensor:
586
+ """Integrate from ``timesteps[0]`` to ``timesteps[-1]``.
587
+
588
+ Args:
589
+ velocity: ``(state, time [B], step_index) -> v``; see the module docstring.
590
+ initial_state: Float32 ``[B, C, H, W]`` state at ``timesteps[0]``.
591
+ timesteps: Descending float32 schedule on the state's device
592
+ (``schedules.build_timesteps``; log-SNR solvers need a first point
593
+ below 1).
594
+ solver: Numerical method.
595
+ noise_scale: SDE noise multiplier (eta for DPM++ 2M SDE); deterministic
596
+ solvers ignore it.
597
+ generator: Source of the injected noise (a CPU generator gives the same
598
+ noise on every GPU); required by stochastic solvers.
599
+ callback: Receives ``x_t - t v`` of each evaluated point after each update.
600
+
601
+ Returns:
602
+ The float32 state at ``timesteps[-1]``.
603
+
604
+ Raises:
605
+ ValueError: For an invalid state, schedule, noise scale or generator.
606
+ """
607
+
608
+ host_times = _validate(initial_state, timesteps)
609
+ _validate_noise(solver, noise_scale, generator)
610
+ if solver_requires_finite_noisy_endpoint(solver):
611
+ _require_finite_log_snr(host_times, solver)
612
+ run = _Run(velocity, timesteps, host_times, callback)
613
+ match solver, generator:
614
+ case Solver.EULER, _:
615
+ return _euler(run, initial_state)
616
+ case Solver.EULER_MARUYAMA, torch.Generator() as noise:
617
+ return _euler_maruyama(
618
+ run, initial_state, noise_scale=noise_scale, generator=noise
619
+ )
620
+ case (
621
+ Solver.ER_SDE | Solver.ER_SDE_BT
622
+ ) as er_solver, torch.Generator() as noise:
623
+ context = _er_context(
624
+ run,
625
+ initial_state,
626
+ noise_scale=noise_scale,
627
+ generator=noise,
628
+ brownian=er_solver is Solver.ER_SDE_BT,
629
+ )
630
+ return _er_sde(run, initial_state, context)
631
+ case Solver.DPMPP_2M, _:
632
+ return _dpmpp_2m(run, initial_state)
633
+ case Solver.DPMPP_2M_SDE, torch.Generator() as noise:
634
+ return _dpmpp_2m_sde(run, initial_state, eta=noise_scale, generator=noise)
635
+ case Solver.ABM2, _:
636
+ return _abm2(run, initial_state)
637
+ case _ as unreachable:
638
+ raise ValueError(f"Unsupported solver call: {unreachable}")
dflow/text_conditioning.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompts to ``TextConditioning``: tokenize, encode, standardize, project.
2
+
3
+ For a prompt the model receives ``L + 3`` tokens of width 2304:
4
+
5
+ 1. the T5Gemma2 hidden states after layers 2, 6 and 12 (``text_encoder``),
6
+ each standardized per channel with fixed statistics (FP32);
7
+ 2. three linear maps 640 -> 2304, one per tap, summed in FP32;
8
+ 3. three learned suffix tokens appended.
9
+
10
+ A blank prompt (empty or whitespace only) is the learned unconditional
11
+ sequence: the unconditional token followed by the same three suffix tokens.
12
+ This is the null text used for CFG and for an empty negative prompt.
13
+
14
+ Batching rule: the denoiser runs each batch as one dense attention forward
15
+ without padding, so every prompt of a batch must have the same token count.
16
+ ``DFlowTextEncoder.encode`` raises on unequal counts;
17
+ ``DFlowTextEncoder.encode_grouped`` splits a list into equal-length groups.
18
+ A prompt repeated over a batch always qualifies.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from collections.abc import Callable, Sequence
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import Tensor, nn
30
+
31
+ from .layout import is_compiled_layout, is_stored_layout
32
+ from .prompt_emphasis import (
33
+ EmphasisSettings,
34
+ TokenEmphasis,
35
+ parse_prompt_weights,
36
+ token_emphasis,
37
+ )
38
+ from .text_encoder import (
39
+ COMPUTE_DTYPE,
40
+ ENCODER_CONFIG,
41
+ EncoderTaps,
42
+ EncoderWeighting,
43
+ T5Gemma2Encoder,
44
+ )
45
+ from .tokenization import PromptTokenizer
46
+ from .types import SUFFIX_TOKEN_COUNT, TextConditioning
47
+
48
+ __all__ = [
49
+ "SUFFIX_TOKEN_COUNT",
50
+ "TEXT_ADAPTER_KEY_MAP",
51
+ "TEXT_ADAPTER_REQUIRED_FLAGS",
52
+ "TEXT_WIDTH",
53
+ "DFlowTextEncoder",
54
+ "TextAdapter",
55
+ "TextConditioningGroup",
56
+ ]
57
+
58
+ TEXT_WIDTH = 2304
59
+ _TAP_COUNT = 3
60
+
61
+ # Training checkpoint key -> key relative to ``TextAdapter`` (the public file adds
62
+ # the prefix ``text_adapter.``).
63
+ TEXT_ADAPTER_KEY_MAP: dict[str, str] = {
64
+ "conditioning._encoder._proj_lo.weight": "proj_lo.weight",
65
+ "conditioning._encoder._proj_mid.weight": "proj_mid.weight",
66
+ "conditioning._encoder._proj_hi.weight": "proj_hi.weight",
67
+ "conditioning._encoder._tap_statistics.mean": "tap_mean",
68
+ "conditioning._encoder._tap_statistics.std": "tap_std",
69
+ "conditioning.uncond_token": "uncond_token",
70
+ "conditioning.learned_padding_tokens": "suffix_tokens",
71
+ }
72
+ # Training checkpoint keys that are not published: each must hold this value.
73
+ TEXT_ADAPTER_REQUIRED_FLAGS: dict[str, bool] = {
74
+ "conditioning._encoder._tap_statistics.calibrated": True,
75
+ }
76
+
77
+
78
+ class TextAdapter(nn.Module):
79
+ """Tap standardization, the three projections and the learned tokens.
80
+
81
+ Projection weights are bf16 (as published); statistics and learned tokens
82
+ stay FP32 across ``.to(dtype)`` moves.
83
+ """
84
+
85
+ tap_mean: Tensor
86
+ tap_std: Tensor
87
+ uncond_token: Tensor
88
+ suffix_tokens: Tensor
89
+
90
+ def __init__(self) -> None:
91
+ super().__init__()
92
+ hidden = ENCODER_CONFIG.hidden_size
93
+ self.proj_lo = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
94
+ self.proj_mid = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
95
+ self.proj_hi = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
96
+ self.register_buffer("tap_mean", torch.zeros(_TAP_COUNT, hidden))
97
+ self.register_buffer("tap_std", torch.ones(_TAP_COUNT, hidden))
98
+ self.register_buffer("uncond_token", torch.zeros(1, TEXT_WIDTH))
99
+ self.register_buffer(
100
+ "suffix_tokens", torch.zeros(SUFFIX_TOKEN_COUNT, TEXT_WIDTH)
101
+ )
102
+
103
+ def _apply(self, fn: Callable[[Tensor], Tensor], recurse: bool = True) -> nn.Module:
104
+ """Apply device moves without rounding the FP32 tensors."""
105
+
106
+ kept = {
107
+ name: tensor.detach().float()
108
+ for name, tensor in self.named_buffers(recurse=False)
109
+ }
110
+ super()._apply(fn, recurse=recurse)
111
+ for name, tensor in self.named_buffers(recurse=False):
112
+ tensor.data = kept[name].to(device=tensor.device)
113
+ return self
114
+
115
+ def project(self, taps: EncoderTaps) -> Tensor:
116
+ """Return the summed projections ``[B, L, 2304]`` FP32 of three taps.
117
+
118
+ Each tap is standardized per channel in FP32; each projection runs
119
+ under bf16 autocast and is summed in FP32.
120
+ """
121
+
122
+ total: Tensor | None = None
123
+ projections = (self.proj_lo, self.proj_mid, self.proj_hi)
124
+ tap_values = (taps.low, taps.middle, taps.high)
125
+ device = taps.low.device
126
+ with torch.autocast(device_type=device.type, dtype=COMPUTE_DTYPE):
127
+ for slot, (projection, tap) in enumerate(
128
+ zip(projections, tap_values, strict=True)
129
+ ):
130
+ normalized = (tap.float() - self.tap_mean[slot]) / self.tap_std[slot]
131
+ projected = F.linear(normalized, projection.weight).float()
132
+ total = projected if total is None else total + projected
133
+ if total is None:
134
+ raise RuntimeError("TextAdapter has no projections.")
135
+ return total
136
+
137
+ def conditioning_tokens(self, taps: EncoderTaps) -> Tensor:
138
+ """Return ``[B, L + 3, 2304]`` FP32: projected taps, then the suffix."""
139
+
140
+ projected = self.project(taps)
141
+ suffix = self.suffix_tokens.float().expand(projected.shape[0], -1, -1)
142
+ return torch.cat((projected, suffix), dim=1)
143
+
144
+ def unconditional_tokens(self, batch: int) -> Tensor:
145
+ """Return the null text ``[batch, 4, 2304]`` FP32: unconditional token,
146
+ then the suffix."""
147
+
148
+ sequence = torch.cat((self.uncond_token, self.suffix_tokens), dim=0).float()
149
+ return sequence.unsqueeze(0).expand(batch, -1, -1).contiguous()
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class _PreparedPrompt:
154
+ """One prompt ready to encode.
155
+
156
+ Attributes:
157
+ ids: Token ids, or None for the null text.
158
+ emphasis: Per-token emphasis over ``ids``, or None.
159
+ """
160
+
161
+ ids: tuple[int, ...] | None
162
+ emphasis: TokenEmphasis | None
163
+
164
+ @property
165
+ def length(self) -> int:
166
+ """Return the conditioning token count (suffix included)."""
167
+
168
+ if self.ids is None:
169
+ return 1 + SUFFIX_TOKEN_COUNT
170
+ return len(self.ids) + SUFFIX_TOKEN_COUNT
171
+
172
+
173
+ @dataclass(frozen=True)
174
+ class TextConditioningGroup:
175
+ """Prompts of equal token count and their conditioning.
176
+
177
+ Attributes:
178
+ indices: Positions of the group's prompts in the input list.
179
+ conditioning: Their conditioning, rows in ``indices`` order.
180
+ """
181
+
182
+ indices: tuple[int, ...]
183
+ conditioning: TextConditioning
184
+
185
+
186
+ class DFlowTextEncoder(nn.Module):
187
+ """Prompts to ``TextConditioning`` with the bundled T5Gemma2 encoder.
188
+
189
+ Args:
190
+ tokenizer: The prompt tokenizer.
191
+ encoder: The 12-layer T5Gemma2 encoder.
192
+ adapter: The trained tap projections and learned tokens.
193
+ """
194
+
195
+ def __init__(
196
+ self,
197
+ *,
198
+ tokenizer: PromptTokenizer,
199
+ encoder: T5Gemma2Encoder,
200
+ adapter: TextAdapter,
201
+ ) -> None:
202
+ super().__init__()
203
+ self.tokenizer = tokenizer
204
+ self.encoder = encoder
205
+ self.adapter = adapter
206
+
207
+ @classmethod
208
+ def from_directory(
209
+ cls, directory: str | Path, *, adapter: TextAdapter, device: torch.device
210
+ ) -> DFlowTextEncoder:
211
+ """Load the tokenizer and encoder of a ``text_encoder/`` folder.
212
+
213
+ Args:
214
+ directory: The bundled ``text_encoder/`` folder.
215
+ adapter: The loaded ``text_adapter`` of the model weights.
216
+ device: Execution device.
217
+ """
218
+
219
+ return cls(
220
+ tokenizer=PromptTokenizer.from_directory(directory),
221
+ encoder=T5Gemma2Encoder.from_directory(directory, device=device),
222
+ adapter=adapter.to(device=device),
223
+ )
224
+
225
+ def compile_layers(self) -> None:
226
+ """Compile the encoder layers (``T5Gemma2Encoder.compile_layers``)."""
227
+
228
+ self.encoder.compile_layers()
229
+
230
+ def _prepare(
231
+ self, prompt: str, emphasis: EmphasisSettings | None
232
+ ) -> _PreparedPrompt:
233
+ """Tokenize one prompt and map its emphasis onto the tokens.
234
+
235
+ Raises:
236
+ ValueError: For a stored (uncompiled) layout.
237
+ PromptTooLongError: If the prompt is too long.
238
+ """
239
+
240
+ if not prompt.strip():
241
+ return _PreparedPrompt(ids=None, emphasis=None)
242
+ if is_compiled_layout(prompt):
243
+ if is_stored_layout(prompt):
244
+ raise ValueError(
245
+ "This is a stored layout; compile it at the image size first "
246
+ "with dflow.layout.compile_layout(layout, width, height)."
247
+ )
248
+ return _PreparedPrompt(
249
+ ids=self.tokenizer.tokenize(prompt).ids, emphasis=None
250
+ )
251
+ if emphasis is None:
252
+ return _PreparedPrompt(
253
+ ids=self.tokenizer.tokenize(prompt).ids, emphasis=None
254
+ )
255
+ parsed = parse_prompt_weights(prompt)
256
+ tokenized = self.tokenizer.tokenize(parsed.clean_text)
257
+ return _PreparedPrompt(
258
+ ids=tokenized.ids,
259
+ emphasis=token_emphasis(parsed, tokenized.offsets, emphasis),
260
+ )
261
+
262
+ def encode(
263
+ self, prompts: Sequence[str], *, emphasis: EmphasisSettings | None
264
+ ) -> TextConditioning:
265
+ """Encode prompts of equal token count as one batch.
266
+
267
+ Args:
268
+ prompts: Prompts in batch order: plain text, compiled layout JSON,
269
+ or blank for the null text.
270
+ emphasis: Settings to parse and apply ``(phrase:weight)`` markup
271
+ in plain prompts, or None to encode them verbatim.
272
+
273
+ Raises:
274
+ ValueError: If the prompts have different token counts (use
275
+ ``encode_grouped``), the list is empty or a prompt is invalid.
276
+ PromptTooLongError: If a prompt is too long.
277
+ """
278
+
279
+ if not prompts:
280
+ raise ValueError("At least one prompt is required.")
281
+ prepared = [self._prepare(prompt, emphasis) for prompt in prompts]
282
+ lengths = sorted({row.length for row in prepared})
283
+ if len(lengths) != 1:
284
+ raise ValueError(
285
+ "Prompts of one batch must have the same token count; got "
286
+ f"{[row.length for row in prepared]}. Use encode_grouped."
287
+ )
288
+ return self._encode_prepared(prepared, emphasis=emphasis)
289
+
290
+ def encode_grouped(
291
+ self, prompts: Sequence[str], *, emphasis: EmphasisSettings | None
292
+ ) -> list[TextConditioningGroup]:
293
+ """Encode prompts in groups of equal token count (first-seen order).
294
+
295
+ Raises:
296
+ ValueError: If the list is empty or a prompt is invalid.
297
+ PromptTooLongError: If a prompt is too long.
298
+ """
299
+
300
+ if not prompts:
301
+ raise ValueError("At least one prompt is required.")
302
+ prepared = [self._prepare(prompt, emphasis) for prompt in prompts]
303
+ groups: dict[int, list[int]] = {}
304
+ for index, row in enumerate(prepared):
305
+ groups.setdefault(row.length, []).append(index)
306
+ return [
307
+ TextConditioningGroup(
308
+ indices=tuple(indices),
309
+ conditioning=self._encode_prepared(
310
+ [prepared[index] for index in indices], emphasis=emphasis
311
+ ),
312
+ )
313
+ for indices in groups.values()
314
+ ]
315
+
316
+ def _device(self) -> torch.device:
317
+ """Return the adapter's device."""
318
+
319
+ return self.adapter.uncond_token.device
320
+
321
+ @torch.no_grad()
322
+ def _encode_prepared(
323
+ self, prepared: Sequence[_PreparedPrompt], *, emphasis: EmphasisSettings | None
324
+ ) -> TextConditioning:
325
+ """Encode equal-length prepared prompts."""
326
+
327
+ device = self._device()
328
+ length = prepared[0].length
329
+ tokens = torch.empty(
330
+ (len(prepared), length, TEXT_WIDTH), device=device, dtype=torch.float32
331
+ )
332
+ null_rows = [pos for pos, row in enumerate(prepared) if row.ids is None]
333
+ text_rows = [pos for pos, row in enumerate(prepared) if row.ids is not None]
334
+ if null_rows:
335
+ tokens[null_rows] = self.adapter.unconditional_tokens(len(null_rows))
336
+ if text_rows:
337
+ rows = [prepared[pos] for pos in text_rows]
338
+ tokens[text_rows] = self._encode_text(rows, emphasis=emphasis)
339
+ key_bias, value_scale = _emphasis_tensors(prepared, device=device)
340
+ return TextConditioning(
341
+ tokens=tokens, key_bias=key_bias, value_scale=value_scale
342
+ )
343
+
344
+ def _encode_text(
345
+ self, rows: Sequence[_PreparedPrompt], *, emphasis: EmphasisSettings | None
346
+ ) -> Tensor:
347
+ """Run the encoder and adapter on text rows of equal length."""
348
+
349
+ device = self._device()
350
+ ids = torch.tensor(
351
+ [row.ids for row in rows if row.ids is not None],
352
+ dtype=torch.int64,
353
+ device=device,
354
+ )
355
+ weighting = None
356
+ if emphasis is not None and emphasis.encoder:
357
+ key_bias, value_scale = _emphasis_tensors(rows, device=device, suffix=False)
358
+ if key_bias is not None or value_scale is not None:
359
+ weighting = EncoderWeighting(key_bias=key_bias, value_scale=value_scale)
360
+ return self.adapter.conditioning_tokens(self.encoder(ids, weighting=weighting))
361
+
362
+
363
+ def _emphasis_tensors(
364
+ rows: Sequence[_PreparedPrompt], *, device: torch.device, suffix: bool = True
365
+ ) -> tuple[Tensor | None, Tensor | None]:
366
+ """Return FP32 ``[B, L]`` key bias and value scale, each None if neutral.
367
+
368
+ ``suffix`` appends the neutral suffix positions (conditioning tokens);
369
+ without it the rows cover the encoder tokens only.
370
+ """
371
+
372
+ if all(row.emphasis is None for row in rows):
373
+ return None, None
374
+ extra = SUFFIX_TOKEN_COUNT if suffix else 0
375
+ biases: list[list[float]] = []
376
+ scales: list[list[float]] = []
377
+ for row in rows:
378
+ width = row.length - SUFFIX_TOKEN_COUNT + extra
379
+ match row.emphasis:
380
+ case TokenEmphasis() as weights:
381
+ biases.append([*weights.key_bias, *([0.0] * extra)])
382
+ scales.append([*weights.value_scale, *([1.0] * extra)])
383
+ case None:
384
+ biases.append([0.0] * width)
385
+ scales.append([1.0] * width)
386
+ has_bias = any(
387
+ row.emphasis is not None and row.emphasis.has_key_bias() for row in rows
388
+ )
389
+ has_scale = any(
390
+ row.emphasis is not None and row.emphasis.has_value_scale() for row in rows
391
+ )
392
+ return (
393
+ torch.tensor(biases, dtype=torch.float32, device=device) if has_bias else None,
394
+ torch.tensor(scales, dtype=torch.float32, device=device) if has_scale else None,
395
+ )
dflow/text_encoder.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dense T5Gemma2-270M text encoder, layers 1-12, with three hidden-state taps.
2
+
3
+ The bundled ``text_encoder/`` folder holds the tokenizer and the used subset
4
+ of Google's ``t5gemma-2-270m-270m`` encoder: the token embeddings and the first
5
+ 12 layers (the model reads hidden states after layers 2, 6 and 12, so later
6
+ layers never run). Each layer is a Gemma 3 block with bidirectional attention:
7
+
8
+ - embeddings scaled by ``sqrt(640)``; the end-of-image id uses its own vector;
9
+ - Gemma RMSNorm ``x * rsqrt(mean(x^2) + eps) * (1 + w)`` in FP32, four per layer
10
+ (before and after attention and the MLP);
11
+ - 4 query heads and 1 key/value head of width 256, per-head RMSNorm on queries
12
+ and keys, then RoPE; logits scaled by ``256 ** -0.5``;
13
+ - sliding layers see keys within ``-256 <= key - query <= 255`` positions
14
+ (window 512); layers 6 and 12 see every token; each kind has its own RoPE;
15
+ - GeGLU MLP (tanh GELU), width 2048.
16
+
17
+ Precision: the residual stream stays FP32 (Gemma has massive-activation
18
+ channels); matrix multiplies and attention run under CUDA bf16 autocast; the
19
+ taps are FP32.
20
+
21
+ Prompt emphasis may add a per-key logit bias and a per-token value scale in
22
+ every layer's attention; both are explicit tensor inputs.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import math
29
+ from collections.abc import Callable, Mapping
30
+ from dataclasses import dataclass
31
+ from enum import StrEnum
32
+ from pathlib import Path
33
+
34
+ import torch
35
+ import torch.nn.functional as F
36
+ from safetensors.torch import load_file
37
+ from torch import Tensor, nn
38
+
39
+ __all__ = [
40
+ "COMPUTE_DTYPE",
41
+ "ENCODER_CONFIG",
42
+ "EncoderTaps",
43
+ "EncoderWeighting",
44
+ "LayerKind",
45
+ "T5Gemma2Encoder",
46
+ "T5Gemma2EncoderConfig",
47
+ ]
48
+
49
+ # Matrix-multiply and attention dtype (autocast); the residual stream is FP32.
50
+ COMPUTE_DTYPE = torch.bfloat16
51
+ CONFIG_FILENAME = "config.json"
52
+ WEIGHTS_FILENAME = "model.safetensors"
53
+ # Stored dtype of every bundled tensor (the source checkpoint's dtype).
54
+ STORAGE_DTYPE = torch.bfloat16
55
+
56
+
57
+ class LayerKind(StrEnum):
58
+ """Attention span of one encoder layer."""
59
+
60
+ SLIDING = "sliding_attention"
61
+ FULL = "full_attention"
62
+
63
+
64
+ class RopeType(StrEnum):
65
+ """RoPE frequency schedules of the two layer kinds."""
66
+
67
+ DEFAULT = "default"
68
+ LINEAR = "linear"
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class RopeSettings:
73
+ """RoPE frequencies of one layer kind.
74
+
75
+ Attributes:
76
+ theta: Base period.
77
+ rope_type: ``DEFAULT``, or ``LINEAR`` (frequencies divided by ``factor``).
78
+ factor: Linear scaling factor (1 for ``DEFAULT``).
79
+ """
80
+
81
+ theta: float
82
+ rope_type: RopeType
83
+ factor: float
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class T5Gemma2EncoderConfig:
88
+ """Architecture of the bundled encoder subset (``text_encoder/config.json``)."""
89
+
90
+ vocab_size: int
91
+ hidden_size: int
92
+ intermediate_size: int
93
+ num_attention_heads: int
94
+ num_key_value_heads: int
95
+ head_dim: int
96
+ query_pre_attn_scalar: float
97
+ rms_norm_eps: float
98
+ sliding_window: int
99
+ layer_types: tuple[LayerKind, ...]
100
+ sliding_rope: RopeSettings
101
+ full_rope: RopeSettings
102
+ embed_scale: float
103
+ eoi_token_index: int
104
+ tap_layers: tuple[int, int, int]
105
+
106
+ @property
107
+ def num_layers(self) -> int:
108
+ """Return the number of bundled layers."""
109
+
110
+ return len(self.layer_types)
111
+
112
+ def rope(self, kind: LayerKind) -> RopeSettings:
113
+ """Return the RoPE settings of ``kind``."""
114
+
115
+ match kind:
116
+ case LayerKind.SLIDING:
117
+ return self.sliding_rope
118
+ case LayerKind.FULL:
119
+ return self.full_rope
120
+ case _ as unreachable:
121
+ raise ValueError(f"Unsupported layer kind: {unreachable}")
122
+
123
+ def to_json_dict(self) -> dict[str, object]:
124
+ """Return the JSON form written to ``text_encoder/config.json``."""
125
+
126
+ def rope(settings: RopeSettings) -> dict[str, object]:
127
+ return {
128
+ "theta": settings.theta,
129
+ "rope_type": settings.rope_type.value,
130
+ "factor": settings.factor,
131
+ }
132
+
133
+ return {
134
+ "vocab_size": self.vocab_size,
135
+ "hidden_size": self.hidden_size,
136
+ "intermediate_size": self.intermediate_size,
137
+ "num_attention_heads": self.num_attention_heads,
138
+ "num_key_value_heads": self.num_key_value_heads,
139
+ "head_dim": self.head_dim,
140
+ "query_pre_attn_scalar": self.query_pre_attn_scalar,
141
+ "rms_norm_eps": self.rms_norm_eps,
142
+ "sliding_window": self.sliding_window,
143
+ "layer_types": [kind.value for kind in self.layer_types],
144
+ "sliding_rope": rope(self.sliding_rope),
145
+ "full_rope": rope(self.full_rope),
146
+ "embed_scale": self.embed_scale,
147
+ "eoi_token_index": self.eoi_token_index,
148
+ "tap_layers": list(self.tap_layers),
149
+ }
150
+
151
+
152
+ # The used subset of google/t5gemma-2-270m-270m: embeddings and layers 1-12.
153
+ ENCODER_CONFIG = T5Gemma2EncoderConfig(
154
+ vocab_size=262_144,
155
+ hidden_size=640,
156
+ intermediate_size=2048,
157
+ num_attention_heads=4,
158
+ num_key_value_heads=1,
159
+ head_dim=256,
160
+ query_pre_attn_scalar=256.0,
161
+ rms_norm_eps=1e-6,
162
+ sliding_window=512,
163
+ layer_types=(
164
+ *(LayerKind.SLIDING,) * 5,
165
+ LayerKind.FULL,
166
+ *(LayerKind.SLIDING,) * 5,
167
+ LayerKind.FULL,
168
+ ),
169
+ sliding_rope=RopeSettings(theta=10_000.0, rope_type=RopeType.DEFAULT, factor=1.0),
170
+ full_rope=RopeSettings(theta=1_000_000.0, rope_type=RopeType.LINEAR, factor=8.0),
171
+ embed_scale=640**0.5,
172
+ eoi_token_index=256_000,
173
+ tap_layers=(2, 6, 12),
174
+ )
175
+
176
+
177
+ def _check_config_file(path: Path) -> None:
178
+ """Raise unless ``path`` holds exactly ``ENCODER_CONFIG`` (plus provenance).
179
+
180
+ Raises:
181
+ ValueError: On any architecture mismatch.
182
+ """
183
+
184
+ raw = json.loads(path.read_text(encoding="utf-8"))
185
+ if not isinstance(raw, dict):
186
+ raise ValueError(f"{path} must hold a JSON object.")
187
+ expected = ENCODER_CONFIG.to_json_dict()
188
+ mismatched = [key for key, value in expected.items() if raw.get(key) != value]
189
+ if mismatched:
190
+ raise ValueError(
191
+ f"{path} does not describe the bundled T5Gemma2 encoder subset; "
192
+ f"mismatched keys: {mismatched}."
193
+ )
194
+
195
+
196
+ def _rope_inv_freq(settings: RopeSettings, head_dim: int) -> Tensor:
197
+ """Return FP32 RoPE inverse frequencies ``[head_dim // 2]``, computed on the
198
+ CPU (as the reference) so every device sees the same values."""
199
+
200
+ exponents = torch.arange(0, head_dim, 2, dtype=torch.int64, device="cpu").to(
201
+ torch.float32
202
+ )
203
+ inv_freq = 1.0 / (settings.theta ** (exponents / float(head_dim)))
204
+ match settings.rope_type:
205
+ case RopeType.DEFAULT:
206
+ return inv_freq
207
+ case RopeType.LINEAR:
208
+ return inv_freq / settings.factor
209
+ case _ as unreachable:
210
+ raise ValueError(f"Unsupported RoPE type: {unreachable}")
211
+
212
+
213
+ def _rotate_half(values: Tensor) -> Tensor:
214
+ """Half-split rotary permutation ``[-x2, x1]``."""
215
+
216
+ half = values.shape[-1] // 2
217
+ return torch.cat((-values[..., half:], values[..., :half]), dim=-1)
218
+
219
+
220
+ class _Float32Module(nn.Module):
221
+ """A module whose listed tensors stay FP32 across ``.to(dtype)`` moves."""
222
+
223
+ _fp32_names: tuple[str, ...] = ()
224
+
225
+ def _apply(self, fn: Callable[[Tensor], Tensor], recurse: bool = True) -> nn.Module:
226
+ """Apply device moves without rounding the FP32 tensors."""
227
+
228
+ kept = {
229
+ name: tensor.detach().to(dtype=torch.float32)
230
+ for name, tensor in self._named_fp32()
231
+ }
232
+ super()._apply(fn, recurse=recurse)
233
+ for name, tensor in self._named_fp32():
234
+ tensor.data = kept[name].to(device=tensor.device)
235
+ return self
236
+
237
+ def _named_fp32(self) -> list[tuple[str, Tensor]]:
238
+ """Return the FP32 tensors by name."""
239
+
240
+ named: dict[str, Tensor] = dict(self.named_parameters(recurse=False))
241
+ named.update(dict(self.named_buffers(recurse=False)))
242
+ return [(name, named[name]) for name in self._fp32_names]
243
+
244
+
245
+ class GemmaRMSNorm(_Float32Module):
246
+ """Gemma RMSNorm with an FP32 ``(1 + w)`` affine; returns the input dtype."""
247
+
248
+ _fp32_names = ("weight",)
249
+
250
+ def __init__(self, width: int, *, eps: float) -> None:
251
+ super().__init__()
252
+ self.weight = nn.Parameter(torch.zeros(width, dtype=torch.float32))
253
+ self.eps = eps
254
+
255
+ def forward(self, values: Tensor) -> Tensor:
256
+ """Normalize in FP32 and return the input dtype."""
257
+
258
+ normed = values.to(dtype=torch.float32)
259
+ normed = normed * torch.rsqrt(
260
+ normed.pow(2).mean(dim=-1, keepdim=True) + self.eps
261
+ )
262
+ return (normed * (1.0 + self.weight)).to(dtype=values.dtype)
263
+
264
+
265
+ class ScaledEmbedding(_Float32Module):
266
+ """FP32 token embeddings scaled by ``embed_scale``, with the end-of-image
267
+ token's own vector."""
268
+
269
+ _fp32_names = ("weight", "eoi_embedding")
270
+
271
+ def __init__(self, config: T5Gemma2EncoderConfig) -> None:
272
+ super().__init__()
273
+ self.weight = nn.Parameter(
274
+ torch.zeros(config.vocab_size, config.hidden_size, dtype=torch.float32)
275
+ )
276
+ self.eoi_embedding = nn.Parameter(
277
+ torch.zeros(config.hidden_size, dtype=torch.float32)
278
+ )
279
+ self.embed_scale = config.embed_scale
280
+ self.eoi_token_index = config.eoi_token_index
281
+
282
+ def forward(self, ids: Tensor) -> Tensor:
283
+ """Embed ``[B, L]`` ids as FP32 ``[B, L, hidden]``."""
284
+
285
+ values = F.embedding(ids, self.weight) * self.embed_scale
286
+ is_eoi = (ids == self.eoi_token_index).unsqueeze(-1)
287
+ return torch.where(is_eoi, self.eoi_embedding.to(values.dtype), values)
288
+
289
+
290
+ class EncoderAttention(nn.Module):
291
+ """Bidirectional grouped-query attention of one layer."""
292
+
293
+ def __init__(self, config: T5Gemma2EncoderConfig) -> None:
294
+ super().__init__()
295
+ width, heads = config.hidden_size, config.num_attention_heads
296
+ kv_heads, head_dim = config.num_key_value_heads, config.head_dim
297
+ self.q_proj = nn.Linear(width, heads * head_dim, bias=False)
298
+ self.k_proj = nn.Linear(width, kv_heads * head_dim, bias=False)
299
+ self.v_proj = nn.Linear(width, kv_heads * head_dim, bias=False)
300
+ self.o_proj = nn.Linear(heads * head_dim, width, bias=False)
301
+ self.q_norm = GemmaRMSNorm(head_dim, eps=config.rms_norm_eps)
302
+ self.k_norm = GemmaRMSNorm(head_dim, eps=config.rms_norm_eps)
303
+ self.heads, self.kv_heads, self.head_dim = heads, kv_heads, head_dim
304
+ self.scale = config.query_pre_attn_scalar**-0.5
305
+
306
+ def forward(
307
+ self,
308
+ values: Tensor,
309
+ *,
310
+ cos: Tensor,
311
+ sin: Tensor,
312
+ attn_bias: Tensor | None,
313
+ value_scale: Tensor | None,
314
+ ) -> Tensor:
315
+ """Attend over ``[B, L, hidden]`` values.
316
+
317
+ Args:
318
+ values: Normalized layer input.
319
+ cos, sin: FP32 RoPE tables ``[L, 1, head_dim]`` of this layer kind.
320
+ attn_bias: Additive logit bias broadcastable to ``[B, 1, L, L]``
321
+ (window mask and emphasis key bias) in the compute dtype, or
322
+ None.
323
+ value_scale: Per-token value multiplier ``[B, L, 1, 1]``, or None.
324
+ """
325
+
326
+ batch, length, _ = values.shape
327
+ q = self.q_proj(values).view(batch, length, self.heads, self.head_dim)
328
+ k = self.k_proj(values).view(batch, length, self.kv_heads, self.head_dim)
329
+ v = self.v_proj(values).view(batch, length, self.kv_heads, self.head_dim)
330
+ q, k = self.q_norm(q), self.k_norm(k)
331
+ if value_scale is not None:
332
+ v = v * value_scale.to(dtype=v.dtype)
333
+ cos_q, sin_q = cos.to(dtype=q.dtype), sin.to(dtype=q.dtype)
334
+ q = q * cos_q + _rotate_half(q) * sin_q
335
+ k = k * cos_q + _rotate_half(k) * sin_q
336
+ groups = self.heads // self.kv_heads
337
+ out = F.scaled_dot_product_attention(
338
+ q.transpose(1, 2),
339
+ k.repeat_interleave(groups, dim=2).transpose(1, 2),
340
+ v.repeat_interleave(groups, dim=2).transpose(1, 2),
341
+ attn_mask=attn_bias,
342
+ scale=self.scale,
343
+ )
344
+ out = out.transpose(1, 2).reshape(batch, length, self.heads * self.head_dim)
345
+ return self.o_proj(out)
346
+
347
+
348
+ class EncoderMLP(nn.Module):
349
+ """GeGLU feed-forward block (tanh GELU)."""
350
+
351
+ def __init__(self, config: T5Gemma2EncoderConfig) -> None:
352
+ super().__init__()
353
+ width, hidden = config.hidden_size, config.intermediate_size
354
+ self.gate_proj = nn.Linear(width, hidden, bias=False)
355
+ self.up_proj = nn.Linear(width, hidden, bias=False)
356
+ self.down_proj = nn.Linear(hidden, width, bias=False)
357
+
358
+ def forward(self, values: Tensor) -> Tensor:
359
+ """Apply the gated projection."""
360
+
361
+ gate = F.gelu(self.gate_proj(values), approximate="tanh")
362
+ return self.down_proj(gate * self.up_proj(values))
363
+
364
+
365
+ class EncoderLayer(nn.Module):
366
+ """One sandwich-normed Gemma 3 encoder block."""
367
+
368
+ def __init__(self, config: T5Gemma2EncoderConfig, kind: LayerKind) -> None:
369
+ super().__init__()
370
+ eps = config.rms_norm_eps
371
+ self.pre_self_attn_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
372
+ self.self_attn = EncoderAttention(config)
373
+ self.post_self_attn_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
374
+ self.pre_feedforward_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
375
+ self.mlp = EncoderMLP(config)
376
+ self.post_feedforward_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
377
+ self.kind = kind
378
+ self._compiled: Callable[..., Tensor] | None = None
379
+
380
+ def compile_layer(self) -> None:
381
+ """Compile this layer's forward (full graph, dynamic sequence length).
382
+
383
+ Raises:
384
+ RuntimeError: If the layer is already compiled.
385
+ """
386
+
387
+ if self._compiled is not None:
388
+ raise RuntimeError("EncoderLayer is already compiled.")
389
+ self._compiled = torch.compile(self._forward_impl, fullgraph=True, dynamic=True)
390
+
391
+ def forward(
392
+ self,
393
+ values: Tensor,
394
+ *,
395
+ cos: Tensor,
396
+ sin: Tensor,
397
+ attn_bias: Tensor | None,
398
+ value_scale: Tensor | None,
399
+ ) -> Tensor:
400
+ """Apply the block to the FP32 residual stream ``[B, L, hidden]``."""
401
+
402
+ call = self._forward_impl if self._compiled is None else self._compiled
403
+ return call(
404
+ values, cos=cos, sin=sin, attn_bias=attn_bias, value_scale=value_scale
405
+ )
406
+
407
+ def _forward_impl(
408
+ self,
409
+ values: Tensor,
410
+ *,
411
+ cos: Tensor,
412
+ sin: Tensor,
413
+ attn_bias: Tensor | None,
414
+ value_scale: Tensor | None,
415
+ ) -> Tensor:
416
+ """Attention and MLP residual updates."""
417
+
418
+ attn = self.self_attn(
419
+ self.pre_self_attn_layernorm(values),
420
+ cos=cos,
421
+ sin=sin,
422
+ attn_bias=attn_bias,
423
+ value_scale=value_scale,
424
+ )
425
+ values = values + self.post_self_attn_layernorm(attn)
426
+ mlp = self.mlp(self.pre_feedforward_layernorm(values))
427
+ return values + self.post_feedforward_layernorm(mlp)
428
+
429
+
430
+ @dataclass(frozen=True)
431
+ class EncoderTaps:
432
+ """FP32 hidden states ``[B, L, 640]`` after layers 2, 6 and 12."""
433
+
434
+ low: Tensor
435
+ middle: Tensor
436
+ high: Tensor
437
+
438
+
439
+ @dataclass(frozen=True)
440
+ class EncoderWeighting:
441
+ """Prompt emphasis inside the encoder's attention.
442
+
443
+ Attributes:
444
+ key_bias: FP32 ``[B, L]`` additive logit bias on each token's key, or
445
+ None.
446
+ value_scale: FP32 ``[B, L]`` multiplier on each token's value, or None.
447
+ """
448
+
449
+ key_bias: Tensor | None
450
+ value_scale: Tensor | None
451
+
452
+
453
+ class T5Gemma2Encoder(_Float32Module):
454
+ """Embeddings and the first 12 T5Gemma2 encoder layers, returning three taps.
455
+
456
+ Args:
457
+ config: The architecture (``ENCODER_CONFIG``).
458
+ """
459
+
460
+ _fp32_names = ("sliding_inv_freq", "full_inv_freq")
461
+ sliding_inv_freq: Tensor
462
+ full_inv_freq: Tensor
463
+
464
+ def __init__(self, config: T5Gemma2EncoderConfig = ENCODER_CONFIG) -> None:
465
+ super().__init__()
466
+ self.config = config
467
+ self.embed_tokens = ScaledEmbedding(config)
468
+ self.layers = nn.ModuleList(
469
+ EncoderLayer(config, kind) for kind in config.layer_types
470
+ )
471
+ for kind, name in ((LayerKind.SLIDING, "sliding"), (LayerKind.FULL, "full")):
472
+ self.register_buffer(
473
+ f"{name}_inv_freq",
474
+ _rope_inv_freq(config.rope(kind), config.head_dim),
475
+ persistent=False,
476
+ )
477
+ self._compiled = False
478
+
479
+ @classmethod
480
+ def from_directory(
481
+ cls, directory: str | Path, *, device: torch.device
482
+ ) -> T5Gemma2Encoder:
483
+ """Load the bundled weights of a ``text_encoder/`` folder onto ``device``.
484
+
485
+ Linear weights stay in their stored bf16 (the dtype autocast feeds the
486
+ matrix multiplies); embeddings and norms are FP32 copies.
487
+
488
+ Raises:
489
+ FileNotFoundError: If the weights are missing.
490
+ ValueError: If the config or any tensor name, shape or dtype differs.
491
+ """
492
+
493
+ path = Path(directory)
494
+ _check_config_file(path / CONFIG_FILENAME)
495
+ weights_path = path / WEIGHTS_FILENAME
496
+ if not weights_path.is_file():
497
+ raise FileNotFoundError(f"No {WEIGHTS_FILENAME} in {path}.")
498
+ state = load_file(str(weights_path), device="cpu")
499
+ bad_dtypes = sorted(k for k, t in state.items() if t.dtype != STORAGE_DTYPE)
500
+ if bad_dtypes:
501
+ raise ValueError(
502
+ f"{weights_path} tensors must be {STORAGE_DTYPE}; not: {bad_dtypes}."
503
+ )
504
+ with torch.device(device):
505
+ encoder = cls(ENCODER_CONFIG)
506
+ encoder._cast_linears(STORAGE_DTYPE)
507
+ encoder.load_state_dict(state, strict=True)
508
+ return encoder.to(device=device).eval().requires_grad_(False)
509
+
510
+ def _cast_linears(self, dtype: torch.dtype) -> None:
511
+ """Store every linear weight in ``dtype``."""
512
+
513
+ for module in self.modules():
514
+ match module:
515
+ case nn.Linear():
516
+ module.weight.data = module.weight.data.to(dtype=dtype)
517
+ case _:
518
+ pass
519
+
520
+ def _layers(self) -> list[tuple[int, EncoderLayer]]:
521
+ """Return ``(1-based index, layer)`` pairs."""
522
+
523
+ out: list[tuple[int, EncoderLayer]] = []
524
+ for index, module in enumerate(self.layers, start=1):
525
+ match module:
526
+ case EncoderLayer():
527
+ out.append((index, module))
528
+ case _:
529
+ raise TypeError("T5Gemma2Encoder.layers must hold EncoderLayer.")
530
+ return out
531
+
532
+ def compile_layers(self) -> None:
533
+ """Compile every layer separately (``torch.compile``, full graph,
534
+ dynamic sequence length).
535
+
536
+ Raises:
537
+ RuntimeError: If the layers are already compiled.
538
+ """
539
+
540
+ if self._compiled:
541
+ raise RuntimeError("T5Gemma2Encoder layers are already compiled.")
542
+ for _, layer in self._layers():
543
+ layer.compile_layer()
544
+ self._compiled = True
545
+
546
+ def _rope_tables(
547
+ self, *, length: int, device: torch.device
548
+ ) -> dict[LayerKind, tuple[Tensor, Tensor]]:
549
+ """Return each layer kind's FP32 ``(cos, sin)`` ``[L, 1, head_dim]``."""
550
+
551
+ positions = torch.arange(length, device=device, dtype=torch.int64)
552
+ positions = positions.to(dtype=torch.float32).unsqueeze(1)
553
+ tables: dict[LayerKind, tuple[Tensor, Tensor]] = {}
554
+ for kind, inv_freq in (
555
+ (LayerKind.SLIDING, self.sliding_inv_freq),
556
+ (LayerKind.FULL, self.full_inv_freq),
557
+ ):
558
+ freqs = positions * inv_freq.view(1, -1)
559
+ emb = torch.cat((freqs, freqs), dim=-1)
560
+ tables[kind] = (emb.cos().unsqueeze(1), emb.sin().unsqueeze(1))
561
+ return tables
562
+
563
+ def _attention_biases(
564
+ self, *, length: int, key_bias: Tensor | None, device: torch.device
565
+ ) -> dict[LayerKind, Tensor | None]:
566
+ """Return each layer kind's additive attention bias in the compute dtype.
567
+
568
+ Sliding layers mask keys outside the window when the prompt is longer
569
+ than it; the emphasis key bias is added for both kinds.
570
+ """
571
+
572
+ key = (
573
+ None
574
+ if key_bias is None
575
+ else key_bias.to(dtype=COMPUTE_DTYPE)[:, None, None, :]
576
+ )
577
+ window = self.config.sliding_window
578
+ left, right = (window + 1) // 2 - 1, window // 2
579
+ sliding = key
580
+ if length - 1 > min(left, right):
581
+ steps = torch.arange(length, device=device)
582
+ delta = steps.view(-1, 1) - steps.view(1, -1)
583
+ outside = (delta > left) | (-delta > right)
584
+ mask = torch.zeros((length, length), device=device, dtype=COMPUTE_DTYPE)
585
+ mask = mask.masked_fill(outside, -math.inf)[None, None]
586
+ sliding = mask if key is None else mask + key
587
+ return {LayerKind.SLIDING: sliding, LayerKind.FULL: key}
588
+
589
+ def forward(
590
+ self, token_ids: Tensor, *, weighting: EncoderWeighting | None
591
+ ) -> EncoderTaps:
592
+ """Encode an unpadded ``[B, L]`` id batch on the encoder's device.
593
+
594
+ Args:
595
+ token_ids: int64 token ids, every row a full prompt (no padding).
596
+ weighting: Prompt emphasis inside attention, or None.
597
+
598
+ Returns:
599
+ The FP32 hidden states after layers 2, 6 and 12.
600
+ """
601
+
602
+ device = token_ids.device
603
+ length = int(token_ids.shape[1])
604
+ key_bias = None if weighting is None else weighting.key_bias
605
+ value_scale = (
606
+ None
607
+ if weighting is None or weighting.value_scale is None
608
+ else weighting.value_scale[:, :, None, None]
609
+ )
610
+ biases = self._attention_biases(length=length, key_bias=key_bias, device=device)
611
+ ropes = self._rope_tables(length=length, device=device)
612
+ taps: dict[int, Tensor] = {}
613
+ with torch.autocast(device_type=device.type, dtype=COMPUTE_DTYPE):
614
+ values = self.embed_tokens(token_ids)
615
+ for index, layer in self._layers():
616
+ cos, sin = ropes[layer.kind]
617
+ values = layer(
618
+ values,
619
+ cos=cos,
620
+ sin=sin,
621
+ attn_bias=biases[layer.kind],
622
+ value_scale=value_scale,
623
+ )
624
+ if index in self.config.tap_layers:
625
+ taps[index] = values
626
+ low, middle, high = (taps[index] for index in self.config.tap_layers)
627
+ return EncoderTaps(low=low, middle=middle, high=high)
dflow/tokenization.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompt tokenization for the T5Gemma2 text encoder, exactly as in training.
2
+
3
+ - The tokenizer's special-token frame (``<bos>``) wraps every prompt.
4
+ - Text the image should show is tokenized one character at a time, so its
5
+ spelling becomes token identity: in a plain prompt every straight
6
+ (``"..."``) or curly (``“...”``) double-quoted span on one line, quote marks
7
+ included; in a JSON layout prompt the string value of every ``"text"`` key
8
+ and every escaped-quote (``\\"...\\"``) span inside other string values.
9
+ - Everything else is tokenized normally.
10
+ - A prompt over ``MAX_PROMPT_TOKENS`` tokens (frame included) raises; prompts
11
+ are never truncated.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from collections.abc import Sequence
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ from transformers import AutoTokenizer, PreTrainedTokenizerBase
22
+
23
+ from .layout import is_compiled_layout
24
+
25
+ __all__ = [
26
+ "MAX_PROMPT_TOKENS",
27
+ "PromptTokenizer",
28
+ "PromptTooLongError",
29
+ "TokenizedPrompt",
30
+ "quoted_segments",
31
+ "structured_segments",
32
+ ]
33
+
34
+ # The longest prompt the model was trained on, in tokens (special tokens included).
35
+ MAX_PROMPT_TOKENS = 6144
36
+
37
+ _QUOTED_SPAN = re.compile(r"\"[^\"\n]*\"|“[^”\n]*”")
38
+ # A JSON string literal (quote marks included) and one escape sequence in it.
39
+ _JSON_STRING = re.compile(r"\"(?:[^\"\\]|\\.)*\"")
40
+ _JSON_ESCAPE = re.compile(r"\\.")
41
+ _JSON_KEY_COLON = re.compile(r"\s*:")
42
+ _JSON_ESCAPED_QUOTE = '\\"'
43
+ # The JSON key whose string value is visible text (a layout item's ``text``).
44
+ _VISIBLE_TEXT_KEY = '"text"'
45
+ # Probe text used to find the special tokens the tokenizer adds around text.
46
+ _FRAME_PROBE = "a"
47
+
48
+ type Segment = tuple[int, int, bool]
49
+ type Offset = tuple[int, int]
50
+
51
+
52
+ class PromptTooLongError(ValueError):
53
+ """A prompt has more tokens than the model was trained on."""
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class TokenizedPrompt:
58
+ """Token ids of one prompt and each token's character span in it.
59
+
60
+ Attributes:
61
+ ids: Token ids, special tokens included.
62
+ offsets: Per token, its ``(start, end)`` character span in the prompt;
63
+ ``(0, 0)`` for special tokens.
64
+ """
65
+
66
+ ids: tuple[int, ...]
67
+ offsets: tuple[Offset, ...]
68
+
69
+
70
+ def _segments_from_spans(text: str, spans: Sequence[Offset]) -> list[Segment]:
71
+ """Cover ``text`` with ``(start, end, in_span)`` segments for ordered,
72
+ non-overlapping ``spans``."""
73
+
74
+ segments: list[Segment] = []
75
+ cursor = 0
76
+ for start, end in spans:
77
+ if start > cursor:
78
+ segments.append((cursor, start, False))
79
+ segments.append((start, end, True))
80
+ cursor = end
81
+ if cursor < len(text):
82
+ segments.append((cursor, len(text), False))
83
+ return segments
84
+
85
+
86
+ def quoted_segments(text: str) -> list[Segment]:
87
+ """Split a plain prompt into ``(start, end, is_quoted)`` segments covering it.
88
+
89
+ Quoted segments are balanced straight or curly double quotes on one line,
90
+ quote marks included. Single quotes are not quotes (apostrophes).
91
+ """
92
+
93
+ return _segments_from_spans(
94
+ text, [match.span() for match in _QUOTED_SPAN.finditer(text)]
95
+ )
96
+
97
+
98
+ def _escaped_quote_spans(literal: str, *, offset: int) -> list[Offset]:
99
+ """Spans of balanced ``\\"...\\"`` pairs inside one JSON string literal,
100
+ shifted by ``offset``; an unpaired last escaped quote is ignored."""
101
+
102
+ quotes = [
103
+ match.start()
104
+ for match in _JSON_ESCAPE.finditer(literal)
105
+ if match.group(0) == _JSON_ESCAPED_QUOTE
106
+ ]
107
+ return [
108
+ (offset + quotes[pos], offset + quotes[pos + 1] + len(_JSON_ESCAPED_QUOTE))
109
+ for pos in range(0, len(quotes) - 1, 2)
110
+ ]
111
+
112
+
113
+ def structured_segments(text: str) -> list[Segment]:
114
+ """Split a JSON layout prompt into ``(start, end, is_visible_text)`` segments.
115
+
116
+ Visible text is the string value of every ``"text"`` key (quote marks
117
+ included) and each balanced ``\\"...\\"`` span inside any other string
118
+ value. String literals are lexed whole.
119
+
120
+ Raises:
121
+ ValueError: If ``text`` has a double quote outside a string literal.
122
+ """
123
+
124
+ spans: list[Offset] = []
125
+ cursor = 0
126
+ after_text_key = False
127
+ for match in _JSON_STRING.finditer(text):
128
+ start, end = match.span()
129
+ between = text[cursor:start]
130
+ if '"' in between:
131
+ raise ValueError(
132
+ f"Layout prompt has an unterminated string at {cursor}: {text[:120]!r}"
133
+ )
134
+ if _JSON_KEY_COLON.match(text, end) is not None:
135
+ after_text_key = match.group(0) == _VISIBLE_TEXT_KEY
136
+ elif after_text_key and between.strip() == ":":
137
+ spans.append((start, end))
138
+ after_text_key = False
139
+ else:
140
+ spans.extend(_escaped_quote_spans(match.group(0), offset=start))
141
+ after_text_key = False
142
+ cursor = end
143
+ if '"' in text[cursor:]:
144
+ raise ValueError(
145
+ f"Layout prompt has an unterminated string at {cursor}: {text[:120]!r}"
146
+ )
147
+ return _segments_from_spans(text, spans)
148
+
149
+
150
+ def _int_rows(raw: object, *, name: str) -> list[list[int]]:
151
+ """Return a tokenizer output field as integer rows.
152
+
153
+ Raises:
154
+ TypeError: If the field is not a list of integer lists.
155
+ """
156
+
157
+ match raw:
158
+ case list() if all(
159
+ isinstance(row, list) and all(isinstance(v, int) for v in row)
160
+ for row in raw
161
+ ):
162
+ return [[int(v) for v in row] for row in raw]
163
+ case _:
164
+ raise TypeError(f"Tokenizer {name} must be a list of integer lists.")
165
+
166
+
167
+ def _offset_rows(raw: object) -> list[list[Offset]]:
168
+ """Return tokenizer offset mappings as ``(start, end)`` rows.
169
+
170
+ Raises:
171
+ TypeError: If the field is not a list of integer-pair lists.
172
+ """
173
+
174
+ match raw:
175
+ case list():
176
+ rows: list[list[Offset]] = []
177
+ for row in raw:
178
+ match row:
179
+ case list():
180
+ pairs: list[Offset] = []
181
+ for pair in row:
182
+ match pair:
183
+ case (int() as start, int() as end):
184
+ pairs.append((start, end))
185
+ case [int() as start, int() as end]:
186
+ pairs.append((start, end))
187
+ case _:
188
+ raise TypeError(
189
+ "Tokenizer offsets must be integer pairs."
190
+ )
191
+ rows.append(pairs)
192
+ case _:
193
+ raise TypeError("Tokenizer offsets must be rows of pairs.")
194
+ return rows
195
+ case _:
196
+ raise TypeError("Tokenizer offset_mapping must be a list of rows.")
197
+
198
+
199
+ class PromptTokenizer:
200
+ """The T5Gemma2 tokenizer with the training-time prompt rules.
201
+
202
+ Args:
203
+ tokenizer: The fast T5Gemma2 tokenizer.
204
+ max_tokens: The longest allowed prompt in tokens.
205
+
206
+ Raises:
207
+ RuntimeError: If the special-token frame cannot be located.
208
+ """
209
+
210
+ def __init__(
211
+ self, tokenizer: PreTrainedTokenizerBase, *, max_tokens: int = MAX_PROMPT_TOKENS
212
+ ) -> None:
213
+ if max_tokens <= 0:
214
+ raise ValueError(f"max_tokens must be positive, got {max_tokens}.")
215
+ self.tokenizer = tokenizer
216
+ self.max_tokens = max_tokens
217
+ self.prefix_ids, self.suffix_ids = self._special_token_frame()
218
+
219
+ @classmethod
220
+ def from_directory(cls, directory: str | Path) -> PromptTokenizer:
221
+ """Load the tokenizer files of a bundled ``text_encoder/`` folder.
222
+
223
+ Raises:
224
+ FileNotFoundError: If ``tokenizer.json`` is missing.
225
+ """
226
+
227
+ path = Path(directory)
228
+ if not (path / "tokenizer.json").is_file():
229
+ raise FileNotFoundError(f"No tokenizer.json in {path}.")
230
+ # The folder's config.json is ours (no transformers version), which
231
+ # transformers would otherwise take for an old Mistral checkpoint.
232
+ loaded = AutoTokenizer.from_pretrained(
233
+ str(path), local_files_only=True, fix_mistral_regex=False
234
+ )
235
+ if not isinstance(loaded, PreTrainedTokenizerBase) or not loaded.is_fast:
236
+ raise TypeError(f"{path} does not hold a fast tokenizer.")
237
+ return cls(loaded)
238
+
239
+ def _encode(self, texts: Sequence[str], *, special: bool) -> list[list[int]]:
240
+ """Return the plain token ids of each text."""
241
+
242
+ encoded = self.tokenizer(
243
+ list(texts),
244
+ padding=False,
245
+ truncation=False,
246
+ add_special_tokens=special,
247
+ )
248
+ return _int_rows(encoded["input_ids"], name="input_ids")
249
+
250
+ def _special_token_frame(self) -> tuple[tuple[int, ...], tuple[int, ...]]:
251
+ """Return the special-token ids the tokenizer adds before and after text.
252
+
253
+ Raises:
254
+ RuntimeError: If the plain ids are not a run inside the framed ids.
255
+ """
256
+
257
+ plain = self._encode([_FRAME_PROBE], special=False)[0]
258
+ framed = self._encode([_FRAME_PROBE], special=True)[0]
259
+ width = len(plain)
260
+ for start in range(len(framed) - width + 1):
261
+ if framed[start : start + width] == plain:
262
+ return tuple(framed[:start]), tuple(framed[start + width :])
263
+ raise RuntimeError("Could not locate plain tokens inside the special frame.")
264
+
265
+ def tokenize(self, text: str) -> TokenizedPrompt:
266
+ """Tokenize one prompt (plain or a compiled JSON layout prompt).
267
+
268
+ Raises:
269
+ PromptTooLongError: If the prompt exceeds ``max_tokens``.
270
+ ValueError: If a JSON layout prompt has an unterminated string.
271
+ """
272
+
273
+ segments = (
274
+ structured_segments(text)
275
+ if is_compiled_layout(text)
276
+ else quoted_segments(text)
277
+ )
278
+ pieces: list[str] = []
279
+ starts: list[int] = []
280
+ for start, end, by_character in segments:
281
+ if by_character:
282
+ pieces.extend(text[start:end])
283
+ starts.extend(range(start, end))
284
+ else:
285
+ pieces.append(text[start:end])
286
+ starts.append(start)
287
+ ids: list[int] = list(self.prefix_ids)
288
+ offsets: list[Offset] = [(0, 0)] * len(self.prefix_ids)
289
+ if pieces:
290
+ encoded = self.tokenizer(
291
+ pieces,
292
+ padding=False,
293
+ truncation=False,
294
+ add_special_tokens=False,
295
+ return_offsets_mapping=True,
296
+ )
297
+ id_rows = _int_rows(encoded["input_ids"], name="input_ids")
298
+ offset_rows = _offset_rows(encoded["offset_mapping"])
299
+ for base, row_ids, row_offsets in zip(
300
+ starts, id_rows, offset_rows, strict=True
301
+ ):
302
+ ids.extend(row_ids)
303
+ offsets.extend((base + lo, base + hi) for lo, hi in row_offsets)
304
+ ids.extend(self.suffix_ids)
305
+ offsets.extend([(0, 0)] * len(self.suffix_ids))
306
+ if len(ids) > self.max_tokens:
307
+ raise PromptTooLongError(
308
+ f"The prompt has {len(ids)} tokens; the model takes at most "
309
+ f"{self.max_tokens}. Shorten it: {text[:120]!r}"
310
+ )
311
+ return TokenizedPrompt(ids=tuple(ids), offsets=tuple(offsets))
dflow/types.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Types shared between the text path, the denoiser and the sampler.
2
+
3
+ These are the contracts between modules: the text path produces
4
+ ``TextConditioning``; the denoiser consumes it and runs one of the
5
+ ``DFlowPath`` routings per forward.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+ from typing import TYPE_CHECKING
13
+
14
+ if TYPE_CHECKING:
15
+ from torch import Tensor
16
+
17
+
18
+ # Learned suffix tokens appended to every prompt's text tokens.
19
+ SUFFIX_TOKEN_COUNT = 3
20
+
21
+
22
+ class DFlowPath(StrEnum):
23
+ """Which trained routing of the 18 middle layers a forward runs.
24
+
25
+ FULL: every token through all 30 image layers (the main prediction).
26
+ PATH_DROP: the middle is skipped for every token (the weak pass of
27
+ path-drop guidance).
28
+ THREE_QUARTER: one image token per 2x2 group (and every text token) goes
29
+ through the middle; the rest skip it.
30
+ """
31
+
32
+ FULL = "full"
33
+ PATH_DROP = "path_drop"
34
+ THREE_QUARTER = "three_quarter"
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class TextConditioning:
39
+ """Text tokens for a prompt batch, ready for the denoiser's text refiner.
40
+
41
+ All prompts in a batch have the same token count ``L`` (the dense
42
+ attention path has no padding); batches of different lengths run as
43
+ separate forwards.
44
+
45
+ Attributes:
46
+ tokens: ``[B, L, 2304]`` float32: the summed projected encoder taps
47
+ followed by the learned suffix tokens (or the learned
48
+ unconditional token and the suffix for an empty prompt).
49
+ key_bias: ``[B, L]`` float32 additive attention-logit bias on each
50
+ text token's key (prompt emphasis with weight > 0), or None when no
51
+ token is weighted.
52
+ value_scale: ``[B, L]`` float32 multiplier on each text token's value
53
+ (prompt emphasis with weight <= 0), or None when no token is
54
+ weighted.
55
+ """
56
+
57
+ tokens: Tensor
58
+ key_bias: Tensor | None
59
+ value_scale: Tensor | None
dflow/vae.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The dinac3_96 autoencoder that maps between images and dflow latents.
2
+
3
+ dflow_2b generates whitened dinac3_96 latents: 96 channels at 1/16 of the
4
+ image resolution. The autoencoder is a separate repository; it is
5
+ downloaded at a pinned commit and its own Python package (``dinac3/`` in that
6
+ repository) is imported from the download under a private module name, so it
7
+ never clashes with an installed copy.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib.util
13
+ import sys
14
+ import threading
15
+ from pathlib import Path
16
+ from types import ModuleType
17
+ from typing import Protocol, cast
18
+
19
+ import torch
20
+ from huggingface_hub import snapshot_download
21
+ from torch import Tensor
22
+
23
+ VAE_REPOSITORY = "data-archetype/dinac3_96"
24
+ # dinac3_96 v1.0 with its final documentation commit.
25
+ VAE_REVISION = "d0ca36daa3e429a510ba465a5f7f8139c66d2f82"
26
+ LATENT_CHANNELS = 96
27
+ LATENT_STRIDE = 16
28
+ _PACKAGE_DIR = "dinac3"
29
+ _PRIVATE_MODULE = "_dflow_dinac3"
30
+ _DOWNLOAD_PATTERNS = ("config.json", "model.safetensors", f"{_PACKAGE_DIR}/*.py")
31
+ _IMPORT_LOCK = threading.Lock()
32
+
33
+
34
+ class _Dinac3Model(Protocol):
35
+ """The part of ``dinac3.Dinac3`` dflow uses."""
36
+
37
+ def encode(self, images: Tensor) -> Tensor:
38
+ """Whitened float32 latents of ``[-1, 1]`` images."""
39
+ ...
40
+
41
+ def decode(self, latents: Tensor, height: int, width: int) -> Tensor:
42
+ """Float32 RGB (unclamped, about ``[-1, 1]``) of whitened latents."""
43
+ ...
44
+
45
+
46
+ class _Dinac3Factory(Protocol):
47
+ """``dinac3.Dinac3.from_pretrained``."""
48
+
49
+ def from_pretrained(
50
+ self,
51
+ path_or_repo: str | Path,
52
+ *,
53
+ device: torch.device | str,
54
+ dtype: torch.dtype,
55
+ compile_encoder: bool,
56
+ compile_decoder: bool,
57
+ revision: str | None,
58
+ ) -> _Dinac3Model:
59
+ """Load and prepare the autoencoder."""
60
+ ...
61
+
62
+
63
+ class DFlowVae:
64
+ """Encode images to and decode them from dflow latents.
65
+
66
+ Images are ``[B, 3, H, W]`` float32 RGB in ``[-1, 1]`` with H and W
67
+ multiples of 16; latents are ``[B, 96, H/16, W/16]`` float32, whitened.
68
+ """
69
+
70
+ def __init__(self, model: _Dinac3Model, *, revision: str) -> None:
71
+ """Wrap a loaded autoencoder; ``revision`` records the commit it came from."""
72
+
73
+ self.model = model
74
+ self.revision = revision
75
+
76
+ @classmethod
77
+ def from_pretrained(
78
+ cls,
79
+ *,
80
+ device: torch.device,
81
+ compile: bool,
82
+ local_dir: Path | None = None,
83
+ revision: str = VAE_REVISION,
84
+ cache_dir: Path | None = None,
85
+ ) -> DFlowVae:
86
+ """Download (or reuse) the pinned dinac3_96 release and load it in bf16.
87
+
88
+ Args:
89
+ device: CUDA device.
90
+ compile: ``torch.compile`` the encoder and decoder (dynamic shapes).
91
+ local_dir: An existing local copy of the repository to load from
92
+ instead of the Hub (offline use).
93
+ revision: Hub commit to download; the pinned release by default.
94
+ cache_dir: Hugging Face cache directory, or None for the default.
95
+
96
+ Raises:
97
+ FileNotFoundError: If ``local_dir`` lacks the package or weights.
98
+ ValueError: On a non-CUDA device.
99
+ """
100
+
101
+ if device.type != "cuda":
102
+ raise ValueError(f"dflow inference needs a CUDA device, got {device}.")
103
+ root = (
104
+ local_dir
105
+ if local_dir is not None
106
+ else Path(
107
+ snapshot_download(
108
+ VAE_REPOSITORY,
109
+ revision=revision,
110
+ allow_patterns=list(_DOWNLOAD_PATTERNS),
111
+ cache_dir=None if cache_dir is None else str(cache_dir),
112
+ )
113
+ )
114
+ )
115
+ factory = _import_factory(root)
116
+ model = factory.from_pretrained(
117
+ root,
118
+ device=device,
119
+ dtype=torch.bfloat16,
120
+ compile_encoder=compile,
121
+ compile_decoder=compile,
122
+ revision=None,
123
+ )
124
+ return cls(model, revision=revision)
125
+
126
+ def decode(self, latents: Tensor) -> Tensor:
127
+ """Decode whitened latents to float32 RGB ``[B, 3, 16h, 16w]``, unclamped."""
128
+
129
+ height = int(latents.shape[-2]) * LATENT_STRIDE
130
+ width = int(latents.shape[-1]) * LATENT_STRIDE
131
+ return self.model.decode(latents.float(), height, width)
132
+
133
+ def encode(self, images: Tensor) -> Tensor:
134
+ """Encode ``[-1, 1]`` RGB images to whitened float32 latents.
135
+
136
+ Raises:
137
+ ValueError: If the image height or width is not a multiple of 16.
138
+ """
139
+
140
+ height, width = int(images.shape[-2]), int(images.shape[-1])
141
+ if height % LATENT_STRIDE or width % LATENT_STRIDE:
142
+ raise ValueError(
143
+ f"Image size {width}x{height} must be a multiple of {LATENT_STRIDE} "
144
+ "on both sides."
145
+ )
146
+ return self.model.encode(images.float())
147
+
148
+
149
+ def _import_factory(root: Path) -> _Dinac3Factory:
150
+ """Import ``root/dinac3`` under a private module name and return ``Dinac3``.
151
+
152
+ Raises:
153
+ FileNotFoundError: If the package or weights are missing under ``root``.
154
+ """
155
+
156
+ package_init = root / _PACKAGE_DIR / "__init__.py"
157
+ missing = [
158
+ path
159
+ for path in (package_init, root / "config.json", root / "model.safetensors")
160
+ if not path.is_file()
161
+ ]
162
+ if missing:
163
+ raise FileNotFoundError(
164
+ f"Incomplete {VAE_REPOSITORY} download at {root}: missing {missing}."
165
+ )
166
+ with _IMPORT_LOCK:
167
+ module = sys.modules.get(_PRIVATE_MODULE)
168
+ if module is None or Path(module.__file__ or "") != package_init:
169
+ module = _load_package(package_init)
170
+ return cast("_Dinac3Factory", module.Dinac3)
171
+
172
+
173
+ def _load_package(package_init: Path) -> ModuleType:
174
+ """Execute a package from its ``__init__.py`` under the private name,
175
+ replacing any earlier copy and its submodules.
176
+
177
+ Raises:
178
+ ImportError: If Python cannot build a module spec for the file, or the
179
+ package fails to import (a missing dependency). The partly
180
+ imported modules are removed first, so a retry imports afresh.
181
+ """
182
+
183
+ spec = importlib.util.spec_from_file_location(
184
+ _PRIVATE_MODULE,
185
+ package_init,
186
+ submodule_search_locations=[str(package_init.parent)],
187
+ )
188
+ if spec is None or spec.loader is None:
189
+ raise ImportError(f"Cannot import the autoencoder package at {package_init}.")
190
+ _drop_private_modules()
191
+ module = importlib.util.module_from_spec(spec)
192
+ sys.modules[_PRIVATE_MODULE] = module
193
+ try:
194
+ spec.loader.exec_module(module)
195
+ except ImportError:
196
+ _drop_private_modules()
197
+ raise
198
+ return module
199
+
200
+
201
+ def _drop_private_modules() -> None:
202
+ """Remove the private autoencoder package and its submodules from
203
+ ``sys.modules``."""
204
+
205
+ for name in [
206
+ name
207
+ for name in sys.modules
208
+ if name == _PRIVATE_MODULE or name.startswith(f"{_PRIVATE_MODULE}.")
209
+ ]:
210
+ del sys.modules[name]
dflow/version.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Package and model version."""
2
+
3
+ __version__ = "0.21.0"
4
+ MODEL_VERSION = "0.21"
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ transformers>=5.12,<6
2
+ numpy>=2,<3
3
+ pillow>=12,<13
4
+ safetensors>=0.7
5
+ scipy>=1.17,<2
6
+ timm==1.0.26
7
+ torchsde==0.2.6