# SPDX-License-Identifier: GPL-3.0-only # Copyright 2026 Data Archetype """The dflow guider: ``dflow``'s guidance plan and solver behind ComfyUI's GUIDER interface, driven by the stock ``SamplerCustomAdvanced`` node. Noise and seed contract (the same as ``dflow.inference``): - The initial noise is the NOISE input's tensor. Stock ``RandomNoise`` draws it with ``torch.randn`` of the latent shape from a CPU generator seeded with its seed, which is exactly the noise ``DFlowEngine.sample`` draws for that seed, so a stock graph reproduces the package bit for bit. - Stochastic solvers draw from a fresh CPU generator seeded with the NOISE node's seed; the three-quarter routing from a CUDA generator with that seed. - A schedule that starts at the noisy end (``t >= 1 - 1e-4``) starts from the noise alone, as ``DFlowEngine.sample`` does without image-to-image; the latent input is ignored there, as stock samplers ignore it at full denoise. A schedule that starts later (a sliced SIGMAS) noises the latent to its first time, ``(1 - t) latent + t noise``, as ``ImageToImage`` does. """ from __future__ import annotations from collections.abc import Callable from dataclasses import replace from typing import TYPE_CHECKING import comfy.sampler_helpers import torch from torch import Tensor from ..dflow.guidance import ( BranchCall, BranchText, GuidancePlan, GuidanceSettings, build_guidance_plan, check_three_quarter_size, ) from ..dflow.layout import LayoutSizeMismatchError, compile_layout, is_compiled_layout from ..dflow.modeling import PreparedText, self_attention_gain_tensor from ..dflow.schedules import FINITE_NOISY_ENDPOINT_EPSILON from ..dflow.solvers import solve, solver_is_stochastic from ..dflow.types import DFlowPath from ..dflow.vae import LATENT_CHANNELS, LATENT_STRIDE from .types import ( DFlowConditioning, DFlowModelHandle, DFlowSamplerSpec, ScheduleBinding, ) if TYPE_CHECKING: from .preview import DFlowModelPatcher ComfySamplerCallback = Callable[[int, Tensor, Tensor, int], None] VelocityFn = Callable[[Tensor, Tensor, int], Tensor] # First schedule times at or above this start from the noise alone. NOISE_START_TIME = float( torch.tensor(1.0 - FINITE_NOISY_ENDPOINT_EPSILON, dtype=torch.float32) ) class DFlowGuider: """Guided dflow sampling for ``SamplerCustomAdvanced``. Args: model: The loaded model. positive: The prompt conditioning. negative: The negative conditioning, or None for the learned null text (used only by CFG and the contrastive PDG modes). guidance: Validated guidance settings. model_patcher: Preview surface ComfyUI reads from the guider. Raises: ValueError: If a conditioning came from another model or the batches differ. """ def __init__( self, *, model: DFlowModelHandle, positive: DFlowConditioning, negative: DFlowConditioning | None, guidance: GuidanceSettings, model_patcher: DFlowModelPatcher, ) -> None: _require_model(model, positive, "positive") if negative is not None: _require_model(model, negative, "negative") if negative.batch != positive.batch: raise ValueError( f"The negative conditioning has batch {negative.batch}, the " f"positive {positive.batch}; set the same batch_size on both." ) self.model = model self.positive = positive self.negative = negative self.guidance = guidance self.model_patcher = model_patcher def with_guidance(self, guidance: GuidanceSettings) -> DFlowGuider: """A guider with the same model and conditioning and new settings.""" return DFlowGuider( model=self.model, positive=self.positive, negative=self.negative, guidance=guidance, model_patcher=self.model_patcher, ) def sample( self, noise: Tensor, latent_image: Tensor, sampler: object, sigmas: Tensor, *, denoise_mask: Tensor | None = None, callback: ComfySamplerCallback | None = None, disable_pbar: bool = False, seed: int | None = None, ) -> Tensor: """Sample latents (ComfyUI's ``GUIDER.sample`` signature). Args: noise: ``[B, 96, h, w]`` initial noise from the NOISE node. latent_image: ``[B, 96, h, w]`` start latents (zeros for an empty latent). sampler: The SAMPLER output of ``DFlow Time Schedule`` or a sliced schedule. sigmas: The descending schedule from the same node. denoise_mask: ComfyUI noise mask, or None. callback: ComfyUI's per-step preview and progress callback. disable_pbar: Unused (ComfyUI reports progress via ``callback``). seed: The NOISE node's seed. Returns: Float32 latents ``[B, 96, h, w]`` on the model's device. Raises: TypeError: For a sampler that is not a scheduled dflow sampler or a missing seed. ValueError: For inconsistent shapes, sizes or layout prompts. """ del disable_pbar spec, binding = _scheduled_sampler(sampler) seed_value = _require_seed(seed) self._validate_inputs(noise, latent_image, binding) device = self.model.device with torch.inference_mode(): timesteps = sigmas.to(device=device, dtype=torch.float32).contiguous() host_times = timesteps.tolist() plan = self._plan(binding, host_times) device_noise = noise.to(device=device, dtype=torch.float32) device_latent = latent_image.to(device=device, dtype=torch.float32) velocity = self._velocity(plan, seed_value, len(noise)) if denoise_mask is not None: velocity = _masked( velocity, latent=device_latent, noise=device_noise, mask=comfy.sampler_helpers.prepare_mask( denoise_mask, noise.shape, device ).to(dtype=torch.float32), ) return solve( velocity, _start_state(device_noise, device_latent, timesteps, host_times[0]), timesteps, solver=spec.solver, noise_scale=spec.noise_scale, generator=( torch.Generator(device="cpu").manual_seed(seed_value) if solver_is_stochastic(spec.solver) else None ), callback=_comfy_callback(callback), ) def _validate_inputs( self, noise: Tensor, latent_image: Tensor, binding: ScheduleBinding ) -> None: """Check shapes, batch, the schedule's size and layout prompt sizes. Raises: ValueError: On any mismatch. """ if noise.ndim != 4 or int(noise.shape[1]) != LATENT_CHANNELS: raise ValueError( f"dflow samples [batch, {LATENT_CHANNELS}, height, width] latents; " f"got noise of shape {tuple(noise.shape)}." ) if tuple(latent_image.shape) != tuple(noise.shape): raise ValueError( f"The latent {tuple(latent_image.shape)} and the noise " f"{tuple(noise.shape)} differ in shape." ) if int(noise.shape[0]) != self.positive.batch: raise ValueError( f"The latent batch is {noise.shape[0]} but the conditioning holds " f"{self.positive.batch} prompts; set the same batch_size on the " "text encode and latent nodes." ) width = int(noise.shape[3]) * LATENT_STRIDE height = int(noise.shape[2]) * LATENT_STRIDE if (binding.width, binding.height) != (width, height): raise ValueError( f"The schedule was built for {binding.width}x{binding.height} but " f"the latent is {width}x{height}; connect the sampled latent to " "the schedule node." ) check_three_quarter_size(self.guidance, width, height) self.model.engine.check_prompts(self.positive.prompts) conditionings = ( [self.positive] if self.negative is None else [ self.positive, self.negative, ] ) for conditioning in conditionings: if conditioning.layout_size not in (None, (width, height)): layout_width, layout_height = conditioning.layout_size raise LayoutSizeMismatchError( f"DFlow Layout Encode compiled the layout for " f"{layout_width}x{layout_height}; the latent is " f"{width}x{height}. Set its width and height to the latent's." ) for prompt in conditioning.prompts: if is_compiled_layout(prompt): compile_layout(prompt, width, height) def _plan(self, binding: ScheduleBinding, host_times: list[float]) -> GuidancePlan: """The guidance plan over ``host_times`` (as ``DFlowEngine.sample``).""" return build_guidance_plan( self.guidance, schedule=replace(binding.schedule, steps=len(host_times) - 1), log_snr_shift=binding.log_snr_shift, timesteps=host_times, ) def _texts(self, batch: int) -> dict[BranchText, PreparedText]: """The positive text and, when guidance needs it, the negative text (the learned null text when no negative is connected).""" texts = {BranchText.POSITIVE: self.positive.text} if self.guidance.uses_negative: texts[BranchText.NEGATIVE] = ( self.negative.text if self.negative is not None else _null_text(self.model, batch) ) return texts def _velocity(self, plan: GuidancePlan, seed: int, batch: int) -> VelocityFn: """The guided velocity function the solver integrates.""" model = self.model.engine.model device = self.model.device texts = self._texts(batch) routing = torch.Generator(device=device).manual_seed(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=device ) return 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 velocity def _require_model( model: DFlowModelHandle, conditioning: DFlowConditioning, name: str ) -> None: """Require conditioning encoded by ``model``. Raises: ValueError: Otherwise. """ if conditioning.model is not model: raise ValueError( f"The {name} conditioning was encoded by a different DFlow Loader; " "connect the text encoder and model outputs of the same loader." ) def _scheduled_sampler(sampler: object) -> tuple[DFlowSamplerSpec, ScheduleBinding]: """The dflow sampler and the schedule it is paired with. Raises: TypeError: If ``sampler`` is not a dflow sampler with a schedule. """ match sampler: case DFlowSamplerSpec(binding=None): raise TypeError( "Connect the sampler output of DFlow Time Schedule to " "SamplerCustomAdvanced, not the DFlow Sampler " "output: guidance needs the schedule the sigmas came from." ) case DFlowSamplerSpec(binding=ScheduleBinding() as binding) as spec: return spec, binding case _: raise TypeError( "The dflow guider runs dflow's own solvers; connect the sampler " f"output of DFlow Time Schedule, not {type(sampler).__name__}." ) def _require_seed(seed: int | None) -> int: """The NOISE node's seed. Raises: TypeError: If the noise source has no integer seed. """ if seed is None or isinstance(seed, bool) or not isinstance(seed, int): raise TypeError( "dflow sampling needs the integer seed of a NOISE node such as " f"RandomNoise; got {seed!r}." ) return seed def _null_text(model: DFlowModelHandle, batch: int) -> PreparedText: """The learned null text for ``batch`` rows, refined.""" engine = model.engine return engine.model.prepare_text( engine.text_encoder.encode([""] * batch, emphasis=None) ) def _start_state( noise: Tensor, latent: Tensor, timesteps: Tensor, first_time: float ) -> Tensor: """The solver's initial state (see the module docstring).""" if first_time >= NOISE_START_TIME: return noise.contiguous(memory_format=torch.channels_last) time = timesteps[0] return ((1.0 - time) * latent + time * noise).contiguous( memory_format=torch.channels_last ) def _masked( velocity: VelocityFn, *, latent: Tensor, noise: Tensor, mask: Tensor ) -> VelocityFn: """Keep the latent outside the mask. There the velocity is the one whose clean estimate is the latent at the current state, ``(x_t - latent) / t``, so the region returns to the latent even after a stochastic solver injects noise; at ``t = 0`` it is the straight-path velocity ``noise - latent``. """ straight = noise - latent def masked(state: Tensor, time: Tensor, index: int) -> Tensor: t = time.to(dtype=state.dtype).view(-1, 1, 1, 1) kept = torch.where( t > 0.0, (state - latent) / t.clamp_min(torch.finfo(state.dtype).tiny), straight, ) return mask * velocity(state, time, index) + (1.0 - mask) * kept return masked def _comfy_callback( callback: ComfySamplerCallback | None, ) -> Callable[[Tensor, int, int], None] | None: """Forward each update's clean estimate to ComfyUI's preview callback.""" if callback is None: return None def publish(predicted_x0: Tensor, completed: int, total: int) -> None: callback(completed - 1, predicted_x0, predicted_x0, total) return publish