File size: 4,473 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
"""Joint-head networks for IDFF.

A single trunk feeds two linear heads: the denoiser x1_hat(x_t, t) and the score s_hat(x_t, t)
(paper, Sec. "Sample-Based Vector Field Learning"). SiLU activations keep the score smooth, so the
Jacobian used by the K >= 2 correction is well defined (ReLU networks are not suitable for K >= 2).
"""
import math

import torch
from torch import nn


class SiLU(nn.Module):
    """SiLU written as x * sigmoid(x).

    Mathematically identical to ``torch.nn.SiLU``, but built from primitives that support nested
    forward-mode differentiation, which the K >= 3 contracted derivatives require (the fused
    ``aten::silu`` kernel does not support forward-over-forward AD).
    """

    def forward(self, x):
        return x * torch.sigmoid(x)


class TimeFeatures(nn.Module):
    """Fourier features of the flow time t: [t, sin(2 pi k t), cos(2 pi k t)] for k = 1..n_freq."""

    def __init__(self, n_freq=4):
        super().__init__()
        self.register_buffer("freqs", 2.0 * math.pi * torch.arange(1, n_freq + 1).float())
        self.out_dim = 1 + 2 * n_freq

    def forward(self, t):
        ang = t[:, None] * self.freqs[None]
        return torch.cat([t[:, None], torch.sin(ang), torch.cos(ang)], dim=-1)


class JointHeadMLP(nn.Module):
    """MLP with a shared trunk and two heads, returning ``(x1_hat, s_hat)``.

    Args:
        dim: data dimension.
        hidden, depth: trunk width and number of hidden layers.
        sigma0: path bandwidth used in training (needed for the score preconditioner).
        base_std: std of the base distribution x0 around its mean (1 for N(0, I)).
        num_positions: if given, adds a learned embedding of the sequence position n
            (dual-time indexing for time series: t is the flow time, n the sequence position).
        base_std_first: base std at position n = 0 when ``num_positions`` is set (x0 ~ N(0, I) there).
        residual: if True, x1_hat = x_t + head(x_t, t); convenient for time series where
            consecutive frames are close. It changes only the parameterisation, not the objective.
        score_floor: floor of the score preconditioner.

    The score head is preconditioned as s_hat = h_s / c(t) with
    c(t) = sqrt(b^2 (1 - t)^2 + sigma_t^2 + floor^2), the local noise scale of p_t. This rescales
    the head output only; the head is still trained to the marginal score by the IDFF objective.
    """

    def __init__(self, dim, hidden=256, depth=3, sigma0=0.2, base_std=1.0, num_positions=None,
                 base_std_first=1.0, residual=False, n_freq=4, pos_dim=64, score_floor=1e-2):
        super().__init__()
        self.dim = dim
        self.sigma0 = float(sigma0)
        self.base_std = float(base_std)
        self.base_std_first = float(base_std_first)
        self.residual = residual
        self.score_floor = float(score_floor)
        self.time = TimeFeatures(n_freq)
        in_dim = dim + self.time.out_dim
        self.pos = None
        if num_positions is not None:
            self.pos = nn.Embedding(num_positions, pos_dim)
            in_dim += pos_dim
        layers = [nn.Linear(in_dim, hidden), SiLU()]
        for _ in range(depth - 1):
            layers += [nn.Linear(hidden, hidden), SiLU()]
        self.trunk = nn.Sequential(*layers)
        self.head_x1 = nn.Linear(hidden, dim)
        self.head_score = nn.Linear(hidden, dim)

    def forward(self, x, t, n=None):
        batch = x.shape[0]
        if not torch.is_tensor(t):
            t = torch.tensor(float(t), device=x.device, dtype=x.dtype)
        t = t.to(dtype=x.dtype).reshape(-1)
        if t.numel() == 1:
            t = t.expand(batch)
        feats = [x.reshape(batch, -1), self.time(t)]
        if self.pos is not None:
            if n is None:
                raise ValueError("this model was built with num_positions; pass the sequence position n")
            feats.append(self.pos(n.long()))
        h = self.trunk(torch.cat(feats, dim=-1))
        x1_hat = self.head_x1(h)
        if self.residual:
            x1_hat = x.reshape(batch, -1) + x1_hat
        b = torch.full_like(t, self.base_std)
        if self.pos is not None:
            b = torch.where(n.reshape(-1) == 0, torch.full_like(t, self.base_std_first), b)
        var = (b * (1.0 - t)) ** 2 + self.sigma0 ** 2 * t * (1.0 - t) + self.score_floor ** 2
        s_hat = self.head_score(h) / torch.sqrt(var)[:, None]
        return x1_hat.reshape_as(x), s_hat.reshape_as(x)