How to handle that error in pytorch: expected Long but found double
I'm given a function that is supposed to calculate the square-root of a matrix
import torch
from torch.autograd import Function

class MatrixSquareRoot(Function):
  &quot;&quot;&quot;Square root of a positive definite matrix.
  NOTE: matrix square root is not differentiable for matrices with
  zero eigenvalues.
  See Lin, Tsung-Yu, and Subhransu Maji.
  &quot;Improved Bilinear Pooling with CNNs.&quot; BMVC 17
  &quot;&quot;&quot;
  @staticmethod
  def forward(ctx, input):
    dim = input.shape[0]
    norm = torch.norm(input.double())
    Y = input/norm
    I = torch.eye(dim,dim,device=input.device).type(input.dtype)
    Z = torch.eye(dim,dim,device=input.device).type(input.dtype)
    for i in range(15):
      T = 0.5*(3.0*I - Z.mm(Y))
      Y = Y.mm(T)
      Z = T.mm(Z)
      sqrtm = Y*torch.sqrt(norm)
      #ctx.mark_dirty(Y,I,Z)
      ctx.save_for_backward(sqrtm)
    return sqrtm #, I, Y, Z
    
  @staticmethod
  def backward(ctx, grad_output):
    grad_input = None
    sqrtm, = ctx.saved_tensors
    dim = sqrtm.shape[0]
    norm = torch.norm(sqrtm)
    A = sqrtm/norm
    I = torch.eye(dim, dim, device=sqrtm.device).type(sqrtm.dtype)
    Q = grad_output/norm
    for i in range(15):
      Q = 0.5*(Q.mm(3.0*I-A.mm(A))-A.t().mm(A.t().mm(Q)-Q.mm(A)))
      A = 0.5*A.mm(3.0*I-A.mm(A))
      grad_input = 0.5*Q
    return grad_input

sqrtm = MatrixSquareRoot.apply # call: sqrtm(tensor of size d x d)

But when I'm trying to apply it to a matrix that has a square root, I'm getting that error:
&gt;&gt;&gt; x = torch.tensor([[1,-12],[0,4]])
&gt;&gt;&gt; sqrtm(x)

---------------------------------------------------------------------------
&lt;ipython-input-28-9310ac844935&gt; in forward(ctx, input)
     15     Z = torch.eye(dim,dim,device=input.device).type(input.dtype)
     16     for i in range(15):
---&gt; 17       T = 0.5*(3.0*I - Z.mm(Y))
     18       Y = Y.mm(T)
     19       Z = T.mm(Z)

RuntimeError: expected scalar type Long but found Double

I also tried to convert to Long by calling sqrtm(x.type(torch.LongTensor)) instead but it does produce the same error.

just change the tensor type as follows
x = torch.tensor([[1,-12],[0,4]],dtype=torch.float)
sqrtm(x)

