项目场景:
尝试训练一个模型,前200个epoch主要用于训练主干,后续50个epoch用于微调最后一层全连接层,之后可以将多个模型的全连接层抽出来拼到其中一个主干后面,用于多分支的投票。所以在训练200个epoch过后需要冻结前面的卷积层的参数,不参与参数更新。
问题描述
通过下方的代码,冻结除全连接层以外的所有层,并且重建了optimizer与scheduler,但是训练最终的模型通过netron查看参数,发现依旧有细微的差异,即模型没有完全冻结成功。
if epoch == 200:
for name, param in model.named_parameters():
if 'fc' not in name:
param.requires_grad = False
else:
param.requires_grad = True
optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=optimizer.param_groups[-1]['lr'], weight_decay=0.0001)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 50)
解决方案:
我使用的是shuffleNetV2,经过查询资料,网络中的BN层需要手动进行冻结才能完成彻底的冻结,修改代码如下:
def set_batchnorm_to_eval(module):
"""将所有BatchNorm层设置为评估模式"""
if isinstance(module, nn.BatchNorm2d) or isinstance(module, nn.BatchNorm1d):
module.eval()
......
if epoch == 200:
for name, param in model.named_parameters():
if 'fc' not in name:
param.requires_grad = False
else:
param.requires_grad = True
model.apply(set_batchnorm_to_eval)
optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=optimizer.param_groups[-1]['lr'], weight_decay=0.0001)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 50)
修改后问题解决,问题的关键在于某个层或者算子,结构不能简单的通过requires_grad = False进行冻结,甚至使用的优化器,也可能有影响。