Skip to content

Commit 075742a

Browse files
yashb98pytorchmergebot
authored andcommitted
[dynamo] Split OrderedSetVariable off SetVariable to match CPython (#196167)
## Issue Part of #192874, the `OrderedSetVariable(SetVariable)` row. `torch.utils._ordered_set.OrderedSet` is a pure-Python `collections.abc.MutableSet`, not a subclass of `set`: `issubclass(OrderedSet, set)` is `False`. `OrderedSetVariable` inherited `SetVariable`, so wherever the two types differ Dynamo used `set`'s behaviour, and a few paths treated the tracked object as a `set` or a `dict` that it is not. ## Summary The most visible effect is that an `OrderedSet` loses its insertion order when it crosses the compile boundary, because reconstruction and `repr` iterated an unordered set of the keys instead of the ordered backing dict: ```python import torch from torch.utils._ordered_set import OrderedSet def f(x): s = OrderedSet([3, 1, 2]) return s, repr(s), x + 1 torch.compile(f, backend="eager")(torch.ones(2)) ``` Before this change the returned set is `OrderedSet([1, 2, 3])` and `repr(s)` is `'OrderedSet([1, 2, 3])'`. After it, both keep `[3, 1, 2]`, which is what eager produces. Every operation that yields an OrderedSet is affected the same way: returning one, `copy`, `union`, `difference`, `symmetric_difference`, the operators, `add`, `update` and `repr`. Passing an OrderedSet into a compiled function did not work. Membership, iteration and mutation each failed: ```python def g(x, s): s.add(9) return 2 in s, list(s), x + 1 torch.compile(g, backend="eager")(torch.ones(2), OrderedSet([3, 1, 2])) ``` Before, this raises `AssertionError: Expected dict, got OrderedSet` while building guards, `2 in s` on its own fails a `set.__contains__` guard, and the `add` never reaches the caller. After, it returns `(True, [3, 1, 2, 9])` and the caller's set is `OrderedSet([3, 1, 2, 9])`, matching eager. The remaining differences are smaller and all now match eager: - `pop()` removed an arbitrary element rather than the most recently inserted one. `OrderedSet([3, 1, 2]).pop()` was `1`, now `2`. - `|=`, `&=` and `^=` with a non-set operand rebound the name to a new object instead of mutating in place, so `s is alias` was `False` afterwards. - `some_set - ordered_set` returned a `set`; `Set.__rsub__` builds an OrderedSet. - `reversed(s)` was unsupported; it now yields reverse insertion order. - an unhashable key, as in `{1, 2} in s` or `s.discard({1, 2})`, silently returned a result or coerced the key the way `set` does; it now raises `TypeError`, and so does `hash(s)`. ## Fix `OrderedSetVariable` becomes a sibling of `SetVariable` under `BaseSetVariable`, following the shape of #193580 (frozenset) and #193649 (dict_keys). `OrderedSet`'s public method surface is exactly `set`'s, so `tp_methods` registers the same named entries pointing at the same implementations, with `isdisjoint` coming from the base. What `OrderedSet` does differently is overridden on the class: - reconstruction, `repr` and `as_python_constant` iterate `self.items`, which is insertion ordered, instead of the unordered `set_items`. - `pop` removes the most recently inserted key. - the in-place operators call `update`, `intersection_update`, `symmetric_difference_update` and `difference_update`, so they accept any iterable and mutate in place like `MutableSet`. - `nb_subtract_impl` and `nb_and_impl` follow CPython's operand order for the reflected and intersection cases, and `__reversed__` yields reverse insertion order. - `is_hashable`, `hash_impl` and an OrderedSet-specific `sq_contains_impl` are declared here, since they are no longer inherited from `SetVariable`. - the `_dict` member exposes the backing dict so inlined `OrderedSet` methods trace. A passed-in OrderedSet is guarded through that dict already, so the per-key `SET_CONTAINS` guard and the key-order registration that assume a real `set` or `dict` are skipped for it. The references to `SetVariable` outside `sets.py` that matched an OrderedSet through inheritance now name `OrderedSetVariable` as well: the set-mutation replay handler in `side_effects.py`, `_unpack_fast_types` in `utils.py`, three checks in `builtin.py`, two in `higher_order_ops.py`, the `list.extend` fast path in `lists.py`, and `vt_identity_compare` in `object_protocol.py`. The builder wraps a passed-in set or OrderedSet with `track_mutable`, so mutations to it replay to the caller as they already do for a set built inside the region. ## Test plan New `OrderedSetHierarchyTests` in `test/dynamo/test_sets.py`, 17 tests, covering the hierarchy, ordering, `pop`, the operators, `reversed`, unhashable keys, the unbound `OrderedSet.method(...)` forms, explicit `__init__` calls, and reads and mutations of a passed-in OrderedSet and of a passed-in non-literal set. They pass with this change and fail on `main`. The full file runs 222 passed, 1 skipped on Python 3.10 and 3.12. `lintrunner` and `pyrefly` report no issues on the changed files. ## BC-breaking? Not for user code: results that previously disagreed with eager now agree with it. For out-of-tree code that touches Dynamo internals, `isinstance(x, SetVariable)` no longer matches an OrderedSet tracker, and `BaseSetVariable` is the check that matches all four set-family trackers. Related: #196111 was opened for the same row. Happy to consolidate. Authored with AI assistance. Pull Request resolved: #196167 Approved by: https://github.com/guilhermeleobas
1 parent 545e70c commit 075742a

8 files changed

Lines changed: 880 additions & 55 deletions

File tree

‎test/dynamo/test_sets.py‎

Lines changed: 607 additions & 0 deletions
Large diffs are not rendered by default.

‎torch/_dynamo/side_effects.py‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1669,14 +1669,26 @@ def _codegen_deque_mutation(ctx: SideEffectReplayContext) -> None:
16691669
@register_side_effect_replay_handler(
16701670
name="const_dict_or_set_mutation",
16711671
matcher=lambda ctx: isinstance(
1672-
ctx.var, (variables.ConstDictVariable, variables.SetVariable)
1672+
ctx.var,
1673+
(
1674+
variables.ConstDictVariable,
1675+
variables.SetVariable,
1676+
variables.OrderedSetVariable,
1677+
),
16731678
),
16741679
priority=70,
16751680
)
16761681
def _codegen_const_dict_or_set_mutation(ctx: SideEffectReplayContext) -> None:
16771682
cg = ctx.codegen
16781683
var = ctx.var
1679-
if not isinstance(var, (variables.ConstDictVariable, variables.SetVariable)):
1684+
if not isinstance(
1685+
var,
1686+
(
1687+
variables.ConstDictVariable,
1688+
variables.SetVariable,
1689+
variables.OrderedSetVariable,
1690+
),
1691+
):
16801692
raise AssertionError(type(var))
16811693
# Reconstruct works as follow:
16821694
# (1) Skip codegen if there are no new items

‎torch/_dynamo/variables/builder.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1341,7 +1341,11 @@ def build_key_value(
13411341
for i, v in enumerate(L)
13421342
]
13431343
result = set_var_cls(items, source=self.source)
1344-
return self.tx.output.side_effects.track_object_existing(value, result)
1344+
# Value mutation, like the literal-set path through wrap_literal:
1345+
# track_object_existing would give AttributeMutationExisting, which
1346+
# SideEffects.mutation never flags, so add/discard/|= on a
1347+
# passed-in set or OrderedSet would silently not reach the caller.
1348+
return self.tx.output.side_effects.track_mutable(value, result)
13451349
elif istype(value, frozenset) and all(
13461350
(
13471351
# For DBR quantization, we could get a frozenset of torch funcs.

‎torch/_dynamo/variables/builtin.py‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@
147147
type_implements_sq_length,
148148
vt_identity_compare,
149149
)
150-
from .sets import FrozensetVariable, SetVariable
150+
from .sets import FrozensetVariable, OrderedSetVariable, SetVariable
151151
from .tensor import (
152152
FakeItemVariable,
153153
supported_comparison_ops,
@@ -2459,6 +2459,7 @@ def call_frozenset(
24592459
variables.SetVariable,
24602460
variables.FrozensetVariable,
24612461
variables.DictKeySetVariable,
2462+
variables.OrderedSetVariable,
24622463
variables.ConstDictVariable,
24632464
),
24642465
):
@@ -3231,6 +3232,7 @@ def call_not_(
32313232
SetVariable,
32323233
FrozensetVariable,
32333234
variables.DictKeySetVariable,
3235+
OrderedSetVariable,
32343236
),
32353237
):
32363238
return VariableTracker.build(tx, len(a.items) == 0)
@@ -3418,6 +3420,7 @@ def _make_result(
34183420
variables.SetVariable,
34193421
variables.FrozensetVariable,
34203422
variables.DictKeySetVariable,
3423+
variables.OrderedSetVariable,
34213424
ConstDictVariable,
34223425
),
34233426
):
@@ -3884,14 +3887,10 @@ def call_function(
38843887
obj,
38853888
(variables.IteratorVariable, variables.LocalGeneratorObjectVariable),
38863889
):
3887-
if isinstance(
3888-
obj,
3889-
(
3890-
ConstDictVariable,
3891-
variables.OrderedSetVariable,
3892-
variables.DictKeySetVariable,
3893-
),
3894-
):
3890+
# An OrderedSet's key order is already guarded through the
3891+
# ``_dict`` source VariableBuilder registers; the object itself
3892+
# is not a dict and the guard manager would reject it.
3893+
if isinstance(obj, (ConstDictVariable, variables.DictKeySetVariable)):
38953894
tx.output.guard_on_key_order.add(obj.source)
38963895
if isinstance(obj, variables.MappingProxyVariable):
38973896
install_guard(

‎torch/_dynamo/variables/higher_order_ops.py‎

Lines changed: 5 additions & 2 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 DictKeySetVariable, FrozensetVariable, SetVariable
70+
from .sets import DictKeySetVariable, FrozensetVariable, OrderedSetVariable, SetVariable
7171

7272

7373
if TYPE_CHECKING:
@@ -249,7 +249,9 @@ 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, FrozensetVariable, DictKeySetVariable)):
252+
elif isinstance(
253+
var, (SetVariable, FrozensetVariable, DictKeySetVariable, OrderedSetVariable)
254+
):
253255
for key in var.items:
254256
mismatched_vars.update(find_mismatched_vars(key.vt, types, allow_none))
255257
else:
@@ -4380,6 +4382,7 @@ def _call_function(
43804382
SetVariable,
43814383
FrozensetVariable,
43824384
DictKeySetVariable,
4385+
OrderedSetVariable,
43834386
),
43844387
):
43854388
unimplemented(

‎torch/_dynamo/variables/lists.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,12 @@ 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 DictKeySetVariable, FrozensetVariable, SetVariable
533+
from .sets import (
534+
DictKeySetVariable,
535+
FrozensetVariable,
536+
OrderedSetVariable,
537+
SetVariable,
538+
)
534539
from .user_defined import UserDefinedObjectVariable
535540

536541
sz = len(self.items)
@@ -540,7 +545,13 @@ def list_extend(
540545
self.items.extend(unpack_iterable(tx, args[0]))
541546
elif isinstance(
542547
args[0],
543-
(ConstDictVariable, SetVariable, FrozensetVariable, DictKeySetVariable),
548+
(
549+
ConstDictVariable,
550+
SetVariable,
551+
FrozensetVariable,
552+
DictKeySetVariable,
553+
OrderedSetVariable,
554+
),
544555
):
545556
items = [item.vt for item in args[0].items]
546557
self.items.extend(items)

‎torch/_dynamo/variables/object_protocol.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,12 @@ def vt_identity_compare(
9090
from .functions import UserMethodVariable
9191
from .lists import ListVariable
9292
from .misc import ExceptionVariable, TracebackVariable
93-
from .sets import DictKeySetVariable, FrozensetVariable, SetVariable
93+
from .sets import (
94+
DictKeySetVariable,
95+
FrozensetVariable,
96+
OrderedSetVariable,
97+
SetVariable,
98+
)
9499

95100
if isinstance(
96101
left,
@@ -100,6 +105,7 @@ def vt_identity_compare(
100105
SetVariable,
101106
FrozensetVariable,
102107
DictKeySetVariable,
108+
OrderedSetVariable,
103109
TracebackVariable,
104110
ExceptionVariable,
105111
UserMethodVariable,

0 commit comments

Comments
 (0)