I am trying to implement an autoregressive transformer model similar to the paper attention is all you need. From what I have understood, in order to replicate the architecture fully, I need to give the transformer decoder 3 masks.

1. Target subsequent mask: this is for causality.

3. Encoder padding indices: just to look at non-padded inputs from the encoder.

The snippet is here:

y = self.decoder(y, x,


With masks being generated like this:

def generate_no_peek_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)


I found out what the problem was. It was not from subsequent mask. It was caused by bad key_padding_mask. PyTorch expects the key_padding_mask to be true wherever there is a padding token and false wherever there is none. I was generating the padding mask in exactly the opposite way. So the correct mask will be:
def generate_padding_mask(self, seq, pad_idx):