这代表将模型加载到指定设备上。
其中,device=torch.device("cpu")代表的使用cpu,而device=torch.device("cuda")则代表的使用GPU。
当我们指定了设备之后,就需要将模型加载到相应设备中,此时需要使用model=model.to(device),将模型加载到相应的设备中。
将由GPU保存的模型加载到CPU上。
将torch.load()函数中的map_location参数设置为torch.device('cpu')
|
1 2 3 |
device = torch.device('cpu') model = TheModelClass(*args, **kwargs) model.load_state_dict(torch.load(PATH, map_location=device)) |
将由GPU保存的模型加载到GPU上。确保对输入的tensors调用input = input.to(device)方法。
|
2 3 4 |
device = torch.device("cuda") model = TheModelClass(*args, **kwargs) model.load_state_dict(torch.load(PATH)) model.to(device) |
将由CPU保存的模型加载到GPU上。确保对输入的tensors调用input = input.to(device)方法。map_location是将模型加载到GPU上,model.to(torch.device('cuda'))是将模型参数加载为CUDA的tensor。最后保证使用.to(torch.device('cuda'))方法将需要使用的参数放入CUDA。
|
1 2 3 4 |
device = torch.device("cuda") model = TheModelClass(*args, **kwargs) model.load_state_dict(torch.load(PATH, map_location="cuda:0")) # Choose whatever GPU device number you want model.to(device) |
本文详细介绍了如何在PyTorch中将模型从CPU迁移到GPU,从GPU迁移到CPU,以及从CPU迁移到GPU的具体步骤。通过设置device参数和使用model.to()方法,可以轻松实现模型在不同设备之间的迁移。

1万+

被折叠的 条评论
为什么被折叠?



