Embedding Error Index

Lucas_Gongora: <p>Hi,</p>
<p>I am facing a problem with Embeddings: <em>IndexError: index out of range in self</em> as shown bellow:</p>
<pre><code class="lang-auto">    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
</code></pre>
<p>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</p>
<pre><code class="lang-auto">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)

        self.init_weights()

    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.bias.data.zero_()
        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
</code></pre>
<p>I believe the error is at: <em>self.ensemble = TransformerModel(ntoken=48, ninp=50, nhead=1, nhid=200, nlayers=2, dropout=0.5)</em> where i cannot find the proper dimensions of the variables of the function.</p>
<p>I am running something like:</p>
<pre><code class="lang-auto">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)
</code></pre>

ptrblck: <p>The error seems to be raised in:</p>
<pre><code class="lang-python">src = self.encoder(src) * math.sqrt(self.ninp)
</code></pre>
<p>which points to <code>self.encoder = nn.Embedding(ntoken, ninp)</code>.<br>
Could you check the <code>min</code> and <code>max</code> values of <code>src</code> and make sure they are in the valid input range for this layer <code>[0, ntoken-1]</code>?</p>

Lucas_Gongora: <p>I have already solved, thank you very much</p>