Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions array_api_compat/common/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ def your_function(x, y):
is_pydata_sparse_array

"""
namespaces: set[Namespace] = set()
namespaces: list[Namespace] = []
for x in xs:
xp, info = _cls_to_namespace(cast(Hashable, type(x)), api_version, use_compat)
if info is _ClsToXPInfo.SCALAR:
Expand All @@ -663,7 +663,19 @@ def your_function(x, y):
)
xp = get_ns(api_version=api_version)

namespaces.add(xp)
namespaces.append(xp)

# Use a list of modules to avoid a graph break under torch.compile:
# torch._dynamo.exc.Unsupported: Dynamo cannot determine whether the underlying object is hashable
# Explanation: Dynamo does not know whether the underlying python object for
# PythonModuleVariable(<module 'array_api_compat.torch' from ...) is hashable
names = set(x.__name__ for x in namespaces)
unique_namespaces = []
for ns in namespaces:
if (name := ns.__name__) in names:
unique_namespaces.append(ns)
names.remove(name)
namespaces = unique_namespaces

try:
(xp,) = namespaces
Expand Down
2 changes: 1 addition & 1 deletion tests/test_no_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Array:
# Dummy array namespace that doesn't depend on any array library
def __array_namespace__(self, api_version=None):
class Namespace:
pass
__name__: str = "foobar"
return Namespace()

def _test_dependency(mod):
Expand Down
15 changes: 15 additions & 0 deletions tests/test_torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,18 @@ def test_round():
r = xp.round(x, decimals=1, out=o)
assert xp.all(r == o)
assert r is o


def test_dynamo_array_namespace():
"""Check that torch.compiling array_namespace does not incur graph breaks."""
from array_api_compat import array_namespace

def foo(x):
xp = array_namespace(x)
return xp.multiply(x, x)

bar = torch.compile(fullgraph=True)(foo)

x = torch.arange(3)
y = bar(x)
assert xp.all(y == x**2)
Loading