If your loss function accepts batches of inputs, you could assign the batch of scores to d with a range indexing: [i*bs:(i+1)*bs].
This would avoid looping one by one in both loops and could calculate the loss for multiple sample pairs.