Solved by Aldebaran in post #11 
              
              
                If help someone, I’ve implemented a better solution to this question inpired by N-Pair Loss published on NIPS 2016: 
import torch
from torch import nn


class NPairsLoss(nn.Module):
    """
    The N-Pairs Loss.
    It measures the loss given predicted tensors x1, x2 both with shape [batch_size, hid…