RuntimeError: Input and hidden tensors are not at the same device, found input tensor at cuda:0 and

本文介绍了解决BiLSTM在GPU上运行时出现的输入张量与隐藏层张量不在同一设备上的错误。通过将所有张量统一到同一设备上解决了此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dl初学菜狗,轻喷
在运行BiLSTM代码的时候遇到的错误,因为使用cpu跑太慢了,改用gpu加速,遇到的问题。

因为BiLSTM里面含有隐藏层hidden-layer,BiLSTM和其他网络相比特殊之处在于隐藏层初始化是在网络的前向传播处发生的,这就意味着即使使用model.to(device)也不会对后面在网络内部的新初始化的变量位置产生什么影响(即变量还是在cpu上),所以当tensor一部分在cpu上一部分在gpu上的时候就会报错:
报错信息RuntimeError: Input and hidden tensors are not at the same device, found input tensor at cuda:0 and hidden tensor at cpu
解决方案
对于隐藏层初始化变量将其移动到device上

def init_hidden(self):
    return (torch.randn(2, self.batch, self.hidden_dim // 2)).to(self.device)

def init_hidden_lstm(self):
    return (torch.randn(2, self.batch, self.hidden_dim // 2).to(self.device),
            torch.randn(2, self.batch, self.hidden_dim // 2).to(self.device))

重要的事情说三遍:
所有的tensor变量都需要保持在一个设备上面,不能一部分在GPU上一部分在CPU上
所有的tensor变量都需要保持在一个设备上面,不能一部分在GPU上一部分在CPU上
所有的tensor变量都需要保持在一个设备上面,不能一部分在GPU上一部分在CPU上

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值