File size: 5,200 Bytes
0252cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Probability path, coefficient schedules and the IDFF training objective.

Equation and section references are to the TMLR paper "Implicit Dynamical Flow Fusion (IDFF) for
Generative Modeling".
"""
import math

import torch


def pad_like(t, x):
    """Reshape a scalar or (batch,) time tensor so that it broadcasts against ``x``."""
    if not torch.is_tensor(t):
        t = torch.tensor(t, dtype=x.dtype, device=x.device)
    if t.dim() == 0:
        return t
    return t.reshape(-1, *([1] * (x.dim() - 1)))


def sigma_t(t, sigma0):
    """Standard deviation of the conditional path, sigma_t = sigma0 * sqrt(t (1 - t))  (Eq. ppath)."""
    if torch.is_tensor(t):
        return sigma0 * torch.sqrt((t * (1.0 - t)).clamp_min(0.0))
    return sigma0 * math.sqrt(max(t * (1.0 - t), 0.0))


def sample_conditional_path(x0, x1, t, sigma0):
    """Draw x_t = t x1 + (1 - t) x0 + sigma_t eps with eps ~ N(0, I)  (Eq. ppath).

    Returns ``(x_t, eps, sigma_t)`` with ``sigma_t`` broadcastable against ``x1``.
    """
    eps = torch.randn_like(x1)
    tt = pad_like(t, x1)
    st = sigma_t(tt, sigma0)
    xt = tt * x1 + (1.0 - tt) * x0 + st * eps
    return xt, eps, st


def gamma_schedule(t, gamma_bar, shape="beta22"):
    """Langevin amplitude gamma_t^1 >= 0, vanishing at t = 0 and t = 1.

    Shapes follow the schedule ablation of the paper (Appendix, "Schedule shape ablation"):
    ``beta22``  4 gamma_bar t (1 - t)        (default, Beta(2,2))
    ``triangular``  gamma_bar min(t, 1 - t)
    ``sine``  gamma_bar sin(pi t)
    ``beta33``  16 gamma_bar t^2 (1 - t)^2   (peak normalised to gamma_bar)
    """
    if shape == "beta22":
        return 4.0 * gamma_bar * t * (1.0 - t)
    if shape == "triangular":
        return gamma_bar * min(t, 1.0 - t)
    if shape == "sine":
        return gamma_bar * math.sin(math.pi * t)
    if shape == "beta33":
        return 16.0 * gamma_bar * (t * (1.0 - t)) ** 2
    raise ValueError(f"unknown schedule shape: {shape!r}")


def idff_loss(model, x1, x0=None, t=None, sigma0=0.2, beta_eps=1e-2, model_kwargs=None):
    """IDFF training objective (Eq. idff_loss).

        beta(t)^2 ||x1_hat(x_t, t) - x1||^2  +  lambda_1(t)^2 ||s_hat(x_t, t) + eps / sigma_t||^2,

    with beta(t) = 1 / (1 - t + beta_eps) and lambda_1(t) = sigma_t. The score term regresses the
    score head onto the conditional score grad log p_t(x_t | x0, x1) = -eps / sigma_t; by Fisher's
    identity its minimiser is the marginal score grad log p_t(x_t). Because lambda_1 = sigma_t, the
    term is evaluated in the algebraically identical, numerically stable form ||sigma_t s_hat + eps||^2.

    Args:
        model: callable ``model(x_t, t, **model_kwargs) -> (x1_hat, s_hat)``.
        x1: data batch.
        x0: base samples; defaults to N(0, I) (independent coupling).
        t: times in [0, 1], shape (batch,); defaults to U(0, 1).
        sigma0: path bandwidth; must be > 0, otherwise the score head receives no signal.

    Returns:
        ``(loss, stats)`` where ``stats`` holds the two terms as floats.
    """
    if sigma0 <= 0:
        raise ValueError("sigma0 must be > 0: with sigma0 = 0 the score target -eps/sigma_t is undefined")
    if x0 is None:
        x0 = torch.randn_like(x1)
    if t is None:
        t = torch.rand(x1.shape[0], device=x1.device, dtype=x1.dtype)
    xt, eps, st = sample_conditional_path(x0, x1, t, sigma0)
    x1_hat, s_hat = model(xt, t, **(model_kwargs or {}))
    beta = 1.0 / (1.0 - pad_like(t, x1) + beta_eps)
    denoiser = ((beta * (x1_hat - x1)) ** 2).flatten(1).mean(1).mean()
    score = ((st * s_hat + eps) ** 2).flatten(1).mean(1).mean()
    return denoiser + score, {"denoiser": denoiser.item(), "score": score.item()}


def ot_coupling(x0, x1):
    """Re-pair a minibatch with the exact optimal-transport plan (squared Euclidean cost).

    This is the minibatch-OT coupling of OT-CFM (Tong et al.), used by the OT-IDFF variant. The score
    head remains valid under any coupling (Fisher's identity does not need independence). Requires POT.
    """
    from torchcfm.optimal_transport import OTPlanSampler

    return OTPlanSampler(method="exact").sample_plan(x0, x1)


def sequence_training_pairs(data, batch_size, sigma0, generator=None):
    """Draw a training batch for the time-series model (Algorithm 3, IDFF Training (Time-Series)).

    For position n = 0 the base sample is x0 ~ N(0, I). For n > 0 it is the previous frame,
    x0 ~ N(x^{n-1}, sigma0^2 I), matching the Markovian initialisation used at sampling time.

    Args:
        data: tensor of shape (num_sequences, length, dim).

    Returns:
        ``(x0, x1, n)`` with ``n`` the (batch,) long tensor of positions.
    """
    num_seq, length = data.shape[0], data.shape[1]
    dev = data.device
    seq = torch.randint(num_seq, (batch_size,), device=dev, generator=generator)
    n = torch.randint(length, (batch_size,), device=dev, generator=generator)
    x1 = data[seq, n]
    prev = data[seq, (n - 1).clamp_min(0)]
    noise = torch.randn(x1.shape, device=dev, dtype=x1.dtype, generator=generator)
    first = (n == 0).reshape(-1, *([1] * (x1.dim() - 1)))
    x0 = torch.where(first, noise, prev + sigma0 * noise)
    return x0, x1, n