Skip to content

[dynamo] Split DequeIteratorVariable off ListIteratorVariable to match CPython - #193261

Closed
Bryanzzy1 wants to merge 1 commit into
pytorch:mainfrom
Bryanzzy1:fix/192874-deque-iterator-vt-split
Closed

Bryanzzy1 wants to merge 1 commit into
pytorch:mainfrom
Bryanzzy1:fix/192874-deque-iterator-vt-split

Conversation

@Bryanzzy1

@Bryanzzy1 Bryanzzy1 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In CPython, _deque_iterator is not a subclass of list_iterator, but Dynamo modeled DequeIteratorVariable as a subclass of ListIteratorVariable. This aligns the VariableTracker hierarchy with CPython. Part of #192874.

Fix

DequeIteratorVariable now inherits IteratorVariable directly instead of ListIteratorVariable, mirroring CPython where _deque_iterator and list_iterator are siblings. It carries its own iterate-over-materialized-items logic plus the existing per-step mutation check. TupleIteratorVariable stays a ListIteratorVariable subclass (matches CPython).

Breaking the subclass link touches three isinstance(x, ListIteratorVariable) sites that previously matched deque iterators transitively:

  • GET_YIELD_FROM_ITER now checks (ListIteratorVariable, DequeIteratorVariable) so list, tuple, and deque keep the same yield from behavior.
  • _unpack_fast_types re-adds DequeIteratorVariable so deque iterators keep the fast unpack_var_sequence path instead of the generic iterator protocol.
  • The list_iterator_mutation side-effect replay handler is source-based; deque iterators are always built sourceless with ValueMutationNew and never reached it, so no change is needed there.

Test Plan

python test/dynamo/test_iterators.py TestIterators.test_deque_iterator_not_a_list_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_deque_iterator
python test/dynamo/test_iterators.py

Authored with an AI assistant.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

@pytorch-bot

pytorch-bot Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 15 Cancelled Jobs, 2 Unrelated Failures, 2 Unclassified Failures

As of commit 9d5dce1 with merge base 26314d9 (image):

NEW FAILURE - The following job has failed:

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

  • pull / linux-jammy-cuda13.0-cudnn9-py3.10-clang20 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    lf-l-x86iavx512-8-64

    AI verdict: AI verdict: infra issue

    The failure is a Kubernetes pod scheduling issue ("Pod lf-l-x86iavx512-8-64-zf5jc-runner-9phgm-workflow is unhealthy with phase status Pending: backoff timeout"), not a build or test failure. The runner pod failed to come online before any code was compiled.

    Full reasoning on HUD →

  • pull / linux-jammy-cuda13.2-cudnn9-py3.10-clang20 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    lf-l-x86iavx512-8-64

    AI verdict: AI verdict: infra issue

    The failure is a Kubernetes pod scheduling timeout ("Pod lf-l-x86iavx512-8-64-zf5jc-runner-nkvjz-workflow is unhealthy with phase status Pending: backoff timeout"). The CI runner never came online, so no code was built or tested. This is purely infrastructure failure.

    Full reasoning on HUD →

CANCELLED JOBS - The following jobs were cancelled. Please retry:

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Aug 13, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Aug 13, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@Bryanzzy1
Bryanzzy1 force-pushed the fix/192874-deque-iterator-vt-split branch 2 times, most recently from ab5697d to 8156ddf Compare August 13, 2026 03:00
@Bryanzzy1 Bryanzzy1 changed the title Split DequeIteratorVariable off ListIteratorVariable to match CPython [dynamo] Split DequeIteratorVariable off ListIteratorVariable to match CPython Aug 13, 2026
@Bryanzzy1

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Aug 13, 2026
@Bryanzzy1
Bryanzzy1 marked this pull request as ready for review August 13, 2026 03:04
@Bryanzzy1

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorch-bot

pytorch-bot Bot commented Aug 13, 2026

Copy link
Copy Markdown

You don't have permissions to rebase this PR since you are a first time contributor. If you think this is a mistake, please contact PyTorch Dev Infra.

@Bryanzzy1

Copy link
Copy Markdown
Contributor Author

@guilhermeleobas the two cuda13 builds failed on ErrImagePull, the runner couldn't pull its image, so I don't think it's from this change. I can't rerun them myself as a first-time contributor. Could you re-run those two jobs when you get a chance? Thanks.

# PyListIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3842
_cpython_type = type(iter([]))

class BaseListIteratorVariable(IteratorVariable):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Let's avoid having a BaseListIterator that doesn't exist in CPython.

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.

I dropped the base class. DequeIteratorVariable now inherits IteratorVariable directly, same as CPython where _deque_iterator isn't a list_iterator subclass.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I said not to do that but I think that's perhaps the best approach here, given that we're probably copying too much code from ListIteratorVariable

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.

I agree. I will keep the base class since it is cleaner than duplicating ListIteratorVariable

@Bryanzzy1
Bryanzzy1 force-pushed the fix/192874-deque-iterator-vt-split branch 2 times, most recently from 8482a66 to b31a3f6 Compare August 13, 2026 15:17
Comment thread torch/_dynamo/utils.py Outdated
@@ -1308,6 +1308,7 @@ def _unpack_fast_types() -> tuple[type, ...]:
variables.DequeVariable,
variables.ListVariable,
variables.ListIteratorVariable,
variables.lists.DequeIteratorVariable,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should this be just variables.DequeIteratorVariable?

@Bryanzzy1 Bryanzzy1 Aug 13, 2026 •

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.

I applied the utils.py naming fix.

# PyListIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3842
_cpython_type = type(iter([]))

class BaseListIteratorVariable(IteratorVariable):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I said not to do that but I think that's perhaps the best approach here, given that we're probably copying too much code from ListIteratorVariable

@Bryanzzy1
Bryanzzy1 force-pushed the fix/192874-deque-iterator-vt-split branch from b31a3f6 to a96237c Compare August 13, 2026 18:41
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 13, 2026
indrajeetapache added a commit to indrajeetapache/pytorch that referenced this pull request Aug 16, 2026
…h CPython

tuple_iterator is not a subclass of list_iterator. Share the iterator
logic on BaseListIteratorVariable so the two VTs are siblings, matching
CPython. Deque iterators are left for pytorch#193261.

Fixes pytorch#192874
Comment thread torch/_dynamo/symbolic_convert.py Outdated
@@ -6534,7 +6492,8 @@ def YIELD_VALUE(self, inst: Instruction) -> None:

def GET_YIELD_FROM_ITER(self, inst: Instruction) -> None:
tos = self.stack[-1]
if not isinstance(tos, ListIteratorVariable):
# base class matches list, tuple, and deque iterators alike
if not isinstance(tos, BaseListIteratorVariable):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Better be explicit than implicit.

Suggested change
if not isinstance(tos, BaseListIteratorVariable):
if not isinstance(tos, ListIteratorVariable, DequeIteratorVariable):

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.

Done. Small note that isinstance needs a tuple for multiple types, so I used isinstance(tos, (ListIteratorVariable, DequeIteratorVariable)). Tuple iterators are still covered since they subclass ListIteratorVariable.

Comment thread torch/_dynamo/variables/__init__.py Outdated
@@ -216,6 +219,7 @@
"AutogradFunctionVariable",
"BackwardHookVariable",
"BaseBuiltinVariable",
"BaseListIteratorVariable",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Don't add BaseListIteratorVariable

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.

I removed it from the exports.

@Bryanzzy1
Bryanzzy1 force-pushed the fix/192874-deque-iterator-vt-split branch from a96237c to ccaaa6c Compare August 17, 2026 18:07
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) are pending/not yet run. The first few are:

  • EasyCLA

Dig deeper by viewing the pending checks on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

…h CPython

Dynamo modeled deque iterators as a subclass of ListIteratorVariable, but
in CPython _deque_iterator is not a subclass of list_iterator. This aligns
the VariableTracker hierarchy with CPython (pytorch#192874).

The shared iterator-over-materialized-items logic moves into an internal
BaseListIteratorVariable(IteratorVariable). ListIteratorVariable and
DequeIteratorVariable both inherit it, so DequeIteratorVariable is no longer a
subclass of ListIteratorVariable. TupleIteratorVariable is left untouched
(tracked separately).

Behavior is preserved. GET_YIELD_FROM_ITER previously used
isinstance(x, ListIteratorVariable) to detect one of our materialized-list
iterators; it now checks (ListIteratorVariable, DequeIteratorVariable)
explicitly (tuple iterators still match via ListIteratorVariable). Deque
iterators are also added to _unpack_fast_types so they keep the fast
unpack_var_sequence path instead of falling back to the generic iterator
protocol once they no longer subclass ListIteratorVariable.

Test Plan:

```
python test/dynamo/test_iterators.py TestIterators.test_deque_iterator_not_a_list_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_deque_iterator
python test/dynamo/test_iterators.py
```

Authored with an AI assistant.
@Bryanzzy1
Bryanzzy1 force-pushed the fix/192874-deque-iterator-vt-split branch from ccaaa6c to 9d5dce1 Compare August 18, 2026 16:35
@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@Bryanzzy1 can you sign the CLA?

@Bryanzzy1

Copy link
Copy Markdown
Contributor Author

@Bryanzzy1 can you sign the CLA?

@guilhermeleobas EasyCLA should pass now; it shows "authorized to contribute" on the latest commit. The earlier failure was because a commit was authored under an old noreply email; I corrected the author and re-pushed, the code was not changed. Should be good to re-run @pytorchbot merge whenever you're ready.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@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-rocm-py3.10-mi350 / test (distributed, 2, 3, linux.rocm.gpu.gfx950.2)

Details for Dev Infra team Raised by workflow job

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 18 checks: pull / linux-jammy-cuda13.2-cudnn9-py3.10-clang20 / build, pull / linux-jammy-cuda13.0-cudnn9-py3.10-clang20 / build, trunk / macos-py3-arm64 / build, trunk / dynamo-unittest / dynamo-test (3.11) / test (dynamo_wrapped, 3, 7, mt-l-x86iavx512-8-64), trunk / dynamo-unittest / dynamo-test (3.12) / test (dynamo_wrapped, 3, 7, mt-l-x86iavx512-8-64), trunk / cross-compile-linux-test-cuda13 / test (aoti_cross_compile_for_windows, 1, 1, lf-l-x86aavx2-29-113-l4, win-vs2022-cuda13.0-py3), trunk / cross-compile-linux-test-cuda132 / test (aoti_cross_compile_for_windows, 1, 1, lf-l-x86aavx2-29-113-l4, win-vs2022-cuda13.2-py3), trunk / verify-cachebench-cpu-test / test (verify_cachebench, 1, 1, lf-l-x86iavx512-8-64), trunk / linux-jammy-rocm-py3.10-mi350 / test (distributed, 2, 3, linux.rocm.gpu.gfx950.2), inductor / unit-test / inductor-test / test (inductor_cpp_wrapper, 2, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-test / test (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-test / test (inductor, 1, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-test-cuda132 / test (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-test-cuda132 / test (inductor_distributed, 1, 1, mt-l-x86aavx2-45-167-a10g-4), inductor / unit-test / inductor-test-cuda132 / test (inductor, 1, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-test-cuda132 / test (inductor_cpp_wrapper, 1, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-cpu-test / test (inductor_amx, 2, 2, mt-l-x86iamx-8-64), inductor / unit-test / inductor-cpu-test / test (inductor_amx, 1, 2, mt-l-x86iamx-8-64)

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

indrajeetapache added a commit to indrajeetapache/pytorch that referenced this pull request Aug 19, 2026
…h CPython

tuple_iterator is not a subclass of list_iterator. Reparent
TupleIteratorVariable onto BaseListIteratorVariable (already introduced
by pytorch#193261 for deque) so list and tuple iterators are siblings.

Call sites check ListIteratorVariable and TupleIteratorVariable
explicitly rather than exporting the shared base, which has no CPython
counterpart. GET_YIELD_FROM_ITER also keeps DequeIteratorVariable after
the pytorch#193261 split.

Part of pytorch#192874

Co-authored-by: Cursor <[email protected]>
indrajeetapache added a commit to indrajeetapache/pytorch that referenced this pull request Aug 19, 2026
…h CPython

tuple_iterator is not a subclass of list_iterator. Reparent
TupleIteratorVariable onto BaseListIteratorVariable (already introduced
by pytorch#193261 for deque) so list and tuple iterators are siblings.

Call sites check ListIteratorVariable and TupleIteratorVariable
explicitly rather than exporting the shared base, which has no CPython
counterpart. GET_YIELD_FROM_ITER also keeps DequeIteratorVariable after
the pytorch#193261 split.

Part of pytorch#192874
meta-codesync Bot pushed a commit to pytorch/benchmark that referenced this pull request Aug 20, 2026
… (#193261)

Summary:
## Summary
In CPython, `_deque_iterator` is not a subclass of `list_iterator`, but Dynamo modeled `DequeIteratorVariable` as a subclass of `ListIteratorVariable`. This aligns the VariableTracker hierarchy with CPython. Part of #192874.

## Fix
`DequeIteratorVariable` now inherits `IteratorVariable` directly instead of `ListIteratorVariable`, mirroring CPython where `_deque_iterator` and `list_iterator` are siblings. It carries its own iterate-over-materialized-items logic plus the existing per-step mutation check. `TupleIteratorVariable` stays a `ListIteratorVariable` subclass (matches CPython).

Breaking the subclass link touches three `isinstance(x, ListIteratorVariable)` sites that previously matched deque iterators transitively:
- `GET_YIELD_FROM_ITER` now checks `(ListIteratorVariable, DequeIteratorVariable)` so list, tuple, and deque keep the same `yield from` behavior.
- `_unpack_fast_types` re-adds `DequeIteratorVariable` so deque iterators keep the fast `unpack_var_sequence` path instead of the generic iterator protocol.
- The `list_iterator_mutation` side-effect replay handler is source-based; deque iterators are always built sourceless with `ValueMutationNew` and never reached it, so no change is needed there.

## Test Plan
```
python test/dynamo/test_iterators.py TestIterators.test_deque_iterator_not_a_list_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_deque_iterator
python test/dynamo/test_iterators.py
```

Authored with an AI assistant.

X-link: pytorch/pytorch#193261
Approved by: https://github.com/guilhermeleobas

Reviewed By: jeanschmidt

Differential Revision: D116640619

fbshipit-source-id: 4cea3cee2f1e89db65d2748d7dfc0d75b27d27ee
pytorchmergebot pushed a commit that referenced this pull request Aug 20, 2026
…h CPython (#193717)

## Summary

In CPython, `tuple_iterator` is not a subclass of `list_iterator`:

```
>>> issubclass(type(iter(())), type(iter([])))
False
```

`dir()` on both is the same (`__iter__`, `__next__`, `__length_hint__`), so there is no extra method table to model. Dynamo still had `TupleIteratorVariable(ListIteratorVariable)`, which made every `isinstance(x, ListIteratorVariable)` check match tuple iterators too.

#193261 has landed and already introduced `BaseListIteratorVariable` for the deque split. This PR rebases on that and reparents `TupleIteratorVariable` onto the same base so list and tuple iterators are siblings.

Review feedback from #193727 (`@guilhermeleobas`) is incorporated:

- Do **not** export `BaseListIteratorVariable` (no CPython counterpart). It stays internal to `lists.py`.
- Be explicit at call sites: `ListIteratorVariable` and `TupleIteratorVariable`, not the shared base.
- `GET_YIELD_FROM_ITER` checks `ListIteratorVariable`, `TupleIteratorVariable`, and `DequeIteratorVariable`. Deque has to stay listed after #193261, because deque iterators are no longer a `ListIteratorVariable` subclass.

Also in this PR:

- `python_type()` / `as_python_constant()` on `TupleIteratorVariable` return a real `tuple_iterator`.
- `TupleIteratorVariable` is added to the unpack fast path.
- Regression tests cover the hierarchy, `yield from`, and `type(iter((1, 2, 3)))`.

Part of #192874

## Test plan

```
python test/dynamo/test_iterators.py TestIterators.test_tuple_iterator_not_a_list_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_tuple_iterator
python test/dynamo/test_iterators.py TestIterators.test_tuple_iterator_python_type
python test/dynamo/test_iterators.py
```

Pull Request resolved: #193717
Approved by: https://github.com/guilhermeleobas
cyyever pushed a commit to cyyever/pytorch that referenced this pull request Aug 22, 2026
…h CPython (pytorch#193717)

## Summary

In CPython, `tuple_iterator` is not a subclass of `list_iterator`:

```
>>> issubclass(type(iter(())), type(iter([])))
False
```

`dir()` on both is the same (`__iter__`, `__next__`, `__length_hint__`), so there is no extra method table to model. Dynamo still had `TupleIteratorVariable(ListIteratorVariable)`, which made every `isinstance(x, ListIteratorVariable)` check match tuple iterators too.

pytorch#193261 has landed and already introduced `BaseListIteratorVariable` for the deque split. This PR rebases on that and reparents `TupleIteratorVariable` onto the same base so list and tuple iterators are siblings.

Review feedback from pytorch#193727 (`@guilhermeleobas`) is incorporated:

- Do **not** export `BaseListIteratorVariable` (no CPython counterpart). It stays internal to `lists.py`.
- Be explicit at call sites: `ListIteratorVariable` and `TupleIteratorVariable`, not the shared base.
- `GET_YIELD_FROM_ITER` checks `ListIteratorVariable`, `TupleIteratorVariable`, and `DequeIteratorVariable`. Deque has to stay listed after pytorch#193261, because deque iterators are no longer a `ListIteratorVariable` subclass.

Also in this PR:

- `python_type()` / `as_python_constant()` on `TupleIteratorVariable` return a real `tuple_iterator`.
- `TupleIteratorVariable` is added to the unpack fast path.
- Regression tests cover the hierarchy, `yield from`, and `type(iter((1, 2, 3)))`.

Part of pytorch#192874

## Test plan

```
python test/dynamo/test_iterators.py TestIterators.test_tuple_iterator_not_a_list_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_tuple_iterator
python test/dynamo/test_iterators.py TestIterators.test_tuple_iterator_python_type
python test/dynamo/test_iterators.py
```

Pull Request resolved: pytorch#193717
Approved by: https://github.com/guilhermeleobas

(cherry picked from commit d0f59eb)
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…torch#193580)

## Issue

Part of pytorch#192874, the `FrozensetVariable(SetVariable)` row. That tracker lists eight rows, so this does not close it.

## Summary

Under `torch.compile`, calling a mutating `set` method on a `frozenset` raised an internal assertion instead of the `AttributeError` CPython raises:

```python
import torch

def f(fs):
    fs.add(4)          # frozenset has no .add
    return fs

torch.compile(f, backend="eager")(frozenset({1, 2, 3}))
```

Before, with `fullgraph=False`, where a graph break was expected:

```
AssertionError: mutation_type is None for FrozensetVariable() in check_allowed_side_effect
```

After, with `fullgraph=False`, matching eager:

```
AttributeError: 'frozenset' object has no attribute 'add'
```

After, with `fullgraph=True`, an ordinary unsupported-call error:

```
Unsupported method call
  Explanation: Dynamo does not know how to trace method `add` of class `frozenset`
```

The same applied to `pop`, `remove`, `discard`, `clear`, `intersection_update`, `difference_update` and `symmetric_difference_update`. `update` is the exception: it already returned early on `not self.is_mutable()`, so it degraded correctly before this change.

Cause: `FrozensetVariable` subclassed `SetVariable`, so it picked up all nine mutating entries of `SetVariable.tp_methods` through the tp_methods MRO merge. In CPython `frozenset` and `set` are siblings, not parent and child.

## Fix

A new `BaseSetVariable(VariableTracker)` holds the shared read-only surface: the eight read-only `tp_methods` (`isdisjoint`, `intersection`, `union`, `difference`, `symmetric_difference`, `issubset`, `issuperset`, `copy`), the `nb_or_impl` / `nb_and_impl` / `nb_xor_impl` / `nb_subtract_impl` slots, and the storage, guard and iteration helpers. `SetVariable(BaseSetVariable)` keeps the nine mutating `tp_methods` and the `nb_inplace_*` slots, so `FrozensetVariable(BaseSetVariable)` can reach neither group.

Eight `SetVariable` references outside `sets.py` that used to match frozensets transitively are widened to `BaseSetVariable`: seven `isinstance` checks (`builtin.py` x3, `higher_order_ops.py` x2, `lists.py`, `object_protocol.py`) and the `_unpack_fast_types()` tuple in `utils.py`. `BaseSetVariable` is exported from `variables/__init__.py`.

Two `isinstance(..., SetVariable)` checks are deliberately left alone, because the split makes them more accurate: `SET_ADD` and `SET_UPDATE` in `symbolic_convert.py` assert their accumulator is a mutable set, and the `const_dict_or_set_mutation` replay handler in `side_effects.py` emits `update` and `clear`, neither of which exists on a frozenset. `OrderedSetClassVariable.call_method` also stops routing unbound `OrderedSet.union(some_frozenset, ...)` calls into the frozenset tracker, which matches eager, where that raises.

### Why a base class

The split follows a line CPython already draws. `frozenset` and `set` are both `collections.abc.Set`, only `set` is a `MutableSet`, and `set(dir(MutableSet)) - set(dir(Set))` is exactly `{add, clear, discard, pop, remove, __ior__, __iand__, __isub__, __ixor__}`. That is the group `SetVariable` keeps, so `BaseSetVariable` is `Set` and `SetVariable` is `MutableSet`. (`update` and the three `*_update` methods have no ABC counterpart, but they are mutators too, so they stay on `SetVariable`.) Happy to rename it `AbstractSetVariable` if that reads better.

It also avoids a large copy. If `FrozensetVariable` inherited `VariableTracker` directly, it would have to duplicate 31 methods and 2 class constants, 355 lines, out of `SetVariable`: everything now in `BaseSetVariable` that `FrozensetVariable` does not already shadow (it shadows only five, `copy`, `intersection`, `difference`, `symmetric_difference` and `tp_methods`).

`BaseListVariable`, `BaseUserFunctionVariable` and `BaseBuiltinVariable` are used the same way in the same package, and pytorch#193261 takes the same approach (`BaseListIteratorVariable`) for the deque iterator row.

`DictKeySetVariable` and `OrderedSetVariable` still subclass `SetVariable`. They are separate rows of pytorch#192874 and out of scope here.

## Test plan

New `FrozensetHierarchyTests` in `test/dynamo/test_sets.py`, 6 tests. Run against the same test file with only `torch` swapped:

```
patched     Ran 6 tests, OK
unpatched   Ran 6 tests, FAILED (failures=9, errors=1)
```

Being precise about what that demonstrates, since not all six are regression coverage:

- `test_frozenset_has_no_mutating_methods` sub-tests all nine mutators under `fullgraph=True`. Eight fail unpatched: `add`, `pop`, `remove`, `discard`, `clear`, `intersection_update`, `difference_update`, `symmetric_difference_update`. The `update` sub-test passes unpatched, per the early return noted above.
- `test_frozenset_mutating_method_graph_breaks` covers `fullgraph=False` and fails unpatched with the `mutation_type is None` assertion above. This is the user-visible bug.
- `test_frozenset_not_a_set_variable` is a structural assertion, not behaviour. It errors unpatched with `ImportError: cannot import name 'BaseSetVariable'`, so it guards against the classes being merged again rather than proving a fix.
- The remaining three pass both before and after and are non-regression guards: `test_frozenset_inplace_operators_rebind_not_mutate`, `test_frozenset_readonly_ops_still_work`, `test_regular_set_mutations_unaffected`.

Suites run locally, all against the patched tree:

```
test/dynamo/test_sets.py              Ran 196 tests, OK (skipped=1)
test/dynamo/test_functions.py         Ran 531 tests, OK (skipped=9, expected failures=2)
test/dynamo/test_dicts.py             Ran 323 tests, OK (expected failures=1)
test/dynamo/test_higher_order_ops.py  Ran 224 tests, OK (skipped=17, expected failures=1)
test/dynamo/test_repros.py            Ran 388 tests, OK (skipped=19, expected failures=4)
test/dynamo/test_misc.py              Ran 822 tests, FAILED (failures=1, errors=1, skipped=13, expected failures=4)
```

The two `test_misc.py` problems are environmental and pre-existing on this machine: `test_pybind11_enum_conversion` needs `ninja`, which is not installed, and `test_debugmode_respects_custom_op_aliasing_env_override` spawns a subprocess that imports the unbuilt source tree from the working directory (it passes when run from another directory). Neither traceback contains a `set`, `frozenset` or `SetVariable` frame.

These ran on a nightly CPU wheel, `2.15.0.dev20260812+cpu`, with the repository sources overlaid (the `tools/nightly.py` workflow in CONTRIBUTING.md) rather than a from-source build. The change is pure Python with no C++ coupling, so the modified code is the code under test, but I have run no CUDA or distributed suites locally and am relying on CI for those.

Lint, at the versions the repo pins:

```
lintrunner 0.12.7 --take RUFF,PYFMT,NEWLINE,SPACES,CODESPELL,FLAKE8,TYPEIGNORE,NOQA,TABS
  ok No lint issues.
ruff 0.14.4  All checks passed! / 8 files already formatted
```

`pyrefly 0.58.0` reports 131 pre-existing errors on these files, all `missing-attribute` or `missing-module-attribute` against `torch._C` symbols, caused by the build-generated stubs being absent from a non-source checkout. None falls on a line this change adds, checked by intersecting the reported error locations with the added lines; `sets.py` reports zero. I did not run a pre-change `pyrefly` baseline, so that is an attribution check rather than a differential one.

## Checklist

- [x] Passes lint (`spin fixlint`)
- [x] Added/updated tests
- [ ] Updated documentation (not applicable)
- [ ] Included benchmark results (not applicable, no expected perf impact)

## BC-breaking?

No for user-visible behaviour. An internal assertion that used to escape becomes either the `AttributeError` CPython raises or, under `fullgraph=True`, an ordinary unsupported-call error. For out-of-tree code touching Dynamo internals, `isinstance(x, SetVariable)` no longer matches a frozenset tracker and needs `BaseSetVariable`.

Related: pytorch#192867 (draft) also edits `torch/_dynamo/variables/sets.py`. Happy to rebase onto whichever lands first.

Authored with AI assistance.

Pull Request resolved: pytorch#193580
Approved by: https://github.com/guilhermeleobas
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…h CPython (pytorch#193261)

## Summary
In CPython, `_deque_iterator` is not a subclass of `list_iterator`, but Dynamo modeled `DequeIteratorVariable` as a subclass of `ListIteratorVariable`. This aligns the VariableTracker hierarchy with CPython. Part of pytorch#192874.

## Fix
`DequeIteratorVariable` now inherits `IteratorVariable` directly instead of `ListIteratorVariable`, mirroring CPython where `_deque_iterator` and `list_iterator` are siblings. It carries its own iterate-over-materialized-items logic plus the existing per-step mutation check. `TupleIteratorVariable` stays a `ListIteratorVariable` subclass (matches CPython).

Breaking the subclass link touches three `isinstance(x, ListIteratorVariable)` sites that previously matched deque iterators transitively:
- `GET_YIELD_FROM_ITER` now checks `(ListIteratorVariable, DequeIteratorVariable)` so list, tuple, and deque keep the same `yield from` behavior.
- `_unpack_fast_types` re-adds `DequeIteratorVariable` so deque iterators keep the fast `unpack_var_sequence` path instead of the generic iterator protocol.
- The `list_iterator_mutation` side-effect replay handler is source-based; deque iterators are always built sourceless with `ValueMutationNew` and never reached it, so no change is needed there.

## Test Plan
```
python test/dynamo/test_iterators.py TestIterators.test_deque_iterator_not_a_list_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_deque_iterator
python test/dynamo/test_iterators.py
```

Authored with an AI assistant.

Pull Request resolved: pytorch#193261
Approved by: https://github.com/guilhermeleobas
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…h CPython (pytorch#193717)

## Summary

In CPython, `tuple_iterator` is not a subclass of `list_iterator`:

```
>>> issubclass(type(iter(())), type(iter([])))
False
```

`dir()` on both is the same (`__iter__`, `__next__`, `__length_hint__`), so there is no extra method table to model. Dynamo still had `TupleIteratorVariable(ListIteratorVariable)`, which made every `isinstance(x, ListIteratorVariable)` check match tuple iterators too.

pytorch#193261 has landed and already introduced `BaseListIteratorVariable` for the deque split. This PR rebases on that and reparents `TupleIteratorVariable` onto the same base so list and tuple iterators are siblings.

Review feedback from pytorch#193727 (`@guilhermeleobas`) is incorporated:

- Do **not** export `BaseListIteratorVariable` (no CPython counterpart). It stays internal to `lists.py`.
- Be explicit at call sites: `ListIteratorVariable` and `TupleIteratorVariable`, not the shared base.
- `GET_YIELD_FROM_ITER` checks `ListIteratorVariable`, `TupleIteratorVariable`, and `DequeIteratorVariable`. Deque has to stay listed after pytorch#193261, because deque iterators are no longer a `ListIteratorVariable` subclass.

Also in this PR:

- `python_type()` / `as_python_constant()` on `TupleIteratorVariable` return a real `tuple_iterator`.
- `TupleIteratorVariable` is added to the unpack fast path.
- Regression tests cover the hierarchy, `yield from`, and `type(iter((1, 2, 3)))`.

Part of pytorch#192874

## Test plan

```
python test/dynamo/test_iterators.py TestIterators.test_tuple_iterator_not_a_list_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_tuple_iterator
python test/dynamo/test_iterators.py TestIterators.test_tuple_iterator_python_type
python test/dynamo/test_iterators.py
```

Pull Request resolved: pytorch#193717
Approved by: https://github.com/guilhermeleobas
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
… to match CPython (#194348)

## Summary

In CPython, `_deque_reverse_iterator` is not a subclass of `_deque_iterator`:

```
>>> from collections import deque
>>> issubclass(type(reversed(deque())), type(iter(deque())))
False
```

`dir()` on both is the same (`__iter__`, `__next__`, `__length_hint__`). Dynamo still had `DequeReverseIteratorVariable(DequeIteratorVariable)`, so every `isinstance(x, DequeIteratorVariable)` check also matched reverse deque iterators.

This follows the same shape as #193261 (deque forward) and #193717 (tuple): reparent onto the existing `BaseListIteratorVariable` so the two deque iterator VTs are siblings. No new base class.

The deque mutation snapshot (`source_deque` / `saved_state`) cannot be inherited from `DequeIteratorVariable` after the split, or reverse iterators would still type-check as deque iterators. It is copied onto `DequeReverseIteratorVariable` so `reversed(d)` still raises `RuntimeError: deque mutated during iteration`.

### Files touched

| File | What changed |
| --- | --- |
| `torch/_dynamo/variables/lists.py` | `DequeReverseIteratorVariable` now subclasses `BaseListIteratorVariable`. Mutation snapshot copied so reverse iterators stay siblings. |
| `torch/_dynamo/symbolic_convert.py` | `GET_YIELD_FROM_ITER` lists `DequeReverseIteratorVariable` explicitly (same pattern as list/tuple/deque after #193717). |
| `torch/_dynamo/utils.py` | `_unpack_fast_types` adds `DequeReverseIteratorVariable` so reverse deque unpack keeps the fast path. |
| `torch/_dynamo/variables/__init__.py` | Import `DequeReverseIteratorVariable` (not exported in `__all__`, same as `DequeIteratorVariable`). |
| `test/dynamo/test_iterators.py` | Hierarchy, `yield from reversed(deque)`, and `type(reversed(deque))` regression tests. |

Not touched: `side_effects.py`. Deque iterators are built sourceless with `ValueMutationNew` and never hit the list/tuple iterator replay handler (#193261). Reverse is the same.

Part of #192874

## Test plan

```
python test/dynamo/test_iterators.py TestIterators.test_deque_reverse_iterator_not_a_deque_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_deque_reverse_iterator
python test/dynamo/test_iterators.py TestIterators.test_deque_reverse_iterator_python_type
python test/dynamo/test_iterators.py
python test/dynamo/test_sequence_ops.py -k deque_reverse
```

Pull Request resolved: #194348
Approved by: https://github.com/guilhermeleobas, https://github.com/hameerabbasi
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
… to match CPython (pytorch#194348)

## Summary

In CPython, `_deque_reverse_iterator` is not a subclass of `_deque_iterator`:

```
>>> from collections import deque
>>> issubclass(type(reversed(deque())), type(iter(deque())))
False
```

`dir()` on both is the same (`__iter__`, `__next__`, `__length_hint__`). Dynamo still had `DequeReverseIteratorVariable(DequeIteratorVariable)`, so every `isinstance(x, DequeIteratorVariable)` check also matched reverse deque iterators.

This follows the same shape as pytorch#193261 (deque forward) and pytorch#193717 (tuple): reparent onto the existing `BaseListIteratorVariable` so the two deque iterator VTs are siblings. No new base class.

The deque mutation snapshot (`source_deque` / `saved_state`) cannot be inherited from `DequeIteratorVariable` after the split, or reverse iterators would still type-check as deque iterators. It is copied onto `DequeReverseIteratorVariable` so `reversed(d)` still raises `RuntimeError: deque mutated during iteration`.

### Files touched

| File | What changed |
| --- | --- |
| `torch/_dynamo/variables/lists.py` | `DequeReverseIteratorVariable` now subclasses `BaseListIteratorVariable`. Mutation snapshot copied so reverse iterators stay siblings. |
| `torch/_dynamo/symbolic_convert.py` | `GET_YIELD_FROM_ITER` lists `DequeReverseIteratorVariable` explicitly (same pattern as list/tuple/deque after pytorch#193717). |
| `torch/_dynamo/utils.py` | `_unpack_fast_types` adds `DequeReverseIteratorVariable` so reverse deque unpack keeps the fast path. |
| `torch/_dynamo/variables/__init__.py` | Import `DequeReverseIteratorVariable` (not exported in `__all__`, same as `DequeIteratorVariable`). |
| `test/dynamo/test_iterators.py` | Hierarchy, `yield from reversed(deque)`, and `type(reversed(deque))` regression tests. |

Not touched: `side_effects.py`. Deque iterators are built sourceless with `ValueMutationNew` and never hit the list/tuple iterator replay handler (pytorch#193261). Reverse is the same.

Part of pytorch#192874

## Test plan

```
python test/dynamo/test_iterators.py TestIterators.test_deque_reverse_iterator_not_a_deque_iterator
python test/dynamo/test_iterators.py TestIterators.test_yield_from_deque_reverse_iterator
python test/dynamo/test_iterators.py TestIterators.test_deque_reverse_iterator_python_type
python test/dynamo/test_iterators.py
python test/dynamo/test_sequence_ops.py -k deque_reverse
```

Pull Request resolved: pytorch#194348
Approved by: https://github.com/guilhermeleobas, https://github.com/hameerabbasi
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: dynamo 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.

5 participants