I guess w_sum * mask_d is zero in the last step. if you print it, you can find it out. Also I’m wondering why you do w_max.data[w_max.data < 0] = 0.
You may try smooth tricks, like add  eps*seq_length in w_sum  and eps in w. But I think it would better to find the cause of this problem in your model.