只有浮点和复杂数据类型的张量需要梯度

Only Tensors of floating point and complex dtype can require gradients

当我在 torch.no_grad() 上下文中 运行 进行卷积运算时,我收到以下错误:

RuntimeError: Only Tensors of floating-point and complex dtype can require gradients.
import torch.nn as nn
import torch


with torch.no_grad():
    ker_t = torch.tensor([[1, -1] ,[-1, 1]])
    in_t = torch.tensor([ [14, 7, 6, 2,] , [4 ,8 ,11 ,1], [3, 5, 9 ,10], [12, 15, 16, 13] ])
    print(in_t.shape)
    in_t = torch.unsqueeze(in_t,0)
    in_t = torch.unsqueeze(in_t,0)
    print(in_t.shape)

    conv = nn.Conv2d(1, 1, kernel_size=2,stride=2,dtype=torch.long)
    conv.weight[:] = ker_t
    conv(in_t)

现在我确定如果我将我的输入转换为浮点数,这条消息就会消失,但我想使用整数。

但我的印象是,如果我在 with torch.no_grad() 上下文中,它应该关闭对渐变的需求。

在注册卷积层的权重时,nn.Conv2d 需要梯度。
但是,如果只是在forward pass之后,就不需要使用卷积layer:可以使用底层卷积function:

import torch.nn.functional as nnf

ker_t = torch.tensor([[1, -1] ,[-1, 1]])[None, None, ...]
in_t = torch.tensor([ [14, 7, 6, 2,] , [4 ,8 ,11 ,1], [3, 5, 9 ,10], [12, 15, 16, 13] ])[None, None, ...]
out = nnf.conv2d(in_t, ker_t, stride=2)

会给你这个输出:

tensor([[[[11, -6],
          [ 1, -4]]]])