使用多卡并行训练时,调用model里面的某个子模块时,会报如下错误:
AttributeError: ‘DistributedDataParallel’ object has no attribute ‘xxxx’
class train_model(nn.Module):
def __init__(self, args):
.
.
.
def forward(self, x):
x = self.backbone(x)
x = self.layer1(x)
x = self.layer2(x)
.
.
.
在训练代码中:若采用多卡并行训练,model = nn.DataParallel(train_model)
若想调用backbone之后的结果, x=model.backbone(feats)
则会报错:AttributeError: ‘DistributedDataParallel’ object has no attribute ‘backbone’
此时,model下的子网络结构backbone、layer1、layer2的调用方法会发生改变,如下所示
x=model.module.backbone(feats)
直接调用(不加module)适合单卡训练的情况

在使用多卡并行训练时,通过nn.DataParallel包装模型会导致直接调用子模块如backbone、layer1等报错。解决方法是在调用时加上'module'前缀,如model.module.backbone(feats)。这使得在多GPU环境下也能正确访问子网络结构。注意,此方式只适用于多卡训练,单卡训练则直接调用无需加'module'。
1万+





