File size: 12,087 Bytes
f1586f7 |
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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
# Copyright 2024 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Pytorch neural network definitions."""
from typing import Sequence, Union
import torch
from torch import nn
import torch.nn.functional as F
from models.utils import Conv2dSamePadding
class ExtraConvBlock(nn.Module):
"""Additional convolution block."""
def __init__(
self,
channel_dim,
channel_multiplier,
):
super().__init__()
self.channel_dim = channel_dim
self.channel_multiplier = channel_multiplier
self.layer_norm = nn.LayerNorm(
normalized_shape=channel_dim, elementwise_affine=True, bias=True
)
self.conv = nn.Conv2d(
self.channel_dim,
self.channel_dim * self.channel_multiplier,
kernel_size=3,
stride=1,
padding=1,
)
self.conv_1 = nn.Conv2d(
self.channel_dim * self.channel_multiplier,
self.channel_dim,
kernel_size=3,
stride=1,
padding=1,
)
def forward(self, x):
x = self.layer_norm(x)
x = x.permute(0, 3, 1, 2)
res = self.conv(x)
res = F.gelu(res, approximate='tanh')
x = x + self.conv_1(res)
x = x.permute(0, 2, 3, 1)
return x
class ExtraConvs(nn.Module):
"""Additional CNN."""
def __init__(
self,
num_layers=5,
channel_dim=256,
channel_multiplier=4,
):
super().__init__()
self.num_layers = num_layers
self.channel_dim = channel_dim
self.channel_multiplier = channel_multiplier
self.blocks = nn.ModuleList()
for _ in range(self.num_layers):
self.blocks.append(
ExtraConvBlock(self.channel_dim, self.channel_multiplier)
)
def forward(self, x):
for block in self.blocks:
x = block(x)
return x
class ConvChannelsMixer(nn.Module):
"""Linear activation block for PIPs's MLP Mixer."""
def __init__(self, in_channels):
super().__init__()
self.mlp2_up = nn.Linear(in_channels, in_channels * 4)
self.mlp2_down = nn.Linear(in_channels * 4, in_channels)
def forward(self, x):
x = self.mlp2_up(x)
x = F.gelu(x, approximate='tanh')
x = self.mlp2_down(x)
return x
class PIPsConvBlock(nn.Module):
"""Convolutional block for PIPs's MLP Mixer."""
def __init__(
self, in_channels, kernel_shape=3, use_causal_conv=False, block_idx=None
):
super().__init__()
self.use_causal_conv = use_causal_conv
self.block_name = f'block_{block_idx}'
self.kernel_shape = kernel_shape
self.layer_norm = nn.LayerNorm(
normalized_shape=in_channels, elementwise_affine=True, bias=False
)
self.mlp1_up = nn.Conv1d(
in_channels,
in_channels * 4,
kernel_shape,
stride=1,
padding=0 if self.use_causal_conv else 1,
groups=in_channels,
)
self.mlp1_up_1 = nn.Conv1d(
in_channels * 4,
in_channels * 4,
kernel_shape,
stride=1,
padding=0 if self.use_causal_conv else 1,
groups=in_channels * 4,
)
self.layer_norm_1 = nn.LayerNorm(
normalized_shape=in_channels, elementwise_affine=True, bias=False
)
self.conv_channels_mixer = ConvChannelsMixer(in_channels)
def forward(self, x, causal_context=None, get_causal_context=False):
to_skip = x
x = self.layer_norm(x)
new_causal_context = {}
num_extra = 0
if causal_context is not None:
name1 = self.block_name + '_causal_1'
x = torch.cat([causal_context[name1], x], dim=-2)
num_extra = causal_context[name1].shape[-2]
new_causal_context[name1] = x[..., -(self.kernel_shape - 1) :, :]
x = x.permute(0, 2, 1)
if self.use_causal_conv:
x = F.pad(x, (2, 0))
x = self.mlp1_up(x)
x = F.gelu(x, approximate='tanh')
if causal_context is not None:
x = x.permute(0, 2, 1)
name2 = self.block_name + '_causal_2'
num_extra = causal_context[name2].shape[-2]
x = torch.cat([causal_context[name2], x[..., num_extra:, :]], dim=-2)
new_causal_context[name2] = x[..., -(self.kernel_shape - 1) :, :]
x = x.permute(0, 2, 1)
if self.use_causal_conv:
x = F.pad(x, (2, 0))
x = self.mlp1_up_1(x)
x = x.permute(0, 2, 1)
if causal_context is not None:
x = x[..., num_extra:, :]
x = x[..., 0::4] + x[..., 1::4] + x[..., 2::4] + x[..., 3::4]
x = x + to_skip
to_skip = x
x = self.layer_norm_1(x)
x = self.conv_channels_mixer(x)
x = x + to_skip
return x, new_causal_context
class PIPSMLPMixer(nn.Module):
"""Depthwise-conv version of PIPs's MLP Mixer."""
def __init__(
self,
input_channels: int,
output_channels: int,
hidden_dim: int = 512,
num_blocks: int = 12,
kernel_shape: int = 3,
use_causal_conv: bool = False,
):
"""Inits Mixer module.
A depthwise-convolutional version of a MLP Mixer for processing images.
Args:
input_channels (int): The number of input channels.
output_channels (int): The number of output channels.
hidden_dim (int, optional): The dimension of the hidden layer. Defaults
to 512.
num_blocks (int, optional): The number of convolution blocks in the
mixer. Defaults to 12.
kernel_shape (int, optional): The size of the kernel in the convolution
blocks. Defaults to 3.
use_causal_conv (bool, optional): Whether to use causal convolutions.
Defaults to False.
"""
super().__init__()
self.hidden_dim = hidden_dim
self.num_blocks = num_blocks
self.use_causal_conv = use_causal_conv
self.linear = nn.Linear(input_channels, self.hidden_dim)
self.layer_norm = nn.LayerNorm(
normalized_shape=hidden_dim, elementwise_affine=True, bias=False
)
self.linear_1 = nn.Linear(hidden_dim, output_channels)
self.blocks = nn.ModuleList([
PIPsConvBlock(
hidden_dim, kernel_shape, self.use_causal_conv, block_idx=i
)
for i in range(num_blocks)
])
def forward(self, x, causal_context=None, get_causal_context=False):
x = self.linear(x)
all_causal_context = {}
for block in self.blocks:
x, new_causal_context = block(x, causal_context, get_causal_context)
if get_causal_context:
all_causal_context.update(new_causal_context)
x = self.layer_norm(x)
x = self.linear_1(x)
return x, all_causal_context
class BlockV2(nn.Module):
"""ResNet V2 block."""
def __init__(
self,
channels_in: int,
channels_out: int,
stride: Union[int, Sequence[int]],
use_projection: bool,
):
super().__init__()
self.padding = (1, 1, 1, 1)
# Handle assymetric padding created by padding="SAME" in JAX/LAX
if stride == 1:
self.padding = (1, 1, 1, 1)
elif stride == 2:
self.padding = (0, 2, 0, 2)
else:
raise ValueError(
'Check correct padding using padtype_to_padsin jax._src.lax.lax'
)
self.use_projection = use_projection
if self.use_projection:
self.proj_conv = Conv2dSamePadding(
in_channels=channels_in,
out_channels=channels_out,
kernel_size=1,
stride=stride,
padding=0,
bias=False,
)
self.bn_0 = nn.InstanceNorm2d(
num_features=channels_in,
eps=1e-05,
momentum=0.1,
affine=True,
track_running_stats=False,
)
self.conv_0 = Conv2dSamePadding(
in_channels=channels_in,
out_channels=channels_out,
kernel_size=3,
stride=stride,
padding=0,
bias=False,
)
self.conv_1 = Conv2dSamePadding(
in_channels=channels_out,
out_channels=channels_out,
kernel_size=3,
stride=1,
padding=1,
bias=False,
)
self.bn_1 = nn.InstanceNorm2d(
num_features=channels_out,
eps=1e-05,
momentum=0.1,
affine=True,
track_running_stats=False,
)
def forward(self, inputs):
x = shortcut = inputs
x = self.bn_0(x)
x = torch.relu(x)
if self.use_projection:
shortcut = self.proj_conv(x)
x = self.conv_0(x)
x = self.bn_1(x)
x = torch.relu(x)
# no issues with padding here as this layer always has stride 1
x = self.conv_1(x)
return x + shortcut
class BlockGroup(nn.Module):
"""Higher level block for ResNet implementation."""
def __init__(
self,
channels_in: int,
channels_out: int,
num_blocks: int,
stride: Union[int, Sequence[int]],
use_projection: bool,
):
super().__init__()
blocks = []
for i in range(num_blocks):
blocks.append(
BlockV2(
channels_in=channels_in if i == 0 else channels_out,
channels_out=channels_out,
stride=(1 if i else stride),
use_projection=(i == 0 and use_projection),
)
)
self.blocks = nn.ModuleList(blocks)
def forward(self, inputs):
out = inputs
for block in self.blocks:
out = block(out)
return out
class ResNet(nn.Module):
"""ResNet model."""
def __init__(
self,
blocks_per_group: Sequence[int],
channels_per_group: Sequence[int] = (64, 128, 256, 512),
use_projection: Sequence[bool] = (True, True, True, True),
strides: Sequence[int] = (1, 2, 2, 2),
):
"""Initializes a ResNet model with customizable layers and configurations.
This constructor allows defining the architecture of a ResNet model by
setting the number of blocks, channels, projection usage, and strides for
each group of blocks within the network. It provides flexibility in
creating various ResNet configurations.
Args:
blocks_per_group: A sequence of 4 integers, each indicating the number
of residual blocks in each group.
channels_per_group: A sequence of 4 integers, each specifying the number
of output channels for the blocks in each group. Defaults to (64, 128,
256, 512).
use_projection: A sequence of 4 booleans, each indicating whether to use
a projection shortcut (True) or an identity shortcut (False) in each
group. Defaults to (True, True, True, True).
strides: A sequence of 4 integers, each specifying the stride size for
the convolutions in each group. Defaults to (1, 2, 2, 2).
The ResNet model created will have 4 groups, with each group's
architecture defined by the corresponding elements in these sequences.
"""
super().__init__()
self.initial_conv = Conv2dSamePadding(
in_channels=3,
out_channels=channels_per_group[0],
kernel_size=(7, 7),
stride=2,
padding=0,
bias=False,
)
block_groups = []
for i, _ in enumerate(strides):
block_groups.append(
BlockGroup(
channels_in=channels_per_group[i - 1] if i > 0 else 64,
channels_out=channels_per_group[i],
num_blocks=blocks_per_group[i],
stride=strides[i],
use_projection=use_projection[i],
)
)
self.block_groups = nn.ModuleList(block_groups)
def forward(self, inputs):
result = {}
out = inputs
out = self.initial_conv(out)
result['initial_conv'] = out
for block_id, block_group in enumerate(self.block_groups):
out = block_group(out)
result[f'resnet_unit_{block_id}'] = out
return result |