I compared the output of your code with my current implementation, it does not yield the same value, after searching for the difference, I found the bug is here
mask = Variable(mask.unsqueeze(1)).type_as(encoded_target)  # no need to expand, thanks to array broadcasting
output *= mask
encoded_target *= mask # not equivalent to encoded_target[mask] = 0