Skip to content

[inductor] Add structural divisibility analysis to statically_known_multiple_of - #177214

Closed
liqiangxl wants to merge 2 commits into
pytorch:mainfrom
liqiangxl:llu/is_multiple_of_check
Closed

liqiangxl wants to merge 2 commits into
pytorch:mainfrom
liqiangxl:llu/is_multiple_of_check

Conversation

@liqiangxl

@liqiangxl liqiangxl commented Mar 11, 2026 •

Copy link
Copy Markdown
Collaborator

Add _is_multiple_of() that recurses over sympy expression structure (Mul, Add, FloorDiv, Mod) to prove divisibility, before falling back to statically_known_true. This is a demand-driven variant of the modular arithmetic analysis used in Halide and TVM.

Unlocks tt.divisibility hints for product expressions like shape[0] * shape[1] when torch._check(shape[1] % 16 == 0).

Fixes #177146

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 Mar 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 822fddb with merge base a4de454 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot

pytorch-bot Bot commented Mar 11, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@jerryzh168 jerryzh168 added the bot-triaged This is a label only to be used by the auto triage bot label Mar 19, 2026
@jerryzh168
jerryzh168 requested review from eellison and jansel March 19, 2026 17:28
@jerryzh168 jerryzh168 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Mar 19, 2026
@liqiangxl
liqiangxl force-pushed the llu/is_multiple_of_check branch from 21424be to 49ff39b Compare March 20, 2026 20:45
@liqiangxl

Copy link
Copy Markdown
Collaborator Author

Resolved conflicts with main.

@jansel jansel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fix lints

Comment on lines +407 to +440
def _is_multiple_of(self, numerator: Expr, denominator: int) -> bool:
"""
Structural divisibility check: returns True only if numerator is
provably a multiple of denominator. Recurses over sympy expression
structure before falling back to statically_known_true.
"""
# Rule 1 — concrete value
if isinstance(numerator, (int, sympy.Integer)):
return int(numerator) % denominator == 0

# Rule 2 — product: any factor divisible → product divisible
if isinstance(numerator, sympy.Mul):
for factor in numerator.args:
if self._is_multiple_of(factor, denominator):
return True
# Also check if combined constant factors are divisible
const = 1
for factor in numerator.args:
if isinstance(factor, (int, sympy.Integer)):
const *= int(factor)
if const != 1 and const % denominator == 0:
return True

# Rule 3 — sum: all terms divisible → sum divisible
if isinstance(numerator, sympy.Add):
if all(self._is_multiple_of(term, denominator) for term in numerator.args):
return True

# Rule 4 — FloorDiv(a, b): if a is multiple of b*n
if isinstance(numerator, FloorDiv):
a, b = numerator.args
if isinstance(b, (int, sympy.Integer)):
if self._is_multiple_of(a, int(b) * denominator):
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could you simplify to:

return sympy.gcd(numerator, denominator) == denominator

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for the suggestion. It doesn't work with a simple repalcement using sympy.gcd.

Why doesn't work:
The divisibility facts are stored as axioms in ShapeEnv, shape_env.axioms[Eq(Mod(s1, 16), 0)] = True.
This does not change s1's sympy representation, it is still a bare symbol.
So sympy.gcd(s1 * s2, 16) returns 1 instead of 16, even though s1 is axiomatically a multiple of 16.

To make it work: we need the following steps which seems non-trivial.

  1. Scan ShapeEnv axioms for all Mod(symbol, k) == 0 facts,
  2. Substitute each such symbol with k * fresh_symbol,
  3. Call sympy.gcd on the rewritten expression.

@jansel
jansel requested a review from laithsakka March 20, 2026 21:11
"""
# Rule 1 — concrete value
if isinstance(numerator, (int, sympy.Integer)):
return int(numerator) % denominator == 0

@laithsakka laithsakka Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

  1. do we want to use class Mod(sympy.Function).

is this not handled by statically_known_true trivially? or we are just trying to be faster.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

  1. No, it goes to expr = sympy.Eq(Mod(numerator, denominator), 0) even both numerator and denominator are int.
  2. It is a performance optimization, but also required to terminate the recursion, e.g., (ks * 1024) % 16 will iterate to ks % 16 and 1024 % 16

for factor in numerator.args:
if isinstance(factor, (int, sympy.Integer)):
const *= int(factor)
if const != 1 and const % denominator == 0:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why const != 1 ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It was initilized to 1, stays at 1 means no const factors.
Not absolutely required. Added to skip evaluating 1 % denominator.

if len(free_symbols(numerator)) > 20:
return False

if isinstance(denominator, (int, sympy.Integer)):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

mm which one shall go first this or self.statically_known_true(expr)...
the cheaper probably i cant tel which one is cheaper, but given that self.statically_known_true is not giving regressions shall we do it first?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

good point. I don't have data about the cost, but the following code comment seems to suggest thatstatically_known_true is not cheap.

        # The reason we skip compute here is to avoid the cost of trying to eval this symbolically.
        # see https://github.com/sympy/sympy/issues/28200

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

right but _is_multiple_of calls it many times vs one time in the other branch
(each leaf in the recursion is return self.statically_known_true(expr))

expr = left > right
return self.statically_known_true(expr)

def _is_multiple_of(self, numerator: Expr, denominator: int) -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

FYI many of the ideas here work also if denominator is not int, consider generalizing but its fine as is we can do that incrementally as we need.

@jansel

jansel commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

@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: trunk / linux-jammy-cuda13.0-py3.10-gcc11-no-ops / build

Details for Dev Infra team Raised by workflow job

mhusnain-tech added a commit to mhusnain-tech/pytorch that referenced this pull request Mar 25, 2026
…ion and strict validation


**Overview:**
This PR refactors `statically_known_multiple_of` to resolve 42 test failures (including `vision_maskrcnn`) and aligns the implementation with the structural recursion logic introduced in pytorch#177214.

**Key Improvements:**
* **Integration with `_is_multiple_of`:** Leveraged the new structural recursion helper for integer denominators to ensure consistency with pytorch#177214 and avoid logic duplication.
* **Strict Validation Fix:** Enforced `is_integer == True` post-algebraic cancellation. This specifically addresses the regressions in vision models where indeterminate symbolic states (`None`) were previously misidentified as multiples.
* **GCD Fallback:** Retained a guarded `sympy.gcd` check to handle complex additive symbolic expressions (e.g., $2a + 2b$ being a multiple of $2$) that structural recursion might miss.
* **Performance Guards:** Maintained a 15-symbol complexity cap and added exception handling to prevent backend hangs during complex graph compilations.

**Validation:**
Verified that strict validation prevents over-optimistic optimizations, ensuring all downstream model tests pass while maintaining robust symbolic propagation.
@jansel

jansel commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

@claude please diagnose the CI failures

@claude

claude Bot commented Mar 26, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 27s —— View job


CI Failure Diagnosis

  • Gather CI status and identify failing jobs
  • Download and analyze logs from failing jobs
  • Determine if failures are related to this PR or are pre-existing trunk issues
  • Provide diagnosis and recommendations

Summary

All CI failures are pre-existing trunk issues, unrelated to this PR. This PR only modifies test/inductor/test_codegen_triton.py and torch/_inductor/sizevars.py — neither of which is involved in the build failures.

Root Cause

Every failing job hits the same C++ compilation error in aten/src/ATen/native/cuda/Loops.cuh:98:

error: identifier "check_cast" is undefined
    gpu_kernel_nocast(sub_iter, f, check_cast);
                                   ^

This was introduced by commit b0f830d ("Revert 'Support kernels with opaque types (#174211)'"), which is part of the merge base (e8cde84). The revert removed the check_cast parameter from the gpu_kernel_nocast function signature (changing (iter, f, check_cast = true) to (iter, f)) but did not update the recursive call on line 98, which still passes the now-undeclared check_cast variable.

Affected Jobs

Job Error PR-related?
linux-jammy-cuda12.8-cudnn9-py3.10-clang15 / build check_cast undefined in Loops.cuh No
linux-jammy-rocm-py3.10 / build check_cast undeclared in Loops.cuh (HIP variant) No
linux-jammy-cuda13.0-py3.10-gcc11-no-ops / build check_cast undefined in Loops.cuh No
win-vs2022-cuda12.8-py3 / build check_cast not found in Loops.cuh No

Recommendation

Rebasing onto viable/strict (as the Dr. CI bot suggests) should resolve these failures, since the broken Loops.cuh was likely fixed on trunk after the merge base.

View trunk workflow run · View pull workflow run

@jansel

jansel commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

@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 llu/is_multiple_of_check onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout llu/is_multiple_of_check && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the llu/is_multiple_of_check branch from 6a7db52 to 822fddb Compare March 27, 2026 03:10
@pytorch-bot pytorch-bot Bot removed ciflow/trunk Trigger trunk jobs on your pull request ciflow/inductor labels Mar 27, 2026
@jansel jansel added ciflow/trunk Trigger trunk jobs on your pull request ciflow/inductor labels Mar 27, 2026
@jansel

jansel commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

@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

mhusnain-tech added a commit to mhusnain-tech/pytorch that referenced this pull request Mar 29, 2026
… logic with pytorch#177214

This commit addresses critical CI failures caused by the accidental removal of core methods during a previous merge conflict resolution. 

Key changes include:
- Restored `expect_true` and `statically_known_power_of_2` methods to `sizevars.py`, resolving widespread AttributeErrors across the inductor test suite.
- Refactored `statically_known_multiple_of` to eliminate redundancy with pytorch#177214. 
- Removed expensive `sympy.gcd` and `sympy.cancel` fallbacks to prevent performance regressions, relying instead on the structural `_is_multiple_of` helper for efficiency.
- Validated that the simplified logic maintains compliance with structural divisibility rules while reducing symbolic overhead.
AaronWang04 pushed a commit to AaronWang04/pytorch that referenced this pull request Mar 31, 2026
…ultiple_of (pytorch#177214)

Add `_is_multiple_of()` that recurses over sympy expression structure (Mul, Add, FloorDiv, Mod) to prove divisibility, before falling back to statically_known_true. This is a demand-driven variant of the modular arithmetic analysis used in Halide and TVM.

Unlocks tt.divisibility hints for product expressions like `shape[0] * shape[1]` when `torch._check(shape[1] % 16 == 0)`.

Fixes pytorch#177146

Pull Request resolved: pytorch#177214
Approved by: https://github.com/jansel, https://github.com/laithsakka
pytorch-bot Bot pushed a commit that referenced this pull request Apr 2, 2026
…ultiple_of (#177214)

Add `_is_multiple_of()` that recurses over sympy expression structure (Mul, Add, FloorDiv, Mod) to prove divisibility, before falling back to statically_known_true. This is a demand-driven variant of the modular arithmetic analysis used in Halide and TVM.

Unlocks tt.divisibility hints for product expressions like `shape[0] * shape[1]` when `torch._check(shape[1] % 16 == 0)`.

Fixes #177146

Pull Request resolved: #177214
Approved by: https://github.com/jansel, https://github.com/laithsakka
IvanKobzarev pushed a commit to IvanKobzarev/pytorch that referenced this pull request Apr 3, 2026
…ultiple_of (pytorch#177214)

Add `_is_multiple_of()` that recurses over sympy expression structure (Mul, Add, FloorDiv, Mod) to prove divisibility, before falling back to statically_known_true. This is a demand-driven variant of the modular arithmetic analysis used in Halide and TVM.

Unlocks tt.divisibility hints for product expressions like `shape[0] * shape[1]` when `torch._check(shape[1] % 16 == 0)`.

Fixes pytorch#177146

Pull Request resolved: pytorch#177214
Approved by: https://github.com/jansel, https://github.com/laithsakka
mhusnain-tech added a commit to mhusnain-tech/pytorch that referenced this pull request Apr 3, 2026
…bility registration

This commit refactors `statically_known_multiple_of` in `torch/_inductor/sizevars.py` to align with the structural divisibility logic merged in pytorch#177214. 

Key changes:
- Updated the performance guard to use the 20 free_symbols limit.
- Delegated integer denominator checks directly to `_is_multiple_of` to leverage new structural recursion rules (Rules 1-6).
- Removed redundant identical-expression and zero-check guards as they are now handled internally by the structural helper.
- Fixed `test_symbolic_multiplication_divisibility_propagation` by properly registering divisibility constraints via `ShapeEnv.divisible`.
- Cleaned up unused imports in `test/inductor/test_utils.py` to resolve linting failures.

Fixes: pytorch#177146
nklshy-aws pushed a commit to nklshy-aws/pytorch that referenced this pull request Apr 7, 2026
…ultiple_of (pytorch#177214)

Add `_is_multiple_of()` that recurses over sympy expression structure (Mul, Add, FloorDiv, Mod) to prove divisibility, before falling back to statically_known_true. This is a demand-driven variant of the modular arithmetic analysis used in Halide and TVM.

Unlocks tt.divisibility hints for product expressions like `shape[0] * shape[1]` when `torch._check(shape[1] % 16 == 0)`.

Fixes pytorch#177146

Pull Request resolved: pytorch#177214
Approved by: https://github.com/jansel, https://github.com/laithsakka
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ultiple_of (pytorch#177214)

Add `_is_multiple_of()` that recurses over sympy expression structure (Mul, Add, FloorDiv, Mod) to prove divisibility, before falling back to statically_known_true. This is a demand-driven variant of the modular arithmetic analysis used in Halide and TVM.

Unlocks tt.divisibility hints for product expressions like `shape[0] * shape[1]` when `torch._check(shape[1] % 16 == 0)`.

Fixes pytorch#177146

Pull Request resolved: pytorch#177214
Approved by: https://github.com/jansel, https://github.com/laithsakka
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ultiple_of (pytorch#177214)

Add `_is_multiple_of()` that recurses over sympy expression structure (Mul, Add, FloorDiv, Mod) to prove divisibility, before falling back to statically_known_true. This is a demand-driven variant of the modular arithmetic analysis used in Halide and TVM.

Unlocks tt.divisibility hints for product expressions like `shape[0] * shape[1]` when `torch._check(shape[1] % 16 == 0)`.

Fixes pytorch#177146

Pull Request resolved: pytorch#177214
Approved by: https://github.com/jansel, https://github.com/laithsakka
@albanD albanD removed the bot-triaged This is a label only to be used by the auto triage bot label Oct 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Divisibility constraints are not propagated through symbolic expressions in Inductor

7 participants