RuntimeError: Expected all tensors to be on the same device

RuntimeError: Expected all tensors to be on the same device

我收到以下错误:

RuntimeError: Expected all tensors to be on the same device

但是,我的两个张量都在使用 .to(device=t.device)

            self.indices_buf = torch.LongTensor().to(device=t.device)
            self.beams_buf = torch.LongTensor().to(device=t.device)
            self.beams_buf_float = torch.FloatTensor().to(device=t.device)

此处self.beams_buf_float.type(torch.LongTensor)给出Expected all tensors to be on the same device错误。

        torch.div(self.indices_buf, vocab_size, out=self.beams_buf_float)
        self.beams_buf = self.beams_buf_float.type(torch.LongTensor)

我在这里很困惑,因为他们都在使用device=t.device

调用self.beams_buf_float.type(torch.LongTensor)时,生成的张量设备设置为默认设备(即cpu)。

在维护原始设备的同时将张量转换为新类型的正确方法是调用 self.brams_buf_float.to(torch.long)self.brams_buf_float.long()