"""Float32 solvers for the linear flow-matching path. Conventions (see ``schedules``): ``x_t = (1 - t) x_0 + t noise``, times run from the noisy end (``t`` near 1) to ``t = 0``, and the velocity callable returns ``v = noise - x_0`` at ``(x_t, t)``, so ``x_0 = x_t - t v`` and an Euler step is ``x + (t_next - t) v``. The solver state is float32. Every solver calls ``velocity(state, time, step_index)`` where ``time`` is a float32 ``[B]`` tensor holding ``timesteps[step_index]``: each evaluation sits exactly on a schedule point, and ``step_index`` is that point's index (``0 .. steps``; ABM2 also evaluates the last point). Guidance uses the index to look up its per-step plan. The schedule is read to the host once before the loop; the per-step code has no host synchronisation. """ from __future__ import annotations import itertools import math from dataclasses import dataclass from enum import StrEnum from typing import Protocol import numpy as np import torch import torch.nn.functional as F from torch import Tensor from .brownian_noise import BrownianIntervalNormal, standard_normal DEFAULT_SDE_NOISE_SCALE = 1.0 DEFAULT_DPMPP_2M_SDE_ETA = 0.5 # Floor of t in Euler-Maruyama's velocity-to-score conversion. _SCORE_TIME_FLOOR = 1.0e-4 _ER_MAX_STAGE = 3 _ER_QUADRATURE_POINTS = 16 _ER_NOISE_EXPONENT = 0.3 _ER_NOISE_OFFSET = 10.0 class Solver(StrEnum): """Numerical solvers. EULER: first-order ODE. EULER_MARUYAMA: first-order reverse SDE (noise scale 1 is the SDE's own). ER_SDE: third-stage extended reverse-time SDE with independent normals. ER_SDE_BT: ER_SDE with Brownian-tree noise (schedule-consistent paths). DPMPP_2M: second-order multistep ODE in half-log-SNR. DPMPP_2M_SDE: DPM++ 2M SDE midpoint method (noise scale is eta). ABM2: Adams-Bashforth-Moulton predictor-corrector (two evaluations a step). """ EULER = "euler" EULER_MARUYAMA = "euler_maruyama" ER_SDE = "er_sde" ER_SDE_BT = "er_sde_bt" DPMPP_2M = "dpmpp_2m" DPMPP_2M_SDE = "dpmpp_2m_sde" ABM2 = "abm2" def default_noise_scale(solver: Solver) -> float: """Return the recommended noise scale (eta for DPM++ 2M SDE) of a solver.""" match solver: case Solver.DPMPP_2M_SDE: return DEFAULT_DPMPP_2M_SDE_ETA case ( Solver.EULER | Solver.EULER_MARUYAMA | Solver.ER_SDE | Solver.ER_SDE_BT | Solver.DPMPP_2M | Solver.ABM2 ): return DEFAULT_SDE_NOISE_SCALE case _ as unreachable: raise ValueError(f"Unsupported solver: {unreachable}") def solver_is_stochastic(solver: Solver) -> bool: """Return whether a solver injects noise (and needs a generator).""" match solver: case ( Solver.EULER_MARUYAMA | Solver.ER_SDE | Solver.ER_SDE_BT | Solver.DPMPP_2M_SDE ): return True case Solver.EULER | Solver.DPMPP_2M | Solver.ABM2: return False case _ as unreachable: raise ValueError(f"Unsupported solver: {unreachable}") def solver_requires_finite_noisy_endpoint(solver: Solver) -> bool: """Return whether a solver evaluates log-SNR at the first point (needs t < 1).""" match solver: case Solver.ER_SDE | Solver.ER_SDE_BT | Solver.DPMPP_2M | Solver.DPMPP_2M_SDE: return True case Solver.EULER | Solver.EULER_MARUYAMA | Solver.ABM2: return False case _ as unreachable: raise ValueError(f"Unsupported solver: {unreachable}") class VelocityFunction(Protocol): """The velocity at one schedule point.""" def __call__(self, state: Tensor, time: Tensor, step_index: int, /) -> Tensor: """Return ``v`` like ``state`` for float32 times ``[B]`` at ``step_index``.""" ... class SolverCallback(Protocol): """Observer of each completed solver update.""" def __call__(self, predicted_x0: Tensor, completed: int, total: int, /) -> None: """Receive the latest clean estimate after ``completed`` of ``total``.""" ... @dataclass(frozen=True) class _Run: """Validated per-solve inputs shared by every solver loop.""" velocity: VelocityFunction times: Tensor host_times: tuple[float, ...] callback: SolverCallback | None @property def intervals(self) -> int: """Number of solver updates.""" return len(self.host_times) - 1 def time_batch(self, index: int, batch: int) -> Tensor: """Return ``times[index]`` as a float32 ``[batch]`` vector.""" return self.times[index].expand(batch) def evaluate(self, state: Tensor, index: int) -> Tensor: """Evaluate the velocity at schedule point ``index``, cast like ``state``.""" time = self.time_batch(index, int(state.shape[0])) return self.velocity(state, time, index).to(dtype=state.dtype) def report(self, state: Tensor, velocity: Tensor, index: int, done: int) -> None: """Send ``state - t_index v`` to the callback when one is set.""" if self.callback is not None: self.callback(state - self.times[index] * velocity, done, self.intervals) def _validate(state: Tensor, timesteps: Tensor) -> tuple[float, ...]: """Check state and schedule invariants once; return the host times. Raises: ValueError: For a non-float32 or non-4D state, or a schedule that is not a strictly descending finite float32 vector in [0, 1] of length >= 2. """ if state.dim() != 4 or state.dtype != torch.float32: raise ValueError( f"The solver state must be float32 [B, C, H, W]; got {state.dtype} " f"with shape {tuple(state.shape)}." ) if timesteps.dim() != 1 or timesteps.dtype != torch.float32: raise ValueError("timesteps must be a float32 vector.") if timesteps.device != state.device: raise ValueError( f"timesteps are on {timesteps.device} but the state is on {state.device}." ) host = tuple(float(value) for value in timesteps.cpu().tolist()) if len(host) < 2 or not all(math.isfinite(value) for value in host): raise ValueError("timesteps need at least two finite points.") if any(value < 0.0 or value > 1.0 for value in host): raise ValueError("timesteps must lie in [0, 1].") if any(a <= b for a, b in itertools.pairwise(host)): raise ValueError("timesteps must be strictly descending.") return host def _require_finite_log_snr(host_times: tuple[float, ...], solver: Solver) -> None: """Require evaluation times in (0, 1) for a log-SNR solver. Raises: ValueError: If a model-evaluation time is 0 or 1. """ if any(value <= 0.0 or value >= 1.0 for value in host_times[:-1]): raise ValueError( f"{solver.value} evaluates log-SNR: every point but the last must lie " "in (0, 1). Build the schedule with finite_noisy_endpoint=True." ) def _euler(run: _Run, state: Tensor) -> Tensor: """First-order Euler; the step is the float32 difference of the points.""" deltas = (run.times[1:] - run.times[:-1]).cpu().tolist() for index in range(run.intervals): velocity = run.evaluate(state, index) run.report(state, velocity, index, index + 1) state = state + float(deltas[index]) * velocity return state def _euler_maruyama( run: _Run, state: Tensor, *, noise_scale: float, generator: torch.Generator ) -> Tensor: """Reverse-SDE Euler-Maruyama: drift ``v - t score``, diffusion ``2 t``. The score is ``-((1 - t) v + x) / max(t, 1e-4)``. A final step to t = 0 returns ``x - t v``. """ deltas = (run.times[1:] - run.times[:-1]).cpu().tolist() batch = int(state.shape[0]) for index in range(run.intervals): t0 = run.host_times[index] dt = float(deltas[index]) time = torch.full((batch,), t0, device=state.device, dtype=torch.float32) velocity = run.velocity(state, time, index).to(dtype=state.dtype) run.report(state, velocity, index, index + 1) if index == run.intervals - 1 and run.host_times[index + 1] == 0.0: state = state - t0 * velocity continue noise = standard_normal( tuple(state.shape), generator=generator, device=state.device ) time_view = time.view(batch, 1, 1, 1) safe_time = time_view.clamp(min=_SCORE_TIME_FLOOR) score = -(((1.0 - safe_time) * velocity) + state) / safe_time drift = velocity - time_view * score scale = noise_scale * math.sqrt(2.0 * t0) * math.sqrt(abs(dt)) state = state + dt * drift + scale * noise return state def _half_log_snr_float64(times: Tensor) -> Tensor: """Return ``log((1 - t) / t)`` in float64 (t clamped above 0).""" times64 = times.clamp(min=torch.finfo(times.dtype).tiny).to(dtype=torch.float64) return torch.log1p(-times64) - torch.log(times64) def _require_increasing(lambdas: Tensor, host_times: tuple[float, ...]) -> None: """Require half-log-SNR to rise over every step that does not end at 0. Raises: ValueError: Otherwise. """ values = lambdas.cpu().tolist() for index, (current, following) in enumerate(itertools.pairwise(values)): if host_times[index + 1] != 0.0 and following - current <= 0.0: raise ValueError("The schedule must raise half-log-SNR over every step.") def _dpmpp_2m_update( state: Tensor, denoised: Tensor, previous: tuple[Tensor, Tensor] | None, current_lambda: Tensor, next_lambda: Tensor, ) -> Tensor: """One DPM++ 2M update; ``previous`` is (denoised, lambda) of the last step.""" step = next_lambda - current_lambda if previous is None: extrapolated = denoised else: previous_denoised, previous_lambda = previous ratio = (current_lambda - previous_lambda) / step extrapolated = (1.0 + 1.0 / (2.0 * ratio)) * denoised - ( 1.0 / (2.0 * ratio) ) * previous_denoised log_sigma_ratio = F.logsigmoid(-next_lambda) - F.logsigmoid(-current_lambda) sigma_ratio = torch.exp(log_sigma_ratio).to(dtype=state.dtype) alpha_next = torch.sigmoid(next_lambda).to(dtype=state.dtype) coefficient = (alpha_next * (-torch.expm1(-step))).to(dtype=state.dtype) return sigma_ratio * state + coefficient * extrapolated def _dpmpp_2m(run: _Run, state: Tensor) -> Tensor: """DPM++ 2M in half-log-SNR; a final step to t = 0 returns ``x - t v``.""" lambdas = _half_log_snr_float64(run.times) _require_increasing(lambdas, run.host_times) previous: tuple[Tensor, Tensor] | None = None for index in range(run.intervals): velocity = run.evaluate(state, index) denoised = state - run.times[index] * velocity run.report(state, velocity, index, index + 1) if run.host_times[index + 1] == 0.0: state = denoised else: state = _dpmpp_2m_update( state, denoised, previous, lambdas[index], lambdas[index + 1] ) previous = (denoised, lambdas[index]) return state @dataclass(frozen=True) class _SdeStep: """One DPM++ 2M SDE interval: times, half-log-SNR step and eta.""" current_time: Tensor next_time: Tensor step: Tensor eta: float def _dpmpp_2m_sde_update( state: Tensor, denoised: Tensor, previous: tuple[Tensor, Tensor] | None, interval: _SdeStep, generator: torch.Generator, ) -> Tensor: """One DPM++ 2M SDE midpoint update; ``previous`` is (denoised, step).""" eta = interval.eta stochastic_step = interval.step * (1.0 + eta) sigma_ratio = (interval.next_time / interval.current_time) * torch.exp( -interval.step * eta ) coefficient = (1.0 - interval.next_time) * (-torch.expm1(-stochastic_step)) result = sigma_ratio.to(state.dtype) * state result = result + coefficient.to(state.dtype) * denoised if previous is not None: previous_denoised, previous_step = previous ratio = previous_step / interval.step result = result + ( 0.5 * coefficient.to(state.dtype) / ratio.to(state.dtype) * (denoised - previous_denoised) ) if eta == 0.0: return result normal = standard_normal( tuple(state.shape), generator=generator, device=state.device ) noise_scale = interval.next_time * torch.sqrt( -torch.expm1(-2.0 * interval.step * eta) ) return result + noise_scale.to(state.dtype) * normal def _dpmpp_2m_sde( run: _Run, state: Tensor, *, eta: float, generator: torch.Generator ) -> Tensor: """DPM++ 2M SDE (eta 0 is the deterministic midpoint method).""" lambdas = _half_log_snr_float64(run.times) _require_increasing(lambdas, run.host_times) previous_denoised: Tensor | None = None previous_step: Tensor | None = None for index in range(run.intervals): velocity = run.evaluate(state, index) denoised = state - run.times[index] * velocity run.report(state, velocity, index, index + 1) if run.host_times[index + 1] == 0.0: state = denoised else: step = lambdas[index + 1] - lambdas[index] previous = ( None if previous_denoised is None or previous_step is None else (previous_denoised, previous_step) ) interval = _SdeStep(run.times[index], run.times[index + 1], step, eta) state = _dpmpp_2m_sde_update(state, denoised, previous, interval, generator) previous_step = step previous_denoised = denoised return state def _er_noise_scaler(er_lambda: Tensor) -> Tensor: """ER-SDE noise-scaling function ``l (exp(l^0.3) + 10)``.""" return er_lambda * (torch.exp(er_lambda.pow(_ER_NOISE_EXPONENT)) + _ER_NOISE_OFFSET) def _er_stochastic_time(er_lambda: Tensor) -> Tensor: """ER Brownian clock ``1 / (exp(l^0.3) + 10)^2``.""" denominator = torch.exp(er_lambda.pow(_ER_NOISE_EXPONENT)) + _ER_NOISE_OFFSET return denominator.square().reciprocal() @dataclass(frozen=True) class _ErSdeContext: """Per-solve ER-SDE constants: lambdas, quadrature rule and noise source.""" times: Tensor er_lambdas: Tensor nodes: Tensor weights: Tensor noise_scale: float generator: torch.Generator tree: BrownianIntervalNormal | None # Host Brownian-clock time per point (read once; BT only). clock: tuple[float, ...] def _er_context( run: _Run, state: Tensor, *, noise_scale: float, generator: torch.Generator, brownian: bool, ) -> _ErSdeContext: """Prepare ER-SDE constants (and the Brownian tree) before the loop.""" times = run.times half_log_snr = torch.log1p(-times) - torch.log(times) er_lambdas = torch.exp(-half_log_snr) nodes_np, weights_np = np.polynomial.legendre.leggauss(_ER_QUADRATURE_POINTS) nodes = torch.as_tensor(nodes_np, device=times.device, dtype=torch.float32) weights = torch.as_tensor(weights_np, device=times.device, dtype=torch.float32) tree: BrownianIntervalNormal | None = None clock: tuple[float, ...] = () if brownian and noise_scale > 0.0: tree = BrownianIntervalNormal( state=state, start=0.0, end=1.0 / (1.0 + _ER_NOISE_OFFSET) ** 2, generator=generator, ) clock = tuple( float(_er_stochastic_time(er_lambdas[index]).item()) for index in range(len(run.host_times)) ) return _ErSdeContext( times, er_lambdas, nodes, weights, noise_scale, generator, tree, clock ) def _er_quadrature( context: _ErSdeContext, lambda_s: Tensor, lambda_t: Tensor ) -> tuple[Tensor, Tensor]: """Gauss-Legendre ER-SDE correction integrals over one interval.""" midpoint = (lambda_s + lambda_t) / 2.0 half_span = (lambda_s - lambda_t) / 2.0 positions = midpoint + half_span * context.nodes scaled = _er_noise_scaler(positions) second = half_span * torch.sum(context.weights / scaled) third = half_span * torch.sum(context.weights * (positions - lambda_s) / scaled) return second, third @dataclass(frozen=True) class _ErHistory: """Clean estimate and its first divided difference from the last step.""" denoised: Tensor derivative: Tensor | None def _er_sde_step( context: _ErSdeContext, state: Tensor, denoised: Tensor, history: _ErHistory | None, index: int, ) -> tuple[Tensor, Tensor | None]: """One non-terminal ER-SDE update; returns the state and the derivative.""" lambdas = context.er_lambdas lambda_s, lambda_t = lambdas[index], lambdas[index + 1] alpha_s = context.times[index] / lambda_s alpha_t = context.times[index + 1] / lambda_t noise_t = _er_noise_scaler(lambda_t) ratio = noise_t / _er_noise_scaler(lambda_s) next_state = (alpha_t / alpha_s) * ratio * state next_state = next_state + alpha_t * (1.0 - ratio) * denoised derivative: Tensor | None = None stage = min(_ER_MAX_STAGE, index + 1) if stage >= 2 and history is not None: second, third = _er_quadrature(context, lambda_s, lambda_t) delta = lambda_t - lambda_s derivative = (denoised - history.denoised) / (lambda_s - lambdas[index - 1]) next_state = next_state + alpha_t * (delta + second * noise_t) * derivative if stage >= 3 and history.derivative is not None: span = (lambda_s - lambdas[index - 2]) / 2.0 second_derivative = (derivative - history.derivative) / span next_state = ( next_state + alpha_t * (delta.square() / 2.0 + third * noise_t) * second_derivative ) if context.noise_scale > 0.0: if context.tree is None: noise = standard_normal( tuple(state.shape), generator=context.generator, device=state.device ) else: noise = context.tree.sample( state=state, start=context.clock[index], end=context.clock[index + 1], ) variance = lambda_t.square() - lambda_s.square() * ratio.square() stochastic = alpha_t * torch.sqrt(torch.clamp(variance, min=0.0)) next_state = next_state + context.noise_scale * stochastic * noise return next_state.to(dtype=state.dtype), derivative def _er_sde(run: _Run, state: Tensor, context: _ErSdeContext) -> Tensor: """Third-stage VP ER-SDE; a final step to t = 0 returns ``x - t v``.""" history: _ErHistory | None = None for index in range(run.intervals): velocity = run.evaluate(state, index) denoised = state - run.times[index] * velocity run.report(state, velocity, index, index + 1) derivative: Tensor | None = None if run.host_times[index + 1] == 0.0: state = denoised else: state, derivative = _er_sde_step(context, state, denoised, history, index) history = _ErHistory(denoised, derivative) return state def _abm2(run: _Run, state: Tensor) -> Tensor: """ABM2: Euler bootstrap, then AB2 predictor and trapezoidal corrector, re-evaluating the velocity at the corrected state.""" times = run.times previous_velocity = run.evaluate(state, 0) state = state + (times[1] - times[0]) * previous_velocity current_velocity = run.evaluate(state, 1) run.report(state, current_velocity, 1, 1) for index in range(1, run.intervals): previous_step = times[index] - times[index - 1] current_step = times[index + 1] - times[index] ratio = current_step / previous_step predicted = state + current_step * ( (1.0 + 0.5 * ratio) * current_velocity + (-0.5 * ratio) * previous_velocity ) predicted_velocity = run.evaluate(predicted, index + 1) state = state + 0.5 * current_step * (current_velocity + predicted_velocity) previous_velocity = current_velocity current_velocity = run.evaluate(state, index + 1) run.report(state, current_velocity, index + 1, index + 1) return state def _validate_noise(solver: Solver, noise_scale: float, generator: object) -> None: """Check the noise scale, and that stochastic solvers have a generator. Raises: ValueError: For a negative or non-finite scale, or a missing generator. """ if not math.isfinite(noise_scale) or noise_scale < 0.0: raise ValueError(f"noise_scale must be finite and >= 0, got {noise_scale}.") if solver_is_stochastic(solver) and generator is None: raise ValueError(f"{solver.value} injects noise: pass a torch.Generator.") def solve( velocity: VelocityFunction, initial_state: Tensor, timesteps: Tensor, *, solver: Solver, noise_scale: float, generator: torch.Generator | None, callback: SolverCallback | None = None, ) -> Tensor: """Integrate from ``timesteps[0]`` to ``timesteps[-1]``. Args: velocity: ``(state, time [B], step_index) -> v``; see the module docstring. initial_state: Float32 ``[B, C, H, W]`` state at ``timesteps[0]``. timesteps: Descending float32 schedule on the state's device (``schedules.build_timesteps``; log-SNR solvers need a first point below 1). solver: Numerical method. noise_scale: SDE noise multiplier (eta for DPM++ 2M SDE); deterministic solvers ignore it. generator: Source of the injected noise (a CPU generator gives the same noise on every GPU); required by stochastic solvers. callback: Receives ``x_t - t v`` of each evaluated point after each update. Returns: The float32 state at ``timesteps[-1]``. Raises: ValueError: For an invalid state, schedule, noise scale or generator. """ host_times = _validate(initial_state, timesteps) _validate_noise(solver, noise_scale, generator) if solver_requires_finite_noisy_endpoint(solver): _require_finite_log_snr(host_times, solver) run = _Run(velocity, timesteps, host_times, callback) match solver, generator: case Solver.EULER, _: return _euler(run, initial_state) case Solver.EULER_MARUYAMA, torch.Generator() as noise: return _euler_maruyama( run, initial_state, noise_scale=noise_scale, generator=noise ) case ( Solver.ER_SDE | Solver.ER_SDE_BT ) as er_solver, torch.Generator() as noise: context = _er_context( run, initial_state, noise_scale=noise_scale, generator=noise, brownian=er_solver is Solver.ER_SDE_BT, ) return _er_sde(run, initial_state, context) case Solver.DPMPP_2M, _: return _dpmpp_2m(run, initial_state) case Solver.DPMPP_2M_SDE, torch.Generator() as noise: return _dpmpp_2m_sde(run, initial_state, eta=noise_scale, generator=noise) case Solver.ABM2, _: return _abm2(run, initial_state) case _ as unreachable: raise ValueError(f"Unsupported solver call: {unreachable}")