RuntimeError: Input and parameter tensors are not at the same device, found input tensor at cpu and

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

在学习pytorch的时候遇到的错误,意思是,输入和参数的张量不是在同一个device里,有一部分在CPU有一部分在GPU.

下面是一个例子,参考于 https://github.com/zergtant/pytorch-handbook/blob/master/chapter3/3.3-rnn.ipynb

只需要将下面代码 #x = x.cuda() #y = y.cuda()取消注释就可以运行。
因为下面的x,y这两个tensor放在CPU里,所以只需要把他们放入GPU中

import torch
import torch.nn as nn
from torch.nn import functional as F
from torch import optim
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.animation
import math, random
TIME_STEP = 10  # rnn 时序步长数
INPUT_SIZE = 1  # rnn 的输入维度
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
H_SIZE = 64  # of rnn 隐藏单元个数
EPOCHS = 300  # 总共训练次数
h_state = None  # 隐藏层状态

steps = np.linspace(0, np.pi * 2, 256, dtype=np.float32)
x_np = np.sin(steps)
y_np = np.cos(steps)


class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()
        self.rnn = nn.RNN(
            input_size=INPUT_SIZE,
            hidden_size=H_SIZE,
            num_layers=1,
            batch_first=True,
        )
        self.out = nn.Linear(H_SIZE, 1)

    def forward(self, x, h_state):
        # x (batch, time_step, input_size)
        # h_state (n_layers, batch, hidden_size)
        # r_out (batch, time_step, hidden_size)
        r_out, h_state = self.rnn(x, h_state)
        outs = []  # 保存所有的预测值
        for time_step in range(r_out.size(1)):  # 计算每一步长的预测值
            outs.append(self.out(r_out[:, time_step, :]))
        return torch.stack(outs, dim=1), h_state
        # 也可使用以下这样的返回值
        # r_out = r_out.view(-1, 32)
        # outs = self.out(r_out)
        # return outs, h_state


rnn = RNN().to(DEVICE)
optimizer = torch.optim.Adam(rnn.parameters())  # Adam优化,几乎不用调参
criterion = nn.MSELoss()  # 因为最终的结果是一个数值,所以损失函数用均方误差
rnn.train()

plt.figure(2)
for step in range(EPOCHS):
    start, end = step * np.pi, (step + 1) * np.pi  # 一个时间周期
    steps = np.linspace(start, end, TIME_STEP, dtype=np.float32)
    x_np = np.sin(steps)
    y_np = np.cos(steps)
    x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) # shape (batch, time_step, input_size)
    y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis])
    
    #加上这两行就不会报错了
    #x = x.cuda()
    #y = y.cuda()
    
    prediction, h_state = rnn(x, h_state)  # rnn output
    # 这一步非常重要
    h_state = h_state.data  # 重置隐藏层的状态, 切断和前一次迭代的链接
    loss = criterion(prediction, y)
    # 这三行写在一起就可以
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if (step + 1) % 20 == 0:  # 每训练20个批次可视化一下效果,并打印一下loss
        print("EPOCHS: {},Loss:{:4f}".format(step, loss))
        #plt.plot(steps, y_np.flatten(), 'r-')
        #plt.plot(steps, prediction.data.numpy().flatten(), 'b-')
        #plt.draw()
        #plt.pause(0.01)

上面的代码我注释掉画图的部分。
如果不注释,会出现这个错误。
TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
这是因为GPU的tensor不能转化为numpy。
如果需要画图的话,可以把所以数据都放在cpu中

DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")

改为

DEVICE = torch.device("CUP")

或者使用tensorboard等可视化工具

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
这个错误是由于输入张量和隐藏张量的数据类型不匹配导致的。根据引用\[1\],报错信息显示输入张量是Double类型,而隐藏张量是Float类型。这种情况下,需要确保两者的数据类型一致。 解决方案可以参考引用\[2\]和引用\[3\]提供的方法。首先,可以使用`to()`方法将隐藏层初始化变量移动到相同的设备上。例如,在初始化隐藏层时,可以使用以下代码将其移动到设备上: ```python 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)) ``` 另外,如果输入张量在CPU上而模型参数在GPU上,可以使用`to()`方法将输入张量移动到相同的设备上。具体操作如下: ```python # 错误1: 输入x在cuda(gpu)中, 模型参数在cpu中 # 找到输入参数x,然后再调用使用参数x之前添加一行代码x.to(device)(其中device=“cuda”) x = x.to(device) ``` 如果输入张量在GPU上而模型参数在CPU上,可以使用`to()`方法将模型参数移动到相同的设备上。具体操作如下: ```python # 错误2: 输入x在cpu中, 模型参数在cuda(gpu)中 # 找到定义model的代码,在定义的后面添加一行代码 model.to(device) model.to(device) ``` 通过以上方法,可以确保输入张量和隐藏张量的数据类型和设备位置一致,从而解决这个错误。 #### 引用[.reference_title] - *1* [RuntimeError: Input and parameter tensors are not the same dtype, found input tensor with Double](https://blog.csdn.net/li_jiaoyang/article/details/116060386)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [RuntimeError: Input and hidden tensors are not at the same device, found input tensor at cuda:0 and](https://blog.csdn.net/kz_java/article/details/122527069)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [RuntimeError:Input and parameter tensors are not at the same device, found input tensor at cuda:0 an](https://blog.csdn.net/qq_45056135/article/details/125227784)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值