from __future__ import annotations import math from typing import Literal import torch def linear_beta_schedule(timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2) -> torch.Tensor: """ 经典线性 beta 调度(DDPM)。 """ return torch.linspace(beta_start, beta_end, timesteps, dtype=torch.float32) def cosine_beta_schedule(timesteps: int, s: float = 0.008) -> torch.Tensor: """ Cosine 调度(Nichol & Dhariwal, 2021)。 参考实现:alpha_bar(t) = cos^2((t+s)/(1+s)*pi/2) """ steps = timesteps + 1 x = torch.linspace(0, timesteps, steps, dtype=torch.float64) t = x / timesteps alpha_bar = torch.cos((t + s) / (1 + s) * math.pi / 2) ** 2 alpha_bar = alpha_bar / alpha_bar[0] betas = 1 - (alpha_bar[1:] / alpha_bar[:-1]) return betas.clamp(1e-8, 0.999).float() def get_beta_schedule( schedule: Literal["linear", "cosine"], timesteps: int, ) -> torch.Tensor: """ 统一入口:返回长度为 timesteps 的 betas。 """ if schedule == "linear": return linear_beta_schedule(timesteps) if schedule == "cosine": return cosine_beta_schedule(timesteps) raise ValueError(f"未知 schedule: {schedule}")