gpt4 book ai didi

python - Pytorch : AttributeError: 'function' object has no attribute 'cuda'

转载 作者:行者123 更新时间:2023-12-04 10:46:36 25 4
gpt4 key购买 nike

import torch
import models
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
model = models.__dict__['resnet18']
model = torch.nn.DataParallel(model,device_ids = [0]) #PROBLEM CAUSING LINE
model.to('cuda:0')

要运行此代码,您需要克隆此存储库: https://github.com/SoftwareGift/FeatherNets_Face-Anti-spoofing-Attack-Detection-Challenge-CVPR2019.git

请在克隆目录的根文件夹中运行这段代码。

我收到以下错误 AttributeError: 'function' object has no attribute 'cuda'我也尝试将 torch.device 对象用于相同的功能,但会导致相同的错误。
请询问所需的任何其他详细信息。 PyTorch 新手在这里
python :3.7 火炬:1.3.1

最佳答案

代替

model = torch.nn.DataParallel(model,device_ids = [0])


model = torch.nn.DataParallel(model(), device_ids=[0])

(注意 () 内部模型后的 DataParallel )。区别很简单: models模块包含创建模型而不是模型实例的类/函数。如果您跟踪导入,您会发现 models.__dict__['resnet18']解析为 this功能。由于 DataParallel包装一个实例,而不是一个类本身,它是不兼容的。 ()调用此模型构建函数/类构造函数来创建此模型的实例。

一个更简单的例子如下
class MyNet(nn.Model):
def __init__(self):
self.linear = nn.Linear(4, 4)
def forward(self, x):
return self.linear(x)

model = nn.DataParallel(MyNet) # this is what you're doing
model = nn.DataParallel(MyNet()) # this is what you should be doing

您的错误消息提示 function (因为没有 model()function 类型)没有属性 cuda ,这是 nn.Model 的方法实例。

关于python - Pytorch : AttributeError: 'function' object has no attribute 'cuda' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59678247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com