File size: 10,579 Bytes
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 | """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))
|