【问题标题】:Pytorch : Getting the output gradient w.r.t input with gpuPytorch:使用 gpu 获取输出梯度 w.r.t 输入
【发布时间】:2022-01-13 02:15:02
【问题描述】:

我可以通过像下面这样更改输入来获得 w.r.t 输入的输出梯度。 但是当我将设备从 cpu 更改为 gpu 时,它没有被计算(我得到“None”)。如何获得渐变?

    action_batch = torch.tensor(action_batch, requires_grad=True, 
    dtype=torch.float32).to(self.device)


    self.critic_optimizer.zero_grad()
    print(action_batch.grad)
    critic_loss.backward()
    print("================**")
    print(action_batch.grad)
    self.critic_optimizer.step()

cpu 渐变

None
================**
tensor([[ 1.0538e-03, -1.6932e-04,  2.3841e-04,  9.9767e-04, -6.7008e-05,
      5.3555e-04],
    [-2.1002e-04, -3.2479e-05, -1.1147e-04, -1.9382e-04,  1.4175e-05,
     -1.0733e-04],
    [ 6.6836e-04, -1.9548e-05,  2.0143e-04,  3.8290e-04,  1.4578e-04,
      6.7998e-05],
    ...,
    [-9.7949e-05,  1.8074e-06, -2.8979e-05, -6.0738e-05, -1.3045e-06,
     -5.1929e-06],
    [-7.9130e-04,  2.3325e-04, -3.9635e-04, -1.1324e-03, -1.7819e-04,
     -2.4061e-04],
    [ 2.6802e-03,  1.1562e-05,  7.2858e-04,  1.7266e-03,  2.2337e-04,
      2.1766e-04]])

gpu 渐变

None
================**
None

【问题讨论】:

  • 嗨,欢迎来到 stackoverflow。请粘贴代码而不是图像
  • print(action_batch.to('cpu').grad)
  • 可悲的是,这行不通。因为“action_batch.grad”对于 gpu 来说是 None 。请查看“gpu 渐变”图片。
  • 谢谢大家ㅠㅜ

标签: input pytorch gradient autograd


【解决方案1】:

我解决了这个问题!!! action_batch =torch.FloatTensor(action_batch).to(self.device) action_batch.requires_grad = True

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 2022-01-14
    • 2019-01-10
    • 2017-01-26
    • 2019-11-19
    • 2020-02-27
    • 2021-09-04
    • 2019-09-24
    相关资源
    最近更新 更多