Take a look at the following example where we perform random negative sampling and modify the loss function to binary cross-entropy. This could be a viable method to fulfill the requirement. import torch from torch import nn def negative_sampling ( pos_ids , ch , C , num_negative_samples ) : neg_ids = torch . randint ( 0 , C , ( label . size ( 0 ) , num_negative_samples ) ) label = torch . ones ( ( label . size ( 0 ) , 1 ) ) id = torch . cat ( ( pos_ids , neg_ids ) , 1 ) label = torch . cat ( ( label , torch . zeros ( ( label . size ( 0 ) , num_negative_samples ) ) ) , 1 ) hidden = hidden [ id ] logits = logits [ id ] out = torch . bmm ( hidden , logits . unsqueeze ( - 1 ) ) . squeeze ( - 1 ) loss = nn . BCEWithLogitsLoss ( ) ( out , label ) return loss