Skip to content
Closed
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: 15 additions & 1 deletion torch/_prims/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

prim = torch.library.Library("prims", "DEF")
prim_impl = torch.library.Library("prims", "IMPL", "CompositeExplicitAutograd")
prim_backend_select_impl = torch.library.Library("prims", "IMPL", "BackendSelect")
prim_autograd_impl = torch.library.Library("prims", "IMPL", "Autograd")
prim_meta_impl = torch.library.Library("prims", "IMPL", "Meta")

Expand Down Expand Up @@ -453,14 +454,27 @@ def _autograd_impl(*args, **kwargs):
flat_args, args_spec = tree_flatten((args, kwargs))
return BackwardsNotSupported.apply(args_spec, *flat_args)

_meta_impl = _wrap_tensor_meta(meta)

def _backend_select_impl(*args, **kwargs):
if kwargs.get("device") and kwargs["device"].type == "meta":
return _meta_impl(*args, **kwargs)
else:
return _prim_impl(*args, **kwargs)

name = schema.split("(")[0]
prim_impl.impl(name, _prim_impl)
prim_autograd_impl.impl(name, _autograd_impl)
prim_meta_impl.impl(name, _wrap_tensor_meta(meta))
prim_meta_impl.impl(name, _meta_impl)

_prim_packet = getattr(torch.ops.prims, name)
_prim = _prim_packet.default

from torch._subclasses.fake_tensor import contains_tensor_types

if not any(contains_tensor_types(a.type) for a in _prim._schema.arguments):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this map 1-to-1 with the logic that codegen uses to determine when to generate backend select kernels?

def needs_backend_select(f: NativeFunction, selector: SelectiveBuilder) -> bool:

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hypothetically yes, but prims are simpler than native_functions.yaml so I guessed a simplified version would work.

prim_backend_select_impl.impl(name, _backend_select_impl)

for p in (_prim_packet, _prim):
p.__doc__ = doc
p.impl_nvfuser = impl_nvfuser # type: ignore[attr-defined]
Expand Down