"""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 )