Skip to content

[typings] Automatically type decorator return types as tuple | X - #43446

Open
tomaarsen wants to merge 30 commits into
huggingface:mainfrom
tomaarsen:feat/auto_decorator_return_typing
Open

tomaarsen wants to merge 30 commits into
huggingface:mainfrom
tomaarsen:feat/auto_decorator_return_typing

Conversation

@tomaarsen

@tomaarsen tomaarsen commented Jan 23, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

What does this PR do?

This PR updates the can_return_tuple and check_model_inputs capture_outputs (see #43446 (comment)) typings such that:

from transformers.utils import can_return_tuple
from transformers.utils.generic import check_model_inputs
try:
    from typing import reveal_type
except ImportError:
    from typing_extensions import reveal_type


@can_return_tuple
def my_func(foo: int, bar: int, **kwargs) -> dict[str, int]:
    return {
        "sum": foo + bar,
        "product": foo * bar,
    }

result = my_func(1, 2)
reveal_type(result)  # tuple[Unknown, ...] | dict[str, int]


@check_model_inputs
def my_second_func(foo: int, bar: int, **kwargs) -> dict[str, int | float]:
    return {
        "minus": float(foo - bar),
        "div": foo / bar,
    }

result2 = my_second_func(1, 2)
reveal_type(result2)  # tuple[Unknown, ...] | dict[str, int | float]

In short: functions and method that use can_return_tuple or check_model_inputs must currently be typed like tuple | X, but can now be typed like X as well.

I also had Copilot help me write a check_decorator_return_types.py file that ensures that functions decorated with can_return_tuple or check_model_inputs:

  1. Have an explicit, non-None return annotation.
  2. Are not annotated with a union that already includes tuple.

The latter can be auto-fixed with python utils/check_decorator_return_types.py --fix_and_overwrite, and the former must be manually fixed. This checking script is included in make fix-repo and the CI. The script only runs in about ~5 seconds for me.

Before submitting

Who can review?

cc @zucchini-nlp @vasqu @tarekziade

  • Tom Aarsen

…rn type

This updates the typings of these two functions, so that a wrapped function that has return type X is automatically typed as `tuple | X`.
It verifies that users don't use e.g. `tuple | BaseModelOutputWithPooling` return typings anymore, as they should use `BaseModelOutputWithPooling` instead then. It also makes sure that a typing is used
This is the main actual change, the rest is just typings
And remove return_dict from altclip and clap: the can_return_tuple should take care of it fully
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Comment thread src/transformers/utils/generic.py Outdated
Comment on lines +37 to +38
P = ParamSpec("P")
T = TypeVar("T")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer note: the ParamSpec and TypeVar as used here match Python's own typing documentation exactly: https://docs.python.org/3.10/library/typing.html#typing.ParamSpec

They also use an example of a decorator, so the implementation here is quite standard/common.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't hurt to add the doc link as comment to the wrappers we use it at below - it's like 1:1 matching the example :D

@tomaarsen tomaarsen Jan 23, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very true! Done in dbd43d6 & 3fd9571

Comment thread utils/check_decorator_return_types.py Resolved
Comment thread utils/check_decorator_return_types.py Resolved

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work! I have just a few questions about the auto-checker


self.post_init()

@check_model_inputs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

accidentally deleted?

Comment thread utils/check_decorator_return_types.py Resolved
Comment thread utils/check_decorator_return_types.py Resolved
Comment thread utils/check_decorator_return_types.py Resolved
Comment thread utils/check_decorator_return_types.py Resolved

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm

Maybe we should start splitting into more than fix-repo again @Cyrilvallez 👀

Comment thread src/transformers/utils/generic.py Outdated
Comment on lines +37 to +38
P = ParamSpec("P")
T = TypeVar("T")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't hurt to add the doc link as comment to the wrappers we use it at below - it's like 1:1 matching the example :D

Comment thread utils/check_decorator_return_types.py Resolved
Comment thread utils/check_decorator_return_types.py Resolved
Comment thread utils/check_decorator_return_types.py Resolved
@github-actions

Copy link
Copy Markdown
Contributor

@tomaarsen

Copy link
Copy Markdown
Member Author

I updated this PR with @Cyrilvallez' latest changes regarding model_check_inputs -> capture_outputs, so that methods wrapped with capture_outputs are also nicely typed:

from transformers.utils import can_return_tuple
from transformers.utils.output_capturing import capture_outputs

try:
    from typing import reveal_type
except ImportError:
    from typing_extensions import reveal_type


@can_return_tuple
def my_func(foo: int, bar: int, **kwargs) -> dict[str, int]:
    return {
        "sum": foo + bar,
        "product": foo * bar,
    }


result = my_func(1, 2)
reveal_type(result)  # tuple[Unknown, ...] | dict[str, int]


@capture_outputs
def my_second_func(foo: int, bar: int, **kwargs) -> dict[str, int | float]:
    return {
        "minus": float(foo - bar),
        "div": foo / bar,
    }


result2 = my_second_func(1, 2)
reveal_type(result2)  # tuple[Unknown, ...] | dict[str, int | float]
ty check demo.py
info[revealed-type]: Revealed type
  --> demo_can_return_tuple_hint.py:19:13
   |
18 | result = my_func(1, 2)
19 | reveal_type(result)  # tuple[Unknown, ...] | dict[str, int]
   |             ^^^^^^ `tuple[Unknown, ...] | dict[str, int]`
   |

info[revealed-type]: Revealed type
  --> demo_can_return_tuple_hint.py:31:13
   |
30 | result2 = my_second_func(1, 2)
31 | reveal_type(result2)  # tuple[Unknown, ...] | dict[str, int | float]
   |             ^^^^^^^ `tuple[Unknown, ...] | dict[str, int | float]`
   |

Found 2 diagnostics

This should help cut down some bloat from our modeling/modular files without considerably complicating any of the decorators. Ideally, we can get this merged somewhat quickly, as the merge conflicts start quickly too.

also cc @molbap as you're also working on decorator-related cleanup in #43590 right now

  • Tom Aarsen

@ArthurZucker

Copy link
Copy Markdown
Collaborator

@vasqu could you take a look when you get a chance? This is waiting on a maintainer: it has been waiting for a maintainer review.

@vasqu

vasqu commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator

Hmm it's quite outdated since a lot of models have been merged since then; are you up to revisit this @tomaarsen?

@tomaarsen

Copy link
Copy Markdown
Member Author

For sure, should be relatively simple to revisit as the majority of the changes are generated by the one correctness script. I'm on it.

  • Tom Aarsen

@tomaarsen

tomaarsen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member Author

Reverted the actual changes in modeling/modular, keeping only the can_return_type/capture_outputs typing, utility script, Makefile, workflow, and test changes. As expected, this now triggers the CI with the new Check repository consistency rules:

ValueError: Found decorator return-type violations:

src/transformers/models/afmoe/modeling_afmoe.py:526: function 'forward' decorated with '@capture_outputs' must not be annotated with a union that includes 'tuple'
src/transformers/models/afmoe/modular_afmoe.py:331: function 'forward' decorated with '@capture_outputs' must not be annotated with a union that includes 'tuple'
...
src/transformers/models/zamba2/modular_zamba2.py:595: function 'forward' decorated with '@can_return_tuple' must not be annotated with a union that includes 'tuple'

Time to auto-fix them with the script.

  • Tom Aarsen

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: afmoe, aimv2, albert, align, altclip, aria, audioflamingo3, autoformer, aya_vision, bart, beit, bert, bert_generation, bigbird_pegasus, biogpt, blenderbot

@tomaarsen

tomaarsen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member Author

For reviewing, you should mostly ignore the src/transformers/models changes, those were created in a few ways:

  1. Auto-generated with python utils/check_decorator_return_types.py --fix_and_overwrite + a modular conversion (e3cf490)
  2. Manually add missing return types (acf7453) + a modular conv (0639b3b)
  3. Manually remove tuple | from modular files that inherit the can_return_tuple / capture_outputs decorators (as the utility function doesn't automatically fix those!) (826baf2) + a modular conv (7366871)

After this is merged, for new PRs that e.g. use tuple | BaseModelOutput as their return type on a decorated method, the CI will fail with a useful warning. Makefile will also auto-fix where possible, with some exceptions (e.g. missing type hint and if the decorator is inherited & the auto-fix won't recognize it).

And as a reminder, the idea of this PR is that:

  • Model authors only use the BaseModelOutput subclass as the return type
  • Model users see tuple[Any] | BaseModelOutput as the return type due to the automatic decorator typing

Now, I'm running into a new issue, cc @tarekziade
These decorators now infer the intended return types, but ty reports eight errors inside the wrappers around self.config and .to_tuple() on an "unconstrained T" (https://github.com/huggingface/transformers/actions/runs/39619789953/job/119289872602?pr=43446). What do you reckon I should do? I can add like ~4 cast calls, but I'm personally not the biggest fan of that. Perhaps that's how transformers does it nowadays though?

Kind of ironic that I'm trying to improve typing here, and what's blocking me now is typing 😆

  • Tom Aarsen

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's just move. the AST part to mlinter!

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should live in the mlinter now!

@tomaarsen

tomaarsen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member Author

Ah nice, yeah that would be very clean! For this PR, that would leave the generic.py and output_capturing.py changes, plus the both automatic and manual modeling/modular changes, and the "automatic detection and fixing" can go to mlinter & be added as a rule in transformers eventually in a different PR. Then this PR could be merged soon-ish instead of waiting for the mlinter work to be ready / released.

Then only the generic.py and output_capturing.py typing constraints remain. cc @tarekziade I reckon you have a good view on those. Also, do you want me to open a PR on mlinter? I'm not familiar with the repo yet, but I can set something up quickly.

  • Tom Aarsen

@vasqu

vasqu commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator

Is the mlinter not just for detecting? It should not auto fix anything

@tomaarsen

Copy link
Copy Markdown
Member Author

Yeah, I just looked more into mlinter, it only detects. An auto-fix is nice, but not very important, it'll be very simple for users to fix themselves.

  • Tom Aarsen

@vasqu

vasqu commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator

Do we keep something in transformers that auto fixes this e.g. via make fix-repo?

@tarekziade

Copy link
Copy Markdown
Collaborator

FYI auto fix is on my radar for mlinter if there's interest we can use this one for a first auto fix capable rule

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants