VSCode pylance auto-completion for `HfArgumentParser` (limited support)
Author: vwxyzjn
Pull request: yes

# Problem description

This PR empowers limited support of VSCode auto-completion for `HfArgumentParser`.  Currently, the return type of `parse_args_into_dataclasses` is `DataClass = NewType("DataClass", Any)`, which limits pylance's ability to infer types even if we specifically assert a dataclass type fo the args.


<img width="672" alt="image" src="https://github.com/huggingface/transformers/assets/5555347/6c8cf0c2-40c7-4436-bdfb-e08a74ec4882">

# What does this PR do?

This PR modifies the return type to be `List[TypeVar("T")]`. So when **we assert the args to be of a certain type** (i.e., `assert isinstance(args, RewardConfig)`), auto-completion works as expected. 


<img width="595" alt="image" src="https://github.com/huggingface/transformers/assets/5555347/5d6de0e9-7f71-4291-a49e-0081f89a6de9">



## Alternatives considered

Some `argparse` libraries such as [tyro](https://github.com/brentyi/tyro) can automatically infer the type of the args, but it doesn't seem to work with the current `HfArgumentParser` paradigm for two reasons:

1. The inferred type seems only to support one type, so the inferred type is `args2: RewardConfig | Config2`, so we can't parse multiple dataclasses in `parse_args_into_dataclasses` and infer type correctly.
<img width="601" alt="image" src="https://github.com/huggingface/transformers/assets/5555347/de2a3f98-0014-48f3-b986-c56c7f73a602">

2. Automatic type detection also requires us to change the workflow: we need to do `parse_args_into_dataclasses([RewardConfig, Config2])` instead of `parse_args_into_dataclasses()`

<img width="428" alt="image" src="https://github.com/huggingface/transformers/assets/5555347/b0fbd3cb-f1c8-448d-bb25-1e9743f333fa">




<!--
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 -->



## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] 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.

CC @muellerzr, @pacman100, @lewtun, @brentyi

<!-- 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:

- text models: @ArthurZucker and @younesbelkada
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @gante
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @pacman100

Integrations:

- deepspeed: HF Trainer/Accelerate: @pacman100
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc and @younesbelkada

Documentation: @stevhliu and @MKhalusova

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


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

Hello!

As some alternative suggestions, `typing.Generic` does make specificity in `parse_args_into_dataclasses()` possible.

(1) [This implementation](https://gist.github.com/brentyi/a003d480f25c7aeebd531ab88e75dac3) gets us:

![image](https://github.com/huggingface/transformers/assets/6992947/71a8ada5-ae58-4227-b5fa-f08434da13a9)

(2) `typing.overload` can also help, although there are some limitations from Python's type system[^1]. [This implementation](https://gist.github.com/brentyi/67963d83f7e278ec0a4b4eb1f8988e52) gets us:

![image](https://github.com/huggingface/transformers/assets/6992947/33a7491a-5cb1-404d-adae-d508d051f2cb)

---

As an FYI, `tyro` should correctly resolve the types of:

```python
import dataclasses
import tyro

@dataclasses.dataclass
class TrainArgs:
    lr: float = 3e-4

@dataclasses.dataclass
class RewardConfig:
    weight: float = 0.01

# This currently prefixes arguments with `--0.` for TrainArgs, and `--1.` for RewardConfig. Could be made configurable.
train, reward = tyro.cli(tuple[TrainArgs, RewardConfig])
```

A similar API in HfArgumentParser could make the types much cleaner, but comes with all of the obvious downsides of a breaking change.

[^1]: As in the shared code, a maximum number of dataclasses needs to be hardcoded. This might be solved in the future with better variadic generic support in the Python type system: https://github.com/python/mypy/issues/16394




@brentyi thanks so much for the detailed suggestions! I personally like "(2) typing.overload can also help" and set a maximum to something like 10, but the code will look quite hacky... Would like some input from `transformers` maintainers

@vwxyzjn @brentyi Thanks for opening this PR and the work on improving the codebase! 

As a general note, the type annotations in the library are not intended to be complete or fully compatible with type checkers e.g. running mypy will throw a bunch of errors. They are there as general documentation to guide the user. 

So, in this case, `DataClass` is a more descriptive annotation as a return type than `T`, even though they both effectively represent "Any".  

Hi @amyeroberts thanks for the comment! I agree that type annotation do not necessarily need to work with mypy. The main thing I was thinking is the developer experience with auto-completion. 


## With @brentyi's option 1, we would still get the descriptive API like before

```
def parse_args_into_dataclasses(self) -> Tuple[DataclassT, ...]:
```

but by default it's unable to recognize which dataclass type it is, so for usage like `HfArgumentParser((ModelArguments, RewardModelArguments, EvaluationArguments))`, the auto-completion can cause some confusion (in the screen shot below, pylance thought the `train`'s type is either `TrainArgs` or `RewardConfig`)


<img width="663" alt="image" src="https://github.com/huggingface/transformers/assets/5555347/4c8d5d08-bb48-4354-ac56-7c07d843fe92">



## With @brentyi's option 2

Our internal code would become uglier like 


```
    @overload
    def parse_args_into_dataclasses(self: HfArgumentParser[T1, None, None, None]) -> T1:
        return self._parse_args_into_dataclasses()

    @overload
    def parse_args_into_dataclasses(
        self: HfArgumentParser[T1, T2, None, None]
    ) -> Tuple[T1, T2]:
        return self._parse_args_into_dataclasses()

    @overload
    def parse_args_into_dataclasses(
        self: HfArgumentParser[T1, T2, T3, None]
    ) -> Tuple[T1, T2, T3]:
        return self._parse_args_into_dataclasses()

    @overload
    def parse_args_into_dataclasses(
        self: HfArgumentParser[T1, T2, T3, T4]
    ) -> Tuple[T1, T2, T3, T4]:
        return self._parse_args_into_dataclasses()

    def parse_args_into_dataclasses(self) -> Any:
        return self._parse_args_into_dataclasses()
```

but the user will have a more seamless experience (pylance would correctly recognize `train`'s type is `TrainArgs`)


<img width="598" alt="image" src="https://github.com/huggingface/transformers/assets/5555347/db11a772-ba65-4956-9d88-a0dc63ce9355">


Would you be in favor of either options? 1st option would require the least amount of change of course. Both options are non-breaking and just empower pylance's auto-completion in different ways.



As a user of the library I'd personally appreciate the option 2 approach, it's nice when completions work! But I also agree it adds maintenance burden.

If folks would prefer to avoid `typing.Generic`, an option 3 is to just swap the
```python
DataClass = NewType("DataClass", Any)
DataClassType = NewType("DataClassType", Any)
```
for
```python
DataClass = Any
DataClassType = Any  # or type / typing.Type
```
This will make the assertions in the PR description useful for correct autocompletion; `NewType` has static analysis implications (in this case, preventing type narrowing) + usage connotations that IMO would be nice to avoid here.

I completely understand the motivation behind this. However adding additional code for type checking (in particular overloads) is something which has been proposed and rejected before. The primary reason for this is that we don't formally support type checking and we don't want to add additional code we need to maintain in order to support it. For example: [this comment](https://github.com/huggingface/transformers/issues/23980#issuecomment-1576991446) and [releated PR](https://github.com/huggingface/transformers/pull/24035), or [this comment](https://github.com/huggingface/transformers/pull/26125#issuecomment-1729007149).  



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.