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