File size: 4,552 Bytes
8aa674c |
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 |
import torch
import torch.nn as nn
from torch.nn.modules.batchnorm import _BatchNorm
from torchvision.models.video.resnet import VideoResNet, R2Plus1dStem, BasicBlock
from torch.utils import checkpoint as cp
from mmengine.registry import MODELS
@MODELS.register_module()
class ResNet2Plus1d_TSP(VideoResNet):
"""ResNet (2+1)d backbone.
This model is proposed in `A Closer Look at Spatiotemporal Convolutions for
Action Recognition <https://arxiv.org/abs/1711.11248>`_
"""
def __init__(
self,
layers=[3, 4, 6, 3],
pretrained=None,
norm_eval=True,
with_cp=False,
frozen_stages=-1, # depth 34
):
super().__init__(
block=BasicBlockCP if with_cp else BasicBlock,
conv_makers=[Conv2Plus1D] * 4,
layers=layers,
stem=R2Plus1dStem,
)
# We need exact Caffe2 momentum for BatchNorm scaling
for m in self.modules():
if isinstance(m, torch.nn.BatchNorm3d):
m.eps = 1e-3
m.momentum = 0.9
self.fc = nn.Sequential()
if pretrained != None:
checkpoint = torch.load(pretrained, map_location="cpu")
backbone_dict = {k[9:]: v for k, v in checkpoint["model"].items() if "fc" not in k}
self.load_state_dict(backbone_dict)
print("load pretrained model from {}".format(pretrained))
self.frozen_stages = frozen_stages
self.norm_eval = norm_eval
def _freeze_stages(self):
"""Prevent all the parameters from being optimized before
``self.frozen_stages``."""
if self.frozen_stages >= 0:
self.stem.eval()
for m in self.stem.modules():
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, f"layer{i}")
m.eval()
for param in m.parameters():
param.requires_grad = False
def _norm_eval(self):
if self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval()
def forward(self, x):
self._freeze_stages()
self._norm_eval()
x = self.stem(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
return x
class Conv2Plus1D(nn.Sequential):
def __init__(self, in_planes, out_planes, midplanes, stride=1, padding=1):
midplanes = (in_planes * out_planes * 3 * 3 * 3) // (in_planes * 3 * 3 + 3 * out_planes)
super(Conv2Plus1D, self).__init__(
nn.Conv3d(
in_planes,
midplanes,
kernel_size=(1, 3, 3),
stride=(1, stride, stride),
padding=(0, padding, padding),
bias=False,
),
nn.BatchNorm3d(midplanes),
nn.ReLU(inplace=True),
nn.Conv3d(
midplanes,
out_planes,
kernel_size=(3, 1, 1),
stride=(stride, 1, 1),
padding=(padding, 0, 0),
bias=False,
),
)
@staticmethod
def get_downsample_stride(stride):
return (stride, stride, stride)
class BasicBlockCP(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, conv_builder, stride=1, downsample=None):
midplanes = (inplanes * planes * 3 * 3 * 3) // (inplanes * 3 * 3 + 3 * planes)
super(BasicBlockCP, self).__init__()
self.conv1 = nn.Sequential(
conv_builder(inplanes, planes, midplanes, stride),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True),
)
self.conv2 = nn.Sequential(conv_builder(planes, planes, midplanes), nn.BatchNorm3d(planes))
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
def _inner_forward(x):
"""Forward wrapper for utilizing checkpoint."""
residual = x
out = self.conv1(x)
out = self.conv2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
return out
if x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
|