"""CFG and path-drop guidance (PDG): which forwards each step runs and how their velocities combine. Every denoiser forward is a ``BranchCall``: a text branch (the prompt, or the negative prompt / learned null text), a routing path (``DFlowPath``) and the image self-attention logit gain of that forward. ``GuidanceSettings`` is validated once; ``build_guidance_plan`` resolves it against the run's schedule into one ``GuidanceStep`` per schedule point (``0 .. steps``), so the per-step code is a table lookup plus tensor arithmetic. ``GuidancePlan.guided_velocity`` takes a callable ``evaluate(call) -> velocity`` and returns the guided velocity. The main forward always uses the prompt; its gain is ``GuidanceSettings.self_attention_gain`` (0 on the CFG steps of the alternating modes). Guidance forwards use ``guidance_self_attention_gain``. PDG reference forwards also carry ``PdgGuidance.suffix_caption_bias``: an additive attention-logit bias on the prompt's keys in the suffix layers (0: none). Single-reference steps return ``v_ref + s (v_main - v_ref)`` (or its APG projection); the combined modes return ``v_main + 0.5 (s_cfg (v_main - v_cfg) + s_pdg (v_main - v_pdg))``, where the scales are extra strengths (a quantile-ramp PDG scale has 1 subtracted). A PDG scale of 1 (0 in the combined modes) skips the PDG forward. Guidance rescale pulls the guided norm toward the main norm. """ from __future__ import annotations import itertools import math from bisect import bisect_right from collections.abc import Callable, Sequence from dataclasses import dataclass, field from enum import StrEnum import numpy as np import torch from torch import Tensor from .schedules import ScheduleCdf, TimeSchedule, build_timesteps from .types import DFlowPath SELF_ATTENTION_GAIN_MIN = -0.5 SELF_ATTENTION_GAIN_MAX = 0.1 DEFAULT_SELF_ATTENTION_GAIN = -0.03 DEFAULT_PDG_SCALE = 2.5 # Release default: the PDG reference reads the prompt less in its suffix layers. DEFAULT_SUFFIX_CAPTION_BIAS = -4.0 SUFFIX_CAPTION_BIAS_MIN = -10.0 SUFFIX_CAPTION_BIAS_MAX = 0.0 # A PDG scale within this distance of its neutral value skips the PDG forward. _NEUTRAL_SCALE_TOLERANCE = 1.0e-6 # The LINEAR_LOGSNR curve interpolates between these logSNR anchors. _CURVE_LOGSNR_NOISY = -15.0 _CURVE_LOGSNR_CLEAN = 15.0 _BEZIER_SAMPLES = 4096 # Radial APG band edges in cycles per latent pixel: DC, (0, 1/32], (1/32, 1/8], # (1/8, 1/4] and above 1/4. PROJECTION_BAND_EDGES: tuple[float, ...] = (0.0, 1 / 32, 1 / 8, 1 / 4) PROJECTION_BAND_COUNT = len(PROJECTION_BAND_EDGES) + 1 class BranchText(StrEnum): """Text a forward is conditioned on. POSITIVE: the prompt. NEGATIVE: the negative prompt, or the learned null text when there is none. """ POSITIVE = "positive" NEGATIVE = "negative" class GuidanceBranch(StrEnum): """A denoiser forward a guidance step may need: text branch and path.""" POSITIVE_FULL = "positive_full" POSITIVE_PATH_DROP = "positive_path_drop" POSITIVE_THREE_QUARTER = "positive_three_quarter" NEGATIVE_FULL = "negative_full" NEGATIVE_PATH_DROP = "negative_path_drop" NEGATIVE_THREE_QUARTER = "negative_three_quarter" @staticmethod def of(text: BranchText, path: DFlowPath) -> GuidanceBranch: """Return the branch of a text branch and a path.""" return GuidanceBranch(f"{text.value}_{path.value}") @property def text(self) -> BranchText: """The text branch of this forward.""" return BranchText(self.value.split("_", 1)[0]) @property def path(self) -> DFlowPath: """The routing path of this forward.""" return DFlowPath(self.value.split("_", 1)[1]) @dataclass(frozen=True) class BranchCall: """One denoiser forward: branch, image self-attention logit gain and the suffix layers' prompt-key logit bias (0: none).""" branch: GuidanceBranch self_attention_gain: float suffix_caption_bias: float class PdgMode(StrEnum): """Path-drop guidance policies (the reference is the same network with its middle layers skipped). FULL: middle dropped, prompt text. FULL_CONTRASTIVE: middle dropped, negative text. THREE_QUARTER: one image token per 2x2 group through the middle, prompt. ALTERNATE_CONTRASTIVE_POSITIVE: FULL_CONTRASTIVE on even steps, FULL on odd. ALTERNATE_PDG_FIRST / ALTERNATE_CFG_FIRST: contrastive full PDG and CFG on alternate steps of the PDG window, starting with PDG / CFG. ALTERNATE_POSITIVE_PDG_FIRST / ALTERNATE_POSITIVE_CFG_FIRST: the same with prompt-text PDG. COMBINED_CFG_PDG: CFG and contrastive PDG every step, differentials averaged. PDG_WITH_ALTERNATING_CFG: contrastive PDG every step, plus CFG (averaged) on odd steps. CFG_TO_PDG: CFG before the PDG window, prompt-text full PDG inside it. """ FULL = "full" FULL_CONTRASTIVE = "full_contrastive" THREE_QUARTER = "three_quarter" ALTERNATE_CONTRASTIVE_POSITIVE = "alternate_contrastive_positive" ALTERNATE_PDG_FIRST = "alternate_pdg_first" ALTERNATE_CFG_FIRST = "alternate_cfg_first" ALTERNATE_POSITIVE_PDG_FIRST = "alternate_positive_pdg_first" ALTERNATE_POSITIVE_CFG_FIRST = "alternate_positive_cfg_first" COMBINED_CFG_PDG = "combined_cfg_pdg" PDG_WITH_ALTERNATING_CFG = "pdg_with_alternating_cfg" CFG_TO_PDG = "cfg_to_pdg" @property def uses_cfg(self) -> bool: """Whether the mode runs CFG forwards (and needs a CFG scale).""" match self: case ( PdgMode.ALTERNATE_PDG_FIRST | PdgMode.ALTERNATE_CFG_FIRST | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST | PdgMode.COMBINED_CFG_PDG | PdgMode.PDG_WITH_ALTERNATING_CFG | PdgMode.CFG_TO_PDG ): return True case ( PdgMode.FULL | PdgMode.FULL_CONTRASTIVE | PdgMode.THREE_QUARTER | PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE ): return False case _ as unreachable: raise ValueError(f"Unsupported PDG mode: {unreachable}") @property def alternates_with_cfg(self) -> bool: """Whether PDG and CFG alternate inside the PDG window.""" return self in _ALTERNATING_MODES @property def averages_cfg(self) -> bool: """Whether CFG and PDG differentials are averaged on shared steps.""" return self in (PdgMode.COMBINED_CFG_PDG, PdgMode.PDG_WITH_ALTERNATING_CFG) def text_at(self, step: int) -> BranchText: """Text of this mode's PDG reference on ``step``.""" match self: case PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE: return BranchText.NEGATIVE if step % 2 == 0 else BranchText.POSITIVE case ( PdgMode.FULL_CONTRASTIVE | PdgMode.ALTERNATE_PDG_FIRST | PdgMode.ALTERNATE_CFG_FIRST | PdgMode.COMBINED_CFG_PDG | PdgMode.PDG_WITH_ALTERNATING_CFG ): return BranchText.NEGATIVE case ( PdgMode.FULL | PdgMode.THREE_QUARTER | PdgMode.CFG_TO_PDG | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST ): return BranchText.POSITIVE case _ as unreachable: raise ValueError(f"Unsupported PDG mode: {unreachable}") @property def uses_negative(self) -> bool: """Whether any step of this mode conditions on the negative text.""" return self.uses_cfg or BranchText.NEGATIVE in ( self.text_at(0), self.text_at(1), ) _ALTERNATING_MODES = frozenset( { PdgMode.ALTERNATE_PDG_FIRST, PdgMode.ALTERNATE_CFG_FIRST, PdgMode.ALTERNATE_POSITIVE_PDG_FIRST, PdgMode.ALTERNATE_POSITIVE_CFG_FIRST, } ) def _alternation_uses_pdg(mode: PdgMode, step: int) -> bool: """Whether an alternating mode runs PDG (not CFG) on ``step``.""" match mode: case PdgMode.ALTERNATE_PDG_FIRST | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST: return step % 2 == 0 case PdgMode.ALTERNATE_CFG_FIRST | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST: return step % 2 == 1 case _ as unsupported: raise ValueError(f"{unsupported} does not alternate PDG and CFG.") def _validate_scale(value: float, name: str) -> None: """Require a finite, non-negative guidance value. Raises: ValueError: Otherwise. """ if not math.isfinite(value) or value < 0.0: raise ValueError(f"{name} must be finite and >= 0, got {value}.") def _validate_gain(value: float, name: str) -> None: """Require a self-attention gain in [-0.5, 0.1]. Raises: ValueError: Otherwise. """ if not ( math.isfinite(value) and SELF_ATTENTION_GAIN_MIN <= value <= SELF_ATTENTION_GAIN_MAX ): raise ValueError( f"{name} must lie in [{SELF_ATTENTION_GAIN_MIN}, " f"{SELF_ATTENTION_GAIN_MAX}], got {value}." ) @dataclass(frozen=True) class StepWindow: """Inclusive solver-step window; ``stop_step`` None is the last step. Raises: ValueError: For a negative start or a stop before the start. """ start_step: int = 0 stop_step: int | None = None def __post_init__(self) -> None: """Validate the bounds that do not depend on the step count.""" if self.start_step < 0: raise ValueError(f"start_step must be >= 0, got {self.start_step}.") if self.stop_step is not None and self.stop_step < self.start_step: raise ValueError( f"stop_step {self.stop_step} is before start_step {self.start_step}." ) def resolve(self, steps: int, name: str) -> tuple[int, int]: """Return (start, stop) for a run of ``steps`` updates. Raises: ValueError: If the window does not fit inside the run. """ stop = steps - 1 if self.stop_step is None else self.stop_step if stop >= steps or self.start_step > stop: raise ValueError( f"The {name} window [{self.start_step}, {stop}] does not fit in " f"{steps} steps (indices 0 to {steps - 1})." ) return self.start_step, stop @dataclass(frozen=True) class CfgGuidance: """Classifier-free guidance against the negative text. Attributes: enabled: Run CFG inside ``window``. The alternating, combined and CFG-to-PDG PDG modes run CFG forwards of their own and need ``scale`` even when this is False. scale: Guidance scale (1 is no guidance); None when unused. window: Steps where plain CFG applies. Raises: ValueError: For a negative scale or CFG enabled without a scale. """ enabled: bool = False scale: float | None = None window: StepWindow = field(default_factory=StepWindow) def __post_init__(self) -> None: """Validate the scale.""" if self.scale is not None: _validate_scale(self.scale, "CfgGuidance.scale") if self.enabled and self.scale is None: raise ValueError("CfgGuidance.scale is required when CFG is enabled.") @dataclass(frozen=True) class ConstantPdgScale: """The same PDG scale at every step.""" scale: float = DEFAULT_PDG_SCALE def __post_init__(self) -> None: """Validate the scale.""" _validate_scale(self.scale, "ConstantPdgScale.scale") @dataclass(frozen=True) class RampPdgScale: """PDG scale linear in the schedule's CDF quantile from ``start_scale`` at the noisy end to ``end_scale`` after ``length`` of the distribution, then held. On the standard schedules step ``i`` of ``N`` sits at quantile ``1 - i/N``, so ``length`` is the fraction of the steps (0.3: until step 15 of 50). The scale is read at every evaluation's actual time. """ start_scale: float = 4.5 end_scale: float = DEFAULT_PDG_SCALE length: float = 0.3 def __post_init__(self) -> None: """Validate scales and length. Raises: ValueError: For negative scales or a length outside (0, 1]. """ _validate_scale(self.start_scale, "RampPdgScale.start_scale") _validate_scale(self.end_scale, "RampPdgScale.end_scale") if not (math.isfinite(self.length) and 0.0 < self.length <= 1.0): raise ValueError( f"RampPdgScale.length must lie in (0, 1], got {self.length}." ) def scale_at_quantile(self, quantile: float) -> float: """Interpolate the two knots (1, start) and (1 - length, end).""" knots = ((1.0, self.start_scale), (1.0 - self.length, self.end_scale)) q = min(1.0, max(knots[-1][0], quantile)) index = min(bisect_right(knots, -q, key=lambda knot: -knot[0]), len(knots) - 1) high, low = knots[max(index - 1, 0)], knots[index] fraction = (high[0] - q) / (high[0] - low[0]) return high[1] + fraction * (low[1] - high[1]) class EndpointCurveKind(StrEnum): """Shape of a per-step PDG curve from the noisy-end scale to the clean-end one. LINEAR: linear in the step index. LINEAR_LOGSNR: linear in the step's log-SNR between -15 and +15. POWER: (step / steps) ** power. S_CURVE: logistic in the step position, normalised to the endpoints. """ LINEAR = "linear" LINEAR_LOGSNR = "linear_logsnr" POWER = "power" S_CURVE = "s_curve" @dataclass(frozen=True) class EndpointPdgCurve: """A per-step PDG scale from ``noisy_scale`` (first point) to ``clean_scale`` (last point). Raises: ValueError: For negative scales, a non-positive power or sharpness, or a knee outside [0, 1]. """ kind: EndpointCurveKind = EndpointCurveKind.POWER noisy_scale: float = 2.0 clean_scale: float = DEFAULT_PDG_SCALE power: float = 3.0 s_curve_knee: float = 0.5 s_curve_sharpness: float = 8.0 def __post_init__(self) -> None: """Validate every parameter.""" _validate_scale(self.noisy_scale, "EndpointPdgCurve.noisy_scale") _validate_scale(self.clean_scale, "EndpointPdgCurve.clean_scale") for name, value in ( ("power", self.power), ("s_curve_sharpness", self.s_curve_sharpness), ): if not (math.isfinite(value) and value > 0.0): raise ValueError(f"EndpointPdgCurve.{name} must be > 0, got {value}.") if not (math.isfinite(self.s_curve_knee) and 0.0 <= self.s_curve_knee <= 1.0): raise ValueError( f"EndpointPdgCurve.s_curve_knee must lie in [0, 1], got " f"{self.s_curve_knee}." ) @dataclass(frozen=True) class BezierPdgCurve: """A per-step PDG scale ``1 + multiplier * y(t)`` with ``y`` a cubic Bezier over flow time from ``(edge, clean_y)`` to ``(1 - edge, noisy_y)``. Raises: ValueError: For negative values, an edge outside (0, 0.5), handles outside [edge, 1 - edge] or a clean handle after the noisy one. """ multiplier: float = 3.0 clean_y: float = 0.205 clean_handle_t: float = 0.010 clean_handle_y: float = 0.408 noisy_handle_t: float = 0.995 noisy_handle_y: float = 0.275 noisy_y: float = 0.523 edge: float = 0.005 def __post_init__(self) -> None: """Validate every control point.""" for name, value in ( ("multiplier", self.multiplier), ("clean_y", self.clean_y), ("clean_handle_y", self.clean_handle_y), ("noisy_handle_y", self.noisy_handle_y), ("noisy_y", self.noisy_y), ): _validate_scale(value, f"BezierPdgCurve.{name}") if not (math.isfinite(self.edge) and 0.0 < self.edge < 0.5): raise ValueError( f"BezierPdgCurve.edge must lie in (0, 0.5), got {self.edge}." ) for name, value in ( ("clean_handle_t", self.clean_handle_t), ("noisy_handle_t", self.noisy_handle_t), ): if not (math.isfinite(value) and self.edge <= value <= 1.0 - self.edge): raise ValueError( f"BezierPdgCurve.{name} must lie in [edge, 1 - edge], got {value}." ) if self.clean_handle_t > self.noisy_handle_t: raise ValueError("BezierPdgCurve.clean_handle_t must be <= noisy_handle_t.") type PdgScaleSchedule = ( ConstantPdgScale | RampPdgScale | EndpointPdgCurve | BezierPdgCurve ) @dataclass(frozen=True) class PdgGuidance: """Path-drop guidance: policy, scale schedule, step window and the reference's suffix caption bias. Attributes: suffix_caption_bias: Additive attention-logit bias on the prompt's token keys (the learned suffix tokens excluded) in the six suffix layers of every PDG reference forward; negative values make the reference read the prompt less. 0 turns it off; the supported range is ``[SUFFIX_CAPTION_BIAS_MIN, SUFFIX_CAPTION_BIAS_MAX]``. Raises: ValueError: For a quantile ramp with CFG_TO_PDG, or a suffix caption bias outside the supported range. """ mode: PdgMode = PdgMode.FULL scale: PdgScaleSchedule = field(default_factory=ConstantPdgScale) window: StepWindow = field(default_factory=StepWindow) suffix_caption_bias: float = DEFAULT_SUFFIX_CAPTION_BIAS def __post_init__(self) -> None: """Reject the ramp with the step-window crossover mode and a bias outside the supported range.""" if not ( math.isfinite(self.suffix_caption_bias) and SUFFIX_CAPTION_BIAS_MIN <= self.suffix_caption_bias <= SUFFIX_CAPTION_BIAS_MAX ): raise ValueError( "suffix_caption_bias must lie in " f"[{SUFFIX_CAPTION_BIAS_MIN}, {SUFFIX_CAPTION_BIAS_MAX}], got " f"{self.suffix_caption_bias}." ) if self.mode is PdgMode.CFG_TO_PDG and isinstance(self.scale, RampPdgScale): raise ValueError( "CFG_TO_PDG switches on the step window; use a constant or " "per-step PDG scale with it, not a quantile ramp." ) class ProjectionMode(StrEnum): """Adaptive projected guidance (APG) on the x0-space guidance update. OFF: plain guidance. GLOBAL: one projection per sample. PER_BAND: one projection per sample and radial frequency band. """ OFF = "off" GLOBAL = "global" PER_BAND = "per_band" @dataclass(frozen=True) class ProjectedGuidance: """APG: the guided x0 is ``x0_main + (w - 1)(D_perp + parallel_weight D_par)`` with ``D = x0_main - x0_reference`` split against ``x0_main``. Attributes: mode: OFF, GLOBAL or PER_BAND. parallel_weight: Weight kept on the parallel part (1 is plain guidance). first_band: PER_BAND only: bands below it stay unprojected (0 is the mean colour, 1 the coarsest structure). Raises: ValueError: For a weight outside [0, 1] or an invalid first band. """ mode: ProjectionMode = ProjectionMode.OFF parallel_weight: float = 1.0 first_band: int = 0 def __post_init__(self) -> None: """Validate weight and band.""" if not ( math.isfinite(self.parallel_weight) and 0.0 <= self.parallel_weight <= 1.0 ): raise ValueError( "ProjectedGuidance.parallel_weight must lie in [0, 1], got " f"{self.parallel_weight}." ) if not 0 <= self.first_band < PROJECTION_BAND_COUNT: raise ValueError( f"ProjectedGuidance.first_band must lie in [0, " f"{PROJECTION_BAND_COUNT - 1}], got {self.first_band}." ) if self.mode is not ProjectionMode.PER_BAND and self.first_band != 0: raise ValueError("ProjectedGuidance.first_band needs PER_BAND mode.") class SparseStepSchedule(StrEnum): """Which steps run the main and CFG forwards on the three-quarter path. PREFIX: the first ``percent`` of the steps. CYCLIC: ``percent`` of the steps spread evenly (50: every other step). """ PREFIX = "prefix" CYCLIC = "cyclic" @dataclass(frozen=True) class SparseMiddleSteps: """Speed option: run the main (and CFG) forwards with one image token per 2x2 group through the middle on some steps; PDG then drops the full middle. Raises: ValueError: For a percent outside [0, 100]. """ percent: float = 0.0 schedule: SparseStepSchedule = SparseStepSchedule.PREFIX def __post_init__(self) -> None: """Validate the percent.""" if not (math.isfinite(self.percent) and 0.0 <= self.percent <= 100.0): raise ValueError( f"SparseMiddleSteps.percent must lie in [0, 100], got {self.percent}." ) def active(self, step: int, steps: int) -> bool: """Whether ``step`` (0-based, of ``steps``) is sparse.""" if self.percent <= 0.0: return False match self.schedule: case SparseStepSchedule.PREFIX: count = math.ceil((self.percent / 100.0) * float(steps)) return step < max(0, min(steps, count)) case SparseStepSchedule.CYCLIC: before = math.floor((float(step) * self.percent) / 100.0) after = math.floor((float(step + 1) * self.percent) / 100.0) return after > before case _ as unreachable: raise ValueError(f"Unsupported sparse step schedule: {unreachable}") @dataclass(frozen=True) class GuidanceSettings: """Complete guidance configuration (defaults: the release's default preset). Attributes: pdg: Path-drop guidance, or None for none. cfg: Classifier-free guidance. self_attention_gain: Image self-attention logit gain of the main forward. guidance_self_attention_gain: Gain of the guidance forwards. projection: APG on single-reference steps. rescale: Guidance rescale in [0, 1] (0 off); exclusive with APG. sparse_middle: Sparse middle steps on the main and CFG forwards. Raises: ValueError: On inconsistent or out-of-range settings. """ pdg: PdgGuidance | None = field(default_factory=PdgGuidance) cfg: CfgGuidance = field(default_factory=CfgGuidance) self_attention_gain: float = DEFAULT_SELF_ATTENTION_GAIN guidance_self_attention_gain: float = 0.0 projection: ProjectedGuidance = field(default_factory=ProjectedGuidance) rescale: float = 0.0 sparse_middle: SparseMiddleSteps = field(default_factory=SparseMiddleSteps) def __post_init__(self) -> None: """Validate gains, CFG needs, APG and rescale.""" _validate_gain(self.self_attention_gain, "self_attention_gain") _validate_gain( self.guidance_self_attention_gain, "guidance_self_attention_gain" ) if self.pdg is not None and self.pdg.mode.uses_cfg and self.cfg.scale is None: raise ValueError(f"PDG mode {self.pdg.mode.value} needs cfg.scale.") if ( self.cfg.scale is not None and not self.cfg.enabled and not (self.pdg is not None and self.pdg.mode.uses_cfg) ): raise ValueError( "cfg.scale is set but neither CFG nor a CFG-using PDG mode is on." ) if not (math.isfinite(self.rescale) and 0.0 <= self.rescale <= 1.0): raise ValueError(f"rescale must lie in [0, 1], got {self.rescale}.") if self.projection.mode is not ProjectionMode.OFF: self._validate_projection() def _validate_projection(self) -> None: """APG needs guidance, excludes rescale and the averaged modes. Raises: ValueError: Otherwise. """ if self.pdg is None and not self.cfg.enabled: raise ValueError("Projected guidance needs CFG or PDG on.") if self.rescale > 0.0: raise ValueError("Projected guidance and guidance rescale are exclusive.") if self.pdg is not None and self.pdg.mode.averages_cfg: raise ValueError( f"Projected guidance needs a single reference; {self.pdg.mode.value} " "averages two." ) @property def uses_negative(self) -> bool: """Whether any forward conditions on the negative (or null) text.""" return self.cfg.enabled or ( self.pdg is not None and self.pdg.mode.uses_negative ) @dataclass(frozen=True) class UnguidedStep: """Only the main forward.""" main: BranchCall @dataclass(frozen=True) class SingleReferenceStep: """``v_ref + scale (v_main - v_ref)`` (or its APG projection).""" main: BranchCall reference: BranchCall scale: float @dataclass(frozen=True) class AveragedStep: """``v_main + 0.5 (cfg_scale (v_main - v_cfg) + pdg_scale (v_main - v_pdg))``; ``pdg`` None (neutral PDG scale) uses ``v_pdg = v_main``.""" main: BranchCall cfg: BranchCall pdg: BranchCall | None cfg_scale: float pdg_scale: float type GuidanceStep = UnguidedStep | SingleReferenceStep | AveragedStep def _sigmoid(value: float) -> float: """Numerically stable logistic function.""" if value >= 0.0: return 1.0 / (1.0 + math.exp(-value)) exp_value = math.exp(value) return exp_value / (1.0 + exp_value) def _positions(count: int) -> list[float]: """Evenly spaced positions in [0, 1] (``[0.0]`` for one point).""" if count == 1: return [0.0] return [float(index) / float(count - 1) for index in range(count)] def _endpoint_weights( curve: EndpointPdgCurve, count: int, times: Sequence[float] ) -> list[float]: """Interpolation weights (0 noisy, 1 clean) of an endpoint curve. Raises: ValueError: For fewer than two points or a degenerate S-curve. """ if count < 2: raise ValueError(f"A {curve.kind.value} PDG curve needs at least two points.") positions = _positions(count) match curve.kind: case EndpointCurveKind.LINEAR: return positions case EndpointCurveKind.POWER: return [position**curve.power for position in positions] case EndpointCurveKind.LINEAR_LOGSNR: span = _CURVE_LOGSNR_CLEAN - _CURVE_LOGSNR_NOISY weights = [] for time in times: clamped = min(max(time, 1e-12), 1.0 - 1e-12) log_snr = -2.0 * (math.log(clamped) - math.log1p(-clamped)) weights.append( min(max((log_snr - _CURVE_LOGSNR_NOISY) / span, 0.0), 1.0) ) return weights case EndpointCurveKind.S_CURVE: raw = [ _sigmoid((position - curve.s_curve_knee) * curve.s_curve_sharpness) for position in positions ] if raw[-1] - raw[0] <= 1e-12: raise ValueError("s_curve_sharpness is too small to normalise.") return [(value - raw[0]) / (raw[-1] - raw[0]) for value in raw] case _ as unreachable: raise ValueError(f"Unsupported endpoint curve: {unreachable}") def _bezier_values(curve: BezierPdgCurve, count: int) -> list[float]: """Per-point ``1 + multiplier * y`` of a Bezier curve, noisy point first.""" u = np.linspace(0.0, 1.0, _BEZIER_SAMPLES, dtype=np.float64) v = 1.0 - u basis = (v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u) xs = (curve.edge, curve.clean_handle_t, curve.noisy_handle_t, 1.0 - curve.edge) ys = (curve.clean_y, curve.clean_handle_y, curve.noisy_handle_y, curve.noisy_y) x_values = basis[0] * xs[0] + basis[1] * xs[1] + basis[2] * xs[2] + basis[3] * xs[3] y_values = basis[0] * ys[0] + basis[1] * ys[1] + basis[2] * ys[2] + basis[3] * ys[3] order = np.argsort(x_values) query = np.asarray([1.0 - position for position in _positions(count)]) interpolated = np.interp(query, x_values[order], y_values[order]) return [1.0 + curve.multiplier * float(value) for value in interpolated.tolist()] def per_step_pdg_scales( curve: EndpointPdgCurve | BezierPdgCurve, *, schedule: TimeSchedule, log_snr_shift: float, ) -> tuple[float, ...]: """Return a per-step curve's PDG scale at each of the ``steps + 1`` points, rounded to float32 (as the training code stores them). LINEAR_LOGSNR reads the shifted schedule's times without the noisy-endpoint cap. """ count = schedule.steps + 1 match curve: case BezierPdgCurve(): values = _bezier_values(curve, count) case EndpointPdgCurve(): times = build_timesteps( schedule, log_snr_shift=log_snr_shift, finite_noisy_endpoint=False, device=torch.device("cpu"), ).tolist() weights = _endpoint_weights(curve, count, times) noisy, clean = curve.noisy_scale, curve.clean_scale values = [noisy + (clean - noisy) * weight for weight in weights] case _ as unreachable: raise ValueError(f"Unsupported PDG curve: {unreachable}") return tuple(torch.tensor(values, dtype=torch.float32, device="cpu").tolist()) @dataclass(frozen=True) class _PlanInputs: """Run-level values the per-step resolution reads.""" settings: GuidanceSettings steps: int times: tuple[float, ...] cdf: ScheduleCdf pdg_values: tuple[float, ...] | None cfg_window: tuple[int, int] | None pdg_window: tuple[int, int] | None @dataclass(frozen=True) class _Activity: """Which guidance runs on one step and the PDG reference path.""" cfg: bool pdg: bool pdg_path: DFlowPath def _concrete_pdg_path(mode: PdgMode) -> DFlowPath: """The reference path of a single-reference PDG mode.""" return ( DFlowPath.THREE_QUARTER if mode is PdgMode.THREE_QUARTER else DFlowPath.PATH_DROP ) def _inside(step: int, window: tuple[int, int] | None) -> bool: """Whether ``step`` lies in an inclusive window (None: never).""" return window is not None and window[0] <= step <= window[1] def _resolve_activity(inputs: _PlanInputs, step: int) -> _Activity: """Resolve which of CFG and PDG run on ``step`` (clamped step index).""" cfg_window = _inside(step, inputs.cfg_window) pdg_window = _inside(step, inputs.pdg_window) pdg = inputs.settings.pdg if pdg is None: return _Activity(cfg_window, False, DFlowPath.PATH_DROP) mode = pdg.mode if pdg_window and mode.alternates_with_cfg: uses_pdg = _alternation_uses_pdg(mode, step) return _Activity(not uses_pdg, uses_pdg, DFlowPath.PATH_DROP) if mode is PdgMode.CFG_TO_PDG: if pdg_window: return _Activity(False, True, DFlowPath.PATH_DROP) start = inputs.pdg_window[0] if inputs.pdg_window is not None else 0 return _Activity(step < start, False, DFlowPath.PATH_DROP) if pdg_window and mode is PdgMode.PDG_WITH_ALTERNATING_CFG: return _Activity(step % 2 == 1, True, DFlowPath.PATH_DROP) if pdg_window and mode is PdgMode.COMBINED_CFG_PDG: return _Activity(True, True, DFlowPath.PATH_DROP) return _Activity(cfg_window, pdg_window, _concrete_pdg_path(mode)) def _pdg_scale(inputs: _PlanInputs, index: int) -> float: """The absolute PDG scale at schedule point ``index``.""" pdg = inputs.settings.pdg if pdg is None: raise ValueError("PDG scale requested without PDG.") match pdg.scale: case ConstantPdgScale(scale=scale): return scale case RampPdgScale() as ramp: return ramp.scale_at_quantile( inputs.cdf.quantile_at_time(inputs.times[index]) ) case EndpointPdgCurve() | BezierPdgCurve(): if inputs.pdg_values is None: raise ValueError("Per-step PDG values were not prepared.") return inputs.pdg_values[index] case _ as unreachable: raise ValueError(f"Unsupported PDG scale: {unreachable}") def _cfg_scale(settings: GuidanceSettings) -> float: """The CFG scale of an active CFG forward.""" if settings.cfg.scale is None: raise ValueError("A CFG forward is active but cfg.scale is None.") return settings.cfg.scale def _resolve_step(inputs: _PlanInputs, index: int) -> GuidanceStep: """Resolve the forwards and combination of schedule point ``index``.""" settings = inputs.settings step = min(index, inputs.steps - 1) activity = _resolve_activity(inputs, step) cfg_on, pdg_on = activity.cfg, activity.pdg mode = settings.pdg.mode if settings.pdg is not None else None averaged = cfg_on and pdg_on and mode is not None and mode.averages_cfg ramp = settings.pdg is not None and isinstance(settings.pdg.scale, RampPdgScale) pdg_scale = _pdg_scale(inputs, index) if pdg_on else 0.0 neutral = 0.0 if averaged and not ramp else 1.0 if pdg_on and math.isclose( pdg_scale, neutral, rel_tol=0.0, abs_tol=_NEUTRAL_SCALE_TOLERANCE ): pdg_on = False alternating_cfg = ( cfg_on and not pdg_on and mode is not None and mode.alternates_with_cfg ) main_gain = 0.0 if alternating_cfg else settings.self_attention_gain guidance_gain = 0.0 if alternating_cfg else settings.guidance_self_attention_gain sparse = settings.sparse_middle.active(step, inputs.steps) dense_path = DFlowPath.THREE_QUARTER if sparse else DFlowPath.FULL pdg_path = DFlowPath.PATH_DROP if sparse else activity.pdg_path caption_bias = settings.pdg.suffix_caption_bias if settings.pdg is not None else 0.0 main = BranchCall( GuidanceBranch.of(BranchText.POSITIVE, dense_path), main_gain, 0.0 ) if not (cfg_on or pdg_on): return UnguidedStep(main) cfg_call = BranchCall( GuidanceBranch.of(BranchText.NEGATIVE, dense_path), guidance_gain, 0.0 ) if averaged: pdg_call = ( BranchCall( GuidanceBranch.of(BranchText.NEGATIVE, pdg_path), guidance_gain, caption_bias, ) if pdg_on else None ) pdg_extra = _pdg_scale(inputs, index) - (1.0 if ramp else 0.0) return AveragedStep(main, cfg_call, pdg_call, _cfg_scale(settings), pdg_extra) if not pdg_on or mode is None: return SingleReferenceStep(main, cfg_call, _cfg_scale(settings)) text = mode.text_at(step) reference = BranchCall( GuidanceBranch.of(text, pdg_path), guidance_gain, caption_bias ) return SingleReferenceStep(main, reference, pdg_scale) def _band_masks(height: int, width: int, device: torch.device) -> Tensor: """Radial ``[bands, H, W]`` FFT masks of ``PROJECTION_BAND_EDGES``.""" fy = torch.fft.fftfreq(height, device=device) fx = torch.fft.fftfreq(width, device=device) radius = torch.sqrt(fy[:, None].square() + fx[None, :].square()) masks = [radius == 0.0] for low, high in itertools.pairwise(PROJECTION_BAND_EDGES): masks.append((radius > low) & (radius <= high)) masks.append(radius > PROJECTION_BAND_EDGES[-1]) return torch.stack(masks).to(dtype=torch.float32) def _parallel_part( delta: Tensor, reference: Tensor, projection: ProjectedGuidance ) -> Tensor: """The part of ``delta`` parallel to ``reference`` (float32 ``[B, C, H, W]``), per sample or per sample and band from ``first_band`` on.""" eps = torch.finfo(torch.float32).eps match projection.mode: case ProjectionMode.GLOBAL: dims = (1, 2, 3) coefficient = (delta * reference).sum(dims, keepdim=True) / ( reference.square().sum(dims, keepdim=True) + eps ) return coefficient * reference case ProjectionMode.PER_BAND: masks = _band_masks( int(delta.shape[-2]), int(delta.shape[-1]), delta.device ) fd = torch.fft.fft2(delta, norm="ortho") fr = torch.fft.fft2(reference, norm="ortho") parallel = torch.zeros_like(fr) for mask in masks[projection.first_band :]: band = fr * mask coefficient = (fd * band.conj()).real.sum((1, 2, 3), keepdim=True) / ( band.abs().square().sum((1, 2, 3), keepdim=True) + eps ) parallel = parallel + coefficient * band return torch.fft.ifft2(parallel, norm="ortho").real case ProjectionMode.OFF: raise ValueError("An OFF projection has no parallel part.") case _ as unreachable: raise ValueError(f"Unsupported projection mode: {unreachable}") def projected_guidance_velocity( *, main: Tensor, reference: Tensor, state: Tensor, time: Tensor, scale: float, projection: ProjectedGuidance, ) -> Tensor: """APG in velocity units: ``v_main + (w - 1)(dv - (1 - parallel_weight) dv_par)``, ``dv = v_main - v_ref`` and ``dv_par`` its part parallel to ``x0_main = x_t - t v_main``.""" t_view = time.to(device=main.device, dtype=torch.float32).view( (-1,) + (1,) * (main.dim() - 1) ) x0_main = state.to(dtype=torch.float32) - t_view * main.to(dtype=torch.float32) delta = (main - reference).to(dtype=torch.float32) parallel = _parallel_part(delta, x0_main, projection) update = (scale - 1.0) * (delta - (1.0 - projection.parallel_weight) * parallel) return (main.to(dtype=torch.float32) + update).to(dtype=main.dtype) def rescale_guided_velocity( *, guided: Tensor, reference: Tensor, rescale: float ) -> Tensor: """Interpolate ``guided`` toward its per-sample rescale to ``reference``'s norm.""" if rescale == 0.0: return guided flat = (int(guided.shape[0]), -1) guided32 = guided.to(dtype=torch.float32) guided_norm = guided32.reshape(flat).norm(dim=1, keepdim=True) reference_norm = ( reference.to(dtype=torch.float32).reshape(flat).norm(dim=1, keepdim=True) ) view = (int(guided.shape[0]),) + (1,) * (guided.dim() - 1) eps = torch.finfo(torch.float32).eps rescaled = guided32 * ( reference_norm.view(view) / guided_norm.clamp_min(eps).view(view) ) return torch.lerp(guided32, rescaled, rescale).to(dtype=guided.dtype) type BranchEvaluator = Callable[[BranchCall], Tensor] @dataclass(frozen=True) class GuidancePlan: """Per-schedule-point guidance of one run (``build_guidance_plan``). Attributes: steps: One ``GuidanceStep`` per schedule point, index 0 the noisy end. projection: APG of the single-reference steps. rescale: Guidance rescale. """ steps: tuple[GuidanceStep, ...] projection: ProjectedGuidance rescale: float def calls(self, index: int) -> tuple[BranchCall, ...]: """The forwards point ``index`` runs, in evaluation order.""" match self.steps[index]: case UnguidedStep(main=main): return (main,) case SingleReferenceStep(main=main, reference=reference): return (main, reference) case AveragedStep(main=main, cfg=cfg, pdg=None): return (main, cfg) case AveragedStep(main=main, cfg=cfg, pdg=BranchCall() as pdg): return (main, cfg, pdg) case _ as unreachable: raise ValueError(f"Unsupported guidance step: {unreachable}") def guided_velocity( self, index: int, state: Tensor, time: Tensor, evaluate: BranchEvaluator ) -> Tensor: """Run point ``index``'s forwards through ``evaluate`` (main first) and return the guided velocity in ``state``'s dtype. Args: index: Schedule point (the solver's ``step_index``). state: The solver state ``x_t`` (APG reads it). time: Float32 ``[B]`` times of the point. evaluate: Runs one forward at ``(state, time)``. """ step = self.steps[index] main = evaluate(step.main) match step: case UnguidedStep(): return main.to(dtype=state.dtype) case SingleReferenceStep(reference=reference, scale=scale): guided = self._single(main, evaluate(reference), state, time, scale) case AveragedStep() as averaged: cfg = evaluate(averaged.cfg) pdg = main if averaged.pdg is None else evaluate(averaged.pdg) guided = main + 0.5 * ( averaged.cfg_scale * (main - cfg) + averaged.pdg_scale * (main - pdg) ) case _ as unreachable: raise ValueError(f"Unsupported guidance step: {unreachable}") if self.rescale > 0.0: guided = rescale_guided_velocity( guided=guided, reference=main, rescale=self.rescale ) return guided.to(dtype=state.dtype) def _single( self, main: Tensor, reference: Tensor, state: Tensor, time: Tensor, scale: float ) -> Tensor: """Combine one reference with the main velocity (plain or APG).""" if self.projection.mode is ProjectionMode.OFF: return reference + scale * (main - reference) return projected_guidance_velocity( main=main, reference=reference, state=state, time=time, scale=scale, projection=self.projection, ) def build_guidance_plan( settings: GuidanceSettings, *, schedule: TimeSchedule, log_snr_shift: float, timesteps: Sequence[float], ) -> GuidancePlan: """Resolve ``settings`` for one run. Args: settings: Validated guidance settings. schedule: The run's schedule family and step count. log_snr_shift: The effective shift the schedule was built with. timesteps: Host copy of the solver's schedule (``steps + 1`` floats, with the noisy-endpoint cap if the solver uses it); the ramp reads its quantiles at these times. Returns: One ``GuidanceStep`` per schedule point. Raises: ValueError: If a window does not fit, ``timesteps`` has the wrong length, or CFG is on with a PDG mode that has no CFG steps and the two windows overlap (PDG would silently take those steps). """ steps = schedule.steps if len(timesteps) != steps + 1: raise ValueError( f"timesteps has {len(timesteps)} points; the schedule has {steps + 1}." ) pdg = settings.pdg pdg_values = None if pdg is not None: match pdg.scale: case EndpointPdgCurve() | BezierPdgCurve() as curve: pdg_values = per_step_pdg_scales( curve, schedule=schedule, log_snr_shift=log_snr_shift ) case ConstantPdgScale() | RampPdgScale(): pass case _ as unreachable: raise ValueError(f"Unsupported PDG scale: {unreachable}") cfg_window = ( settings.cfg.window.resolve(steps, "CFG") if settings.cfg.enabled else None ) pdg_window = pdg.window.resolve(steps, "PDG") if pdg is not None else None _reject_shadowed_cfg(settings, cfg_window, pdg_window) inputs = _PlanInputs( settings=settings, steps=steps, times=tuple(float(time) for time in timesteps), cdf=ScheduleCdf(schedule, log_snr_shift), pdg_values=pdg_values, cfg_window=cfg_window, pdg_window=pdg_window, ) return GuidancePlan( steps=tuple(_resolve_step(inputs, index) for index in range(steps + 1)), projection=settings.projection, rescale=settings.rescale, ) def _reject_shadowed_cfg( settings: GuidanceSettings, cfg_window: tuple[int, int] | None, pdg_window: tuple[int, int] | None, ) -> None: """Reject CFG that a PDG mode without CFG steps would silently replace. Raises: ValueError: If CFG is on, the PDG mode runs no CFG forwards and the CFG and PDG windows share a step. """ pdg = settings.pdg if cfg_window is None or pdg_window is None or pdg is None or pdg.mode.uses_cfg: return first = max(cfg_window[0], pdg_window[0]) last = min(cfg_window[1], pdg_window[1]) if first <= last: raise ValueError( f"CFG and PDG mode {pdg.mode.value} are both active on steps " f"{first}-{last}; PDG would take those steps. Use a PDG mode that " "includes CFG (combined_cfg_pdg, alternate_*, pdg_with_alternating_cfg, " "cfg_to_pdg) or make the step windows disjoint." ) # The three-quarter routing keeps one token of each 2x2 latent group, so the # token grid needs even sides: image sides that are multiples of this. THREE_QUARTER_SIZE_MULTIPLE = 32 def check_three_quarter_size( settings: GuidanceSettings, width: int, height: int ) -> None: """Reject an image size the three-quarter routing cannot run at. Raises: ValueError: If PDG mode ``three_quarter`` or sparse middle steps are on and a side is not a multiple of ``THREE_QUARTER_SIZE_MULTIPLE``. """ three_quarter = settings.pdg is not None and ( settings.pdg.mode is PdgMode.THREE_QUARTER ) if not (three_quarter or settings.sparse_middle.percent > 0.0): return if width % THREE_QUARTER_SIZE_MULTIPLE or height % THREE_QUARTER_SIZE_MULTIPLE: raise ValueError( "PDG mode three_quarter and sparse middle steps need a width and " f"height that are multiples of {THREE_QUARTER_SIZE_MULTIPLE}; got " f"{width}x{height}." )