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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
"""Sampling dflow latents: settings, noise and the guided solver loop.

The engine joins the pieces: prompts are encoded and refined once per call,
the guidance plan decides which forwards each schedule point runs, and the
solver integrates from noise (``t = 1``) to the image (``t = 0``).

Seeds. One integer seed fixes everything random in a call:

- the initial noise is ``torch.randn`` of the latent shape from a CPU
  generator seeded with the seed (the same noise on every GPU);
- stochastic solvers draw from a second CPU generator with the same seed;
- the three-quarter routing draws its kept tokens from a CUDA generator with
  the same seed.
"""

from __future__ import annotations

import math
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import TYPE_CHECKING

import torch
from torch import Tensor

from .configuration import EMPTY_PROMPT_ERROR, InferencePolicy
from .guidance import (
    BranchCall,
    BranchText,
    GuidanceSettings,
    build_guidance_plan,
    check_three_quarter_size,
)
from .layout import compile_layout, is_compiled_layout
from .modeling import DFlowModel, PreparedText, self_attention_gain_tensor
from .prompt_emphasis import EmphasisSettings
from .schedules import (
    TRAINING_BASE_LOG_SNR_SHIFT,
    TimeSchedule,
    build_timesteps,
    resolution_log_snr_shift,
)
from .solvers import (
    DEFAULT_SDE_NOISE_SCALE,
    Solver,
    solve,
    solver_is_stochastic,
    solver_requires_finite_noisy_endpoint,
)
from .types import DFlowPath
from .vae import LATENT_CHANNELS, LATENT_STRIDE

if TYPE_CHECKING:
    from .text_conditioning import DFlowTextEncoder

DEFAULT_WIDTH = 832
DEFAULT_HEIGHT = 1216
MAX_SEED = 2**63 - 1

LatentCallback = Callable[[Tensor, int, int], None]
"""Receives the predicted clean latents ``[B, 96, h, w]``, the number of
completed updates and the total after each solver update."""


@dataclass(frozen=True)
class SamplingSettings:
    """Solver, schedule and timestep shift.

    The log-SNR shift moves every schedule point towards the noisy end
    (negative values). By default it is the shift the model was trained with
    at the image size: ``base_log_snr_shift - ln(width * height / 256^2)``,
    capped at 0 (-2.99 at 832 x 1216).

    Attributes:
        solver: Numerical method.
        noise_scale: Noise multiplier of stochastic solvers (ignored by
            deterministic ones).
        schedule: Spacing and number of solver updates.
        base_log_snr_shift: Size-independent part of the shift.
        resolution_shift: Add the image-size term to the shift.

    Raises:
        ValueError: For a negative or non-finite noise scale or shift.
    """

    solver: Solver = Solver.ER_SDE
    noise_scale: float = DEFAULT_SDE_NOISE_SCALE
    schedule: TimeSchedule = field(default_factory=TimeSchedule)
    base_log_snr_shift: float = TRAINING_BASE_LOG_SNR_SHIFT
    resolution_shift: bool = True

    def __post_init__(self) -> None:
        """Validate the noise scale and the base shift."""

        if not math.isfinite(self.noise_scale) or self.noise_scale < 0.0:
            raise ValueError(f"noise_scale must be >= 0, got {self.noise_scale}.")
        if not math.isfinite(self.base_log_snr_shift):
            raise ValueError("base_log_snr_shift must be finite.")

    def log_snr_shift(self, width: int, height: int) -> float:
        """The effective shift at an image size."""

        if self.resolution_shift:
            return resolution_log_snr_shift(width, height, base=self.base_log_snr_shift)
        return self.base_log_snr_shift

    def timesteps(self, width: int, height: int, device: torch.device) -> Tensor:
        """The descending float32 schedule at an image size."""

        return build_timesteps(
            self.schedule,
            log_snr_shift=self.log_snr_shift(width, height),
            finite_noisy_endpoint=solver_requires_finite_noisy_endpoint(self.solver),
            device=device,
        )


@dataclass(frozen=True)
class GenerationSettings:
    """Everything except the prompt that fixes one generation.

    Attributes:
        width: Image width in pixels, a multiple of 16.
        height: Image height in pixels, a multiple of 16.
        seed: Seed of every random draw (see the module docstring).
        sampling: Solver, schedule and shift.
        guidance: Guidance and self-attention gains.
        emphasis: Prompt-emphasis settings for ``(phrase:weight)`` markup, or
            None to read prompts verbatim. Layout prompts are always verbatim.
        negative_prompt: Text of the negative branch used by CFG and the
            contrastive guidance modes; empty selects the learned null text.

    Raises:
        ValueError: For a size that is not a positive multiple of 16 or a
            seed outside ``[0, 2**63 - 1]``.
    """

    width: int = DEFAULT_WIDTH
    height: int = DEFAULT_HEIGHT
    seed: int = 0
    sampling: SamplingSettings = field(default_factory=SamplingSettings)
    guidance: GuidanceSettings = field(default_factory=GuidanceSettings)
    emphasis: EmphasisSettings | None = field(default_factory=EmphasisSettings)
    negative_prompt: str = ""

    def __post_init__(self) -> None:
        """Validate the size and seed."""

        for name, value in (("width", self.width), ("height", self.height)):
            if value <= 0 or value % LATENT_STRIDE:
                raise ValueError(
                    f"{name} must be a positive multiple of {LATENT_STRIDE}, "
                    f"got {value}."
                )
        if not 0 <= self.seed <= MAX_SEED:
            raise ValueError(f"seed must lie in [0, {MAX_SEED}], got {self.seed}.")

    @property
    def latent_shape(self) -> tuple[int, int, int]:
        """``(channels, height / 16, width / 16)`` of one latent."""

        return (
            LATENT_CHANNELS,
            self.height // LATENT_STRIDE,
            self.width // LATENT_STRIDE,
        )


@dataclass(frozen=True)
class ImageToImage:
    """Start from existing latents instead of pure noise.

    The schedule is built at its full step count and sampling starts at
    ``start_step``: the start latents are noised to that point's time with
    the seed's noise, and the remaining ``steps - start_step`` updates run.
    Guidance step windows count from the start step.

    Attributes:
        latents: ``[B or 1, 96, h, w]`` float32 whitened latents of the
            generation size.
        start_step: Index of the first schedule point, in ``[0, steps)``.
    """

    latents: Tensor
    start_step: int


def resolve_prompt(prompt: str, width: int, height: int) -> str:
    """Return the text the encoder reads for a prompt at an image size.

    A stored layout (the ``summary``/``frame``/``items`` JSON with 0-1000
    boxes) is compiled to the pixel layout the model was trained on at that
    size; an already compiled layout is returned unchanged after its panel
    box is checked against the size. Plain prompts are returned unchanged.

    Raises:
        dflow.layout.LayoutSizeMismatchError: For a layout compiled for
            another size.
        dflow.layout.LayoutError: For an invalid layout.
    """

    if is_compiled_layout(prompt):
        return compile_layout(prompt, width, height)
    return prompt


class DFlowEngine:
    """Samples latents with a loaded denoiser and text encoder.

    Args:
        model: The denoiser on a CUDA device.
        text_encoder: The prompt encoder on the same device.
        policy: The release's inference rules (``config.json`` ``"inference"``).
    """

    def __init__(
        self,
        model: DFlowModel,
        text_encoder: DFlowTextEncoder,
        *,
        policy: InferencePolicy,
    ) -> None:
        self.model = model
        self.text_encoder = text_encoder
        self.policy = policy
        self.device = next(model.parameters()).device

    def check_prompts(self, prompts: Sequence[str]) -> None:
        """Reject blank prompts unless the policy allows them.

        Raises:
            ValueError: ``EMPTY_PROMPT_ERROR`` for a blank prompt.
        """

        if not self.policy.allow_empty_prompt and any(
            not prompt.strip() for prompt in prompts
        ):
            raise ValueError(EMPTY_PROMPT_ERROR)

    def prepare_texts(
        self,
        prompts: Sequence[str],
        settings: GenerationSettings,
    ) -> dict[BranchText, PreparedText]:
        """Encode and refine the positive prompts and, when the guidance uses
        it, the negative prompt repeated over the batch.

        The negative branch never takes prompt emphasis.

        Raises:
            ValueError: If a prompt is blank while the policy forbids it, or the
                positive prompts do not share one token count.
        """

        self.check_prompts(prompts)
        positives = [
            resolve_prompt(prompt, settings.width, settings.height)
            for prompt in prompts
        ]
        texts = {
            BranchText.POSITIVE: self.model.prepare_text(
                self.text_encoder.encode(positives, emphasis=settings.emphasis)
            )
        }
        if settings.guidance.uses_negative:
            negative = resolve_prompt(
                settings.negative_prompt, settings.width, settings.height
            )
            texts[BranchText.NEGATIVE] = self.model.prepare_text(
                self.text_encoder.encode([negative] * len(prompts), emphasis=None)
            )
        return texts

    @torch.inference_mode()
    def sample(
        self,
        prompts: Sequence[str],
        settings: GenerationSettings,
        *,
        image_to_image: ImageToImage | None = None,
        callback: LatentCallback | None = None,
    ) -> Tensor:
        """Sample one latent per prompt.

        Args:
            prompts: Plain prompts, stored or compiled layouts, all with the
                same token count (repeat one prompt for several images).
            settings: Size, seed, sampling and guidance.
            image_to_image: Start latents and start step, or None to start
                from noise.
            callback: Called after each solver update with the predicted
                clean latents.

        Returns:
            Float32 whitened latents ``[B, 96, height / 16, width / 16]``.

        Raises:
            ValueError: On an empty prompt list, unequal prompt lengths, start
                latents of the wrong shape, or a size the three-quarter routing
                cannot run at.
        """

        if not prompts:
            raise ValueError("At least one prompt is required.")
        check_three_quarter_size(settings.guidance, settings.width, settings.height)
        batch = len(prompts)
        texts = self.prepare_texts(prompts, settings)
        sampling = settings.sampling
        full = sampling.timesteps(settings.width, settings.height, self.device)
        noise = self._initial_noise(batch, settings)
        match image_to_image:
            case None:
                timesteps = full
                state = noise
            case ImageToImage(latents=latents, start_step=start):
                timesteps = _slice_schedule(full, start)
                state = _noised_start(latents, noise, timesteps[0], batch)
            case _ as unreachable:
                raise ValueError(f"Unsupported image_to_image: {unreachable}")
        host_times = timesteps.tolist()
        plan = build_guidance_plan(
            settings.guidance,
            schedule=TimeSchedule(
                kind=sampling.schedule.kind,
                steps=len(host_times) - 1,
                beta_mean=sampling.schedule.beta_mean,
                beta_concentration=sampling.schedule.beta_concentration,
            ),
            log_snr_shift=sampling.log_snr_shift(settings.width, settings.height),
            timesteps=host_times,
        )
        routing = torch.Generator(device=self.device).manual_seed(settings.seed)
        gains: dict[float, Tensor] = {}

        def evaluate_at(state: Tensor, time: Tensor) -> Callable[[BranchCall], Tensor]:
            def evaluate(call: BranchCall) -> Tensor:
                path = call.branch.path
                if call.self_attention_gain not in gains:
                    gains[call.self_attention_gain] = self_attention_gain_tensor(
                        call.self_attention_gain, device=self.device
                    )
                return self.model(
                    state,
                    time,
                    texts[call.branch.text],
                    path=path,
                    self_attention_gain=gains[call.self_attention_gain],
                    suffix_caption_bias=call.suffix_caption_bias,
                    generator=routing if path is DFlowPath.THREE_QUARTER else None,
                )

            return evaluate

        def velocity(state: Tensor, time: Tensor, index: int) -> Tensor:
            return plan.guided_velocity(index, state, time, evaluate_at(state, time))

        return solve(
            velocity,
            state,
            timesteps,
            solver=sampling.solver,
            noise_scale=sampling.noise_scale,
            generator=(
                torch.Generator(device="cpu").manual_seed(settings.seed)
                if solver_is_stochastic(sampling.solver)
                else None
            ),
            callback=callback,
        )

    def _initial_noise(self, batch: int, settings: GenerationSettings) -> Tensor:
        """The seed's standard normal latents on the device, channels-last."""

        generator = torch.Generator(device="cpu").manual_seed(settings.seed)
        noise = torch.randn(
            (batch, *settings.latent_shape),
            generator=generator,
            dtype=torch.float32,
            device="cpu",
        )
        return noise.to(device=self.device).contiguous(
            memory_format=torch.channels_last
        )


def _slice_schedule(timesteps: Tensor, start_step: int) -> Tensor:
    """The schedule from ``start_step`` on.

    Raises:
        ValueError: If ``start_step`` leaves no update.
    """

    steps = int(timesteps.shape[0]) - 1
    if not 0 <= start_step < steps:
        raise ValueError(f"start_step must lie in [0, {steps}), got {start_step}.")
    return timesteps[start_step:].contiguous()


def _noised_start(latents: Tensor, noise: Tensor, time: Tensor, batch: int) -> Tensor:
    """``(1 - t) x0 + t noise`` at the first point of a sliced schedule.

    Raises:
        ValueError: If the latents do not match the noise's shape (a batch of
            one is repeated over the prompts).
    """

    if latents.ndim != 4 or tuple(latents.shape[1:]) != tuple(noise.shape[1:]):
        raise ValueError(
            f"Start latents must have shape [B, {', '.join(map(str, noise.shape[1:]))}]"
            f", got {tuple(latents.shape)}."
        )
    if int(latents.shape[0]) not in (1, batch):
        raise ValueError(
            f"Start latents hold {latents.shape[0]} images for {batch} prompts."
        )
    clean = latents.to(device=noise.device, dtype=torch.float32).expand_as(noise)
    return ((1.0 - time) * clean + time * noise).contiguous(
        memory_format=torch.channels_last
    )