Unifying training argument type annotations
Author: jannisborn
Pull request: yes

# 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 -->

This PR fixes the incorrect type annotations in the `TrainingArguments` class. Some arguments can handle complex types like `evaluation_strategy: IntervalStrategy`. However, when calling from CLI, they can be initialized using a `str` as well which is not reflected in the type annotations.

**Solution**: Fix the type annotations to `Union[ComplexType, str]`.

Note that this PR simply ensures consistency between the docstrings and the annotated types. E.g., the docstring for `evaluation_strategy` is already:
```txt
        evaluation_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
            The evaluation strategy...
```


## Before submitting
- [x] 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.

Please have a look @sgugger!

<!-- 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._

I understand that the tests are failing because of:

```txt
ValueError: Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because
the argument parser only supports one type per argument. Problem encountered in field 'evaluation_strategy'.
```

Could this issue of not supporting multiple types be fixed in HF itself? I guess no since it's introduced upstream by `arparse.add_argument` not allowing multiple types? @sgugger 

Ultimately, this is inconsistency between the type annotations and the actually possible types is caused by HF. I think it's quite  problematic because it's a systematic inconsistency that makes things appear more complex as they are. If the annotation has to be a single type, then should it not be the simplest type that can actually be used, in this case `str`? 
In that way, HF would be minimally invasive wrt downstream packages that indeed have stricter type annotation requirements.

The type is not perfectly exact, but note that:
1. the argument will be converted to that type in the post-init, so while the init of the dataclass accepts both `str` and `IntervalStrategy` (or other enum types), the attribute will always be of the enum type.
2. having the enum has main type allows us to properly fill the `choices` part of the parser for CLI help.

So to be able to accept the change in type, we would need some custom code in `HfArgumentParser` to not only stop erroring on those types, but also properly fill the `choices` part. If you're interested in exploring this further, those are the missing steps we would need in order to merge this PR.

Looking at this from the surface, it seems that this PR is (partially?) covered by the PR that was merged earlier today? https://github.com/huggingface/transformers/pull/17933

There:

- "Complex" enumtypes like IntervalStrategy (all that subclass `ExplicitEnum`) now also subclass `str`. As a consequence, the argparse equivalents also accept any string value
- `HfArgumentParser._parse_dataclass_field` (that gives you the Union error) has been updated to allow Union's that include a `str`, because the `str` type is never an issue for argparse (as its the default)

We don't have the error anymore, but we are still losing the autofill of "choices" and all the custom logic we had for enums [here](https://github.com/huggingface/transformers/blob/fbc7598babd06a49797db7142016f0029cdc41b2/src/transformers/hf_argparser.py#L105).

Thanks a lot @BramVanroy, that's a nice coincidence!!

@sgugger: Could we move up that logic about the autofill to an `elif` starting at L94?

I think there should be an if at line 94 that replaces the `field.dtype` by the `field.type.__args__` which is not `str` (like we replace the `field.dtype` that is not None below line 95 for `Optional`), then line 105 and the test for enums will be triggered properly.

Basically something like:
```py
if type(None) not in field.type.__args__:
    # filter `str` in Union
    field.type = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
    origin_type = getattr(field.type, "__origin__", field.type)
elif bool not in field.type.__args__:
``` 
before and replacing the line 
```py
if bool not in field.type.__args__:
```


Just did that!

Thanks! Will play a bit with it tomorrow morning to triple-check nothing breaks then it should be good to merge!

All good in my tests, thanks again for your work on this!