PyTorch错误解决方案及技巧RuntimeError: Attempting to deserialize object on CUDA device 2 but torch.cuda.devic

本文详细解析了PyTorch在GPU环境下常见的错误及其解决方法,包括模型加载失败、多GPU处理机制、内存迁移区别等关键问题,并提供了实用的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PyTorch错误解决方案及技巧

 

    • 报错:RuntimeError: Attempting to deserialize object on CUDA device 2 but torch.cuda.device_count() is 1
    • 原因:在使用Pytorch加载模型时报错。加载的模型是用两个GPU训练的,而加载模型的电脑只有一个GPU,所以会出错。
    • 解决:model = torch.load(model_path)
      改为:model = torch.load(model_path, map_location='cuda:0')
      如果是4块到2块:就把map_location改为:map_location={'cuda:1': 'cuda:0'}
  1. PyTorch多GPU的处理机制
    使用多GPU时,应该记住pytorch的处理逻辑是:

1.在各个GPU上初始化模型。
2.前向传播时,把batch分配到各个GPU上进行计算。
3.得到的输出在主GPU上进行汇总,计算loss并反向传播,更新主GPU上的权值。
4.把主GPU上的模型复制到其它GPU上。

  1. nn.Module.cuda() 和 Tensor.cuda() 的作用效果的区别
    无论是对于模型还是数据,cuda()函数都能实现从CPU到GPU的内存迁移,但是他们的作用效果有所不同。
    • 对于nn.Module:
model = model.cuda() 

model.cuda()

上面两句能够达到一样的效果,即对model自身进行内存迁移。

- 对于Tensor:

和nn.Module不同,调用tensor.cuda()只是返回这个tensor对象在GPU内存上的拷贝,而不会对自身进行改变。因此必须对tensor进行重新赋值,即tensor=tensor.cuda().

 

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is Fal
展开
遇到一个错误:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location='cpu' to map your storages to the CPU.
出错语句:

torch.load(model_file)
改为:

model = torch.load(model_path, map_location='cpu')
 

多个GPU训练的,参考:

<https://blog.youkuaiyun.com/iamjingong/article/details/85308600>

 

torch.cuda.is_available()返回false的解决办法

展开
在使用pytorch的时候,有时会遇到torch.cuda.is_available()返回false的问题,一般出现这个的原因是因为驱动没有安装好的缘故。解决的方案是:

1、安装nvidia相应的驱动版本和对应的cuda和cudnn。

sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update
sudo apt install nvidia-396
 
#开发使用
sudo apt install nvidia-396-dev
有时会碰到nvidia-396找不到的情况,使用

sudo apt search nvidia
后发现库中没有nvidia-396的版本,这时可以安装nvidia-384的版本

sudo apt install nvidia-384
但是该版本似乎不支持cuda9.1,如果碰到与cuda版本不支持的问题,建议可以直接去nvidia官方网站下载驱动进行安装。

https://www.nvidia.cn/Download/index.aspx?lang=cn

cuda和cudnn可以直接使用conda进行安装, 如果遇到问题,可以查阅相关的文档,这里就不赘述了。

conda install cudatoolkit
2、安装nvidia-cuda-toolkit方便使用nvcc

sudo apt-get install nvidia-cuda-toolkit
如果碰到nvcc -V 显示的版本与系统实际安装的版本不同的问题,可以参见

https://zhuanlan.zhihu.com/p/48641682

一般进行驱动的正确安装后,就可以使用gpu进行计算了。

 

将gpu改为cpu时,遇到一个报错:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location='cpu' to map your storages to the CPU.

此时改为:

torch.load("0.9472_0048.weights",map_location='cpu')

就可以解决问题了。

 

方便查阅,整理:

假设我们只保存了模型的参数(model.state_dict())到文件名为modelparameters.pth, model = Net()

1. cpu -> cpu或者gpu -> gpu:

checkpoint = torch.load('modelparameters.pth')

model.load_state_dict(checkpoint)

2. cpu -> gpu 1

torch.load('modelparameters.pth', map_location=lambda storage, loc: storage.cuda(1))

3. gpu 1 -> gpu 0

torch.load('modelparameters.pth', map_location={'cuda:1':'cuda:0'})

4. gpu -> cpu

torch.load('modelparameters.pth', map_location=lambda storage, loc: storage)

 

    • 报错:RuntimeError: Attempting to deserialize object on CUDA device 2 but torch.cuda.device_count() is 1
    • 原因:在使用Pytorch加载模型时报错。加载的模型是用两个GPU训练的,而加载模型的电脑只有一个GPU,所以会出错。
    • 解决:model = torch.load(model_path)
      改为:model = torch.load(model_path, map_location='cuda:0')
      如果是4块到2块:就把map_location改为:map_location={'cuda:1': 'cuda:0'}
  1. PyTorch多GPU的处理机制
    使用多GPU时,应该记住pytorch的处理逻辑是:

1.在各个GPU上初始化模型。
2.前向传播时,把batch分配到各个GPU上进行计算。
3.得到的输出在主GPU上进行汇总,计算loss并反向传播,更新主GPU上的权值。
4.把主GPU上的模型复制到其它GPU上。

  1. nn.Module.cuda() 和 Tensor.cuda() 的作用效果的区别
    无论是对于模型还是数据,cuda()函数都能实现从CPU到GPU的内存迁移,但是他们的作用效果有所不同。
    • 对于nn.Module:
model = model.cuda() 

model.cuda()

上面两句能够达到一样的效果,即对model自身进行内存迁移。

- 对于Tensor:

和nn.Module不同,调用tensor.cuda()只是返回这个tensor对象在GPU内存上的拷贝,而不会对自身进行改变。因此必须对tensor进行重新赋值,即tensor=tensor.cuda().

<think>好的,用户遇到了PyTorchCUDA设备上的反序列化错误,具体错误RuntimeError:Attemptingto deserialize objecton CUDA device2but torch.cuda.device_count()is2。用户提到他们想了解当device_count为2时的解决方法,特别是关于map_location的使用。我需要结合之前的引用内容,提供具体的解决方案。首先,我需要确认这个错误的原因。根据引用中的信息,这类错误通常是因为模型被保存时在特定的GPU设备上,而加载时环境不同,比如可用设备数量或当前设备不同。用户现在有2个设备,但加载时试图访问设备2,而可能当前设备不在那里,或者保存时的设备索引与加载时不一致。 接下来,解决方案的核心是使用torch.load的map_location参数来重新映射存储位置。正确的map_location设置可以解决设备不匹配的问题。可能的选项包括将模型加载到CPU,或者当前活动的GPU上,或者让PyTorch自动选择。需要详细说明map_location的不同用法,特别是当device_count为2时如何处理。比如,用户可能希望将模型加载到特定的GPU,或者所有可用的设备上。同时,要提醒用户关于多GPU训练时模型保存的问题,比如使用DataParallel或DistributedDataParallel的情况,此时保存的模型可能包含module.前缀,加载时需要处理。 另外,用户可能需要检查CUDA环境是否正常,比如通过torch.cuda.device_count()确认设备数量,以及当前活动的设备。这部分可以作为验证步骤加入解决方案中。最后,生成的相关问题需要覆盖常见的后续疑问,比如多卡训练时的保存技巧、设备映射的其他方法,以及环境检查方法。这些能帮助用户更全面地理解和解决问题。</think>针对PyTorch多GPU环境下的反序列化错误,以下是分步解决方案: ### 错误原因分析 当出现`RuntimeError: Attempting to deserialize object on CUDA device 2 but torch.cuda.device_count() is 2`时,说明: 1. 模型是在编号为2的GPU上保存的(设备索引从0开始) 2. 当前环境虽然有两个GPU(device_count=2),但加载时存在设备映射冲突 3. 多卡训练时未正确处理模型保存位置[^1][^2] ### 解决方案 #### 步骤1:强制指定加载位置 ```python model = torch.load('model.pth', map_location={'cuda:2': 'cuda:0'}) # 将设备2映射到设备0 ``` #### 步骤2:动态设备分配(推荐) ```python # 自动选择可用设备(优先使用当前设备) model = torch.load('model.pth', map_location=torch.device('cuda:0')) # 或自动选择所有可用设备 model = torch.load('model.pth', map_location='cuda') ``` #### 步骤3:多GPU训练特殊处理 若使用`DataParallel`训练: ```python # 加载后重新封装模型 model = torch.nn.DataParallel(model) model = model.to(f'cuda:{model.device_ids[0]}') ``` #### 验证步骤 ```python print(torch.cuda.device_count()) # 应输出2 print(torch.cuda.current_device()) # 检查当前活动设备 ``` ### 关键参数说明 | 参数格式 | 作用 | 适用场景 | |---------|------|---------| | `map_location='cpu'` | 加载到CPU | 无GPU环境 | | `map_location={'cuda:2':'cuda:0'}` | 设备映射 | 多卡环境迁移 | | `map_location=torch.device('cuda')` | 自动选择 | 通用解决方案 | ### 注意事项 1. 使用多卡训练时建议通过`torch.cuda.set_device(0)`固定主设备 2. 保存模型前添加`model = model.module`解除DataParallel封装[^3][^4] 3. 跨设备加载后需要手动调用`model.to(device)`
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值