Skip to content

[dynamo] Split OrderedSetVariable off SetVariable to match CPython - #196167

Closed
yashb98 wants to merge 2 commits into
pytorch:mainfrom
yashb98:fix/192874-orderedset-vt-split
Closed

yashb98 wants to merge 2 commits into
pytorch:mainfrom
yashb98:fix/192874-orderedset-vt-split

Conversation

@yashb98

@yashb98 yashb98 commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

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:

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:

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.

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

@pytorch-bot

pytorch-bot Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 4ea8bb0 with merge base 300f0c8 (image):

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 Sep 6, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 6, 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 Sep 6, 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.

@yashb98

yashb98 commented Sep 6, 2026

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 Sep 6, 2026
@yashb98
yashb98 marked this pull request as ready for review September 6, 2026 10:58
@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@yashb98 can you address the test failures?

Comment thread torch/_dynamo/variables/sets.py Resolved
Comment thread torch/_dynamo/variables/sets.py Resolved
@yashb98

yashb98 commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review, both points addressed locally.

The -= repro was spot on: SetVariable.nb_inplace_subtract_impl flagged the mutation but never set should_reconstruct_all, and the replay handler only emits when has_new_items() is true, so a removal-only -= on a passed-in non-literal set was silently skipped. Your exact snippet passes now. I also added tp_init_impl to OrderedSetVariable and made OrderedSetClassVariable.call_function delegate to it (tp_new + tp_init), so the constructor and an explicit init share one argument-handling path.

Separately, the py3.10 CI failures were my test's fault: I used slice(0, 1) as the non-literal element, but slice is only hashable since 3.12. Swapped it for a plain object instance (same idea as your Key) and extended the test to cover the in-place operators on a passed-in non-literal set, so the -= case is locked in as a regression test.

I want to verify before pushing, so I'm running the new tests plus the full test_sets.py on both 3.10 and 3.12 locally, and a local 3.10 arm that mirrors the failing CI shard's exact run_test.py command. Once those finish clean I'll push the update.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

There are some Python 3.10 failures. Can you check?

yashb98 added a commit to yashb98/pytorch that referenced this pull request Sep 10, 2026
…p_init_impl

Address review feedback on pytorch#196167:

- SetVariable.nb_inplace_subtract_impl never set should_reconstruct_all,
  so a removal-only `-=` on a passed-in non-literal set produced no new
  items and the mutation replay handler skipped it; the caller's set kept
  the removed elements. Set the flag, matching difference_update.
- Add OrderedSetVariable.tp_init_impl and make OrderedSetClassVariable's
  call_function delegate to it, so the constructor and an explicit
  OrderedSet.__init__(s, ...) share one argument-handling path. Init
  builds the new items before clearing the old ones, so a TypeError from
  an unhashable element leaves the set unchanged, matching eager.
- test_passed_in_non_literal_set_mutation_reaches_caller used slice
  elements, which are only hashable since Python 3.12; the set literal
  raised TypeError on the py3.10 CI jobs. Use a plain object instance
  instead, extend the test to the in-place operators with fullgraph on
  and off, and add test_explicit_dunder_init_matches_eager.

Part of pytorch#192874.
OrderedSet is a pure-Python MutableSet, not a set subclass, but
OrderedSetVariable inherited SetVariable and with it set's behaviour
wherever the two differ. Make it a BaseSetVariable sibling of
SetVariable with set's full named-method surface, and override what
OrderedSet does differently: reconstruction, repr and
as_python_constant follow insertion order instead of hash order,
pop() returns the most recently inserted element, the in-place
operators are MutableSet's (any iterable, mutate in place), reflected
subtraction and & follow CPython's operand order, reversed() gives
reverse insertion order, and hash() and an unhashable key raise
TypeError like eager.

A passed-in OrderedSet also did not work: membership failed a
SET_CONTAINS guard evaluated as set.__contains__ on the OrderedSet,
iteration registered the object for key-order guarding where a dict is
expected, and mutations were traced but never replayed because the
builder registered it with AttributeMutationExisting. The object is
already guarded through its _dict, so the per-key guard and the
key-order registration are skipped for OrderedSetVariable, and the
builder wraps it with track_mutable like the literal-set path.

Unbound OrderedSet.method(obj, ...) calls run OrderedSet's own method
for any receiver, so the result or exception matches eager, and
OrderedSet(None) is the empty constructor. Call sites that matched
OrderedSetVariable through SetVariable now name it.

Part of pytorch#192874.
…p_init_impl

Address review feedback on pytorch#196167:

- SetVariable.nb_inplace_subtract_impl never set should_reconstruct_all,
  so a removal-only `-=` on a passed-in non-literal set produced no new
  items and the mutation replay handler skipped it; the caller's set kept
  the removed elements. Set the flag, matching difference_update.
- Add OrderedSetVariable.tp_init_impl and make OrderedSetClassVariable's
  call_function delegate to it, so the constructor and an explicit
  OrderedSet.__init__(s, ...) share one argument-handling path. Init
  builds the new items before clearing the old ones, so a TypeError from
  an unhashable element leaves the set unchanged, matching eager.
- test_passed_in_non_literal_set_mutation_reaches_caller used slice
  elements, which are only hashable since Python 3.12; the set literal
  raised TypeError on the py3.10 CI jobs. Use a plain object instance
  instead, extend the test to the in-place operators with fullgraph on
  and off, and add test_explicit_dunder_init_matches_eager.

Part of pytorch#192874.
@yashb98
yashb98 force-pushed the fix/192874-orderedset-vt-split branch from 3fb212d to 4ea8bb0 Compare September 10, 2026 10:05
@yashb98

yashb98 commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Pushed the update. It is rebased onto current main, which also clears the merge conflict the PR had in torch/_dynamo/utils.py; no other changes from the rebase.

On the Python 3.10 failures: they were the test bug from my previous comment. slice is only hashable since 3.12, so the set literal raised TypeError at construction on the 3.10 jobs, before dynamo ran. The element is now a plain object instance. Full test/dynamo/test_sets.py passes on 3.10 and 3.12 (222 passed), including under the exact CI shard command on a 3.10 aarch64 setup, and your -= repro passes on both interpreters.

@guilhermeleobas PTAL when you have a moment.

@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 10, 2026
@guilhermeleobas

Copy link
Copy Markdown
Collaborator

Thanks @yashb98

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 17, 2026
@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

@yashb98

yashb98 commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

@guilhermeleobas thanks for the reviews on #193580 and #196167, and for seeing the tracker through. Is there a follow-up list of dynamo CPython-parity gaps, or an area you'd point a contributor at next? I'd like to keep working in this part of the codebase and can also review PRs there.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

Hi @yashb98, I think the dict keys(), values(), items() inherit from DictViewVariable but in CPython, they all inherit from object.

@yashb98

yashb98 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @guilhermeleobas. I checked this against current main before taking it, and I'd like to confirm the scope with you.

DictKeysVariable, DictValuesVariable and DictItemsVariable are siblings under DictViewVariable, which models no CPython type itself (its docstring says it models _PyDictViewObject). That is the same shape as SetVariable and FrozensetVariable under BaseSetVariable after #192874, so by that tracker's rule I don't think the inheritance itself is a wrong edge.

What I do see on main:

  • hasattr: call_obj_hasattr on the base only checks type(view).__dict__, so hasattr(d.keys(), "__class__") and hasattr(d.values(), "__hash__") are False under torch.compile and True in eager. Your draft Remove some call_obj_hasattr in favor of a centralized hasattr #197322 replaces call_obj_hasattr with a centralized hasattr, so I don't want to duplicate that work.
  • The set operators and unhashability sit on the base, so DictValuesVariable sets eight nb_* slots to None and overrides hash_impl to undo them. Moving them to the keys and items trackers would be a refactor; in my tests it does not change behaviour.

How would you like me to proceed? I can send a small hasattr fix with tests now, wait for #197322 and send only the refactor, or take a different approach if you have one in mind. I can have a PR up on Saturday for whichever you prefer.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

Hi, sorry for the delay.

How would you like me to proceed? I can send a small hasattr fix with tests now, wait for #197322 and send only the refactor, or take a different approach if you have one in mind. I can have a PR up on Saturday for whichever you prefer

Let me try to land this one first as it removes call_obj_hasattr.

@yashb98

yashb98 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

No worries at all, and thanks for getting back to me @guilhermeleobas!

That makes sense. I'll wait for #197322 to land first, then take another look at the dict views on top of it and check with you before opening anything.

yashb98 commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @guilhermeleobas! Now that #197322 has landed, I’ll take another look at how Dynamo handles dict.keys(), dict.values() and dict.items() compared with CPython. I’ll share what I find here and check with you before opening a PR.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@yashb98 sounds good to me! If you're interested, there's also the representation of dict .keys(), .items(), .values() that I think diverges a bit from CPython

@yashb98

yashb98 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @guilhermeleobas! I'd be happy to take this on as well. I'll investigate the representation differences
for dict.keys(), dict.items() and dict.values() as a separate follow-up to the earlier inheritance/set-hash
cleanup. I'll check for overlap with existing work and share the findings and proposed scope here before
opening a PR

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