| """ |
| 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' |
|
|
| |
| |
| |
| 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 |
|
|
| |
| |
| |
| 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) |
|
|
| |
| |
| |
| 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) |
| |
| |
| 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 |
| |
| |
| 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_val = -pred_noise / sqrt_1mab |
| scores.append(torch.norm(score_val, dim=-1)) |
| self.denoiser.train() |
| return torch.stack(scores, dim=-1) |
|
|
| 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 |
|
|