Repository: huggingface/transformers (Python)
Date: 2020-10-22 20:59:50+00:00
Task type: Bug Fix

Issue:
Reformer model does not work with padded sequences
## Environment info
<!-- You can run the command `transformers-cli env` and copy-and-paste its output below.
     Don't forget to fill out the missing fields in that output! -->
     
- `transformers` version: 3.4.0
- Platform: Linux
- Python version: 3.8.5
- PyTorch version (GPU?): 1.6.0 (No)
- Tensorflow version (GPU?): 2.3.0
- Using GPU in script?: No
- Using distributed or parallel set-up in script?: No

### Who can help
<!-- Your issue will be replied to more quickly if you can figure out the right person to tag with @
 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.
 
 albert, bert, GPT2, XLM: @LysandreJik 
 tokenizers: @mfuntowicz
 Trainer: @sgugger
 Speed and Memory Benchmarks: @patrickvonplaten
 Model Cards: @julien-c
 Translation: @sshleifer
 Summarization: @sshleifer
 TextGeneration: @TevenLeScao 
 examples/distillation: @VictorSanh
 nlp datasets: [different repo](https://github.com/huggingface/nlp)
 rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)
 Text Generation: @TevenLeScao
 blenderbot: @mariamabarham
 Bart: @sshleifer
 Marian: @sshleifer
 T5: @patrickvonplaten
 Longformer/Reformer: @patrickvonplaten
 TransfoXL/XLNet: @TevenLeScao 
 examples/seq2seq: @sshleifer
 examples/bert-loses-patience: @JetRunner
 tensorflow: @jplu
 examples/token-classification: @stefan-it
 documentation: @sgugger
 -->
@patrickvonplaten 
## Information

Model I am using (Bert, XLNet ...): Reformer 

The problem arises when using:
* [ ] the official example scripts: (give details below)
* [x] my own modified scripts: (give details below)

The tasks I am working on is:
* [x] an official GLUE/SQUaD task: (give the name) CommonGen
* [ ] my own task or dataset: (give details below)

## To reproduce

Steps to reproduce the behavior:
```python
from transformers import ReformerTokenizer, ReformerModel


tokenizer = ReformerTokenizer.from_pretrained('google/reformer-crime-and-punishment')
seq = tokenizer(['Hello this is a test.', 'This is a test as well'], padding=True, return_tensors='pt')
reformer = ReformerModel.from_pretrained('google/reformer-crime-and-punishment')
out = reformer(**seq)
```
```python
Traceback (most recent call last):
  File "reformerbug.py", line 20, in <module>
    out = reformer(**seq)
  File "/home/fabian/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 722, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/fabian/.local/lib/python3.8/site-packages/transformers/modeling_reformer.py", line 2096, in forward
    embedding_output = self.embeddings(
  File "/home/fabian/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 722, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/fabian/.local/lib/python3.8/site-packages/transformers/modeling_reformer.py", line 252, in forward
    inputs_embeds = self.word_embeddings(input_ids)
  File "/home/fabian/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 722, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/fabian/.local/lib/python3.8/site-packages/torch/nn/modules/sparse.py", line 124, in forward
    return F.embedding(
  File "/home/fabian/.local/lib/python3.8/site-packages/torch/nn/functional.py", line 1814, in embedding
    return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
IndexError: index out of range in self
```
<!-- If you have code snippets, error messages, stack traces please provide them here as well.
     Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
     Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.-->

## Expected behavior
The model should properly calculate the forward pass given the encoded sequence. 
<!-- A clear and concise description of what you would expect to happen. -->



Issue discussion:

Solution patch:
diff --git a/src/transformers/tokenization_pegasus.py b/src/transformers/tokenization_pegasus.py
--- a/src/transformers/tokenization_pegasus.py
+++ b/src/transformers/tokenization_pegasus.py
@@ -47,8 +47,8 @@ class PegasusTokenizer(ReformerTokenizer):
     pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
     max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
+    def __init__(self, *args, pad_token="<pad>", **kwargs):
+        super().__init__(*args, **kwargs, pad_token="<pad>")
         # Don't use reserved words added_token_encoder, added_tokens_decoder because of
         # AssertionError: Non-consecutive added token '1' found. in from_pretrained
         assert len(self.added_tokens_decoder) == 0
diff --git a/src/transformers/tokenization_reformer.py b/src/transformers/tokenization_reformer.py
--- a/src/transformers/tokenization_reformer.py
+++ b/src/transformers/tokenization_reformer.py
@@ -86,19 +86,10 @@ class ReformerTokenizer(PreTrainedTokenizer):
     max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     model_input_names = ["attention_mask"]
 
-    def __init__(
-        self,
-        vocab_file,
-        eos_token="
",
-        unk_token="<unk>",
-        pad_token="<pad>",
-        additional_special_tokens=[],
-        **kwargs
-    ):
+    def __init__(self, vocab_file, eos_token="
", unk_token="<unk>", additional_special_tokens=[], **kwargs):
         super().__init__(
             eos_token=eos_token,
             unk_token=unk_token,
-            pad_token=pad_token,
             additional_special_tokens=additional_special_tokens,
             **kwargs,
         )
diff --git a/src/transformers/tokenization_reformer_fast.py b/src/transformers/tokenization_reformer_fast.py
--- a/src/transformers/tokenization_reformer_fast.py
+++ b/src/transformers/tokenization_reformer_fast.py
@@ -102,7 +102,6 @@ def __init__(
         tokenizer_file=None,
         eos_token="
",
         unk_token="<unk>",
-        pad_token="<pad>",
         additional_special_tokens=[],
         **kwargs
     ):
@@ -111,7 +110,6 @@ def __init__(
             tokenizer_file=tokenizer_file,
             eos_token=eos_token,
             unk_token=unk_token,
-            pad_token=pad_token,
             additional_special_tokens=additional_special_tokens,
             **kwargs,
         )


Test patch:
diff --git a/tests/test_tokenization_reformer.py b/tests/test_tokenization_reformer.py
--- a/tests/test_tokenization_reformer.py
+++ b/tests/test_tokenization_reformer.py
@@ -63,6 +63,50 @@ def test_rust_and_python_full_tokenizers(self):
         rust_ids = rust_tokenizer.encode(sequence)
         self.assertListEqual(ids, rust_ids)
 
+    def test_padding(self, max_length=15):
+        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
+            with self.subTest("{} ({})".format(tokenizer.__class__.__name__, pretrained_name)):
+                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
+
+                # Simple input
+                s = "This is a simple input"
+                s2 = ["This is a simple input 1", "This is a simple input 2"]
+                p = ("This is a simple input", "This is a pair")
+                p2 = [
+                    ("This is a simple input 1", "This is a simple input 2"),
+                    ("This is a simple pair 1", "This is a simple pair 2"),
+                ]
+
+                # Simple input tests
+                self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length")
+
+                # Simple input
+                self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length")
+
+                # Simple input
+                self.assertRaises(
+                    ValueError,
+                    tokenizer_r.batch_encode_plus,
+                    s2,
+                    max_length=max_length,
+                    padding="max_length",
+                )
+
+                # Pair input
+                self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length")
+
+                # Pair input
+                self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length")
+
+                # Pair input
+                self.assertRaises(
+                    ValueError,
+                    tokenizer_r.batch_encode_plus,
+                    p2,
+                    max_length=max_length,
+                    padding="max_length",
+                )
+
     def test_full_tokenizer(self):
         tokenizer = ReformerTokenizer(SAMPLE_VOCAB, keep_accents=True)