论文地址:https://arxiv.org/abs/1902.09212
官方源码:https://github.com/leoxiaobin/deep-high-resolution-net.pytorch
这里引用“太阳花的小绿豆”绘制的一张基于HRNet-32模型的结构图。便于后续理解。
重要的部分写在代码注释里了,阅读的时候注意。
def get_pose_net(cfg, is_train, **kwargs):
model = PoseHighResolutionNet(cfg, **kwargs)
if is_train and cfg['MODEL']['INIT_WEIGHTS']:
model.init_weights(cfg['MODEL']['PRETRAINED'])
return model
使用了PoseHighresolutionNet类,让我们进入到这个类看一下。
首先看forward函数:
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.layer1(x)
所对应的stem net为:
# stem net
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1,
bias=False)
self.bn1 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1,
bias=False)
self.bn2 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(Bottleneck, 64, 4)
这里经过两个卷积bn激活函数的操作,后接一个layer1模块,特征通道数下采样4倍,通道变为256.
其中layer1由_make_layer(Bottleneck, 64, 4)构建。
让我们看下_make_layer的具体操作。
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(
self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False
),
nn.BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
# 通道数由64变为256
self.inplanes = planes * block.expansion
# self.inplanes = 64 * 4 = 256
for i in range(1, blocks):
# 重复堆叠三次,不使用downsample,其实这里的downsample操作也并没有进行下采样。
# 输入通道数为256,输出通道数也为256
# 最后得到特征图的大小为下采样4倍,输出通道256的featuremap
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
Bottleneck类中expansion = 4, self.inplanes = 64 != 64 *4 执行downsample操作。注意这里downsample并没有对模型进行下采样,stride= 1,只是沿用了Resnet的名称,叫成了downsample。
Bottleneck的搭建如下代码:
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion,
momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = 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:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
其中Bottlenck的输入为inplanes,输出为4倍的planes。
STAGE2:
NUM_MODULES: 1
NUM_BRANCHES: 2
BLOCK: BASIC
NUM_BLOCKS:
- 4
- 4
NUM_CHANNELS:
- 32
- 64
FUSE_METHOD: SUM
x_list = []
# NUM_BRANCHES = 2
for i in range(self.stage2_cfg['NUM_BRANCHES']):
if self.transition1[i] is not None:
x_list.append(self.transition1[i](x))
else:
x_list.append(x)
y_list = self.stage2(x_list)
分为Transition模块和Stage模块,其中Transition模块是为了进行下采样,并联不同下采样倍率的操作,Stage模块则是进行特征融合。由低下采样倍率和高下采样倍率的特征图融合在一起。
所对应的 __ init __ 方法里的代码如下:
self.stage2_cfg = extra['STAGE2']
num_channels = self.stage2_cfg['NUM_CHANNELS']
# num_channels [32, 64]
block = blocks_dict[self.stage2_cfg['BLOCK']]
# basic block
num_channels = [
num_channels[i] * block.expansion for i in range(len(num_channels))
]
# num_channels [32 * 1, 64 * 1]
self.transition1 = self._make_transition_layer([256], num_channels)
self.stage2, pre_stage_channels = self._make_stage(
self.stage2_cfg, num_channels)
由_make_transision_layer函数定义
def _make_transition_layer(
self, num_channels_pre_layer, num_channels_cur_layer):
# num_channels_pre_layer 之前layer层的channels个数,在stage2之前是256
# num_channels_cur_layer 现在layer层的channels个数,在stage2为[32, 64]
num_branches_cur = len(num_channels_cur_layer) # 2
num_branches_pre = len(num_channels_pre_layer) # 1
transition_layers = []
# 对应图片上Transition1上的两层3 * 3卷积
for i in range(num_branches_cur): # i = 0, 1
if i < num_branches_pre:
if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
# 如果通道数不相等,则通过卷积层改变通道数
# 如果通道数相等,则无需卷积操作,可以直接使用,接到下面第一个else语句
transition_layers.append(
nn.Sequential(
nn.Conv2d(
num_channels_pre_layer[i],
num_channels_cur_layer[i],
3, 1, 1, bias=False
),
nn.BatchNorm2d(num_channels_cur_layer[i]),
nn.ReLU(inplace=True)
)
)
else:
# 对应Transition2, 3中不进行卷积操作的分支
transition_layers.append(None)
else:
# 对应Transition模块上多出的那一个分支,使用stride = 2 再进行下采样
conv3x3s = []
for j in range(i+1-num_branches_pre):
# 利用num_channels_pre_layer之前shape最小的特征层来生成新的分支
inchannels = num_channels_pre_layer[-1]
outchannels = num_channels_cur_layer[i] \
if j == i-num_branches_pre else inchannels
conv3x3s.append(
nn.Sequential(
nn.Conv2d(
inchannels, outchannels, 3, 2, 1, bias=False
),
# 这里卷积进行下采样,stride = 2
nn.BatchNorm2d(outchannels),
nn.ReLU(inplace=True)
)
)
transition_layers.append(nn.Sequential(*conv3x3s))
return nn.ModuleList(transition_layers)
由_make_stage函数定义:
def _make_stage(self, layer_config, num_inchannels,
multi_scale_output=True):
num_modules = layer_config['NUM_MODULES'] # 1
num_branches = layer_config['NUM_BRANCHES'] # 2
num_blocks = layer_config['NUM_BLOCKS'] # [4, 4]
num_channels = layer_config['NUM_CHANNELS'] # [32, 64]
block = blocks_dict[layer_config['BLOCK']] # BasicBlock
fuse_method = layer_config['FUSE_METHOD'] # SUM
modules = []
# num_modules 表示一个stage中融合进行几次
# 最后一次融合是将其他分支的特征融合到最高分辨率的特征图上,只输出最高分辨率的特征图(multi_scale_output = False)
# 前几次融合是将所有分支的特征融合到每个特征图上,输出所有尺寸特征图(multi_scale_output = True)
for i in range(num_modules):
# multi_scale_output is only used last module
if not multi_scale_output and i == num_modules - 1:
reset_multi_scale_output = False
else:
reset_multi_scale_output = True
modules.append(
HighResolutionModule(
num_branches,
block,
num_blocks,
num_inchannels,
num_channels,
fuse_method,
reset_multi_scale_output
)
)
num_inchannels = modules[-1].get_num_inchannels()
return nn.Sequential(*modules), num_inchannels
def forward(self, x):
if self.num_branches == 1:
# 如果只有一个分支,则直接将单个分支特征图作为输入送进self.branches
return [self.branches[0](x[0])]
# 如果有多个分支,则分别将每个分支特征图作为输入送进self.branches[i],得到x[i]
for i in range(self.num_branches):
x[i] = self.branches[i](x[i])
x_fuse = []
# 把不同分支分别进行上采样和下采样然后融合
for i in range(len(self.fuse_layers)):
y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])
for j in range(1, self.num_branches):
if i == j:
y = y + x[j]
else:
y = y + self.fuse_layers[i][j](x[j])
# 整体部分最后加Relu激活函数
x_fuse.append(self.relu(y))
return x_fuse
def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
num_channels, fuse_method, multi_scale_output=True):
super(HighResolutionModule, self).__init__()
self._check_branches(
num_branches, blocks, num_blocks, num_inchannels, num_channels)
self.num_inchannels = num_inchannels
self.fuse_method = fuse_method
self.num_branches = num_branches
self.multi_scale_output = multi_scale_output
self.branches = self._make_branches(
num_branches, blocks, num_blocks, num_channels)
self.fuse_layers = self._make_fuse_layers()
self.relu = nn.ReLU(True)
def _make_branches(self, num_branches, block, num_blocks, num_channels):
branches = []
# 反复堆叠_make_one_branch,重复num_branches次数
for i in range(num_branches):
branches.append(
self._make_one_branch(i, block, num_blocks, num_channels)
)
return nn.ModuleList(branches)
def _make_one_branch(self, branch_index, block, num_blocks, num_channels,
stride=1):
downsample = None
if stride != 1 or \
self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(
self.num_inchannels[branch_index],
num_channels[branch_index] * block.expansion,
kernel_size=1, stride=stride, bias=False
),
nn.BatchNorm2d(
num_channels[branch_index] * block.expansion,
momentum=BN_MOMENTUM
),
)
layers = []
# 第一个layer接入downsample,但是这里不会进行下采样,堆叠一次basicblock
layers.append(
block(
self.num_inchannels[branch_index],
num_channels[branch_index],
stride,
downsample
)
)
# 通道数[32, 64]
self.num_inchannels[branch_index] = \
num_channels[branch_index] * block.expansion
# num_blocks 为 [4, 4],所以循环次数为3,重复堆叠basicblock
for i in range(1, num_blocks[branch_index]):
layers.append(
block(
self.num_inchannels[branch_index],
num_channels[branch_index]
)
)
return nn.Sequential(*layers)
以上这部分为堆叠BasicBlock四次,对应图中Stage2中左侧的部分。
def _make_fuse_layers(self):
if self.num_branches == 1:
return None
num_branches = self.num_branches # 2
num_inchannels = self.num_inchannels # [32, 64]
fuse_layers = []
# 把j分支的特征融入到i分支中。
for i in range(num_branches if self.multi_scale_output else 1):
fuse_layer = []
for j in range(num_branches):
if j > i:
# 如果j分支大于i分支,则说明j下采样倍率更高,需要进行上采样与i分支融合。
fuse_layer.append(
nn.Sequential(
nn.Conv2d(
num_inchannels[j],
num_inchannels[i],
1, 1, 0, bias=False
),
nn.BatchNorm2d(num_inchannels[i]),
nn.Upsample(scale_factor=2**(j-i), mode='nearest')
)
)
elif j == i:
# j分支等于i分支,不需要进行操作
fuse_layer.append(None)
else:
# j分支大于i分支,需要进行下采样,这里stride = 2
# 判断k是否是最后一层,不是最后一层需要加Relu激活函数,最后一层则不需要添加
conv3x3s = []
for k in range(i-j):
if k == i - j - 1:
num_outchannels_conv3x3 = num_inchannels[i]
conv3x3s.append(
nn.Sequential(
nn.Conv2d(
num_inchannels[j],
num_outchannels_conv3x3,
3, 2, 1, bias=False
),
nn.BatchNorm2d(num_outchannels_conv3x3)
)
)
else:
num_outchannels_conv3x3 = num_inchannels[j]
conv3x3s.append(
nn.Sequential(
nn.Conv2d(
num_inchannels[j],
num_outchannels_conv3x3,
3, 2, 1, bias=False
),
nn.BatchNorm2d(num_outchannels_conv3x3),
nn.ReLU(True)
)
)
fuse_layer.append(nn.Sequential(*conv3x3s))
fuse_layers.append(nn.ModuleList(fuse_layer))
return nn.ModuleList(fuse_layers)
self.final_layer = nn.Conv2d(
in_channels=pre_stage_channels[0],
out_channels=cfg['MODEL']['NUM_JOINTS'],
kernel_size=extra['FINAL_CONV_KERNEL'],
stride=1,
padding=1 if extra['FINAL_CONV_KERNEL'] == 3 else 0
)
Conv2d的参数为k = 1, s = 1, p = 0, out_channels = 17对应17个关键点。
其中关键的部分已经再代码中以注释的形式展现,请认真读注释。
另外只介绍了Stage2的部分,Stage3,4堆叠策略同上,就不再赘述了。