首页 > 解决方案 > 卡在 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()

请任何人帮助!谢谢

标签: pythongpugoogle-colaboratory

解决方案


哦,支持我的朋友,我发现不仅输入设置GPU,模型也需要设置GPU。因此,在培训代码中,我将其更改为:

model = CBOW(vocab_size, embedding_dim)**.to(device)**

然后,效果很好


推荐阅读