File size: 1,281 Bytes
c388140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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}")