I have a loss function defined like this
def Loss(U,G_metric,p,q):
   ''' U is a function takes a vector and return a scalar
       G_metric is a function returns a matrix; it's a metric tensor 
       p ,q are two vectors
   '''
    D = p.size()[0] # get the dimension of p,q
    G = G_metric(q) # get a matrix 

    detG = torch.Tensor([np.linalg.det(G.data.numpy())]) # get its determinants
    invG = torch.Tensor(np.linalg.inv(G.data.numpy())) # get its inverse

    return U(q) + 0.5*torch.log((2*math.pi)**D*detG) + 0.5*p@invG@p # compute the loss

Now I want the gradient w.r.t. p and q
Can I just directly do ?

L = Loss(U,G_metric,p,q)
L.backward()
q.grad
p.grad

to get the gradient vector? Since I use numpy way to compute inverse and determinant (as I couldn’t find a way to do them in pytorch). It seems to me that they treat invG and detG as const during the backward.
The chain rule when differentiate w.r.t. variable q should go all the way back to function G_metric(q)
Thanks