1from typing import Optional, Sequence
2
3import torch
4from torch import nn
5from torch.nn import functional as F
6
7from diffusion_models.gaussian_diffusion.base_diffuser import BaseDiffuser
8from diffusion_models.models.base_diffusion_model import BaseDiffusionModel
9from diffusion_models.models.SimpleUnet import SinusoidalPositionEmbeddings
10
11
[docs]
12class ResidualBlock(nn.Module):
13 def __init__(
14 self,
15 in_channels: int,
16 out_channels: int,
17 time_emb_dim: int,
18 num_groups: int,
19 dropout: float,
20 ):
21 """A GroupNorm residual block conditioned on the timestep embedding."""
22 super().__init__()
[docs]
23 self.norm1 = nn.GroupNorm(num_groups, in_channels)
[docs]
24 self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
[docs]
25 self.time_proj = nn.Linear(time_emb_dim, out_channels)
[docs]
26 self.norm2 = nn.GroupNorm(num_groups, out_channels)
[docs]
27 self.dropout = nn.Dropout(dropout)
[docs]
28 self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
[docs]
29 self.skip = (
30 nn.Conv2d(in_channels, out_channels, 1)
31 if in_channels != out_channels
32 else nn.Identity()
33 )
34
[docs]
35 def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
36 h = self.conv1(F.silu(self.norm1(x)))
37 h = h + self.time_proj(F.silu(t))[:, :, None, None]
38 h = self.conv2(self.dropout(F.silu(self.norm2(h))))
39 return h + self.skip(x)
40
41
[docs]
42class SelfAttention2d(nn.Module):
43 def __init__(self, channels: int, num_groups: int, num_heads: int = 4):
44 """Multi-head self-attention over the spatial positions of a feature map."""
45 super().__init__()
[docs]
46 self.num_heads = num_heads
[docs]
47 self.norm = nn.GroupNorm(num_groups, channels)
[docs]
48 self.qkv = nn.Conv2d(channels, 3 * channels, 1)
[docs]
49 self.proj = nn.Conv2d(channels, channels, 1)
50
[docs]
51 def forward(self, x: torch.Tensor) -> torch.Tensor:
52 batch, channels, height, width = x.shape
53 qkv = self.qkv(self.norm(x))
54 qkv = qkv.reshape(batch, 3, self.num_heads, -1, height * width)
55 query, key, value = (
56 qkv[:, i].transpose(-1, -2) for i in range(3)
57 ) # (B, heads, HW, C / heads)
58 h = F.scaled_dot_product_attention(query, key, value)
59 h = h.transpose(-1, -2).reshape(batch, channels, height, width)
60 return x + self.proj(h)
61
62
[docs]
63class Downsample(nn.Module):
64 def __init__(self, channels: int):
65 super().__init__()
[docs]
66 self.conv = nn.Conv2d(channels, channels, 3, stride=2, padding=1)
67
[docs]
68 def forward(self, x: torch.Tensor) -> torch.Tensor:
69 return self.conv(x)
70
71
[docs]
72class Upsample(nn.Module):
73 def __init__(self, channels: int):
74 super().__init__()
[docs]
75 self.conv = nn.Conv2d(channels, channels, 3, padding=1)
76
[docs]
77 def forward(self, x: torch.Tensor) -> torch.Tensor:
78 return self.conv(F.interpolate(x, scale_factor=2.0, mode="nearest"))
79
80
81class _Stage(nn.Module):
82 """A residual block optionally followed by self-attention."""
83
84 def __init__(self, block: ResidualBlock, attention: Optional[nn.Module]):
85 super().__init__()
86 self.block = block
87 self.attention = attention if attention is not None else nn.Identity()
88
89 def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
90 return self.attention(self.block(x, t))
91
92
[docs]
93class SmallAttentionUnet(BaseDiffusionModel):
94 def __init__(
95 self,
96 diffuser: BaseDiffuser,
97 image_channels: int,
98 base_channels: int = 64,
99 channel_multipliers: Sequence[int] = (1, 2, 4, 4),
100 num_res_blocks: int = 2,
101 attention_levels: int = 2,
102 num_groups: int = 32,
103 dropout: float = 0.0,
104 ):
105 """A small DDPM-style Unet with GroupNorm and low-resolution attention.
106
107 Compared to :class:`~.SimpleUnet.SimpleUnet`, this model uses GroupNorm
108 (so training and evaluation behave identically, which matters for
109 sampling and EMA), residual blocks, and self-attention only at the lowest
110 ``attention_levels`` resolutions. With the defaults it has roughly 25M
111 parameters and fits comfortably on a small GPU at 64x64.
112
113 Args:
114 diffuser: A gaussian diffuser.
115 image_channels: The number of image channels.
116 base_channels: The channel count at the highest resolution.
117 channel_multipliers: Per level channel multiplier. Every level but the
118 first halves the resolution.
119 num_res_blocks: The number of residual blocks per level (down path).
120 attention_levels: The number of lowest-resolution levels (and the
121 bottleneck) which get self-attention.
122 num_groups: The number of GroupNorm groups.
123 dropout: The dropout probability inside residual blocks.
124 """
125 super().__init__(diffuser=diffuser)
126 channels = [base_channels * m for m in channel_multipliers]
127 if any(c % num_groups for c in channels):
128 raise ValueError(
129 f"All channel counts {channels} must be divisible by {num_groups}."
130 )
131 time_emb_dim = base_channels * 4
132 number_of_levels = len(channels)
133 attention_start = number_of_levels - attention_levels
134
135 def stage(in_ch: int, out_ch: int, level: int) -> _Stage:
136 return _Stage(
137 ResidualBlock(in_ch, out_ch, time_emb_dim, num_groups, dropout),
138 SelfAttention2d(out_ch, num_groups)
139 if level >= attention_start
140 else None,
141 )
142
[docs]
143 self.time_mlp = nn.Sequential(
144 SinusoidalPositionEmbeddings(base_channels),
145 nn.Linear(base_channels, time_emb_dim),
146 nn.SiLU(),
147 nn.Linear(time_emb_dim, time_emb_dim),
148 )
[docs]
149 self.conv_in = nn.Conv2d(image_channels, base_channels, 3, padding=1)
150
[docs]
151 self.down_stages = nn.ModuleList()
[docs]
152 self.downsamples = nn.ModuleList()
153 skip_channels = [base_channels]
154 current = base_channels
155 for level, out_ch in enumerate(channels):
156 for _ in range(num_res_blocks):
157 self.down_stages.append(stage(current, out_ch, level))
158 current = out_ch
159 skip_channels.append(current)
160 if level != number_of_levels - 1:
161 self.downsamples.append(Downsample(current))
162 skip_channels.append(current)
163
[docs]
164 self.mid_block1 = stage(current, current, number_of_levels - 1)
[docs]
165 self.mid_block2 = ResidualBlock(
166 current, current, time_emb_dim, num_groups, dropout
167 )
168
[docs]
169 self.up_stages = nn.ModuleList()
[docs]
170 self.upsamples = nn.ModuleList()
171 for level, out_ch in reversed(list(enumerate(channels))):
172 for _ in range(num_res_blocks + 1):
173 self.up_stages.append(
174 stage(current + skip_channels.pop(), out_ch, level)
175 )
176 current = out_ch
177 if level != 0:
178 self.upsamples.append(Upsample(current))
179
[docs]
180 self.num_res_blocks = num_res_blocks
[docs]
181 self.norm_out = nn.GroupNorm(num_groups, current)
[docs]
182 self.conv_out = nn.Conv2d(current, image_channels, 3, padding=1)
183
[docs]
184 def forward(
185 self,
186 x: torch.Tensor,
187 timestep: torch.Tensor,
188 labels: Optional[torch.Tensor] = None,
189 ) -> torch.Tensor:
190 t = self.time_mlp(timestep)
191 x = self.conv_in(x)
192 skips = [x]
193
194 stages = iter(self.down_stages)
195 for level in range(len(self.downsamples) + 1):
196 for _ in range(self.num_res_blocks):
197 x = next(stages)(x, t)
198 skips.append(x)
199 if level < len(self.downsamples):
200 x = self.downsamples[level](x)
201 skips.append(x)
202
203 x = self.mid_block2(self.mid_block1(x, t), t)
204
205 stages = iter(self.up_stages)
206 for level in range(len(self.upsamples) + 1):
207 for _ in range(self.num_res_blocks + 1):
208 x = next(stages)(torch.cat((x, skips.pop()), dim=1), t)
209 if level < len(self.upsamples):
210 x = self.upsamples[level](x)
211
212 return self.conv_out(F.silu(self.norm_out(x)))