File size: 7,337 Bytes
4a2be2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""
DDPM (Denoising Diffusion Probabilistic Model) for 25-dim building property vectors.
MLP-based: 25 → 256 → 256 → 256 → 25
Used by STER-GI Ideas 3 and 4.
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict

DEV = 'cuda' if torch.cuda.is_available() else 'cpu'

# ============================================================
# Beta Schedule
# ============================================================
class BetaSchedule:
    """Linear beta schedule for DDPM."""
    def __init__(self, T=1000, beta_start=1e-4, beta_end=0.02):
        self.T = T
        betas = torch.linspace(beta_start, beta_end, T)
        alphas = 1.0 - betas
        alpha_bars = torch.cumprod(alphas, dim=0)
        
        self.betas = betas.to(DEV)
        self.alphas = alphas.to(DEV)
        self.alpha_bars = alpha_bars.to(DEV)
        self.sqrt_alpha_bars = torch.sqrt(alpha_bars).to(DEV)
        self.sqrt_one_minus_alpha_bars = torch.sqrt(1.0 - alpha_bars).to(DEV)
        self.sqrt_recip_alphas = torch.sqrt(1.0 / alphas).to(DEV)
        self.posterior_variance = betas * (1.0 - alpha_bars) / (1.0 - alpha_bars + 1e-8)

    def forward_diffuse(self, x0, t, noise=None):
        """q(x_t | x_0): add noise according to schedule at step t."""
        if noise is None:
            noise = torch.randn_like(x0)
        sqrt_ab_t = self.sqrt_alpha_bars[t].view(-1, 1)
        sqrt_1mab_t = self.sqrt_one_minus_alpha_bars[t].view(-1, 1)
        return sqrt_ab_t * x0 + sqrt_1mab_t * noise, noise

# ============================================================
# Denoiser Network
# ============================================================
class DenoiserMLP(nn.Module):
    """Predicts noise from noisy input x_t and timestep t."""
    def __init__(self, d=25, h=256, T=1000):
        super().__init__()
        self.t_emb = nn.Embedding(T, h)
        self.net = nn.Sequential(OrderedDict([
            ('in', nn.Linear(d + h, h)),
            ('n1', nn.LayerNorm(h)), ('a1', nn.SiLU()),
            ('h1', nn.Linear(h, h)),
            ('n2', nn.LayerNorm(h)), ('a2', nn.SiLU()),
            ('h2', nn.Linear(h, h)),
            ('n3', nn.LayerNorm(h)), ('a3', nn.SiLU()),
            ('out', nn.Linear(h, d)),
        ]))

    def forward(self, x, t):
        te = self.t_emb(t)
        h = torch.cat([x, te], dim=-1)
        return self.net(h)

# ============================================================
# DDPM Trainer
# ============================================================
class DDPM:
    def __init__(self, d=25, h=256, T=1000):
        self.d = d
        self.h = h
        self.T = T
        self.schedule = BetaSchedule(T)
        self.denoiser = DenoiserMLP(d, h, T).to(DEV)
        self.optimizer = torch.optim.AdamW(self.denoiser.parameters(), lr=3e-4, weight_decay=1e-5)

    def train_step(self, x):
        """Single DDPM training step: predict noise added to input."""
        B = x.shape[0]
        t = torch.randint(0, self.T, (B,), device=DEV)
        x_t, noise = self.schedule.forward_diffuse(x, t)
        pred = self.denoiser(x_t, t)
        loss = F.mse_loss(pred, noise)
        self.optimizer.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(self.denoiser.parameters(), 1.0)
        self.optimizer.step()
        return loss.item()

    @torch.no_grad()
    def sample(self, n=100, steps=None):
        """Generate samples from pure noise (reverse process)."""
        if steps is None:
            steps = self.T
        self.denoiser.eval()
        x = torch.randn(n, self.d, device=DEV)
        step_size = self.T // steps
        
        for t_idx in reversed(range(0, self.T, step_size)):
            t = torch.full((n,), t_idx, device=DEV, dtype=torch.long)
            pred_noise = self.denoiser(x, t)
            alpha = self.schedule.alphas[t_idx]
            alpha_bar = self.schedule.alpha_bars[t_idx]
            beta = self.schedule.betas[t_idx]
            
            if t_idx > 0:
                noise = torch.randn_like(x)
                sigma = torch.sqrt(beta)
                x = (1.0 / torch.sqrt(alpha)) * (
                    x - (beta / torch.sqrt(1.0 - alpha_bar)) * pred_noise
                ) + sigma * noise
            else:
                x = (1.0 / torch.sqrt(alpha)) * (
                    x - (beta / torch.sqrt(1.0 - alpha_bar)) * pred_noise
                )
        
        self.denoiser.train()
        return x

    @torch.no_grad()
    def sdedit(self, x0, t0=100, steps=None):
        """SDEdit: add noise to t0, then reverse denoise → sibling."""
        if steps is None:
            steps = t0
        self.denoiser.eval()
        
        n = x0.shape[0]
        t0_t = torch.full((n,), t0, device=DEV, dtype=torch.long)
        
        # Forward: add noise to t0
        noise = torch.randn_like(x0)
        sqrt_ab = self.schedule.sqrt_alpha_bars[t0].view(-1, 1)
        sqrt_1mab = self.schedule.sqrt_one_minus_alpha_bars[t0].view(-1, 1)
        x_t = sqrt_ab * x0 + sqrt_1mab * noise
        
        # Reverse: denoise from t0 to 0
        step_size = max(1, t0 // steps)
        x = x_t
        for t_idx in reversed(range(t0)):
            if t_idx % step_size != 0 and t_idx > step_size:
                continue
            t = torch.full((n,), t_idx, device=DEV, dtype=torch.long)
            pred_noise = self.denoiser(x, t)
            alpha = self.schedule.alphas[t_idx]
            alpha_bar = self.schedule.alpha_bars[t_idx]
            beta = self.schedule.betas[t_idx]
            
            if t_idx > 0:
                rng_noise = torch.randn_like(x)
                sigma = torch.sqrt(beta)
                x = (1.0 / torch.sqrt(alpha)) * (
                    x - (beta / torch.sqrt(1.0 - alpha_bar)) * pred_noise
                ) + sigma * rng_noise
            else:
                x = (1.0 / torch.sqrt(alpha)) * (
                    x - (beta / torch.sqrt(1.0 - alpha_bar)) * pred_noise
                )
        
        self.denoiser.train()
        return x

    @torch.no_grad()
    def score(self, x, t_vals=[50, 100, 200, 300, 400]):
        """Compute score function magnitude at x for grammar checking (Idea 4)."""
        self.denoiser.eval()
        scores = []
        for t_idx in t_vals:
            t = torch.full((x.shape[0],), t_idx, device=DEV, dtype=torch.long)
            noise = torch.randn_like(x)
            sqrt_ab = self.schedule.sqrt_alpha_bars[t_idx]
            sqrt_1mab = self.schedule.sqrt_one_minus_alpha_bars[t_idx]
            x_t = sqrt_ab * x + sqrt_1mab * noise
            pred_noise = self.denoiser(x_t, t)
            # Score ≈ -pred_noise / sqrt(1-alpha_bar)
            score_val = -pred_noise / sqrt_1mab
            scores.append(torch.norm(score_val, dim=-1))
        self.denoiser.train()
        return torch.stack(scores, dim=-1)  # (B, len(t_vals))

    def save(self, path):
        torch.save({'denoiser': self.denoiser.state_dict(),
                     'd': self.d, 'h': self.h, 'T': self.T}, path)

    @classmethod
    def load(cls, path):
        state = torch.load(path, map_location=DEV)
        model = cls(d=state['d'], h=state['h'], T=state['T'])
        model.denoiser.load_state_dict(state['denoiser'])
        model.denoiser.to(DEV)
        return model