pytorch cpu与gpu load时相互转化 torch.load(map_location=)

本文详细介绍了如何在PyTorch中将模型参数从一个设备加载到另一个设备,包括从CPU到GPU、从GPU到CPU以及在不同GPU间进行迁移的方法。同时,针对在特定环境下可能遇到的运行时错误提供了解决方案。

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

pytorch将cpu训练好的模型参数load到gpu上,或者gpu->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 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(opt.model,map_location='cpu')

 

方便查阅

### 使用 `torch.load` 加载 Checkpoint 文件 在 PyTorch 中,`torch.load()` 函数用于加载由 `torch.save()` 保存的对象。对于 checkpoint 文件而言,通常会包含模型的状态字典 (`state_dict`)、优化器状态以及其他元数据。 #### 参数详解 - **f**: 输入可以是一个文件路径名或类文件对象。 - **map_location**: 这个参数指定了如何重新映射存储位置。如果是在不同设备之间传输模型(比如从 GPUCPU 或者反之),这个选项非常重要[^1]。 - 当目标是将模型从 GPU 转移到 CPU 上执行,应该设置为 `'cpu'` 或者使用 lambda 表达式来处理更复杂的情况[^2]。 ```python model = torch.load('modelparameters.pth', map_location='cpu') ``` - **device (args.device)**: 定义了计算将在哪个硬件资源上完成——通常是 `"cuda"` 对于 GPU 计算或者是 `"cpu"` 如果没有可用的 CUDA 设备。这可以通过调用 `to(device)` 方法应用于整个模型实例。 下面给出一段完整的代码示例展示如何利用这些参数加载一个 checkpoint 并将其移动到指定设备: ```python import torch def load_checkpoint(checkpoint_path, device): """Load a checkpoint file and move it to the specified device.""" # Load checkpoint with appropriate mapping for different devices. if str(device) == "cpu": checkpoint = torch.load( checkpoint_path, map_location=torch.device('cpu') # Move tensors directly onto CPU memory. ) else: checkpoint = torch.load(checkpoint_path) # Assuming 'model' is defined elsewhere as an instance of your neural network class. model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) epoch = checkpoint['epoch'] loss = checkpoint['loss'] # Ensure that all future operations are performed on the correct device. model.to(device) return model, optimizer, epoch, loss # Example usage: if __name__ == "__main__": ckpt_file = "./checkpoints/model_best.pth.tar" args_device = torch.device("cuda" if torch.cuda.is_available() else "cpu") loaded_model, _, start_epoch, _ = load_checkpoint(ckpt_file, args_device) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值