这代表将模型加载到指定设备上。

其中,device=torch.device(“cpu”)代表的使用cpu,而device=torch.device(“cuda”)则代表的使用gpu。

当我们指定了设备之后,就需要将模型加载到相应设备中,此时需要使用model=model.to(device),将模型加载到相应的设备中。

将由gpu保存的模型加载到cpu上。

将torch.load()函数中的map_location参数设置为torch.device(‘cpu’)

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)方法。

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。

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中model.to(device)和map_location=device的区别

一、简介

在已训练并保存在cpu上的gpu上加载模型时,加载模型时经常由于训练和保存模型时设备不同出现读取模型时出现错误,在对跨设备的模型读取时候涉及到两个参数的使用,分别是model.to(device)和map_location=devicel两个参数,简介一下两者的不同。

将map_location函数中的参数设置 torch.load()为 cuda:device_id。这会将模型加载到给定的gpu设备。

调用model.to(torch.device(‘cuda’))将模型的参数张量转换为cuda张量,无论在cpu上训练还是gpu上训练,保存的模型参数都是参数张量不是cuda张量,因此,cpu设备上不需要使用torch.to(torch.device(“cpu”))。

二、实例

了解了两者代表的意义,以下介绍两者的使用。

1、保存在gpu上,在cpu上加载

保存:

torch.save(model.state_dict(), path)

加载:

device = torch.device('cpu')
model = themodelclass(*args, **kwargs)
model.load_state_dict(torch.load(path, map_location=device))

解释:

在使用gpu训练的cpu上加载模型时,请传递 torch.device(‘cpu’)给map_location函数中的 torch.load()参数,使用map_location参数将张量下面的存储器动态地重新映射到cpu设备 。

2、保存在gpu上,在gpu上加载

保存:

torch.save(model.state_dict(), path)

加载:

device = torch.device("cuda")
model = themodelclass(*args, **kwargs)
model.load_state_dict(torch.load(path))
model.to(device)
# make sure to call input = input.to(device) on any input tensors that you feed to the model

解释:

在gpu上训练并保存在gpu上的模型时,只需将初始化model模型转换为cuda优化模型即可model.to(torch.device(‘cuda’))。

此外,请务必.to(torch.device(‘cuda’))在所有模型输入上使用该 功能来准备模型的数据。

请注意,调用my_tensor.to(device) 返回my_tensorgpu上的新副本。

它不会覆盖 my_tensor。

因此,请记住手动覆盖张量: my_tensor = my_tensor.to(torch.device(‘cuda’))

3、保存在cpu,在gpu上加载

保存:

torch.save(model.state_dict(), path)

加载:

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)
# make sure to call input = input.to(device) on any input tensors that you feed to the model

解释:

在已训练并保存在cpu上的gpu上加载模型时,请将map_location函数中的参数设置 torch.load()为 cuda:device_id。

这会将模型加载到给定的gpu设备。

接下来,请务必调用model.to(torch.device(‘cuda’))将模型的参数张量转换为cuda张量。

最后,确保.to(torch.device(‘cuda’))在所有模型输入上使用该 函数来为cuda优化模型准备数据。

请注意,调用 my_tensor.to(device)返回my_tensorgpu上的新副本。

它不会覆盖my_tensor。

因此,请记住手动覆盖张量:my_tensor = my_tensor.to(torch.device(‘cuda’))

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。