I’m trying to define a custom loss function in PyTorch. Currently, it is as follows:
from scipy.spatial.distance import cdist
import numpy as np

class MRRLoss(nn.Module):
""" Mean Reciprocal Rank Loss """
    def __init__(self):
        super(MRRLoss, self).__init__()

    def forward(self, u, v, distance_metric="cosine"):
        #cosine distance between all pair of embedding in u and v batches.
        distances = cdist(u.detach().numpy(), v.detach().numpy(), metric=distance_metric)
        # by construction the diagonal contains the correct elements
        correct_elements = np.expand_dims(np.diag(distances), axis=-1)
        # number of elements ranked wrong.
        return np.sum(distances < correct_elements)

This loss function is used to train a model that generates embeddings for different objects, such as image and text. The objective is that the embedding of image i is as close as possible to the text t that describes it.
The loss has as input batches u and v, respecting image embeddings and text embeddings. It calculates the cosine similarity between all the x1 and x2 embedding pairs. Returns a value showing how many images were wrong ranked.
However, during training I am having the following error:
AttributeError: 'numpy.int64' object has no attribute 'backward'

How could I get around this kind of error?