Skip to content

[pyrefly] Add type annotations to torch/fx/experimental/migrate_gradu… - #180070

Closed
Lucaskabela wants to merge 1 commit into
mainfrom
pyrefly/fx-exp-gradual-types
Closed

Lucaskabela wants to merge 1 commit into
mainfrom
pyrefly/fx-exp-gradual-types

Conversation

@Lucaskabela

Copy link
Copy Markdown
Contributor

…al_types

Remove mypy suppressions. Add return type and parameter type annotations to constraint classes, generator, transformation, and z3 transform.

Authored with Claude.

@pytorch-bot pytorch-bot Bot added the release notes: fx release notes category label Apr 10, 2026
@pytorch-bot

pytorch-bot Bot commented Apr 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

❌ 2 New Failures, 2 Unrelated Failures

As of commit af20acf with merge base ce68080 (image):

NEW FAILURES - The following jobs have failed:

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@Lucaskabela
Lucaskabela force-pushed the pyrefly/fx-exp-gradual-types branch from 820e6c1 to 796bf6c Compare April 10, 2026 23:12
@Lucaskabela

Copy link
Copy Markdown
Contributor Author

@claude review this PR - be specific on Any usage

@claude

claude Bot commented Apr 10, 2026 •

Copy link
Copy Markdown

Claude finished @Lucaskabela's task in 1m 56s —— View job


Review of PR #180070

  • Read changed files and gather context
  • Review constraint.py for Any usage
  • Review constraint_generator.py for Any usage
  • Review constraint_transformation.py for Any usage
  • Review transform_to_z3.py for Any usage
  • Review allowlist_for_publicAPI.json changes
  • Post detailed review

Overall: Good progress removing mypy: allow-untyped-defs / mypy: ignore-errors suppressions and adding concrete types. The constraint classes and generator are well-typed. The main area of concern is Any usage in transform_to_z3.py and the pattern of isinstance guards in the transformation rules.


Any Usage Audit

transform_to_z3.py — 7 uses of Any (the main concern)

  1. transform_to_z3() return type tuple[Any, int] (line 56): The first element of the return tuple is a z3 expression (z3.BoolRef or Python bool). Since z3 is an optional import, the type can't be expressed without a TYPE_CHECKING guard. However, you could define a type alias like _Z3Expr: TypeAlias = Any to at least document the intent and make it greppable. The same applies to:

  2. transform_var() return type tuple[Any, int] (line 256)

  3. transform_dimension() return type tuple[Any, int] (line 296)

  4. transform_algebraic_expression() return type tuple[Any, int] (line 330)

  5. res: list[Any] in transform_var (line 265): This list holds z3 dimension datatypes. Same situation — a named alias would be cleaner than bare Any.

  6. transform_all_constraints() return type Any (line 395): Returns a z3 BoolRef. Same fix applies.

  7. transform_all_constraints_trace_time() return type tuple[Any, Any] (line 425): Both elements are z3 expressions.

  8. evaluate_conditional_with_constraints() has user_constraints: Any = None and return tuple[Any, Any] (lines 496-497): The parameter is a z3 constraint, and the returns are z3 CheckSatResult. These could be _Z3Expr | None and tuple[_Z3Result, _Z3Result] respectively (with appropriate aliases).

Recommendation: All Any in this file exists because z3 is conditionally imported. A single _Z3Expr: TypeAlias = Any alias at the top of the file (or under if TYPE_CHECKING) would make the intent clear and make it easy to tighten later if z3 stubs become available. This is a common pattern in PyTorch for optional dependencies. Fix this →

constraint_generator.py — 0 uses of Any

No Any usage. Well done — the _SymbolDict type alias and Callable[..., tuple[list[Constraint], int]] for _INFERENCE_RULES are good choices.

constraint.py — 0 uses of Any

Clean. The _Operand type alias is a proper union covering all operand types.

constraint_transformation.py — 0 uses of Any

Clean. The _TransformFn type alias is well-defined.


Other Issues

Repetitive isinstance guards in constraint_transformation.py

Every transformation function follows this pattern:

def transform_foo(constraint: Constraint, counter: int) -> tuple[Constraint, int]:
    if not isinstance(constraint, Foo):
        raise TypeError(type(constraint))
    ...

This is 2 lines of boilerplate repeated 14 times. The dispatch already guarantees the correct type via _TRANSFORMATION_RULES[type(constraint)]. If you want the narrowing for the type checker, consider either:

  • Typing the registered functions with the specific subtype (e.g., Transpose instead of Constraint) and using cast() in the dispatch, or
  • Adding a single assert isinstance(...) instead of the raise TypeError (more conventional for "this should never happen" checks).

Not blocking, but worth considering to reduce noise.

constraint_transformation.py:129 — Bug in transform_index_select

new_dims = copy.deepcopy(dims)
if is_valid_index == T():
    new_dims[constraint.index] = constraint.dim_replace  # type: ignore[unsupported-operation]

The new_dims = copy.deepcopy(dims) was moved before the if check, which is fine semantically but changes behavior slightly — the deepcopy now always runs even when the index is invalid. The original code only created new_dims inside the if block. This is a minor perf concern but not a bug since dims is only a short list of DVar.

constraint_transformation.py:302 — New else: return constraint, counter

In generate_binconstraint_t, you added:

        else:
            return constraint, counter

after the isinstance(constraint.lhs, TensorType) branch inside op_precision. This is correct — previously this code path fell through without returning, which would have been a runtime error for non-Dyn, non-TensorType lhs values. Good catch.

The same applies to the else: return constraint, counter added in generate_binconstraint_d (line 380).

constraint.py:36 — Pre-existing duplicate condition in __eq__

return self.conjucts == other.conjucts and self.conjucts == other.conjucts

This redundant and clause exists in Conj.__eq__, Disj.__eq__, and Prod.__eq__. This is pre-existing and not introduced by this PR, but since you're touching these classes, it might be worth cleaning up. Fix this →

allowlist_for_publicAPI.json — Leaking implementation details

The allowlist additions include TYPE_CHECKING, annotations, Sequence, and Constraint. The first three (TYPE_CHECKING, annotations, Sequence) are standard library imports that are now appearing as public API members of the constraint module because of from __future__ import annotations and the top-level imports. These shouldn't be considered public API — you should either:

  • Add __all__ to constraint.py to control what's exported, or
  • Move the Sequence import fully under TYPE_CHECKING (which it already is, so this is puzzling — check if the allowlist test is seeing it through some other mechanism)

Constraint being in the allowlist for transform_to_z3 is reasonable since it's used in the module's API.

Volume of pyrefly: ignore comments

There are a large number of # pyrefly: ignore[...] suppressions added across the files — especially bad-argument-type, bad-index, and missing-attribute. This is expected for a gradual migration, but many of them seem to stem from the _Operand union type being too wide. As a follow-up, narrowing the types of BinaryConstraint.lhs/rhs in specific subclasses could eliminate many of these.


Summary

The annotation quality is high in the constraint classes, generator, and transformation modules. The main gap is in transform_to_z3.py where all 7+ uses of Any are due to the conditionally-imported z3 library. Introducing a named alias like _Z3Expr: TypeAlias = Any would make the intent explicit and is the standard PyTorch pattern for optional dependency types. No blocking issues found.

@Lucaskabela
Lucaskabela force-pushed the pyrefly/fx-exp-gradual-types branch 4 times, most recently from 1c730bf to ec89ad8 Compare April 13, 2026 20:44
@Lucaskabela

Copy link
Copy Markdown
Contributor Author

@claude can you review this PR - focus on the BC related changes

@claude

claude Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

Claude finished @Lucaskabela's task in 4m 20s —— View job


Review of PR #180070 — Focus on Backward Compatibility

  • Gather context: read the full diff and changed files
  • Review allowlist_for_publicAPI.json changes for public API impact
  • Review constraint.py for BC-breaking signature/class changes
  • Review constraint_generator.py for BC-breaking changes
  • Review constraint_transformation.py for BC-breaking changes
  • Review transform_to_z3.py for BC-breaking changes
  • Review tensor_type.py for BC-breaking changes
  • Post detailed review

Note: All classes in torch.fx.experimental.migrate_gradual_types are marked @compatibility(is_backward_compatible=False) or not decorated at all (the constraint classes). TensorType is explicitly @compatibility(is_backward_compatible=False). This significantly reduces the BC risk surface — these are internal/experimental APIs. That said, downstream code (including tests and internal consumers) can still break. Here's what I found:


BC Issue 1 (Behavioral change): Conj, Disj, Prod constructors now copy input

Before: self.conjucts = conjuncts (stores the reference directly)
After: self.conjucts = list(conjuncts) (creates a new list)

This means that code which previously mutated the list after passing it to Conj/Disj/Prod and expected the mutation to be visible through the constraint object will no longer work. In practice, all callers in the codebase pass freshly-constructed list literals, so this is safe. However, this is still a semantic change worth noting.

The Sequence parameter type also means these constructors now accept tuples and generators, which is slightly more permissive than before (not a break, but an interface widening).

Verdict: Low risk. The copy is actually more correct since it prevents aliasing bugs.


BC Issue 2 (Behavioral change): transform_index_select — new_dims deepcopy moved before if guard

constraint_transformation.py:127-129

Before:

if is_valid_index == T():
    new_dims = copy.deepcopy(dims)
    new_dims[constraint.index] = constraint.dim_replace

After:

new_dims = copy.deepcopy(dims)
if is_valid_index == T():
    new_dims[constraint.index] = constraint.dim_replace

Previously, when is_valid_index != T(), new_dims was never defined, and the subsequent reference to new_dims on line 136 (TensorType(new_dims)) would raise an UnboundLocalError. The old code had a latent bug — it only worked because valid_index returns T() for valid indices, and apparently the code path with invalid indices either: (a) was never hit in practice, or (b) the resulting UnboundLocalError was acceptable.

The new code fixes this by always creating new_dims, so when the index is invalid, the output tensor gets the original dims (un-replaced). This changes the behavior for the invalid-index code path from a crash to producing a constraint with original dimensions. This is arguably a bug fix, but it is a behavioral change.

Verdict: Bug fix. The old code would crash on the invalid-index path. The new code produces a meaningful constraint instead.


BC Issue 3 (New else branches): generate_binconstraint_t and generate_binconstraint_d

constraint_transformation.py:302-303 — In generate_binconstraint_t, the op_precision branch previously had:

if constraint.lhs == Dyn: ...
elif isinstance(constraint.lhs, TensorType): ...
# (implicit: fall through to None return for other lhs types)

The PR adds else: return constraint, counter, which means that if constraint.lhs is neither Dyn nor TensorType, the constraint is returned unchanged instead of implicitly returning None (which would cause a TypeError downstream when the caller tries to unpack the result).

constraint_transformation.py:379-380 — Same pattern in generate_binconstraint_d: the op_precision branch previously fell through to None return for non-int, non-Dyn lhs values. Now it returns constraint, counter.

Verdict: Both are bug fixes. The old code would produce None returns leading to downstream crashes. The new code correctly returns the constraint unchanged for unhandled cases.


BC Issue 4: _DynType now exported from tensor_type.py

torch/fx/tensor_type.py:49 — _DynType is now imported by constraint.py via from torch.fx.tensor_type import _DynType, Dyn, TensorType.

_DynType was previously a private implementation detail (underscore-prefixed). It's still not in __all__ for tensor_type.py, and it's only used in type annotations (under from __future__ import annotations), so it's not a runtime dependency. However, it does create a new import relationship.

Verdict: No BC impact. The import is for type annotations only and _DynType remains private.


BC Issue 5: TensorType.__args__ class-level annotation

torch/fx/tensor_type.py:29 — Added __args__: Sequence[DVar | int | _DynType] as a class-level annotation.

This is purely a type annotation (with from __future__ import annotations active, it's a string at runtime, not evaluated). It doesn't create a class variable or change __init__ behavior. However, note that TensorType.__init__ now accepts Sequence[Any] rather than the previous Sequence[object].

Sequence[Any] is actually more permissive than Sequence[object] for type checkers (since Any is compatible with everything without requiring explicit typing). This is a type-annotation-only widening — no runtime impact.

Verdict: No BC impact at runtime. The annotation change is permissive.


BC Issue 6: allowlist_for_publicAPI.json changes

Three changes:

  1. Removed TensorType from constraint module allowlist — This was previously listed as an allowed public re-export. Since this PR adds __all__ to constraint.py (which doesn't include TensorType), the re-export is no longer visible. Anyone doing from torch.fx.experimental.migrate_gradual_types.constraint import TensorType will still work at runtime (the import is still there), but the public API test no longer considers it part of that module's API.

  2. Added Sequence to constraint_transformation module allowlist — This is a stdlib import leaking into the module namespace. Not ideal, but the module is experimental. Consider adding __all__ to constraint_transformation.py to prevent this.

  3. Added Constraint to transform_to_z3 module allowlist — Reasonable, since Constraint is used in the module's function signatures.

Verdict: The TensorType removal from constraint's allowlist is technically a public API surface change, but mitigated by __all__. The Sequence leak is a minor issue. Fix the Sequence leak by adding __all__ to constraint_transformation.py →


BC Issue 7: transform_to_z3.py — removed dead elif branches

constraint_transformation.py line ~175 (original) / transform_to_z3.py line ~174 (original):

Two elif branches were converted to else:

  • elif constraint.lhs == Dyn: → else: (line after if constraint.rhs == Dyn:)
  • elif isinstance(constraint.rhs, int): → else: (inside isinstance(constraint.lhs, int) branch)

These are in transform_to_z3.py within the op_neq handler for BinConstraintD. The original code had unreachable implicit fall-through (returning None) if neither branch matched. The new code handles the residual cases with else. This is correct because the preceding guard (is_dim(constraint.lhs) and is_dim(constraint.rhs)) guarantees both sides are DVar or int, so the elif conditions were exhaustive anyway.

Verdict: No behavioral change in practice — the elif conditions were already exhaustive given the guard. Converting to else is cleaner.


BC Issue 8: New raise statements in transform_var and transform_dimension

transform_to_z3.py:288-290, 331-332 — Added explicit raise AssertionError / raise NotImplementedError at the end of transform_var and transform_dimension, replacing implicit None returns.

Previously, if an unexpected type was passed to these functions, they'd silently return None, causing confusing errors downstream. Now they raise immediately with a clear message.

Verdict: Bug fix. Existing code that relied on None returns from these functions was already broken — this just makes the failure mode explicit.


Summary

Change Type Risk
Conj/Disj/Prod constructors copy input Behavioral Low — all callers pass literals
transform_index_select deepcopy moved Bug fix Low — fixes UnboundLocalError
New else branches in generate_binconstraint_t/d Bug fix Low — fixes None return
_DynType import in constraint.py Annotation-only None
TensorType.__args__ annotation Annotation-only None
TensorType removed from constraint allowlist API surface Low — __all__ now controls this
Sequence added to transformation allowlist API surface leak Low — add __all__ to fix
elif → else in transform_to_z3 Cleanup None — conditions were exhaustive
Explicit raises in transform_var/dimension Bug fix Low — replaces None returns

Overall, the BC risk of this PR is low. The changed module is experimental and explicitly marked as not backward compatible. The behavioral changes are all improvements (bug fixes or defensive copies). The main actionable suggestion is adding __all__ to constraint_transformation.py to prevent Sequence from leaking into the public API surface.

@Lucaskabela
Lucaskabela force-pushed the pyrefly/fx-exp-gradual-types branch from ec89ad8 to f268226 Compare April 13, 2026 21:53
@Lucaskabela Lucaskabela added the suppress-bc-linter Suppresses the failures of API backward-compatibility linter (Lint/bc_linter) label Apr 13, 2026
@Lucaskabela

Copy link
Copy Markdown
Contributor Author

@pytorchbot fix-lint

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully applied lint patches in https://github.com/pytorch/pytorch/actions/runs/24369126278. Please pull locally before pushing more changes.

…al_types

Remove mypy suppressions. Add return type and parameter type annotations
to constraint classes, generator, transformation, and z3 transform.

Authored with Claude.
@Lucaskabela
Lucaskabela force-pushed the pyrefly/fx-exp-gradual-types branch from a4cba81 to af20acf Compare April 13, 2026 23:40
@Lucaskabela
Lucaskabela marked this pull request as ready for review April 14, 2026 14:43
@Lucaskabela
Lucaskabela requested a review from albanD as a code owner April 14, 2026 14:43
from torch.fx.tensor_type import _DynType, Dyn, TensorType


__all__ = [

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Why these changes to all?

test_correct_module_names test enforces a rule: for every module, either

  1. No all — then every non-_ name in the module is considered public, and each must have a module that matches the module it lives in. Imported names like Sequence, Graph, Any fail this check because their module points elsewhere (e.g., typing, torch.fx.graph).
  2. Has all — then only names in all are public, and only those are checked. Imported names not in all are ignored.

Before our changes, these modules had no all, so every imported name leaked as "public". The type annotation work added new imports (_DynType, Sequence) which made this worse.

Adding all with the module's own function names solves both directions: imported names no longer leak, and the module's own functions are properly declared as public.

+ [BinConstraintD(1, new_dim, op_leq) for new_dim in new_dims]
)
return Conj(new_dim_constraints), counter
else:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

BUG - without this, we would fall through and return None!

This is why type checking rules :)

@Lucaskabela

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 14, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: pull / linux-docs / build-docs-cpp-false, pull / linux-docs / build-docs-python-false

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

BoyuanFeng pushed a commit that referenced this pull request Apr 15, 2026
#180070)

…al_types

Remove mypy suppressions. Add return type and parameter type annotations to constraint classes, generator, transformation, and z3 transform.

Authored with Claude.
Pull Request resolved: #180070
Approved by: https://github.com/Skylion007
pytorchmergebot pushed a commit to scotts/pytorch that referenced this pull request Apr 15, 2026
pytorch#180070)

…al_types

Remove mypy suppressions. Add return type and parameter type annotations to constraint classes, generator, transformation, and z3 transform.

Authored with Claude.
Pull Request resolved: pytorch#180070
Approved by: https://github.com/Skylion007
@github-actions
github-actions Bot deleted the pyrefly/fx-exp-gradual-types branch May 15, 2026 02:26
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
pytorch#180070)

…al_types

Remove mypy suppressions. Add return type and parameter type annotations to constraint classes, generator, transformation, and z3 transform.

Authored with Claude.
Pull Request resolved: pytorch#180070
Approved by: https://github.com/Skylion007
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
pytorch#180070)

…al_types

Remove mypy suppressions. Add return type and parameter type annotations to constraint classes, generator, transformation, and z3 transform.

Authored with Claude.
Pull Request resolved: pytorch#180070
Approved by: https://github.com/Skylion007
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: fx release notes category suppress-bc-linter Suppresses the failures of API backward-compatibility linter (Lint/bc_linter)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants