Skip to content

[dynamo] Split OrderedSetVariable off SetVariable - #196111

Closed
Vaishnavi220506 wants to merge 3 commits into
pytorch:mainfrom
Vaishnavi220506:codex/192874-ordered-set-variable-inheritance
Closed

Vaishnavi220506 wants to merge 3 commits into
pytorch:mainfrom
Vaishnavi220506:codex/192874-ordered-set-variable-inheritance

Conversation

@Vaishnavi220506

@Vaishnavi220506 Vaishnavi220506 commented Sep 5, 2026 •

Copy link
Copy Markdown

AI-assisted contribution: Codex prepared the implementation and the following PR description. The contributor should review the patch and take responsibility for the final submission; this disclosure is included to make the assistance explicit.

Summary

OrderedSet is a pure-Python MutableSet, not a built-in set, but OrderedSetVariable inherited SetVariable. This PR makes it a BaseSetVariable sibling of SetVariable, preserves its mutable method surface, and keeps its OrderedSet-specific identity and ordering semantics.

The set-family dispatch paths are updated accordingly, and regression coverage verifies the hierarchy and in-place operator behavior.

Issue

Relates to #192874.

Test plan

  • python -m compileall -q torch/_dynamo/variables/sets.py torch/_dynamo/variables/builtin.py torch/_dynamo/variables/higher_order_ops.py torch/_dynamo/variables/lists.py torch/_dynamo/variables/object_protocol.py torch/_dynamo/side_effects.py torch/_dynamo/utils.py test/dynamo/test_sets.py
  • git diff --check
  • Verified OrderedSet in-place union, intersection, symmetric difference, and subtraction preserve object identity and insertion order.
  • Full Dynamo runtime tests were not run because the checkout is not built and the installed CPU wheel is incompatible with this source overlay.
  • lintrunner -a was unavailable on the development machine.

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 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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 5, 2026
@linux-foundation-easycla

linux-foundation-easycla Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: Vaishnavi220506 / name: Vaishnavi220506 (570e1d4)

@pytorch-bot

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

1 similar comment
@pytorch-bot

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

@Vaishnavi220506

Copy link
Copy Markdown
Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Sep 7, 2026
@Vaishnavi220506

Copy link
Copy Markdown
Author

AI-assisted request: Codex prepared this message after checking the PR status. It is relevant because the current head 9a880cb is unchanged and the pending CI workflows need maintainer approval.

@zou3519, could you please approve the pending ciflow/inductor and ciflow/torchtitan workflows for this PR when you have a chance? The known PYFMT issue is fixed in 9a880cb, and I’m waiting for the new CI results before making any further code changes. Thank you!

OrderedSet is a pure-Python MutableSet rather than a built-in set, but OrderedSetVariable inherited SetVariable. That caused it to match built-in-set checks and inherit set-specific behavior. Make it a BaseSetVariable sibling, explicitly preserve its mutable method surface, and keep OrderedSet-specific identity and ordering semantics. Update Dynamo's set-family dispatch paths accordingly.

Test Plan:

```text
python -m compileall -q torch/_dynamo/variables/sets.py torch/_dynamo/variables/builtin.py torch/_dynamo/variables/higher_order_ops.py torch/_dynamo/variables/lists.py torch/_dynamo/variables/object_protocol.py torch/_dynamo/side_effects.py torch/_dynamo/utils.py test/dynamo/test_sets.py
git diff --check
```

The repository's lintrunner and full Dynamo runtime test environment were unavailable on the development machine; the installed CPU wheel was incompatible with this checkout's source overlay.

Authored with AI assistance.
Authored with AI assistance.
OrderedSet.pop removes the most recently inserted item, but the split implementation selected the first dictionary key. Select the last key instead and cover the LIFO behavior under Dynamo.

Test Plan:

```text
git diff --check
```

Passed.

```text
.\.venv\Scripts\spin.exe lint
```

Could not initialize because the existing environment is missing the packaging module. The required lintrunner executable is also unavailable.

Authored with AI assistance.
@Vaishnavi220506
Vaishnavi220506 force-pushed the codex/192874-ordered-set-variable-inheritance branch from 9a880cb to c25ea96 Compare September 9, 2026 15:54
@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 for your contribution @Vaishnavi220506 but there's already a PR opened for this: #196167

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

Closing as this is duplicated work

pytorchmergebot pushed a commit that referenced this pull request Sep 17, 2026
…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
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 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.

4 participants