使用torch.autograd.gradPyTorch计算矩阵导数 仅当使用pytorch函数时,才会创建pytorch自动分级图

问题描述

我正在尝试使用torch.autograd.grad在PyTorch中计算矩阵导数,但是我遇到了一些问题。这是重现该错误的最小工作示例。

theta = torch.tensor(np.random.uniform(low=-np.pi,high=np.pi),requires_grad=True)
rot_mat = torch.tensor([[torch.cos(theta),torch.sin(theta),0],[-torch.sin(theta),torch.cos(theta),0]],dtype=torch.float,requires_grad=True)
torch.autograd.grad(outputs=rot_mat,inputs=theta,grad_outputs=torch.ones_like(rot_mat),create_graph=True,retain_graph=True)

代码导致错误“图形中似乎未使用过一个差分张量。如果这是所需的行为,请设置allow_unused = True。”

我尝试使用allow_unused = True,但是渐变返回为None。我不确定是什么原因导致图形在此处断开连接。

解决方法

仅当使用pytorch函数时,才会创建pytorch自动分级图。

我认为在创建rot_mat时使用的python 2d列表会断开图形。因此,使用割炬函数可以创建旋转矩阵,也可以仅使用backward()函数来计算梯度。这是示例代码:

import torch
import numpy as np

theta   = torch.tensor(np.random.uniform(low=-np.pi,high=np.pi),requires_grad=True)

# create required values and convert it to torch 1d tensor
cos_t   = torch.cos(theta).view(1)
sin_t   = torch.sin(theta).view(1)
msin_t  = -sin_t
zero    = torch.zeros(1)

# create rotation matrix using only pytorch functions
rot_1d  = torch.cat((cos_t,sin_t,zero,msin_t,cos_t,zero))
rot_mat = rot_1d.view((2,3)) 

# Autograd
rot_mat.backward(torch.ones_like(rot_mat))

# gradient
print(theta.grad)