Fixing failure when labels have different length
Author: haotianteng
Pull request: yes

Pop out label when padding the signal, add it back afterward to avoid the failure caused by different label length.

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR 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.

Models:

- albert, bert, xlm: @LysandreJik
- blenderbot, bart, marian, pegasus, encoderdecoder,  t5: @patrickvonplaten, @patil-suraj
- longformer, reformer, transfoxl, xlnet: @patrickvonplaten
- fsmt: @stas00
- funnel: @sgugger
- gpt2: @patrickvonplaten, @LysandreJik
- rag: @patrickvonplaten, @lhoestq
- tensorflow: @LysandreJik

Library:

- benchmarks: @patrickvonplaten
- deepspeed: @stas00
- ray/raytune: @richardliaw, @amogkam
- text generation: @patrickvonplaten
- tokenizers: @n1t0, @LysandreJik
- trainer: @sgugger
- pipelines: @LysandreJik

Documentation: @sgugger

HF projects:

- datasets: [different repo](https://github.com/huggingface/datasets)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Examples:

- maintained examples (not research project or legacy): @sgugger, @patil-suraj
- research_projects/bert-loses-patience: @JetRunner
- research_projects/distillation: @VictorSanh

 -->


Comments:
The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_19940). All of your documentation changes will be reflected on that endpoint.

Thanks for your PR. I don't see what is failing with the current code, could you provide a reproducible example of a bug?

This is a minimum example:
```python
import numpy as np
import datasets
from transformers import AutoTokenizer, BertForTokenClassification,DataCollatorForTokenClassification,Trainer,TrainingArguments
def tokenize_function(examples):
    input = tokenizer(examples["tokens"], is_split_into_words=True, truncation=True)
    return input

raw_datasets = datasets.load_dataset('conllpp')
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
n_label = len(raw_datasets['train'].features['ner_tags'].feature.names)
model = BertForTokenClassification.from_pretrained('bert-base-uncased',num_labels=n_label)
tokenized_datasets = raw_datasets.map(tokenize_function, 
                                      batched=True)
tokenized_datasets = tokenized_datasets.rename_column("ner_tags", "labels")
tokenized_datasets.set_format("torch") 
#This will make the collector to use the torch_call function and lead to failure when the label has different length.
data_collator = DataCollatorForTokenClassification(tokenizer)
training_args = TrainingArguments(output_dir = "bert_finetune", 
                                  evaluation_strategy = "epoch", 
                                  save_strategy="epoch",
                                  learning_rate=1e-5, 
                                  num_train_epochs=1, 
                                  per_device_train_batch_size=16, 
                                  per_device_eval_batch_size=16, 
                                  weight_decay=0.01, 
                                  push_to_hub = False)
trainer = Trainer(model,
                  training_args,
                  train_dataset=tokenized_datasets['train'],
                  eval_dataset=tokenized_datasets['validation'],
                  data_collator=data_collator,
                  tokenizer=tokenizer)
trainer.train()
```
The error:
Traceback (most recent call last):
  File "collector_issue.py", line 40, in <module>
    trainer.train()
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/transformers/trainer.py", line 1500, in train
    return inner_training_loop(
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/transformers/trainer.py", line 1716, in _inner_training_loop
    for step, inputs in enumerate(epoch_iterator):
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 628, in __next__
    data = self._next_data()
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 671, in _next_data
    data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 61, in fetch
    return self.collate_fn(data)
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/transformers/data/data_collator.py", line 42, in __call__
    return self.torch_call(features)
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/transformers/data/data_collator.py", line 306, in torch_call
    batch = self.tokenizer.pad(
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/transformers/tokenization_utils_base.py", line 2981, in pad
    return BatchEncoding(batch_outputs, tensor_type=return_tensors)
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/transformers/tokenization_utils_base.py", line 206, in __init__
    self.convert_to_tensors(tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis)
  File "/home/haotiant/anaconda3/envs/nlp/lib/python3.8/site-packages/transformers/tokenization_utils_base.py", line 732, in convert_to_tensors
    raise ValueError(
ValueError: Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your features (`labels` in this case) have excessive nesting (inputs type `list` where type `int` is expected).

Which is caused by torch_call function in transformers/data/data_collator.py
Specifically:
https://github.com/huggingface/transformers/blob/2e35bac4e73558d334ea5bbf96a1116f7c0d7fb3/src/transformers/data/data_collator.py#L307-L313

Notice the comment "# Conversion to tensors will fail if we have labels as they are not of the same length yet."
So I just fixed this bug by poping out the labels first and then feed them back, and then the afterward code would take care of the padding.

You have not aligned your TAGS with the tokens in this example, so it won't work anyway.

The error is due to the nested label list which has different lengths. I am not sure what you mean by aligning TAGS with token, I supposed you mean padding the label so they would have same length, but wasn't the collector supposed to do the auto-padding given nested a nested list label?

The collator will do the padding of the labels to add as many pad tokens as in the inputs. But the tokenizer splits a word in multiple subwords, and you haven't done anything for that in your labels. So you still end up with labels being of different sizes.

I think the label padding is after the tokenizer padding:

https://github.com/huggingface/transformers/blob/2e35bac4e73558d334ea5bbf96a1116f7c0d7fb3/src/transformers/data/data_collator.py#L320-325

And the padding is dynamically added for every batch, so I think there will be no problem?

This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.