开局一张图,首先抛出resnet18的网络架构(完整版放在文章最下方)
下面,再配合pytorch官方代码,解析一下resnet18。以resnet18为切入点,由浅入深,理解resnet架构
源码解析
demo
import torch
import torchvision.models as models
resnet18 = models.resnet18()
input = torch.randn(32,3,224,224)
output = resnet18(input)
print(resnet18)
ctrl+鼠标左键点击resnet18,进入resnet.py文件下
映入眼帘的是resnet18的构造函数
#构造函数 conv1为 1 层,conv2、conv3、conv4、conv5均为 4 层(每个 layer 有 2 个 BasicBlock,每个 BasicBlock 有 2 个卷积层),总共为 16 层,最后一层全连接层,总层数=1 + 4 × 4 + 1 = 18,依此类推。
def resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
r"""ResNet-18 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
**kwargs)
构造函数用到了_resnet()
方法来创建网络
def _resnet(
arch: str,
block: Type[Union[BasicBlock, Bottleneck]],
layers: List[int],
pretrained: bool,
progress: bool,
**kwargs: Any
) -> ResNet:
model = ResNet(block, layers, **kwargs)
if pretrained: #加载预训练参数
state_dict = load_state_dict_from_url(model_urls[arch],
progress=progress)
model.load_state_dict(state_dict)
return model
在_resnet()
方法中,又调用了ResNet()
方法创建模型
class ResNet(nn.Module):
def __init__(
self,
block: Type[Union[BasicBlock, Bottleneck]],
layers: List[int],
num_classes: int = 1000,
zero_init_residual: bool = False,
groups: int = 1,
width_per_group: int = 64,
replace_stride_with_dilation: Optional[List[bool]] = None,
norm_layer: Optional[Callable[..., nn.Module]] = None
) -> None:
super(ResNet, self).__init__()
if norm_layer is None:#判断是否传入 norm_layer,没有传入,则使用 BatchNorm2d
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 64
self.dilation = 1
if replace_stride_with_dilation is None: #判断是否传入空洞卷积参数 replace_stride_with_dilation,如果不指定,则赋值为 [False, False, False],表示不使用空洞卷积。
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
self.groups = groups #读取分组卷积的参数
self.base_width = width_per_group
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0]) #这个 layer 的参数没有指定 stride,默认 stride=1,因此这个 layer 不会改变图片大小
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
dilate=replace_stride_with_dilation[0]) #这个layer的stride=2,会降采样
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
dilate=replace_stride_with_dilation[1]) #这个layer的stride=2,会降采样
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
dilate=replace_stride_with_dilation[2]) #这个layer的stride=2,会降采样
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
#网络参数初始化
for m in self.modules():
if isinstance(m, nn.Conv2d): #卷积层采用 kaiming_normal_() 初始化方法 参考:https://arxiv.org/abs/1502.01852
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): #bn 层和 GroupNorm 层初始化为 weight=1,bias=0
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
#每个 BasicBlock 和 Bottleneck 的最后一层 bn 的 weight=0,可以提升准确率 0.2~0.3%。
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type]
def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,
stride: int = 1, dilate: bool = False) -> nn.Sequential:
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:#判断空洞卷积,计算 previous_dilation 参数
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion: #判断 stride 是否为 1,输入通道和输出通道是否相等。如果这两个条件都不成立,那么表明需要建立一个 1 X 1 的卷积层,来改变通道数和改变图片大小。具体是建立 downsample 层,包括 conv1x1 -> norm_layer。
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
#建立第一个 block,把 downsample 传给 block 作为降采样的层,并且 stride 也使用传入的 stride(stride=2)
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion #改变通道数self.inplanes = planes * block.expansion。备注:在 BasicBlock 里,expansion=1,因此这一步不会改变通道数;在 Bottleneck 里,expansion=4,因此这一步会改变通道数
#图片经过第一个 block后,就会改变通道数和图片大小。接下来 for 循环添加剩下的 block。从第 2 个 block 起,输入和输出通道数是相等的,因此就不用传入 downsample 和 stride(那么 block 的 stride 默认使用 1)
for _ in range(1, blocks): #继续添加这个 layer 里接下来的 BasicBlock
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
def _forward_impl(self, x: Tensor) -> Tensor: #整个resnet18的前向传播结构,可以参考文章最后的完整结构图来理解
# See note [TorchScript super()]
x = self.conv1(x)
print("131254214")
print(x.size())
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
def forward(self, x: Tensor) -> Tensor:
return self._forward_impl(x)
可以看到,上面每个layer
都是使用_make_layer()
方法来创建层,下面来解析_make_layer()
def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,
stride: int = 1, dilate: bool = False) -> nn.Sequential:
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:#判断空洞卷积,计算 previous_dilation 参数
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion: #判断 stride 是否为 1,输入通道和输出通道是否相等。如果这两个条件都不成立,那么表明需要建立一个 1 X 1 的卷积层,来改变通道数和改变图片大小。具体是建立 downsample 层,包括 conv1x1 -> norm_layer。
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
#建立第一个 block,把 downsample 传给 block 作为降采样的层,并且 stride 也使用传入的 stride(stride=2)
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion #改变通道数self.inplanes = planes * block.expansion。备注:在 BasicBlock 里,expansion=1,因此这一步不会改变通道数;在 Bottleneck 里,expansion=4,因此这一步会改变通道数
#图片经过第一个 block后,就会改变通道数和图片大小。接下来 for 循环添加剩下的 block。从第 2 个 block 起,输入和输出通道数是相等的,因此就不用传入 downsample 和 stride(那么 block 的 stride 默认使用 1)
for _ in range(1, blocks): #继续添加这个 layer 里接下来的 BasicBlock
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
上面的过程如下图所示:
resnet18用的是BasicBlock
class BasicBlock(nn.Module):
expansion: int = 1
def __init__(
self,
inplanes: int,
planes: int,
stride: int = 1,
downsample: Optional[nn.Module] = None,
groups: int = 1,
base_width: int = 64,
dilation: int = 1,
norm_layer: Optional[Callable[..., nn.Module]] = None
) -> None:
super(BasicBlock, self).__init__()
if norm_layer is None: #判断是否传入了 norm_layer 层,如果没有,则使用 BatchNorm2d。
norm_layer = nn.BatchNorm2d
if groups != 1 or base_width != 64: #校验参数:groups == 1,base_width == 64,dilation == 1。也就是说,在 BasicBlock 中,不使用空洞卷积和分组卷积。
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
if dilation > 1:
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv3x3(inplanes, planes, stride) #定义第 1 组 conv3x3 -> norm_layer -> relu,这里使用传入的 stride 和 inplanes。(如果是 layer2 ,layer3 ,layer4 里的第一个 BasicBlock,那么 stride=2,这里会降采样和改变通道数)。
self.bn1 = norm_layer(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes) #定义第 2 组 conv3x3 -> norm_layer -> relu,这里不使用传入的 stride (默认为 1),输入通道数和输出通道数使用planes,也就是不需要降采样和改变通道数。
self.bn2 = norm_layer(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x: Tensor) -> Tensor:
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
备注:resnet18,34用的是BasicBlock,而resnet50,101等都用的是Bottleneck结构
Bottleneck结构源码如下:
class Bottleneck(nn.Module):
# Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
# while original implementation places the stride at the first 1x1 convolution(self.conv1)
# according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
# This variant is also known as ResNet V1.5 and improves accuracy according to
# https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
expansion: int = 4
def __init__(
self,
inplanes: int,
planes: int,
stride: int = 1,
downsample: Optional[nn.Module] = None,
groups: int = 1,
base_width: int = 64,
dilation: int = 1,
norm_layer: Optional[Callable[..., nn.Module]] = None
) -> None:
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups #计算 width,等于传入的 planes,用于中间的3 × 3卷积。
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv1x1(inplanes, width) #定义第 1 组 conv1x1 -> norm_layer,这里不使用传入的 stride,使用 width,作用是进行降维,减少通道数。
self.bn1 = norm_layer(width)
self.conv2 = conv3x3(width, width, stride, groups, dilation) #定义第 2 组 conv3x3 -> norm_layer,这里使用传入的 stride,输入通道数和输出通道数使用width。(如果是 layer2 ,layer3 ,layer4 里的第一个 Bottleneck,那么 stride=2,这里会降采样)。
self.bn2 = norm_layer(width)
self.conv3 = conv1x1(width, planes * self.expansion) #定义第 3 组 conv1x1 -> norm_layer,这里不使用传入的 stride,使用 planes * self.expansion,作用是进行升维,增加通道数。
self.bn3 = norm_layer(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x: Tensor) -> Tensor:
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
BasicBlock与Bottleneck的不同:
- BasicBlock 中有 1 个 3 × 3 3 \times 3 3×3卷积层,如果是 layer 的第一个 BasicBlock,那么第一个卷积层的 stride=2,作用是进行降采样。
- Bottleneck 中有 2 个 1 × 1 1 \times 1 1×1卷积层, 1 个 3 × 3 3 \times 3 3×3卷积层。先经过第 1 个 1 × 1 1 \times 1 1×1卷积层,进行降维,然后经过 3 × 3 3 \times 3 3×3卷积层(如果是 layer 的第一个 Bottleneck,那么 3 × 3 3 \times 3 3×3卷积层的 stride=2,作用是进行降采样),最后经过 1 × 1 1 \times 1 1×1卷积层,进行升维 。
最后抛出resnet18的完整架构图: