Skip to content

loop_ir_epilogue_lowering.py expression-tree walkers -> object - #194825

Closed
bobrenjc93 wants to merge 1 commit into
pytorch:mainfrom
bobrenjc93:bobren/loop-ir-epilogue-object
Closed

bobrenjc93 wants to merge 1 commit into
pytorch:mainfrom
bobrenjc93:bobren/loop-ir-epilogue-object

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

The tree's leaves are genuinely heterogeneous (nested GemmEpilogueIRExpression nodes, sympy indices, dtypes, ints, floats), which is precisely why the parameter cannot just be the IR type. Every walker already isinstance-narrows before touching expression members, so object captures the accepted boundary while removing the unchecked attribute access Any permits.

Rebased onto current main. The file was largely rewritten upstream by the NVGEMM epilogue work (#194793, #195231, #192298), which deleted ten of the seventeen helpers this PR originally touched -- the affine/softmax/variance matchers, including _source_transform. Seven of the original sites survive, and the same treatment is applied to the three walkers that rewrite introduced (_expression_pattern, _synthetic_reduction_element_ir, _synthetic_reductions_ir) so the module is consistent rather than half converted.

Return types are deliberately left as Any: these walkers hand back raw tree leaves, so narrowing the returns is a separate and much larger change to every caller.

Test plan

lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so there are no net-new type errors:

uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py

The module's tests pass locally on an H100 (21 passed, 168 skipped; the skips are the Blackwell-gated end-to-end cases, and the tests that do run cover the walkers directly -- grouped reduction pattern matching, region construction and the reduction finalizer):

python -m pytest test/inductor/test_nv_universal_gemm.py -q

Authored with assistance from an AI coding assistant.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@pytorch-bot

pytorch-bot Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 1 Pending, 1 Unrelated Failure

As of commit b799042 with merge base 1e9d530 (image):

GREEN LIGHT - PR approved to be merged without human review:

The diff is annotation-only: ten parameters in
torch/_inductor/kernel/loop_ir_epilogue_lowering.py (_expression_values, _walk,
_loaded_names, _contains_reduction, _constant_value, _strip_conversions,
_flatten_associative, _expression_pattern, _synthetic_reduction_element_ir,
_synthetic_reductions_ir) go from Any to object with no statement or return type
changed, and each body still isinstance-narrows to GemmEpilogueIRExpression
before touching .op/.args (lines 80, 174, 331, 342, 402, 411, 435, 515), so no
runtime behavior changes and no new unchecked access appears. The module has no
get_type_hints/singledispatch/__annotations__ use, so the annotations are inert
at runtime, and Any is still imported and used at lines 32-33, 105, 330, 340,
400 so the import does not go dead. All ten symbols are module-private: the only
importers (torch/_inductor/kernel/loop_ir_cutedsl_codegen.py:30,
torch/_inductor/codegen/nv_universal_gemm/epilogue_lowering.py:37,
test/inductor/test_nv_universal_gemm.py) take only public names, and widening a
parameter to object cannot reject an existing call site, so no caller breaks and
no new tests are warranted.

reason: clean
Reviewed commit: b799042

Inference job

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@bobrenjc93 bobrenjc93 added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 25, 2026
@bobrenjc93
bobrenjc93 requested a review from jansel August 25, 2026 23:53
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Aug 25, 2026
@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 7m 57s —— View job


Review complete

Annotation-only change with no runtime effect — safe to land, but the tightening stops short of its stated goal: GemmEpilogueIRExpression.args is still tuple[Any, ...], so every recursive call re-injects Any into the new object parameters, and four sibling helpers with the identical narrowing shape were left on Any.

Full review

PR Review: #194825

Summary

Changes 17 expression-tree walker parameters in torch/_inductor/kernel/loop_ir_epilogue_lowering.py from Any to object. No behavioral risk (annotations are not introspected at runtime here — no singledispatch, get_type_hints, or @overload in the file), and all 17 functions are private with no callers outside this module. The problems below are about completeness and about whether the change achieves what the description claims.

Code Quality

  • The Any this PR is trying to eliminate enters through the dataclass, not the parameters. GemmEpilogueIRExpression.args is declared tuple[Any, ...] (line 30) and kwargs is tuple[tuple[str, Any], ...] (line 31). Every internal recursion — _walk(arg) at line 340, _loaded_names(arg) at 197, _contains_reduction(arg) at 578, _source_transform(expr.args[0], ...) at 405/412/421, _flatten_associative(stripped.args[0], op) at 431 — passes an Any into the newly object-typed parameter. Any is assignable to object silently, so no checker will ever complain, and no narrowing is enforced on the dominant call path. The only sites where object actually constrains anything are the handful of entries from store.value, which is already typed GemmEpilogueIRExpression. As written the change is close to cosmetic.

    The version that would deliver the description's claim ("each helper narrows before accessing IR fields") is args: tuple[object, ...] on the dataclass. That will surface real errors — e.g. name, _, stored = expr.args at line 195 followed by frozenset((name,)) against a declared frozenset[str] return — so it is a larger change, and worth deciding on explicitly rather than leaving implicit. Fix this →

  • Four parameters with the identical narrowing shape were left as Any, so the file now carries two conventions for the same concept. All four begin with the same _strip_conversions + isinstance(..., GemmEpilogueIRExpression) guard as the converted helpers:

    • _synthetic_reductions_ir(expr: Any, ...) (line 495) — guard at line 501
    • _affine_coefficients(expr: Any, ...) (line 594) — guards at lines 597/599
    • _sum_affine_ir(expr: Any, ...) (line 845)
    • coefficients(expr: Any) (line 988, nested in centered_mean_consumer_type_unrolled_ir) — guards at lines 998/1002

    The _sum_affine_ir case is the sharpest: its nested is_sum(candidate: object) at line 850 was converted while the enclosing function's own expr parameter one line above was not, and expr is forwarded straight into _affine_around which now takes object (line 858). _sum_affine_ir and coefficients are one-line changes; the other two require the same treatment the rest of the file already got. Fix this →

  • The object parameters are immediately re-widened to Any by the return types of the tree helpers. _strip_conversions returns Any (line 325), _constant_value returns Any | None (315), _flatten_associative returns list[Any] (428), _shifted_exp returns Any | None (767). Because most converted helpers open with expr = _strip_conversions(expr) — lines 385, 689, 737, 768, 851, 872, 946, 989 — the parameter's object type survives exactly one statement before the local is rebound to Any for the rest of the body. The bodies still permit unchecked attribute access, which is the thing the PR is meant to prevent.

    All the call sites already narrow, so _strip_conversions -> object and _flatten_associative -> list[object] should hold; _constant_value -> object | None is likely fine too, since every float(constant) is already guarded by an isinstance check (lines 611-614, 693-696, 998-1001) and the remaining uses are equality comparisons. Converting the parameters without the returns leaves the narrowing boundary only half-built. Fix this →

  • _affine_around's basis parameter is still unannotated (line 688: def _affine_around(expr: object, basis)). It is invoked at line 690 and receives is_sum/is_normalization/is_variance, all three of which this PR just gave object parameters. Annotating it Callable[[object], bool] is what makes those three conversions load-bearing; leaving it bare means the checker cannot connect the callbacks to the call site.

API Design

  • object documents the domain no better than Any did. The description explains the real contract — "the tree's leaves are genuinely heterogeneous (ints, floats, dtypes)" — but that explanation lives only in the PR body. object tells a reader "literally anything," which is the same information Any conveyed. A module-level alias would encode the actual accepted set and give a checker something to reject:

    _IRNode: TypeAlias = GemmEpilogueIRExpression | sympy.Expr | torch.dtype | str | int | float | bool | None | tuple["_IRNode", ...]

    This is a judgment call rather than a defect, but since the stated purpose of the PR is documenting the boundary, object is the weakest annotation that achieves nothing a checker can act on.

Testing

Not a blocker for an annotation-only change, and no new tests are warranted. Flagging for context: the module's only coverage is TestNVUniversalGemmHeuristics in test/inductor/test_nv_universal_gemm.py (4 tests), which exercises GemmEpilogueIRAnalysis, GemmEpilogueIRExpression, GemmEpilogueIRStore, and grouped_reduction_ir — none of the 17 functions touched here. Any follow-up that changes the dataclass field types per the first finding will land without regression coverage on these walkers.

Backward Compatibility

No concern. All 17 names are private (14 module-level underscore-prefixed, 3 nested closures), the module has no __all__, and the only two in-tree importers — torch/_inductor/kernel/loop_ir_cutedsl_codegen.py:18 and torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py:32 — import only public names. Widening Any to object cannot break a caller regardless.

Recommendation

Approve

Nothing here is a correctness or compatibility risk, and the change is strictly directionally right. The findings are about it being an incomplete version of itself: four sibling parameters left on Any, four helper return types that undo the narrowing one statement into each body, and a dataclass field that keeps Any flowing through every recursive call. Landing as-is is fine; folding in at least the four remaining parameters and _strip_conversions -> object would make the file internally consistent and the annotations actually enforceable.

Note: no .venv was available in this checkout, so I could not run pyrefly or lintrunner to confirm the suggested return-type tightenings typecheck. The confirmation that this file is in pyrefly's scope comes from reading pyrefly.toml (project-includes = ["torch", ...], and torch/_inductor/kernel/loop_ir_epilogue_lowering.py is not in project-excludes) and .lintrunner.toml; the file's # mypy: allow-untyped-defs header is inert since .lintrunner.toml has no MYPY linter entry.

| Branch: [`bobren/loop-ir-epilogue-object`](https://github.com/pytorch/pytorch/tree/bobren/loop-ir-epilogue-object)

@bobrenjc93
bobrenjc93 marked this pull request as ready for review August 25, 2026 23:57
@bobrenjc93
bobrenjc93 force-pushed the bobren/loop-ir-epilogue-object branch from 6e857ed to 9a37aac Compare September 3, 2026 19:15
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased bobren/loop-ir-epilogue-object onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout bobren/loop-ir-epilogue-object && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the bobren/loop-ir-epilogue-object branch from 9a37aac to 452364a Compare September 3, 2026 20:38
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot drci

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, lf-l-x86aavx2-189-704-a10g-8)

Details for Dev Infra team Raised by workflow job

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, lf-l-x86aavx2-189-704-a10g-8)

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@bobrenjc93
bobrenjc93 removed the request for review from jansel September 4, 2026 05:38
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

Use object instead of Any for the expression-tree walker inputs in
loop_ir_epilogue_lowering.py. These helpers walk a tree whose leaves are
genuinely heterogeneous (nested GemmEpilogueIRExpression nodes, sympy
indices, dtypes, ints, floats), which is precisely why the parameter
cannot just be the IR type. Every helper already isinstance-narrows
before touching expression members, so object captures the accepted
boundary while removing the unchecked attribute access Any permits.

This is a rebase onto current main. The file was largely rewritten
upstream by the NVGEMM epilogue work (pytorch#194793, pytorch#195231, pytorch#192298), which
deleted ten of the seventeen helpers this change originally touched --
the affine/softmax/variance matchers, including _source_transform. Seven
of the original sites survive; the same treatment is applied to the
three walkers that rewrite introduced (_expression_pattern,
_synthetic_reduction_element_ir, _synthetic_reductions_ir) so the module
is consistent rather than half converted.

Return types are deliberately left as Any. These walkers hand back raw
tree leaves, so narrowing the returns is a separate and much larger
change to every caller.

Test Plan:

```
lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so
there are no net-new type errors:

```
uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

The module's tests pass locally on an H100 (21 passed, 168 skipped; the
skips are the Blackwell-gated end-to-end cases, and the tests that do
run cover the walkers directly -- grouped reduction pattern matching,
region construction and the reduction finalizer):

```
python -m pytest test/inductor/test_nv_universal_gemm.py -q
```

Authored with assistance from an AI coding assistant.
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased bobren/loop-ir-epilogue-object onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout bobren/loop-ir-epilogue-object && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the bobren/loop-ir-epilogue-object branch from 452364a to b799042 Compare September 4, 2026 05:40
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: New commits were pushed while merging. Please rerun the merge command.

Details for Dev Infra team Raised by workflow job

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)

Details for Dev Infra team Raised by workflow job

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

1 similar comment
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)

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

Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ytorch#194825)

The tree's leaves are genuinely heterogeneous (nested `GemmEpilogueIRExpression` nodes, sympy indices, dtypes, ints, floats), which is precisely why the parameter cannot just be the IR type. Every walker already `isinstance`-narrows before touching expression members, so `object` captures the accepted boundary while removing the unchecked attribute access `Any` permits.

**Rebased onto current main.** The file was largely rewritten upstream by the NVGEMM epilogue work (pytorch#194793, pytorch#195231, pytorch#192298), which deleted ten of the seventeen helpers this PR originally touched -- the affine/softmax/variance matchers, including `_source_transform`. Seven of the original sites survive, and the same treatment is applied to the three walkers that rewrite introduced (`_expression_pattern`, `_synthetic_reduction_element_ir`, `_synthetic_reductions_ir`) so the module is consistent rather than half converted.

Return types are deliberately left as `Any`: these walkers hand back raw tree leaves, so narrowing the returns is a separate and much larger change to every caller.

### Test plan

```
lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so there are no net-new type errors:

```
uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

The module's tests pass locally on an H100 (21 passed, 168 skipped; the skips are the Blackwell-gated end-to-end cases, and the tests that do run cover the walkers directly -- grouped reduction pattern matching, region construction and the reduction finalizer):

```
python -m pytest test/inductor/test_nv_universal_gemm.py -q
```

Authored with assistance from an AI coding assistant.

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

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants