Can you try this?:
class MRRLoss(nn.Module):
""" Mean Reciprocal Rank Loss """
    def __init__(self):
        super(MRRLoss, self).__init__()

    def forward(self, u, v):
        u=torch.reshape(u,(-1,))
        v=torch.reshape(v,(-1,))
        #cosine distance between all pair of embedding in u and v batches.
        cos = nn.CosineSimilarity(dim=0)
        distances=cos(u,v)
        # by construction the diagonal contains the correct elements
        correct_elements = torch.diag(cos(u,v),0).unsqueeze(-1)
        # number of elements ranked wrong.
        return torch.sum(distances < correct_elements)