[T5 Tokenizer] Model has no fixed position ids - there is no hardcode…
Author: patrickvonplaten
Pull request: yes

…d max 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 #16986


## 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 documentation is not available anymore as the PR was closed or merged._

> Oh, that's a serious change if a user forgot to set a `max_length`. I understand it fixes a bug, but still would like @LysandreJik 's take on it as well. Thanks for the PR in any case!

Agree! We should at least put some :exclamation: mark in this PR stating that this change could lead to unexpected behavior OOM if `max_length` is not defined.

That is definitely a breaking change we want to avoid, IMO. This is likely to break user pipelines with OOM errors or a non consistent number of tokens generated. I'd advocate against this change, and would push to:
- Document that while the limit is set to 512, T5 can handle longer lengths and encourage users to define their own max lengths
- Document that this limit will be removed in v5
- Update the warning just for T5 (see below)

<details>
<summary>Updating the warning just for T5</summary>

You can override this method, which is in `tokenization_utils_base.py`, in `tokenization_t5.py` and `tokenization_t5_fast.py`

https://github.com/huggingface/transformers/blob/e6f00a11d7fa34215184e3c797e19e6c7debe0fe/src/transformers/tokenization_utils_base.py#L3379-L3397

I wouldn't recommend skipping the warning altogether as it still gives important information regarding why the text was eventually truncated or padded. But updating the message makes sense:

```diff
    def _eventual_warn_about_too_long_sequence(self, ids: List[int], max_length: Optional[int], verbose: bool):
        """
        Depending on the input and internal state we might trigger a warning about a sequence that is too long for its
        corresponding model

        Args:
            ids (`List[str]`): The ids produced by the tokenization
            max_length (`int`, *optional*): The max_length desired (does not trigger a warning if it is set)
            verbose (`bool`): Whether or not to print more information and warnings.

        """
        if max_length is None and len(ids) > self.model_max_length and verbose:
            if not self.deprecation_warnings.get("sequence-length-is-longer-than-the-specified-maximum", False):
                logger.warning(
-                    "Token indices sequence length is longer than the specified maximum sequence length "
-                    f"for this model ({len(ids)} > {self.model_max_length}). Running this sequence through the model "
-                    "will result in indexing errors"
+                    "The T5 model has no maximum length, but a maximum length is still set for backwards compatibility "
+                    "purposes. To take advantage of the full capabilities of the model, we recommend setting a "
+                    "max_length manually."
                )
            self.deprecation_warnings["sequence-length-is-longer-than-the-specified-maximum"] = True
```
 
</details>

Okey took some time to think about it - it's really not easy. I agree @LysandreJik that the previous change (while correct) is too strong as it might break quite some pipelines. 

To begin with, note that `model_max_length` or `max_length` is only relevant if `truncation=True` is set. So for all other cases this bug is not relevant. 
Now the problem is that by default T5 should **not** have a set maximum length. 
However it is completely reasonable for people to set their own maximum length. To me this means the following: If a user instantiates T5 Tokenizer with `model_max_length` or passes `max_length` when encoding/padding, then these values should **always** be the true max length values and in this case the (incorrectly) hard-coded max length values can be discarded. 
Only if a user does not pass `max_length` when encoding/padding and does not define `model_max_length` at init, then we should fall back to the (incorrect) hard-coded max length values until v5.

In this PR there two things are changed the 2.) can be considered a small breaking change, but it's really a bug correction for me.

1. If T5 Tokenizer is instantiated without a custom `model_max_length` and one of the identifiers for which `model_max_length` is hardcoded is used, the following warning appears:
```
This tokenizer was incorrectly instantiated with a model max length of 512 which will be corrected in Transformers v5.
For now, this behavior is kept to avoid breaking backwards compatibility when padding/encoding with `truncation is True`.
- Be aware that you SHOULD NOT rely on t5-base automatically truncating your input to 512 when padding/encoding.
- If you want to encode/pad to sequences longer than 512 you can either instantiate this tokenizer with `model_max_length` or pass `max_length` when encoding/padding.
- To avoid this warning, please instantiate this tokenizer with `model_max_length` set to your preferred value.
```
Previously no warning appeared. Note that this warning appears every time at init. However it can be disabled as described above and it's also good to warn the user about upcoming changes this way.

2. If T5 Tokenizer is instantiated with a `model_max_length`, this `model_max_length` always counts even if it's longer than the hardcoded ones. This means the following snippet:
```python
#!/usr/bin/env python3
from transformers import T5TokenizerFast

tok = T5TokenizerFast.from_pretrained("t5-base", model_max_length=600)

out = tok(100 * "hello there is a", padding="longest", truncation=True).input_ids
print(len(out))
```

does **not** throw a warning (since the user defines `model_max_length`) and print a length of 600 (not 512). <- this behavior is different from how it was before.
My rational on changing this is the following:
- T5's hardcoded model max lengths are wrong, I'm fine with using those if no `model_max_length` is defined or no `max_length` is passed
- **But**, if a user already passes a `model_max_length` <- then this should be the only source of truth. E.g. In the example above 600 should be tha max length and not 512.


**To be crystal clear 2.) changes the behavior - e.g. run the code snippet before/after the PR, but it's really a bug correction here IMO**


Failure is unrelated