Skip to content

Commit

Permalink
[Dynamo] Support dict_keys from nested dict object (pytorch#143557)
Browse files Browse the repository at this point in the history
Pull Request resolved: pytorch#143557
Approved by: https://github.com/williamwen42
ghstack dependencies: pytorch#143374, pytorch#143547
  • Loading branch information
yanboliang authored and pytorchmergebot committed Dec 19, 2024
1 parent 5fa287a commit c46cfc2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
22 changes: 22 additions & 0 deletions test/dynamo/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2634,6 +2634,28 @@ def fn(x, keys):
opt_fn = torch.compile(fullgraph=True, backend="eager")(fn)
self.assertEqual(opt_fn(x, d.keys()), fn(x, d.keys()))

def test_dict_key_set3(self):
a = {
"domains": {
"d1": {"attr": 1},
"d2": {"attr": 2},
}
}
b = a["domains"].keys()

def fn(x, a, b):
for e in b:
x += a["domains"][e]["attr"]
return x

x = torch.ones(2, 3)
opt_fn = torch.compile(fullgraph=True, backend="eager")(fn)
self.assertEqual(opt_fn(x, a, b), fn(x, a, b))

a["domains"].update({"d3": {"attr": 3}})
opt_fn = torch.compile(fullgraph=True, backend="eager")(fn)
self.assertEqual(opt_fn(x, a, b), fn(x, a, b))

def test_pow_int(self):
def fn(a, b):
return torch.pow(a, b)
Expand Down
13 changes: 8 additions & 5 deletions torch/_dynamo/guards.py
Original file line number Diff line number Diff line change
Expand Up @@ -904,13 +904,16 @@ def requires_key_order_guarding(self, source):
def get_guard_manager_type(self, source, example_value):
guard_manager_enum = GuardManagerType.GUARD_MANAGER
if self.requires_key_order_guarding(source):
assert isinstance(example_value, dict)
# If keys method is not overriden, we can use PyDict_Next to get key
# orderings. Read more in guards.cpp
if type(example_value).keys is type({}).keys:
if isinstance(example_value, dict_keys):
guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER
else:
guard_manager_enum = GuardManagerType.DICT_SUBCLASS_GUARD_MANAGER
assert isinstance(example_value, dict)
# If keys method is not overriden, we can use PyDict_Next to get key
# orderings. Read more in guards.cpp
if type(example_value).keys is type({}).keys:
guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER
else:
guard_manager_enum = GuardManagerType.DICT_SUBCLASS_GUARD_MANAGER
return guard_manager_enum

def manager_guards_on_keys(self, mgr_enum):
Expand Down

0 comments on commit c46cfc2

Please sign in to comment.