Transformer example: Position encoding function works only for even d_model?

Hi,

I am using the transformer example from https://pytorch.org/tutorials/beginner/transformer_tutorial.html
I noticed that if ‘d_model’ in PositionalEncoding function is an odd number, then it throws an error.

‘*** RuntimeError: The expanded size of the tensor (31) must match the existing size (32) at non-singleton dimension 1. Target sizes: [5000, 31]. Tensor sizes: [5000, 32]’

So, are we supposed to use only even numbered ‘d_dim’ or is it an issue with the function?

Thanks,

Interesting observation! The reason it’s happening is:

        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)

Here, torch.sin is used for the even indexes and torch.cos is used for the odd indexes of the input dimension (size = d_model). So, if d_model is odd, there will be a dimension size mismatch (division by 2 leaves a remainder).

I changed the function like this and removed the error.

class PositionalEncoding(nn.Module):

    def __init__(self, d_model, dropout=0.1, max_len=5000):
        super(PositionalEncoding, self).__init__()
        self.dropout = nn.Dropout(p=dropout)

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        if d_model%2 != 0:
            pe[:, 1::2] = torch.cos(position * div_term)[:,0:-1]
        else:
            pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        self.register_buffer('pe', pe)

    def forward(self, x):
        x = x + self.pe[:x.size(0), :]
        return self.dropout(x)

Still not fixed in Pytorch 1.9. If even d_model values are required then this should be an “assert …” line in the code. As it is the error message isn’t helpful