Error training ELMo - RuntimeError: The size of tensor a (5158) must match the size of tensor b (5000) at non-singleton dimension 1
I am trying to train my own custom ELMo model on AllenNLP.
The following bug RuntimeError: The size of tensor a (5158) must match the size of tensor b (5000) at non-singleton dimension 1 arises when training the model. There are instances where the size of tensor a is stated to be other values (e.g. 5300). When I tested on a small subset of files, I was able to train the model successfully.
Based on my intuition, this is something that deals with the number of tokens in my model. More specifically specific files which has tokens more than 5000. However, there is no parameter within the AllenNLP package which allows me to tweak this to bypass this error.
Any advice on how I can overcome this issue? Would tweaking the PyTorch code to set it at a 5000 size work (If yes, how can I do that)? Any insights will be deeply appreciated.
FYI, I am currently using a customised DatasetReader for tokenisation purposes. I've generated my own vocab list before training the model (to save some time) which is used to train the ELMo model via AllenNLP.
Update: I found out that there is this variable from AllenNLP max_len=5000 which is why the error is showing. See code here. I've tweaked the parameter to larger values and ended up with CUDA Out of Memory Error on many occasions instead. Making me believe this should not be touched.
Environment: Python 3.6.9, Linux Ubuntu, allennlp=2.9.1, allennlp-models=2.9.0
Traceback:
Traceback (most recent call last):
  File &quot;/home/jiayi/.local/bin/allennlp&quot;, line 8, in &lt;module&gt;
    sys.exit(run())
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/__main__.py&quot;, line 34, in run
    main(prog=&quot;allennlp&quot;)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/commands/__init__.py&quot;, line 121, in main
    args.func(args)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/commands/train.py&quot;, line 120, in train_model_from_args
    file_friendly_logging=args.file_friendly_logging,
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/commands/train.py&quot;, line 179, in train_model_from_file
    file_friendly_logging=file_friendly_logging,
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/commands/train.py&quot;, line 246, in train_model
    file_friendly_logging=file_friendly_logging,
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/commands/train.py&quot;, line 470, in _train_worker
    metrics = train_loop.run()
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/commands/train.py&quot;, line 543, in run
    return self.trainer.train()
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/training/gradient_descent_trainer.py&quot;, line 720, in train
    metrics, epoch = self._try_train()
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/training/gradient_descent_trainer.py&quot;, line 741, in _try_train
    train_metrics = self._train_epoch(epoch)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/training/gradient_descent_trainer.py&quot;, line 459, in _train_epoch
    batch_outputs = self.batch_outputs(batch, for_training=True)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp/training/gradient_descent_trainer.py&quot;, line 352, in batch_outputs
    output_dict = self._pytorch_model(**batch)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/torch/nn/modules/module.py&quot;, line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp_models/lm/models/language_model.py&quot;, line 257, in forward
    embeddings, mask
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/torch/nn/modules/module.py&quot;, line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp_models/lm/modules/seq2seq_encoders/bidirectional_lm_transformer.py&quot;, line 282, in forward
    token_embeddings = self._position(token_embeddings)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/torch/nn/modules/module.py&quot;, line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File &quot;/home/jiayi/.local/lib/python3.6/site-packages/allennlp_models/lm/modules/seq2seq_encoders/bidirectional_lm_transformer.py&quot;, line 68, in forward
    return x + self.positional_encoding[:, : x.size(1)]
RuntimeError: The size of tensor a (5385) must match the size of tensor b (5000) at non-singleton dimension 1

AllenNLP training config file:
// For more info on config files generally, see https://guide.allennlp.org/using-config-files

local NUM_GRAD_ACC = 4;
local BATCH_SIZE = 1;

local BASE_LOADER = {
  &quot;max_instances_in_memory&quot;: 8,
  &quot;batch_sampler&quot;: {
    &quot;type&quot;: &quot;bucket&quot;,
    &quot;batch_size&quot;: BATCH_SIZE,
    &quot;sorting_keys&quot;: [&quot;source&quot;]
  }
};

{
    &quot;dataset_reader&quot; : {
        &quot;type&quot;: &quot;mimic_reader&quot;,
        &quot;token_indexers&quot;: {
            &quot;tokens&quot;: {
                &quot;type&quot;: &quot;single_id&quot;
            },
            &quot;token_characters&quot;: {
                &quot;type&quot;: &quot;elmo_characters&quot;
            }
        },
        &quot;start_tokens&quot;: [&quot;&lt;S&gt;&quot;],
        &quot;end_tokens&quot;: [&quot;&lt;/S&gt;&quot;],
    },
    &quot;train_data_path&quot;: std.extVar(&quot;MIMIC3_NOTEEVENTS_DISCHARGE_PATH&quot;),
    // Note: We don't set a validation_data_path because the softmax is only
    // sampled during training. Not sampling on GPUs results in a certain OOM
    // given our large vocabulary. We'll need to evaluate against the test set
    // (when we'll want a full softmax) with the CPU.
    &quot;vocabulary&quot;: {
        // Use a prespecified vocabulary for efficiency.
        &quot;type&quot;: &quot;from_files&quot;,
        &quot;directory&quot;: std.extVar(&quot;ELMO_VOCAB_PATH&quot;),
        // Plausible config for generating the vocabulary.
        // &quot;tokens_to_add&quot;: {
        //     &quot;tokens&quot;: [&quot;&lt;S&gt;&quot;, &quot;&lt;/S&gt;&quot;],
        //     &quot;token_characters&quot;: [&quot;&lt;&gt;/S&quot;]
        // },
        // &quot;min_count&quot;: {&quot;tokens&quot;: 3}
    },
    &quot;model&quot;: {
        &quot;type&quot;: &quot;language_model&quot;,
        &quot;bidirectional&quot;: true,
        &quot;num_samples&quot;: 8192,
        # Sparse embeddings don't work with DistributedDataParallel.
        &quot;sparse_embeddings&quot;: false,
        &quot;text_field_embedder&quot;: {
        &quot;token_embedders&quot;: {
            &quot;tokens&quot;: {
            &quot;type&quot;: &quot;empty&quot;
            },
            &quot;token_characters&quot;: {
                &quot;type&quot;: &quot;character_encoding&quot;,
                &quot;embedding&quot;: {
                    &quot;num_embeddings&quot;: 262,
                    // Same as the Transformer ELMo in Calypso. Matt reports that
                    // this matches the original LSTM ELMo as well.
                    &quot;embedding_dim&quot;: 16
                },
                &quot;encoder&quot;: {
                    &quot;type&quot;: &quot;cnn-highway&quot;,
                    &quot;activation&quot;: &quot;relu&quot;,
                    &quot;embedding_dim&quot;: 16,
                    &quot;filters&quot;: [
                        [1, 32],
                        [2, 32],
                        [3, 64],
                        [4, 128],
                        [5, 256],
                        [6, 512],
                        [7, 1024]],
                    &quot;num_highway&quot;: 2,
                    &quot;projection_dim&quot;: 512,
                    &quot;projection_location&quot;: &quot;after_highway&quot;,
                    &quot;do_layer_norm&quot;: true
                }
            }
        }
        },
        // Consider the following.
        // remove_bos_eos: true,
        // Applies to the contextualized embeddings.
        &quot;dropout&quot;: 0.1,
        &quot;contextualizer&quot;: {
            &quot;type&quot;: &quot;bidirectional_language_model_transformer&quot;,
            &quot;input_dim&quot;: 512,
            &quot;hidden_dim&quot;: 4096,
            &quot;num_layers&quot;: 2,
            &quot;dropout&quot;: 0.1,
            &quot;input_dropout&quot;: 0.1
        }
    },
    &quot;data_loader&quot;: BASE_LOADER,
    // &quot;distributed&quot;: {
    //     &quot;cuda_devices&quot;: [0, 1],
    // },
    &quot;trainer&quot;: {
        &quot;num_epochs&quot;: 10,
        &quot;cuda_devices&quot;: [0, 1, 2, 3],
        &quot;optimizer&quot;: {
        // The gradient accumulators in Adam for the running stdev and mean for
        // words not used in the sampled softmax would be decayed to zero with the
        // standard &quot;adam&quot; optimizer.
        &quot;type&quot;: &quot;dense_sparse_adam&quot;
        },
        // &quot;grad_norm&quot;: 10.0,
        &quot;learning_rate_scheduler&quot;: {
        &quot;type&quot;: &quot;noam&quot;,
        // See https://github.com/allenai/calypso/blob/master/calypso/train.py#L401
        &quot;model_size&quot;: 512,
        // See https://github.com/allenai/calypso/blob/master/bin/train_transformer_lm1b.py#L51.
        // Adjusted based on our sample size relative to Calypso's.
        &quot;warmup_steps&quot;: 6000
        },
        &quot;num_gradient_accumulation_steps&quot;: NUM_GRAD_ACC,
        &quot;use_amp&quot;: true
    }
}


By setting the max_tokens variable for the custom DatasetReader built to below 5000, this error no longer persists. This was also suggested by one of AllenNLP's contributor to make sure the tokenizer truncates the input to 5000 tokens.
Same question was posted on AllenNLP: https://github.com/allenai/allennlp/discussions/5601
