T-Stitch / cdf_utils.py
Ouzhang's picture
Add files using upload-large-folder tool
e5371e6 verified
Raw
History Blame Contribute Delete
4.95 kB
"""Shared CDF/CST schedule helpers.
The helpers in this file are intentionally dependency-light so they can be
used by LDM, DiT, and Stable Diffusion training entrypoints.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Iterable, List, Sequence, Tuple
SUPPORTED_SCHEDULES = (
"fixed",
"curriculum",
"linear",
"cosine",
"cst_v1",
"large_bias",
"cst_v2",
"small_bias",
"staircase",
)
SUPPORTED_TRAIN_MODES = (
"junior",
"small",
"senior",
"large",
"joint",
"fmgt",
)
@dataclass(frozen=True)
class CDFInterval:
"""Inclusive-exclusive timestep interval [start, end)."""
start: int
end: int
def clamp_nonempty(self, max_timestep: int) -> "CDFInterval":
start = max(0, min(int(self.start), int(max_timestep) - 1))
end = max(start + 1, min(int(self.end), int(max_timestep)))
return CDFInterval(start=start, end=end)
def clamp01(value: float) -> float:
return max(0.0, min(1.0, float(value)))
def schedule_progress(
progress: float,
schedule: str,
staircase_bins: int = 8,
) -> float:
"""Map training progress in [0, 1] to curriculum progress in [0, 1]."""
progress = clamp01(progress)
schedule = (schedule or "fixed").lower().replace("-", "_")
if schedule in {"fixed"}:
return 1.0
if schedule in {"curriculum", "linear"}:
return progress
if schedule == "cosine":
return 0.5 - 0.5 * math.cos(math.pi * progress)
if schedule in {"cst_v1", "large_bias"}:
return math.sqrt(progress)
if schedule in {"cst_v2", "small_bias"}:
return progress * progress
if schedule == "staircase":
bins = max(1, int(staircase_bins))
return math.floor(progress * bins) / float(bins)
raise ValueError(f"Unsupported CDF schedule: {schedule}. Supported: {SUPPORTED_SCHEDULES}")
def ratio_at_progress(
progress: float,
schedule: str,
ratio_start: float,
ratio_end: float,
staircase_bins: int = 8,
) -> float:
"""Return the active junior ratio for a CDF/CST training step."""
if (schedule or "fixed").lower().replace("-", "_") == "fixed":
return clamp01(ratio_end)
weight = schedule_progress(progress, schedule, staircase_bins=staircase_bins)
return clamp01(float(ratio_start) + (float(ratio_end) - float(ratio_start)) * weight)
def boundary_timestep(ratio: float, num_timesteps: int) -> int:
"""Return t_zeta = floor((1-r)T)."""
return int(math.floor((1.0 - clamp01(ratio)) * int(num_timesteps)))
def junior_interval(ratio: float, num_timesteps: int) -> CDFInterval:
"""Timesteps trained or sampled by the junior model."""
return CDFInterval(boundary_timestep(ratio, num_timesteps), int(num_timesteps)).clamp_nonempty(num_timesteps)
def senior_interval(ratio: float, num_timesteps: int) -> CDFInterval:
"""Timesteps trained or sampled by the senior model."""
return CDFInterval(0, boundary_timestep(ratio, num_timesteps)).clamp_nonempty(num_timesteps)
def interval_for_train_mode(
train_mode: str,
ratio: float,
num_timesteps: int,
) -> CDFInterval:
"""Return the timestep interval for a CDF train mode.
`joint`/`fmgt` return the full interval; routing is handled by the
stitched model itself.
"""
mode = (train_mode or "junior").lower().replace("-", "_")
if mode in {"junior", "small"}:
return junior_interval(ratio, num_timesteps)
if mode in {"senior", "large"}:
return senior_interval(ratio, num_timesteps)
if mode in {"joint", "fmgt"}:
return CDFInterval(0, int(num_timesteps)).clamp_nonempty(num_timesteps)
raise ValueError(f"Unsupported CDF train mode: {train_mode}. Supported: {SUPPORTED_TRAIN_MODES}")
def boundary_interval(
ratio: float,
num_timesteps: int,
boundary_width: int,
) -> CDFInterval:
"""Return a non-empty boundary window around t_zeta."""
center = boundary_timestep(ratio, num_timesteps)
width = max(0, int(boundary_width))
return CDFInterval(center - width, center + width + 1).clamp_nonempty(num_timesteps)
def parse_ratio_list(value: str | Sequence[float]) -> List[float]:
if isinstance(value, str):
values = [item.strip() for item in value.split(",") if item.strip()]
return [clamp01(float(item)) for item in values]
return [clamp01(float(item)) for item in value]
def format_ratio(ratio: float) -> str:
return f"{clamp01(ratio):.1f}"
def ratio_grid(start: float = 0.0, end: float = 1.0, step: float = 0.1) -> List[float]:
values: List[float] = []
n_steps = int(round((float(end) - float(start)) / float(step)))
for idx in range(n_steps + 1):
values.append(clamp01(float(start) + idx * float(step)))
return values
def csv_join(values: Iterable[float]) -> str:
return ",".join(format_ratio(value) for value in values)