Skip to content

[torchgen] Refactor and simplify gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604)#150727

Closed
XuehaiPan wants to merge 22 commits intogh/XuehaiPan/264/basefrom
gh/XuehaiPan/264/head
Closed

[torchgen] Refactor and simplify gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604)#150727
XuehaiPan wants to merge 22 commits intogh/XuehaiPan/264/basefrom
gh/XuehaiPan/264/head

Conversation

@XuehaiPan
Copy link
Collaborator

@XuehaiPan XuehaiPan commented Apr 5, 2025

#129001 (comment) is the motivation for the whole stack of PRs. In torch/__init__.py, torch._C.Type shadows from typing import Type, and there is no type stub for torch._C.Type in torch/_C/__init__.pyi. So we need to use from typing import Type as _Type. After enabling Generic TypeAlias (PEP 585) in the .pyi type stub files, we can use type instead of typing.Type or from typing import Type as _Type.


  • Generic TypeAlias (PEP 585): e.g. typing.List[T] -> list[T], typing.Dict[KT, VT] -> dict[KT, VT], typing.Type[T] -> type[T].
  • Union Type (PEP 604): e.g. Union[X, Y] -> X | Y, Optional[X] -> X | None, Optional[Union[X, Y]] -> X | Y | None.

Note that in .pyi stub files, we do not need from __future__ import annotations. So this PR does not violate issue #117449:


Stack from ghstack (oldest at bottom):

cc @ezyang @malfet @xuzhao9 @gramster @bhosmer @bdhirsh @kadeng

[ghstack-poisoned]
@pytorch-bot
Copy link

pytorch-bot bot commented Apr 5, 2025

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/150727

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (1 Unrelated Failure)

As of commit c49612e with merge base e2ce17c (image):

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

[ghstack-poisoned]
[ghstack-poisoned]
@XuehaiPan XuehaiPan changed the title Refactor and simplify gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604) [torchgen] Refactor and simplify gen_pyi.py to use Generic TypeAlias (PEP 585) and Union Type (PEP 604) Apr 5, 2025
@XuehaiPan XuehaiPan requested a review from Copilot April 5, 2025 08:21
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 3 out of 4 changed files in this pull request and generated 1 comment.

Files not reviewed (1)
  • torch/_C/return_types.pyi.in: Language not supported

[ghstack-poisoned]
@XuehaiPan XuehaiPan requested a review from Copilot April 5, 2025 08:25
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 3 out of 4 changed files in this pull request and generated no comments.

Files not reviewed (1)
  • torch/_C/return_types.pyi.in: Language not supported
Comments suppressed due to low confidence (1)

torch/_subclasses/fake_tensor.py:1021

  • Using 'type: ignore[assignment]' suppresses potential type mismatches between the return type of suggest_memory_format and the expected type. Consider either updating the return type of suggest_memory_format or explicitly casting memory_format to ensure type consistency.
memory_format = None  # type: ignore[assignment]

Comment on lines +204 to +221
def format_function_signature(
name: str, arguments: Iterable[str] = (), return_type: str | None = None
) -> str:
if not isinstance(arguments, (list, tuple)):
arguments = tuple(arguments)
return_type = f" -> {return_type}" if return_type is not None else ""

sig = f"def {name}({', '.join(arguments)}){return_type}: ..."
if len(sig) <= 80 or len(arguments) == 0 or tuple(arguments) == ("self",):
return sig

return "\n".join(
(
f"def {name}(",
*(f" {arg}," for arg in arguments),
f"){return_type}: ...",
)
)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This PR provides a standard way to create a formatted signature. Previously, we did it in a handcrafted way.

XuehaiPan added 2 commits May 2, 2025 16:33
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
XuehaiPan added a commit to XuehaiPan/pytorch that referenced this pull request May 2, 2025
…s (PEP 585) and Union Type (PEP 604)

ghstack-source-id: 2b00421
Pull Request resolved: pytorch#150727
[ghstack-poisoned]
XuehaiPan added a commit to XuehaiPan/pytorch that referenced this pull request May 10, 2025
…s (PEP 585) and Union Type (PEP 604)

ghstack-source-id: 312b22a
Pull Request resolved: pytorch#150727
[ghstack-poisoned]
XuehaiPan added a commit to XuehaiPan/pytorch that referenced this pull request May 14, 2025
…s (PEP 585) and Union Type (PEP 604)

ghstack-source-id: 87a2ba3
Pull Request resolved: pytorch#150727
Copy link
Contributor

@aorenste aorenste left a comment

Choose a reason for hiding this comment

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

Unfortunately PEP604 is python 3.10+ and we have to support python 3.9 - so we can't convert to it yet.

[ghstack-poisoned]
@XuehaiPan
Copy link
Collaborator Author

Unfortunately PEP604 is python 3.10+ and we have to support python 3.9 - so we can't convert to it yet.

It's safe to use PEP604 because pyi stub files are not runnable at runtime. In .pyi files, we also do not need from __future__ import annotations.

@XuehaiPan XuehaiPan requested a review from aorenste May 14, 2025 15:26
@aorenste
Copy link
Contributor

Unfortunately PEP604 is python 3.10+ and we have to support python 3.9 - so we can't convert to it yet.

It's safe to use PEP604 because pyi stub files are not runnable at runtime. In .pyi files, we also do not need from __future__ import annotations.

That's a good point.

Copy link
Contributor

@aorenste aorenste left a comment

Choose a reason for hiding this comment

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

n.b.: I spot-checked the diff in the output .pyi files and they look reasonable as well.


At the moment, this module only handles type stubs for torch and
torch.Tensor. It should eventually be expanded to cover all functions
which come are autogenerated.
Copy link
Contributor

Choose a reason for hiding this comment

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

nit (I know this is just moved from below - but might as well fix if you have to update a new version):

Suggested change
which come are autogenerated.
which are autogenerated.

Extract the TensorMetadata of a tensor.
"""
memory_format: Optional[torch.memory_format] = suggest_memory_format(t)
memory_format = suggest_memory_format(t)
Copy link
Contributor

Choose a reason for hiding this comment

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

Why this change? It seems that memory_format can validly be None and it also seems unrelated to the rest of this PR...

) -> str:
if not isinstance(arguments, (list, tuple)):
arguments = tuple(arguments)
return_type = f" -> {return_type}" if return_type is not None else ""
Copy link
Contributor

Choose a reason for hiding this comment

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

Does return_type is None mean "unknown return type" or "returns None"? It seems to be the former - because here if it's None I think it's implicitly Any (because it's missing)... Maybe a quick comment to clarify.

XuehaiPan added a commit to XuehaiPan/pytorch that referenced this pull request May 14, 2025
…s (PEP 585) and Union Type (PEP 604)

ghstack-source-id: e9a854c
Pull Request resolved: pytorch#150727
@pytorchmergebot
Copy link
Collaborator

Starting merge as part of PR stack under #150728

pytorchmergebot pushed a commit that referenced this pull request May 15, 2025
…nd Union Type (PEP 604) (#150728)

#129001 (comment) is the motivation for the whole stack of PRs. In `torch/__init__.py`, `torch._C.Type` shadows `from typing import Type`, and there is no type stub for `torch._C.Type` in `torch/_C/__init__.pyi`. So we need to use `from typing import Type as _Type`. After enabling [Generic TypeAlias (PEP 585)](https://peps.python.org/pep-0585) in the `.pyi` type stub files, we can use `type` instead of `typing.Type` or `from typing import Type as _Type`.

------

- [Generic TypeAlias (PEP 585)](https://peps.python.org/pep-0585): e.g. `typing.List[T] -> list[T]`, `typing.Dict[KT, VT] -> dict[KT, VT]`, `typing.Type[T] -> type[T]`.
- [Union Type (PEP 604)](https://peps.python.org/pep-0604): e.g. `Union[X, Y] -> X | Y`, `Optional[X] -> X | None`, `Optional[Union[X, Y]] -> X | Y | None`.

Note that in `.pyi` stub files, we do not need `from __future__ import annotations`. So this PR does not violate issue #117449:

- #117449

------

Pull Request resolved: #150728
Approved by: https://github.com/cyyever, https://github.com/aorenste
ghstack dependencies: #150726, #150727
@github-actions github-actions bot deleted the gh/XuehaiPan/264/head branch June 18, 2025 02:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

better-engineering Relatively self-contained tasks for better engineering contributors ciflow/inductor Merged module: codegen Issues related to the codegen for Aten and Autograd module: typing Related to mypy type annotations open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants