SIGN IN SIGN UP

[dynamo] Keep relational guards out of dict-tag skips (#185911)

Dict-tag guard shortcuts can skip checking immutable child managers when a
parent dictionary version has not changed. That is only correct for guards
whose evaluation is independent. Relational guards keep state across multiple
manager visits, so skipping one side of the relation can leave stale state and
turn a real guard failure into a false positive.

This shows up when an immutable value loaded from a dictionary participates in
an object-aliasing relational guard. The dictionary tag matches, the child
subtree is skipped, and the aliasing guard only observes the other operand.

Track whether a guard manager contains relational guards and suppress the
immutable dict-tag shortcut for those managers. Recursive dict-tag safety also
now rejects relational guards that do not have a dedicated fast path. The
existing no-tensor-aliasing fast path remains supported, and cloned root guard
managers now preserve the root no-tensor-aliasing guard pointer so cloned
recursive-dict-tag checks keep the state they need.

Fixes #147212
Generated by my agent

Test Plan:
- ninja -C build torch_python
- python test/dynamo/test_guard_manager.py -k test_clone_preserves_no_tensor_aliasing_guard_for_recursive_dict_tags
- python test/dynamo/test_guard_manager.py -k test_unoptimized_relational_guard_not_tag_safe
- python test/dynamo/test_guard_manager.py -k test_dict_getitem_accessor_with_object_aliasing_guard
- python test/dynamo/test_guard_manager.py
- Direct guard-manager repro now returns same=True and different=False
- Exact CUDA issue snippet returns True then False on current main/fix
- git diff --check
- lintrunner -a --skip CLANGTIDY
- lintrunner -a failed only on pre-existing broad CLANGTIDY diagnostics in torch/csrc/dynamo/guards.cpp

Benchmark Results:
Measured with a direct GuardManager micro-benchmark, 200,000 checks per repeat,
7 repeats, after rebuilding `torch_python` and refreshing `torch/lib/libtorch_python.so`.

- Unaffected immutable-dict fast path:
  - Before main e8fdac84fced: result=True, median 199.7 ns/check, min 199.6 ns/check
  - After fix: result=True, median 195.9 ns/check, min 194.6 ns/check
- Object-aliasing dict-getitem relational guard:
  - Before main e8fdac84fced: result=True but expected False, median 214.3 ns/check, min 211.8 ns/check
  - After fix: result=False as expected, median 226.2 ns/check, min 225.1 ns/check

Pull Request resolved: https://github.com/pytorch/pytorch/pull/185911
Approved by: https://github.com/anijain2305
J
Jason Ansel committed
c2400e40520a66fdc2a3f331953a8b999fecd35a
Parent: c196b7d
Committed by PyTorch MergeBot <pytorchmergebot@users.noreply.github.com> on 8/23/2026, 7:22:14 PM