Embedding Error Index


I am facing a problem with Embeddings: IndexError: index out of range in self as shown bellow:

    y = self.ensemble(x, mask)
  File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/lucasgongora/Documents/KTH/Courses/Thesis/tracab-masters-ball-from-context/model/networks.py", line 33, in forward
    src = self.encoder(src) * math.sqrt(self.ninp)
  File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/sparse.py", line 145, in forward
    return F.embedding(
  File "/usr/local/lib/python3.8/dist-packages/torch/nn/functional.py", line 1913, in embedding
    return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
IndexError: index out of range in self

For context, I am running a database x with dimensions (batch_size x 50 x 48). And I need to input with this configuration. I am training it on The transformer network

class TransformerModel(nn.Module):

    def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):
        super(TransformerModel, self).__init__()
        from torch.nn import TransformerEncoder, TransformerEncoderLayer
        self.model_type = 'Transformer'
        self.pos_encoder = PositionalEncoding(ninp, dropout)
        encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)
        self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)
        self.encoder = nn.Embedding(ntoken, ninp)
        self.ninp = ninp
        self.decoder = nn.Linear(ninp, ntoken)


    def generate_square_subsequent_mask(self, sz):
        mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
        mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
        return mask

    def init_weights(self):
        initrange = 0.1
        self.encoder.weight.data.uniform_(-initrange, initrange)
        self.decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self, src, src_mask):
        src = self.encoder(src) * math.sqrt(self.ninp)
        src = self.pos_encoder(src)
        output = self.transformer_encoder(src, src_mask)
        output = self.decoder(output)
        return output

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)
        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)

class Ensemble_Networks(nn.Module):
    def __init__(self, num_output_target, num_in_players, num_output_players, dim_output_players, num_features,
                 num_inds_players=64, dim_hidden_players=128, num_heads_players=4):
        super(Ensemble_Networks, self).__init__()

        self.ensemble = TransformerModel(ntoken=48, ninp=50, nhead=1, nhid=200, nlayers=2, dropout=0.5)

    def forward(self, x, mask):
        y = self.ensemble(x, mask)
        return y

I believe the error is at: self.ensemble = TransformerModel(ntoken=48, ninp=50, nhead=1, nhid=200, nlayers=2, dropout=0.5) where i cannot find the proper dimensions of the variables of the function.

I am running something like:

mask = self.generate_square_subsequent_mask(50)
        for Epochs in trange(self.n_epochs, desc='Epoch'):
                for step in range(iter_size):
                    x, y = data_import.create_batches(x_train, y_train)
                    y_pred = self.model(x, mask)

The error seems to be raised in:

src = self.encoder(src) * math.sqrt(self.ninp)

which points to self.encoder = nn.Embedding(ntoken, ninp).
Could you check the min and max values of src and make sure they are in the valid input range for this layer [0, ntoken-1]?

I have already solved, thank you very much