dflow_2b / dflow /schedules.py
data-archetype's picture
dflow_2b 0.2
6daffc2
Raw History Blame Contribute Delete
10.6 kB
"""Flow-matching timestep schedules, the log-SNR shift and the schedule CDF.
Time convention (shared with ``solvers`` and ``guidance``): the flow path is
``x_t = (1 - t) x_0 + t noise`` with ``t = 1`` pure noise and ``t = 0`` clean.
A schedule is a strictly descending float32 tensor of ``steps + 1`` times,
noisy end first. The model predicts the velocity ``v = dx_t/dt = noise - x_0``,
so the clean estimate at time ``t`` is ``x_0 = x_t - t v``.
The log-SNR of time ``t`` is ``-2 logit(t)``. An additive log-SNR shift ``s``
moves every interior time to ``sigmoid(logit(t) - s / 2)``; a negative shift
spends more steps near the noisy end. The model was trained with
``s = min(0, -0.25 - ln(width * height / 256^2))``.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from enum import StrEnum
import numpy as np
import torch
from scipy import special, stats
from torch import Tensor
# Resolution-shift constants: base shift and reference side in pixels.
TRAINING_BASE_LOG_SNR_SHIFT = -0.25
RESOLUTION_SHIFT_REFERENCE = 256
# Shifts at or below this magnitude leave the schedule unchanged.
_SHIFT_NO_OP_TOLERANCE = 1.0e-9
# The noisy endpoint t = 1 becomes 1 - this for solvers that evaluate log-SNR.
FINITE_NOISY_ENDPOINT_EPSILON = 1.0e-4
BETA_0_6_SHAPE = 0.6
BETA_1_25_SHAPE = 1.25
DEFAULT_CUSTOM_BETA_MEAN = 0.5
DEFAULT_CUSTOM_BETA_CONCENTRATION = 0.6
class ScheduleKind(StrEnum):
"""Spacing of the schedule's points before the log-SNR shift.
LINEAR: evenly spaced times.
BETA_0_6: equal-probability quantiles of Beta(0.6, 0.6) (dense at both ends).
BETA_1_25: quantiles of Beta(1.25, 1.25) (slightly dense in the middle).
CUSTOM_BETA: quantiles of Beta(mean * concentration,
(1 - mean) * concentration).
"""
LINEAR = "linear"
BETA_0_6 = "beta_0_6"
BETA_1_25 = "beta_1_25"
CUSTOM_BETA = "custom_beta"
@dataclass(frozen=True)
class TimeSchedule:
"""A schedule family and its step count.
Attributes:
kind: Point spacing.
steps: Solver updates; the schedule has ``steps + 1`` points.
beta_mean: Mean of the CUSTOM_BETA distribution, in (0, 1).
beta_concentration: Concentration (alpha + beta) of CUSTOM_BETA, > 0.
Raises:
TypeError: For a non-int step count.
ValueError: For a non-positive step count or invalid beta parameters.
"""
kind: ScheduleKind = ScheduleKind.BETA_1_25
steps: int = 50
beta_mean: float = DEFAULT_CUSTOM_BETA_MEAN
beta_concentration: float = DEFAULT_CUSTOM_BETA_CONCENTRATION
def __post_init__(self) -> None:
"""Validate the step count and the custom beta parameters."""
if isinstance(self.steps, bool) or not isinstance(self.steps, int):
raise TypeError("TimeSchedule.steps must be an int.")
if self.steps < 1:
raise ValueError(f"TimeSchedule.steps must be >= 1, got {self.steps}.")
if not (math.isfinite(self.beta_mean) and 0.0 < self.beta_mean < 1.0):
raise ValueError(
f"TimeSchedule.beta_mean must lie in (0, 1), got {self.beta_mean}."
)
if not (math.isfinite(self.beta_concentration) and self.beta_concentration > 0):
raise ValueError(
"TimeSchedule.beta_concentration must be finite and > 0, got "
f"{self.beta_concentration}."
)
@property
def beta_parameters(self) -> tuple[float, float] | None:
"""Return (alpha, beta) of a beta spacing, or None for LINEAR."""
match self.kind:
case ScheduleKind.LINEAR:
return None
case ScheduleKind.BETA_0_6:
return BETA_0_6_SHAPE, BETA_0_6_SHAPE
case ScheduleKind.BETA_1_25:
return BETA_1_25_SHAPE, BETA_1_25_SHAPE
case ScheduleKind.CUSTOM_BETA:
return (
self.beta_mean * self.beta_concentration,
(1.0 - self.beta_mean) * self.beta_concentration,
)
case _ as unreachable:
raise ValueError(f"Unsupported schedule kind: {unreachable}")
def resolution_log_snr_shift(
width: int,
height: int,
*,
base: float = TRAINING_BASE_LOG_SNR_SHIFT,
reference: int = RESOLUTION_SHIFT_REFERENCE,
) -> float:
"""Return ``min(0, base - ln(width * height / reference^2))``.
This is the timestep shift the model was trained with at a given image
size (-2.99 at 832 x 1216 with the defaults).
Args:
width: Image width in pixels.
height: Image height in pixels.
base: Size-independent part of the shift.
reference: Side in pixels of the square whose area has no size term.
Raises:
ValueError: For a non-positive size or reference, or a non-finite base.
"""
if width <= 0 or height <= 0 or reference <= 0:
raise ValueError(
"width, height and reference must be positive, got "
f"{width} x {height}, reference {reference}."
)
if not math.isfinite(base):
raise ValueError(f"base must be finite, got {base}.")
resolution_term = -math.log((width * height) / float(reference * reference))
return min(0.0, float(base) + resolution_term)
def apply_log_snr_shift(timesteps: Tensor, shift: float) -> Tensor:
"""Shift interior times by ``shift`` in log-SNR; keep exact 0 and 1.
Args:
timesteps: Float tensor of times in [0, 1].
shift: Additive log-SNR shift; |shift| <= 1e-9 returns the input.
Raises:
ValueError: For a non-finite shift.
"""
if not math.isfinite(shift):
raise ValueError(f"log_snr_shift must be finite, got {shift}.")
if abs(shift) <= _SHIFT_NO_OP_TOLERANCE:
return timesteps
finfo = torch.finfo(timesteps.dtype)
clamped = timesteps.clamp(max(float(finfo.tiny), 1.0e-12), 1.0 - float(finfo.eps))
shifted = torch.sigmoid(torch.logit(clamped) - 0.5 * shift)
shifted = torch.where(timesteps == 0.0, torch.zeros_like(shifted), shifted)
return torch.where(timesteps == 1.0, torch.ones_like(shifted), shifted)
def _beta_quantiles(points: int, *, alpha: float, beta: float) -> Tensor:
"""Return Beta(alpha, beta) quantiles of a float32 probability grid, in float32.
Raises:
RuntimeError: If SciPy returns non-finite quantiles.
"""
probabilities = torch.linspace(0.0, 1.0, points, dtype=torch.float32, device="cpu")
values = np.asarray(
stats.beta.ppf(probabilities.to(torch.float64).numpy(), alpha, beta),
dtype=np.float32,
)
if not bool(np.isfinite(values).all()):
raise RuntimeError(f"Beta({alpha}, {beta}) quantiles are not finite.")
return torch.from_numpy(values)
def _ascending_base(schedule: TimeSchedule) -> Tensor:
"""Return the unshifted ascending float32 CPU grid of ``steps + 1`` points."""
points = schedule.steps + 1
parameters = schedule.beta_parameters
if parameters is None:
return torch.linspace(0.0, 1.0, points, dtype=torch.float32, device="cpu")
alpha, beta = parameters
return _beta_quantiles(points, alpha=alpha, beta=beta)
def _cap_noisy_endpoint(descending: Tensor) -> Tensor:
"""Replace an exact ``t = 1`` first point by ``1 - 1e-4`` (or the next float
above its neighbour when that neighbour is already closer to 1).
Raises:
ValueError: If no float32 lies strictly between the neighbour and 1.
"""
if float(descending[0]) != 1.0:
return descending
one = torch.ones((), dtype=descending.dtype, device=descending.device)
candidate = torch.tensor(
1.0 - FINITE_NOISY_ENDPOINT_EPSILON,
dtype=descending.dtype,
device=descending.device,
)
neighbour = descending[1]
if float(neighbour) >= float(candidate):
candidate = torch.nextafter(neighbour, one)
if float(candidate) >= 1.0:
raise ValueError(
"No finite noisy endpoint fits between the second schedule point "
"and t = 1; lower the step count or the log-SNR shift magnitude."
)
capped = descending.clone()
capped[0] = candidate
return capped
def build_timesteps(
schedule: TimeSchedule,
*,
log_snr_shift: float,
finite_noisy_endpoint: bool,
device: torch.device,
) -> Tensor:
"""Build the descending float32 schedule the solver integrates over.
Order of operations (as the training code): unshifted ascending grid,
moved to ``device``, log-SNR shift there, flip to descending, then, when
``finite_noisy_endpoint``, replace the exact ``t = 1`` start by
``1 - 1e-4``. Log-SNR solvers
(``solvers.solver_requires_finite_noisy_endpoint``) need that finite start.
The shift runs on ``device`` because CPU and CUDA ``logit``/``sigmoid`` can
differ in the last bit.
Args:
schedule: Spacing and step count.
log_snr_shift: Effective shift (e.g. ``resolution_log_snr_shift``).
finite_noisy_endpoint: Whether to cap the noisy endpoint below 1.
device: Device of the returned tensor.
Returns:
Float32 tensor ``[steps + 1]``, strictly descending, ending at 0.
Raises:
ValueError: For a non-finite shift or an impossible endpoint cap.
"""
base = _ascending_base(schedule).to(device=device)
descending = torch.flip(apply_log_snr_shift(base, log_snr_shift), dims=(0,))
if finite_noisy_endpoint:
descending = _cap_noisy_endpoint(descending)
return descending.contiguous()
@dataclass(frozen=True)
class ScheduleCdf:
"""CDF of a shifted schedule's time distribution: 1 at the noisy end, 0 clean.
Step ``i`` of an ``N``-step standard schedule sits at quantile ``1 - i / N``
before the endpoint cap; the guidance ramp is defined in this coordinate.
Evaluated on the host from Python floats (no device work).
"""
schedule: TimeSchedule
log_snr_shift: float
def quantile_at_time(self, time: float) -> float:
"""Return the CDF value of the unshifted distribution at a solver time."""
if time <= 0.0:
return 0.0
if time >= 1.0:
return 1.0
logit = math.log(time) - math.log1p(-time)
base_time = float(special.expit(logit + 0.5 * self.log_snr_shift))
parameters = self.schedule.beta_parameters
if parameters is None:
return base_time
alpha, beta = parameters
return float(special.betainc(alpha, beta, base_time))