PyTorch训练多任务模型技巧

一、解决在分布式训练中,如果对同一模型进行多次调用的报错

报错如下:

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: torch.cuda.FloatTensor \[256) is at version 4; expected version 3 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

参考知乎文章《【PyTorch踩坑】一个排查了一下午的坑

经过一些调试发现,只有当某些特定情况下才会触发此报错。下面结合一个对比学习的例子(并不是完整的脚本)来简单描述:

python 复制代码
import torch
import torch.nn as nn

from torchvision.models import resnet50

def main():
    model = resnet50(num_classes=256).cuda()
    model = nn.parallel.DistributedDataParallel(model, 
                                                device_ids=[args.local_rank], 
                                                find_unused_parameters=True)
    criterion = nn.MSELoss()
    
    optimizer = torch.optim.SGD(model.parameters(),
                                lr=0.001,
                                momentum=0.99,
                                weight_decay=1e-4)

    for i in range(10):
        input0 = torch.randn((4, 3, 224, 224), dtype=torch.float32).cuda()
        input2 = torch.randn((4, 3, 224, 224), dtype=torch.float32).cuda()

        out1 = model(input0)
        out2 = model(input1)

        loss = criterion(out1, out2)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

if __name__ == '__main__':
    main()

经过调试发现,当使用nn.DataParallel并行训练或者单卡训练均可正常运行;另外如果将两次模型调用集成到model中,即通过out1, out2 = model(input0, input1) 的方式在分布式训练下也不会报错。

由此可以猜测:在分布式训练中,如果对同一模型进行多次调用则会触发以上报错,即nn.parallel.DistributedDataParallel方法封装的模型,forword()函数和backward()函数必须交替执行,如果执行多个(次)forward()然后执行一次backward()则会报错。

那么解决此问题的入手点则可以聚焦到nn.parallel.DistributedDataParallel接口上。 通过查询PyTorch官方文档发现此接口下的两个参数:

复制代码
- find_unused_parameters: 如果模型的输出有不需要进行反向传播的,此参数需要设置为True;若你的代码运行后卡住不动,基本上就是该参数的问题。
- broadcast_buffers: 该参数默认为True,设置为True时,在模型执行forward之前,gpu0会把buffer中的参数值全部覆盖到别的gpu上。

问题基本可以定位出来了,即broadcast_buffers=True导致参数被覆盖修改。解决办法:

复制代码
 model = nn.parallel.DistributedDataParallel(model, 
                                             device_ids=[args.local_rank], 
                                             broadcast_buffers=False,
                                             find_unused_parameters=True)

参考

distributed: https://pytorch.org/docs/stable/distributed.html

Inplace error if DistributedDataParallel module that contains a buffer is called twice

相关推荐
leoZ23126 分钟前
AI+前端提效-08 AI自动化文档:前端组件、接口、项目文档自动生成
前端·人工智能·深度学习·神经网络·目标检测·自然语言处理·自动化
️学习的小王1 小时前
AI Agent Skills实战教程:从原理到上手编写SKILL.md
人工智能·深度学习·学习·机器学习
萝萝仔1 小时前
02.人工智能训练师三级是什么?谁适合考?考了有什么用?
人工智能·深度学习·机器学习·ai·云计算
YOLO数据集集合2 小时前
蚊子视觉验证数据集 | 蚊虫识别 疟疾防控 病媒生物 细粒度分类 YOLO格式 深度学习数据集
深度学习·yolo·分类·数据集·蚊子分类·蚊虫分类·蚊虫识别
zx_741484812 小时前
【深度学习入门】Windows 下 PyTorch GPU 环境搭建
pytorch·windows·深度学习
CIO_Alliance3 小时前
AI提示系列(2)| Few-shot与ReAct有何不同? 大模型工具调用的底层逻辑详解
前端·人工智能·深度学习·神经网络·react.js·前端框架·ai+ipaas
牧羊人.3333 小时前
动手学深度学习 01:核心组件与完整训练流程
开发语言·人工智能·深度学习
吾在学习路3 小时前
XSKILL: Continual Learning from Experience and Skills in Multimodal Agents
人工智能·深度学习·机器学习
auto_go3 小时前
大模型实战指南(12)——端侧 AI 助手实战:Ollama + 工具调用,让本地模型真正帮你干活
人工智能·深度学习·机器学习
Golden小狗种自己的花[哇]3 小时前
书接上回(Convolution)
人工智能·深度学习