Certainly! Below is the updated code for a UNet-like architecture where each stage consists of small DiT (Diffusion Transformer) blocks. I have improved the variable naming for better readability and have added comments to explain the reasoning behind each step.
import torch
import torch.nn as nn
import torch.nn.functional as F
class AdaLN(nn.Module):
"""
Adaptive Layer Normalization with learned affine parameters conditioned on external information.
Args:
condition_channels (int): Number of channels in the conditioning information.
channels (int): Number of channels in the input tensor.
skip (bool): If True, skip the module and return input as is.
"""
def __init__(self, condition_channels, channels, skip=False):
super().__init__()
self.norm = nn.GroupNorm(1, channels)
self.proj_gamma = nn.Conv2d(condition_channels, channels, kernel_size=1)
self.proj_beta = nn.Conv2d(condition_channels, channels, kernel_size=1)
self.skip = skip
def forward(self, x, condition):
if self.skip:
return x
gamma = self.proj_gamma(condition)
beta = self.proj_beta(condition)
x = self.norm(x)
x = x * gamma + beta
return x
class LayerScale(nn.Module):
"""
Layer scale module to control the outputs of residual connections.
Args:
channels (int): Number of channels in the input tensor.
init_values (float): Initial scaling factor.
"""
def __init__(self, channels, init_values=1e-5):
super().__init__()
self.gamma = nn.Parameter(init_values * torch.ones(channels))
def forward(self, x):
return x * self.gamma.view(1, -1, 1, 1)
class RoPEAttention(nn.Module):
"""
Rotary Position Embedding (RoPE) Attention module implementing multi-head attention with RoPE.
Args:
channels (int): Number of input and output channels.
num_heads (int): Number of attention heads.
base_resolution (int): The base resolution around which RoPE will be scaled.
"""
def __init__(self, channels, num_heads, base_resolution):
super().__init__()
self.channels = channels
self.num_heads = num_heads
self.base_resolution = base_resolution
self.head_dim = channels // num_heads
# Linear projections for queries, keys, and values
self.q_proj = nn.Conv2d(channels, channels, kernel_size=1)
self.k_proj = nn.Conv2d(channels, channels, kernel_size=1)
self.v_proj = nn.Conv2d(channels, channels, kernel_size=1)
self.out_proj = nn.Conv2d(channels, channels, kernel_size=1)
# Layer normalization for queries and keys
self.q_layer_norm = nn.GroupNorm(1, num_heads)
self.k_layer_norm = nn.GroupNorm(1, num_heads)
def create_rotation_matrix(self, height, width, channels):
"""
Creates a rotation matrix for applying RoPE to queries and keys.
Args:
height (int): Height of the input feature map.
width (int): Width of the input feature map.
channels (int): Number of channels in the input tensor.
"""
# Compute scaling factors for height and width
scaling_h = height / self.base_resolution if height > self.base_resolution else 1.0
scaling_w = width / self.base_resolution if width > self.base_resolution else 1.0
# Create position indices
t = torch.arange(height * width, dtype=torch.float32)
t_x = (t % width).float()
t_y = torch.div(t, width, rounding_mode='floor').float()
# Compute frequency bands
freqs_x = 1.0 / ((100.0 * scaling_w) ** (torch.arange(0, channels, 2).float() / channels))
freqs_y = 1.0 / ((100.0 * scaling_h) ** (torch.arange(0, channels, 2).float() / channels))
freqs_x = torch.outer(t_x, freqs_x)
freqs_y = torch.outer(t_y, freqs_y)
# Construct complex exponential embeddings
freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
freqs_cis = torch.cat([freqs_cis_x, freqs_cis_y], dim=-1)
freqs_cis = freqs_cis.view(height, width, channels)
return freqs_cis
def rotate_queries_and_keys(self, queries, keys):
"""
Applies RoPE rotation to queries and keys.
Args:
queries (Tensor): Projected queries.
keys (Tensor): Projected keys.
"""
batch_size, channels, height, width = queries.shape
freqs_cis = self.create_rotation_matrix(height, width, channels).to(queries.device)
# Reshape to (batch_size, height, width, channels)
queries = queries.permute(0, 2, 3, 1).contiguous()
keys = keys.permute(0, 2, 3, 1).contiguous()
# Apply the rotation embeddings
queries_rotated = queries * freqs_cis.real - queries.roll(shifts=1, dims=-1) * freqs_cis.imag
keys_rotated = keys * freqs_cis.real - keys.roll(shifts=1, dims=-1) * freqs_cis.imag
# Reshape back to (batch_size, channels, height, width)
queries_rotated = queries_rotated.permute(0, 3, 1, 2)
keys_rotated = keys_rotated.permute(0, 3, 1, 2)
return queries_rotated, keys_rotated
def forward(self, x):
batch_size, channels, height, width = x.shape
# Project inputs to queries, keys, and values
queries = self.q_proj(x)
keys = self.k_proj(x)
values = self.v_proj(x)
# Apply RoPE rotation to queries and keys
queries, keys = self.rotate_queries_and_keys(queries, keys)
# Reshape for multi-head attention
# Shape: (batch_size, num_heads, seq_length, head_dim)
seq_length = height * width
queries = queries.view(batch_size, self.num_heads, self.head_dim, seq_length).permute(0, 1, 3, 2)
keys = keys.view(batch_size, self.num_heads, self.head_dim, seq_length).permute(0, 1, 3, 2)
values = values.view(batch_size, self.num_heads, self.head_dim, seq_length).permute(0, 1, 3, 2)
# Apply layer normalization to queries and keys
queries = self.q_layer_norm(queries)
keys = self.k_layer_norm(keys)
# Use scaled dot-product attention
with torch.backends.cuda.sdp_kernel(enable_flash=True):
attention_output = nn.functional.scaled_dot_product_attention(queries, keys, values)
# Reshape back to (batch_size, channels, height, width)
attention_output = attention_output.permute(0, 1, 3, 2).contiguous()
attention_output = attention_output.view(batch_size, channels, height, width)
# Project output back to channels
output = self.out_proj(attention_output)
return output
class DiTBlock(nn.Module):
"""
A single block of the Diffusion Transformer (DiT) with attention and MLP layers.
Args:
channels (int): Number of input/output channels.
num_heads (int): Number of attention heads.
condition_channels (int): Number of conditioning channels.
"""
def __init__(self, channels, num_heads, condition_channels):
super().__init__()
# Adaptive Layer Normalization with conditioning
self.norm1 = AdaLN(condition_channels, channels)
# GroupNorm without conditioning
self.norm2 = nn.GroupNorm(1, channels, eps=1e-6)
# Attention module
self.attention = RoPEAttention(channels, num_heads, base_resolution=8)
# MLP module
self.mlp = nn.Sequential(
nn.Conv2d(channels, channels * 4, kernel_size=1),
nn.GELU(),
nn.Conv2d(channels * 4, channels, kernel_size=1)
)
# Layer scaling for residual connections
self.layer_scale1 = LayerScale(channels, init_values=0.0)
self.layer_scale2 = LayerScale(channels, init_values=0.0)
def forward(self, x, condition):
# First residual connection
residual = x
x = self.norm1(x, condition)
x = self.attention(x)
x = self.layer_scale1(x) + residual
# Second residual connection
residual = x
x = self.norm2(x)
x = self.mlp(x)
x = self.layer_scale2(x) + residual
return x
class DiTUNet(nn.Module):
"""
UNet-like architecture using DiT blocks at each downsampling and upsampling step.
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
condition_channels (int): Number of conditioning channels.
num_blocks (int): Number of DiT blocks at each level.
base_channels (int): Number of channels in the first level.
channel_multipliers (list[int]): Multipliers for the number of channels at each level.
num_heads (int): Number of attention heads.
"""
def __init__(self,
in_channels,
out_channels,
condition_channels,
num_blocks,
base_channels=64,
channel_multipliers=[1, 2, 4, 8],
num_heads=8):
super().__init__()
self.num_levels = len(channel_multipliers)
self.downsampling_layers = nn.ModuleList()
self.upsampling_layers = nn.ModuleList()
self.encoder_blocks = nn.ModuleList()
self.decoder_blocks = nn.ModuleList()
self.condition_channels = condition_channels
# Initial convolution to convert input to base_channels
self.input_conv = nn.Conv2d(in_channels, base_channels, kernel_size=3, padding=1)
# Downsampling path
channels = base_channels
for i in range(self.num_levels):
out_channels = channels * channel_multipliers[i]
# Downsampling layer using stride 2 convolution
downsample = nn.Conv2d(channels, out_channels, kernel_size=4, stride=2, padding=1)
self.downsampling_layers.append(downsample)
# Stack of DiT blocks at this level
blocks = nn.ModuleList([DiTBlock(out_channels, num_heads, condition_channels) for _ in range(num_blocks)])
self.encoder_blocks.append(blocks)
channels = out_channels
# Bottleneck DiT blocks
self.bottleneck = nn.ModuleList([DiTBlock(channels, num_heads, condition_channels) for _ in range(num_blocks)])
# Upsampling path
for i in reversed(range(self.num_levels)):
in_channels = channels
out_channels = base_channels * channel_multipliers[i]
# Upsampling layer using transposed convolution
upsample = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=1)
self.upsampling_layers.append(upsample)
# Stack of DiT blocks at this level
blocks = nn.ModuleList([DiTBlock(out_channels, num_heads, condition_channels) for _ in range(num_blocks)])
self.decoder_blocks.append(blocks)
channels = out_channels
# Final convolution to convert to desired output channels
self.output_conv = nn.Conv2d(channels, out_channels, kernel_size=3, padding=1)
def forward(self, x, condition):
# Initial convolution
x = self.input_conv(x)
skip_connections = []
# Encoder path
for downsample, blocks in zip(self.downsampling_layers, self.encoder_blocks):
x = downsample(x)
for block in blocks:
x = block(x, condition)
skip_connections.append(x)
# Bottleneck
for block in self.bottleneck:
x = block(x, condition)
# Decoder path
for upsample, blocks, skip in zip(self.upsampling_layers, self.decoder_blocks, reversed(skip_connections)):
x = upsample(x)
x = x + skip # Add skip connection
for block in blocks:
x = block(x, condition)
# Output convolution
x = self.output_conv(x)
return x
Explanation and Reasoning:
-
AdaLN Module:
- Implements Adaptive Layer Normalization conditioned on external information.
- The external condition (e.g., time step embeddings or other conditional inputs) is projected to compute affine transformation parameters
gamma and beta.
- These parameters are used to scale and shift the normalized input.
-
LayerScale Module:
- Introduced to scale the output of residual connections, which can help in model convergence.
- A learnable parameter
gamma initializes close to zero, allowing the model to learn the optimal scaling during training.
-
RoPEAttention Module:
- Implements multi-head attention with Rotary Position Embeddings (RoPE) for better positional encoding.
- The
create_rotation_matrix function computes the rotation matrices that are applied to the queries and keys.
- Scaled dot-product attention is computed using the rotated queries and keys.
-
DiTBlock Module:
- Comprises an attention layer followed by an MLP, with residual connections and appropriate normalizations.
- Uses
AdaLN for conditioning on external information before the attention layer.
- The
LayerScale modules are applied after each residual connection.
-
DiTUNet Module:
- Implements a UNet-like architecture with encoder and decoder paths.
- Encoder Path:
- Consists of downsampling layers followed by DiT blocks.
- Each downsampling layer reduces spatial dimensions by a factor of 2.
- Skip connections are collected to be used in the decoder path.
- Bottleneck:
- DiT blocks that process the lowest-resolution feature maps.
- Decoder Path:
- Upsampling layers increase spatial dimensions by a factor of 2.
- Skip connections from the encoder path are added to the corresponding decoder layer outputs.
- DiT blocks process the combined features.
- Final Output:
- A convolution layer maps the features to the desired number of output channels.
Variable Naming Improvements:
- Used full, descriptive names like
condition_channels, num_heads, channel_multipliers, etc., for better clarity.
- Functions and variables within modules have been renamed to clearly indicate their purpose, e.g.,
create_rotation_matrix, rotate_queries_and_keys.
Why Certain Decisions Were Made:
- Convolutional Downsampling/Upsampling:
- Convolutions with stride 2 are used for downsampling to efficiently reduce spatial dimensions while learning features.
- Transposed convolutions are used for upsampling to increase spatial dimensions and learn to reconstruct higher-resolution features.
- Skip Connections:
- Essential in UNet architectures to preserve spatial information that might be lost during downsampling.
- They help in combining low-level spatial information with high-level features during upsampling.
- DiT Blocks in Each Stage:
- Using DiT blocks at each stage allows the model to capture complex dependencies at multiple scales.
- Stacking multiple DiT blocks can improve the model's capacity to learn intricate patterns.
- Conditioning Information:
- The
condition input allows the model to be conditioned on external information, such as time steps in diffusion models or class labels.
- This conditioning is integrated through the
AdaLN layers within the DiT blocks.
Usage Example:
To instantiate the DiTUNet model:
# Define model parameters
in_channels = 3
out_channels = 3
condition_channels = 128
num_blocks = 2
base_channels = 64
channel_multipliers = [1, 2, 4, 8]
num_heads = 8
# Create the model
model = DiTUNet(
in_channels=in_channels,
out_channels=out_channels,
condition_channels=condition_channels,
num_blocks=num_blocks,
base_channels=base_channels,
channel_multipliers=channel_multipliers,
num_heads=num_heads
)
# Example input tensors
x = torch.randn(1, in_channels, 256, 256) # Input image
condition = torch.randn(1, condition_channels, 1, 1) # Conditioning information
# Forward pass
output = model(x, condition)
This code provides a UNet-like architecture where each step is a small DiT block, with improved variable naming and explanations for clarity.