Skip to content

Commit 59f3b80

Browse files
yashb98pytorchmergebot
authored andcommitted
[dynamo] Split FrozensetVariable off SetVariable to match CPython (#193580)
## Issue Part of #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 #193261 takes the same approach (`BaseListIteratorVariable`) for the deque iterator row. `DictKeySetVariable` and `OrderedSetVariable` still subclass `SetVariable`. They are separate rows of #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: #192867 (draft) also edits `torch/_dynamo/variables/sets.py`. Happy to rebase onto whichever lands first. Authored with AI assistance. Pull Request resolved: #193580 Approved by: https://github.com/guilhermeleobas
1 parent 723eb3f commit 59f3b80

8 files changed

Lines changed: 426 additions & 281 deletions

File tree

‎test/dynamo/test_sets.py‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,118 @@ def test_construct_from_range(self):
970970
self.assertEqual(list(s), [0, 1, 2, 3])
971971

972972

973+
class FrozensetHierarchyTests(_BaseSetTests):
974+
"""frozenset must not be a subclass of set (CPython parity). Part of #192874."""
975+
976+
def test_frozenset_not_a_set_variable(self):
977+
from torch._dynamo.variables.sets import (
978+
BaseSetVariable,
979+
FrozensetVariable,
980+
SetVariable,
981+
)
982+
983+
self.assertFalse(issubclass(FrozensetVariable, SetVariable))
984+
self.assertTrue(issubclass(FrozensetVariable, BaseSetVariable))
985+
self.assertTrue(issubclass(SetVariable, BaseSetVariable))
986+
# Matches real CPython.
987+
self.assertFalse(issubclass(frozenset, set))
988+
989+
def test_frozenset_has_no_mutating_methods(self):
990+
# Before the VT split, FrozensetVariable inherited SetVariable's
991+
# named methods via the tp_methods MRO-merge, so eight of the nine
992+
# below were reachable on a traced frozenset even though real
993+
# frozenset doesn't have them. `update` is the exception: it already
994+
# returned early on `not self.is_mutable()`, so it degraded correctly.
995+
for name, args in [
996+
("add", (1,)),
997+
("pop", ()),
998+
("remove", (1,)),
999+
("discard", (1,)),
1000+
("clear", ()),
1001+
("update", ({1},)),
1002+
("intersection_update", ({1},)),
1003+
("difference_update", ({1},)),
1004+
("symmetric_difference_update", ({1},)),
1005+
]:
1006+
with self.subTest(name=name):
1007+
self.assertFalse(hasattr(frozenset(), name))
1008+
1009+
@torch.compile(backend="eager", fullgraph=True)
1010+
def fn(fs, _name=name, _args=args):
1011+
return getattr(fs, _name)(*_args)
1012+
1013+
with self.assertRaises(Unsupported):
1014+
fn(frozenset({1, 2, 3}))
1015+
1016+
def test_frozenset_mutating_method_graph_breaks(self):
1017+
# With fullgraph=False a frozenset mutation must graph break and let
1018+
# eager raise the real AttributeError. Before the split it surfaced an
1019+
# internal "mutation_type is None for FrozensetVariable() in
1020+
# check_allowed_side_effect" AssertionError instead.
1021+
@torch.compile(backend="eager")
1022+
def fn(fs):
1023+
fs.add(1)
1024+
return fs
1025+
1026+
with self.assertRaises(AttributeError):
1027+
fn(frozenset({1, 2, 3}))
1028+
1029+
@make_dynamo_test
1030+
def test_frozenset_inplace_operators_rebind_not_mutate(self):
1031+
"""Not a regression test: this also passes before the split.
1032+
1033+
Real frozenset defines no __ior__/__iand__/__ixor__/__isub__, so
1034+
`fs |= other` rebinds the name to a new frozenset built by __or__.
1035+
FrozensetVariable used to inherit SetVariable's nb_inplace_* handlers,
1036+
but binary_iop1 gates on the real CPython type's nb slot bits (see
1037+
object_protocol.binary_iop1) and frozenset sets none of them, so the
1038+
inherited handlers were never reachable. Kept as a guard that the
1039+
split does not change this.
1040+
"""
1041+
fs = frozenset({1, 2, 3})
1042+
other = frozenset({3, 4, 5})
1043+
1044+
fs_or = fs
1045+
fs_or |= other
1046+
self.assertEqual(fs_or, frozenset({1, 2, 3, 4, 5}))
1047+
1048+
fs_and = fs
1049+
fs_and &= other
1050+
self.assertEqual(fs_and, frozenset({3}))
1051+
1052+
fs_xor = fs
1053+
fs_xor ^= other
1054+
self.assertEqual(fs_xor, frozenset({1, 2, 4, 5}))
1055+
1056+
@make_dynamo_test
1057+
def test_frozenset_readonly_ops_still_work(self):
1058+
fs = frozenset({1, 2, 3})
1059+
other = frozenset({3, 4, 5})
1060+
self.assertEqual(fs | other, frozenset({1, 2, 3, 4, 5}))
1061+
self.assertEqual(fs & other, frozenset({3}))
1062+
self.assertEqual(fs - other, frozenset({1, 2}))
1063+
self.assertEqual(fs ^ other, frozenset({1, 2, 4, 5}))
1064+
self.assertEqual(fs.union(other), frozenset({1, 2, 3, 4, 5}))
1065+
self.assertEqual(fs.intersection(other), frozenset({3}))
1066+
self.assertEqual(fs.difference(other), frozenset({1, 2}))
1067+
self.assertEqual(fs.symmetric_difference(other), frozenset({1, 2, 4, 5}))
1068+
self.assertTrue(fs.isdisjoint(frozenset({7, 8})))
1069+
self.assertTrue(frozenset({1, 2}).issubset(fs))
1070+
self.assertTrue(fs.issuperset(frozenset({1, 2})))
1071+
self.assertEqual(fs.copy(), fs)
1072+
self.assertEqual(len(fs), 3)
1073+
self.assertTrue(3 in fs)
1074+
1075+
@make_dynamo_test
1076+
def test_regular_set_mutations_unaffected(self):
1077+
# The mutable-set path must be completely unaffected by the split.
1078+
s = {1, 2, 3}
1079+
s.add(4)
1080+
s.discard(1)
1081+
s |= {10}
1082+
self.assertEqual(s, {2, 3, 4, 10})
1083+
1084+
9731085
if __name__ == "__main__":
9741086
from torch._dynamo.test_case import run_tests
9751087

‎torch/_dynamo/utils.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1310,6 +1310,7 @@ def _unpack_fast_types() -> tuple[type, ...]:
13101310
variables.ListIteratorVariable,
13111311
variables.RangeVariable,
13121312
variables.SetVariable,
1313+
variables.FrozensetVariable,
13131314
variables.TensorVariable,
13141315
variables.TupleVariable,
13151316
)

‎torch/_dynamo/variables/builtin.py‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2434,7 +2434,14 @@ def call_frozenset(
24342434
# Reuse existing HashableTracker keys from a set/frozenset/dict operand
24352435
# instead of re-hashing, mirroring CPython's set_update_internal fast
24362436
# path (do-not-rehash-dict-keys).
2437-
if isinstance(args[0], (variables.SetVariable, variables.ConstDictVariable)):
2437+
if isinstance(
2438+
args[0],
2439+
(
2440+
variables.SetVariable,
2441+
variables.FrozensetVariable,
2442+
variables.ConstDictVariable,
2443+
),
2444+
):
24382445
items = list(args[0].items.keys())
24392446
else:
24402447
items = unpack_iterable(tx, args[0])
@@ -3196,7 +3203,9 @@ def call_not_(
31963203
# Unwrap the underlying ConstDictVariable
31973204
if isinstance(a, DictViewVariable):
31983205
a = a.dv_dict
3199-
if isinstance(a, (ListVariable, ConstDictVariable, SetVariable)):
3206+
if isinstance(
3207+
a, (ListVariable, ConstDictVariable, SetVariable, FrozensetVariable)
3208+
):
32003209
return VariableTracker.build(tx, len(a.items) == 0)
32013210
if isinstance(a, UserDefinedObjectVariable):
32023211
bool_result = self.call_bool(tx, a)
@@ -3369,7 +3378,9 @@ def _make_result(
33693378
# re-wrapping (and thus re-hashing) the underlying VTs, mirroring
33703379
# CPython's do-not-rehash-dict-keys behavior when building a dict from
33713380
# an existing set/frozenset/dict.
3372-
if isinstance(arg, (variables.SetVariable, ConstDictVariable)):
3381+
if isinstance(
3382+
arg, (variables.SetVariable, variables.FrozensetVariable, ConstDictVariable)
3383+
):
33733384
# HashableTracker keys are accepted by ConstDictVariable.__init__.
33743385
return _make_result(dict.fromkeys(arg.items.keys(), value)) # type: ignore[arg-type]
33753386
if isinstance(arg, dict):

‎torch/_dynamo/variables/higher_order_ops.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@
6767
from .dicts import ConstDictVariable
6868
from .lazy import LazyVariableTracker
6969
from .lists import ListVariable, TupleVariable
70-
from .sets import SetVariable
70+
from .sets import FrozensetVariable, SetVariable
7171

7272

7373
if TYPE_CHECKING:
@@ -249,7 +249,7 @@ def find_mismatched_vars(
249249
elif isinstance(var, ConstDictVariable):
250250
for value in var.items.values():
251251
mismatched_vars.update(find_mismatched_vars(value, types, allow_none))
252-
elif isinstance(var, SetVariable):
252+
elif isinstance(var, (SetVariable, FrozensetVariable)):
253253
for key in var.items:
254254
mismatched_vars.update(find_mismatched_vars(key.vt, types, allow_none))
255255
else:
@@ -4352,7 +4352,14 @@ def _call_function(
43524352
# TODO (tmanlaibaatar) support pytree here
43534353
for arg in unpacked_sequence:
43544354
if isinstance(
4355-
arg, (ListVariable, TupleVariable, ConstDictVariable, SetVariable)
4355+
arg,
4356+
(
4357+
ListVariable,
4358+
TupleVariable,
4359+
ConstDictVariable,
4360+
SetVariable,
4361+
FrozensetVariable,
4362+
),
43564363
):
43574364
unimplemented(
43584365
gb_type="strict_mode: improper args",

‎torch/_dynamo/variables/lists.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -530,15 +530,15 @@ def list_extend(
530530
# CPython has a series of checks to optimize list.extend for different data types
531531
# ref: https://github.com/python/cpython/blob/0fd4fd4496c557b68477a99c1c231a5870c91daf/Objects/listobject.c#L1389-L1444
532532
from .dicts import ConstDictVariable
533-
from .sets import SetVariable
533+
from .sets import FrozensetVariable, SetVariable
534534
from .user_defined import UserDefinedObjectVariable
535535

536536
sz = len(self.items)
537537
if isinstance(args[0], (ListVariable, TupleVariable)):
538538
self.items.extend(args[0].items)
539539
elif isinstance(args[0], UserDefinedObjectVariable):
540540
self.items.extend(unpack_iterable(tx, args[0]))
541-
elif isinstance(args[0], (ConstDictVariable, SetVariable)):
541+
elif isinstance(args[0], (ConstDictVariable, SetVariable, FrozensetVariable)):
542542
items = [item.vt for item in args[0].items]
543543
self.items.extend(items)
544544
elif isinstance(args[0], ConstantVariable):

‎torch/_dynamo/variables/object_protocol.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,15 @@ def vt_identity_compare(
8585
from .dicts import ConstDictVariable
8686
from .lists import ListVariable
8787
from .misc import ExceptionVariable, TracebackVariable
88-
from .sets import SetVariable
88+
from .sets import FrozensetVariable, SetVariable
8989

9090
if isinstance(
9191
left,
9292
(
9393
ConstDictVariable,
9494
ListVariable,
9595
SetVariable,
96+
FrozensetVariable,
9697
TracebackVariable,
9798
ExceptionVariable,
9899
),

0 commit comments

Comments
 (0)