Spaces:
Sleeping

DWO / ddpm /models.py
0jg's picture
Ensure DDPM files in correct subdirectory
60b8900 verified
Raw History Blame Contribute Delete
11.1 kB
"""Neural network architectures for diffusion models."""
import math
from typing import cast
import torch
import torch.nn as nn
class SinusoidalPositionalEncoding(nn.Module):
"""Sinusoidal positional encoding for diffusion timestep.
Maps diffusion timestep t to a high-dimensional embedding using sinusoidal functions
similar to transformer positional encodings (Vaswani, et al., (2017))
Args:
dim: Dimension of the embedding
max_period: Maximum period for sinusoidal functions
"""
dim: int
max_period: float
def __init__(self, dim: int, max_period: float = 10000.0) -> None:
super().__init__()
self.dim = dim
self.max_period = max_period
def forward(self, t: torch.Tensor) -> torch.Tensor:
"""Encode timestep t.
Args:
t: Timestep tensor of shape [batch_size]
Returns:
Encoded timestep of shape [batch_size, dim]
"""
device = t.device
half_dim = self.dim // 2
# Create frequency bands
emb = math.log(self.max_period) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
emb = t[:, None] * emb[None, :]
# Apply sin and cos
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
return emb
class ResidualBlock(nn.Module):
"""Residual block with time conditioning for U-Net.
See Ho, et al., (2020), or He, et al., (2016).
"""
def __init__(self, in_channels: int, out_channels: int, time_emb_dim: int) -> None:
super().__init__()
# Use padding=0 and apply replicate padding manually to avoid boundary artifacts
self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=3, padding=0)
self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size=3, padding=0)
self.time_mlp = nn.Linear(time_emb_dim, out_channels)
self.norm1 = nn.GroupNorm(8, out_channels)
self.norm2 = nn.GroupNorm(8, out_channels)
self.act = nn.SiLU()
if in_channels != out_channels:
self.shortcut = nn.Conv1d(in_channels, out_channels, kernel_size=1)
else:
self.shortcut = nn.Identity()
def forward(self, x: torch.Tensor, time_emb: torch.Tensor) -> torch.Tensor:
"""Forward pass with time conditioning."""
# Apply replicate padding manually before conv to avoid boundary artifacts
h = nn.functional.pad(x, (1, 1), mode="replicate")
h = self.conv1(h)
h = self.norm1(h)
h = self.act(h)
# Add time embedding
time_emb = self.time_mlp(time_emb)[:, :, None]
h = h + time_emb
h = nn.functional.pad(h, (1, 1), mode="replicate")
h = self.conv2(h)
h = self.norm2(h)
h = self.act(h)
return h + self.shortcut(x)
class ConditionalUNet(nn.Module):
r"""Conditional U-Net for denoising time series signals.
See Ronneberger, et al., (2015). As implemented in Ho, et al., (2020).
This network takes noisy data $x_t$, diffusion timestep $t$, and conditioning data,
and predicts the noise $\varepsilon$ to be removed.
The architecture follows: $x_t, t, c \to \varepsilon_\theta(x_t, t, c)$
Args:
input_dim: Dimension of input time series
hidden_dim: Hidden dimension for layers
n_layers: Number of layers in encoder/decoder
time_emb_dim: Dimension of timestep embedding
n_input_channels: Number of input channels (e.g., 2 for signal + conditioning)
"""
input_dim: int
hidden_dim: int
n_layers: int
channels: list[int]
physical_position_encoding: torch.Tensor
def __init__(
self,
input_dim: int = 250,
hidden_dim: int = 128,
n_layers: int = 4,
time_emb_dim: int = 128,
n_input_channels: int = 2,
use_position_encoding: bool = False,
) -> None:
super().__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.n_layers = n_layers
# Time embedding
self.time_encoder = SinusoidalPositionalEncoding(time_emb_dim)
self.time_mlp = nn.Sequential(
nn.Linear(time_emb_dim, time_emb_dim * 2),
nn.SiLU(),
nn.Linear(time_emb_dim * 2, time_emb_dim),
)
# Inject physical-time information so the network can distinguish
# absolute trajectory positions away from the boundaries.
# Only enabled for models trained with this feature (e.g. DWO).
self.use_position_encoding = use_position_encoding
if use_position_encoding:
self.register_buffer(
"physical_position_encoding",
self._build_physical_position_encoding(input_dim, hidden_dim),
persistent=False,
)
# Initial projection: concatenate x_t and conditioning
self.init_conv = nn.Conv1d(n_input_channels, hidden_dim, kernel_size=3, padding=0)
# Store channel configuration
self.channels = [hidden_dim * (2**i) for i in range(n_layers)]
# Encoder (downsampling)
self.encoder_blocks = nn.ModuleList()
self.downsample = nn.ModuleList()
for i in range(n_layers):
in_ch = self.channels[i - 1] if i > 0 else hidden_dim
out_ch = self.channels[i]
self.encoder_blocks.append(ResidualBlock(in_ch, out_ch, time_emb_dim))
if i < n_layers - 1:
self.downsample.append(
nn.Conv1d(out_ch, out_ch, kernel_size=3, stride=2, padding=0)
)
# Middle
mid_ch = self.channels[-1]
self.middle_block = ResidualBlock(mid_ch, mid_ch, time_emb_dim)
# Decoder (upsampling) - mirror of encoder
self.decoder_blocks = nn.ModuleList()
self.upsample = nn.ModuleList()
for i in range(n_layers - 1, -1, -1):
# Determine input and output channels
if i == n_layers - 1:
# First decoder block receives only from middle block
in_ch = self.channels[i]
else:
# Other blocks receive concatenated skip connection
in_ch = self.channels[i] * 2
out_ch = self.channels[i - 1] if i > 0 else hidden_dim
self.decoder_blocks.append(ResidualBlock(in_ch, out_ch, time_emb_dim))
# Add upsampling except for the last decoder block
if i > 0:
self.upsample.append(
nn.Sequential(
nn.Upsample(scale_factor=2, mode="linear", align_corners=True),
nn.Conv1d(out_ch, out_ch, kernel_size=3, padding=0),
)
)
# Final projection to output
self.final_conv = nn.Conv1d(hidden_dim, 1, kernel_size=3, padding=0)
def forward(
self, x_t: torch.Tensor, t: torch.Tensor, conditioning: torch.Tensor
) -> torch.Tensor:
r"""Forward pass for noise prediction.
Args:
x_t: Noisy data of shape [batch_size, trajectory_length]
t: Diffusion timestep of shape [batch_size]
conditioning: Conditioning data of shape [batch_size, trajectory_length]
Returns:
Predicted noise $\varepsilon$ of shape [batch_size, trajectory_length]
"""
# Add channel dimension and concatenate x_t with conditioning
x_t = x_t.unsqueeze(1) # [batch, 1, trajectory_length]
if conditioning.dim() == 2:
# Single-channel conditioning: [batch, T] -> [batch, 1, T]
conditioning = conditioning.unsqueeze(1)
# else: multi-channel conditioning already [batch, C, T]
x = torch.cat([x_t, conditioning], dim=1) # [batch, 1+C, trajectory_length]
# Time embedding
time_emb = self.time_encoder(t)
time_emb = self.time_mlp(time_emb)
# Initial convolution with replicate padding
x = nn.functional.pad(x, (1, 1), mode="replicate")
x = self.init_conv(x)
if self.use_position_encoding:
x = x + self.physical_position_encoding.to(dtype=x.dtype)
# Encoder with skip connections
skip_connections = []
for i in range(len(self.encoder_blocks)):
x = self.encoder_blocks[i](x, time_emb)
# Save skip connection before downsampling
if i < len(self.downsample):
skip_connections.append(x)
x = nn.functional.pad(x, (1, 1), mode="replicate")
x = self.downsample[i](x)
# Middle block
x = self.middle_block(x, time_emb)
# Decoder with skip connections
skip_idx = len(skip_connections) - 1
for i in range(len(self.decoder_blocks)):
# First decoder block doesn't get skip connection
if i > 0 and skip_idx >= 0:
# Upsample happened in previous iteration
skip = skip_connections[skip_idx]
# Match spatial dimensions if needed
if x.shape[2] != skip.shape[2]:
x = nn.functional.interpolate(
x, size=skip.shape[2], mode="linear", align_corners=True
)
x = torch.cat([x, skip], dim=1)
skip_idx -= 1
# Apply decoder block
x = self.decoder_blocks[i](x, time_emb)
# Upsample for next iteration (except last)
if i < len(self.upsample):
# Upsample, then apply padding before conv
upsample_block = cast(nn.Sequential, self.upsample[i])
upsample_layer = upsample_block[0]
conv_layer = upsample_block[1]
x = upsample_layer(x)
x = nn.functional.pad(x, (1, 1), mode="replicate")
x = conv_layer(x)
# Final projection with replicate padding
x = nn.functional.pad(x, (1, 1), mode="replicate")
x = self.final_conv(x)
x = x.squeeze(1) # [batch, trajectory_length]
return x
@staticmethod
def _build_physical_position_encoding(input_dim: int, hidden_dim: int) -> torch.Tensor:
"""Build a fixed encoding for physical trajectory positions."""
if input_dim <= 0:
raise ValueError("input_dim must be positive")
positions = torch.arange(input_dim, dtype=torch.float32).unsqueeze(1)
encoding = torch.zeros(input_dim, hidden_dim, dtype=torch.float32)
div_term = torch.exp(
torch.arange(0, hidden_dim, 2, dtype=torch.float32)
* (-math.log(10000.0) / max(hidden_dim, 1))
)
encoding[:, 0::2] = torch.sin(positions * div_term)
encoding[:, 1::2] = torch.cos(positions * div_term[: encoding[:, 1::2].shape[1]])
# Reserve one channel for a monotonic physical-time coordinate.
encoding[:, 0] = torch.linspace(-1.0, 1.0, input_dim, dtype=torch.float32)
return encoding.transpose(0, 1).unsqueeze(0)