python - 卡在 Collab RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:
问题描述
我检查并看到我已经在 GPU (context_vector) 中定义了我的张量,但是当我在 Colab 上运行时,它总是显示错误“期望所有张量在同一设备上,但找到至少两个设备,cpu和cuda”的错误轨迹是这样的:
RuntimeError Traceback (most recent call last)
<ipython-input-16-bf7edd8e474b> in <module>()
85 for context, target in data:
86 context_vector = make_context_vector(context)
---> 87 log_probs = model(context_vector)
88 total_loss += loss_function(log_probs, torch.tensor([target]).to(device))
89 #optimize at the end of each epoch
这是我的 make_context_vector 函数:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def make_context_vector(context):
return torch.tensor(context, dtype=torch.long).to(device)
这是我的转发功能:
def forward(self, inputs):
embeds = sum(self.embeddings(inputs)).view(1,-1)
# print('embeds size: {}'.format(embeds.shape))
out = self.linear1(embeds)
out = self.activation_function1(out)
# print('out1 size: {}'.format(out.shape))
out = self.linear2(out)
out = self.activation_function2(out)
return out
#TRAINING
for epoch in range(50):
total_loss = 0
for context, target in data:
context_vector = make_context_vector(context)
log_probs = model(context_vector)
total_loss += loss_function(log_probs, torch.tensor([target], device = device))
#optimize at the end of each epoch
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
请任何人帮助!谢谢
解决方案
哦,支持我的朋友,我发现不仅输入设置GPU,模型也需要设置GPU。因此,在培训代码中,我将其更改为:
model = CBOW(vocab_size, embedding_dim)**.to(device)**
然后,效果很好
推荐阅读
- react-native - I18nManager.swapLeftAndRightInRTL 方法应该如何工作?
- swift - 如何在 Swift 中将颜色与图像相乘?
- python-3.x - Python - 根据列值创建行副本并按迭代次数增加日期
- javascript - 分发带有样式组件的 React UI 库
- grammar - 为什么这个文法不是 LL(1)?
- angular - 如何在angular7中的路由保护内进行http post调用?
- tensorflow - tensorflow 2 中的 LSTM 从零开始
- javascript - 如何使用 JS 类根据用户输入显示消息?
- android - 使用片段时 getContext() 和 requireContext() 的区别
- amazon-web-services - 如何在 AWS s3 存储桶中找到文件的“文件路径”?