Datasets:
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_VF.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/__config__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/__future__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_classes.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_compile.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_custom_ops.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_environment.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_guards.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_jit_internal.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_linalg_utils.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_lobpcg.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_lowrank.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_namedtensor_internals.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_ops.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_size_docs.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_sources.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_storage_docs.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor_str.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_utils.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_utils_internal.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_vmap_internals.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/functional.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/hub.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/library.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/quasirandom.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/random.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/return_types.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/serialization.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/storage.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/torch_version.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/types.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/version.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_awaits/__init__.py +53 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_awaits/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__init__.py +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/autograd.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/impl.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/autograd.py +307 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/impl.py +715 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__init__.py +545 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-310.pyc +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions.py +0 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py +335 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py +266 -0
- Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_dispatch/__init__.py +0 -0
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_VF.cpython-310.pyc
ADDED
|
Binary file (1.25 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/__config__.cpython-310.pyc
ADDED
|
Binary file (832 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/__future__.cpython-310.pyc
ADDED
|
Binary file (3.46 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (83.6 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_classes.cpython-310.pyc
ADDED
|
Binary file (2.7 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_compile.cpython-310.pyc
ADDED
|
Binary file (1.93 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_custom_ops.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_environment.cpython-310.pyc
ADDED
|
Binary file (343 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_guards.cpython-310.pyc
ADDED
|
Binary file (35 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_jit_internal.cpython-310.pyc
ADDED
|
Binary file (36.6 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_linalg_utils.cpython-310.pyc
ADDED
|
Binary file (5.29 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_lobpcg.cpython-310.pyc
ADDED
|
Binary file (30.6 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_lowrank.cpython-310.pyc
ADDED
|
Binary file (9.82 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_namedtensor_internals.cpython-310.pyc
ADDED
|
Binary file (5.01 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_ops.cpython-310.pyc
ADDED
|
Binary file (40 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_size_docs.cpython-310.pyc
ADDED
|
Binary file (1.22 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_sources.cpython-310.pyc
ADDED
|
Binary file (4.22 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_storage_docs.cpython-310.pyc
ADDED
|
Binary file (1.56 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor.cpython-310.pyc
ADDED
|
Binary file (51.7 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor_str.cpython-310.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_utils.cpython-310.pyc
ADDED
|
Binary file (28.9 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_utils_internal.cpython-310.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_vmap_internals.cpython-310.pyc
ADDED
|
Binary file (6.94 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/functional.cpython-310.pyc
ADDED
|
Binary file (73 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/hub.cpython-310.pyc
ADDED
|
Binary file (27.7 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/library.cpython-310.pyc
ADDED
|
Binary file (56.6 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/quasirandom.cpython-310.pyc
ADDED
|
Binary file (7.03 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/random.cpython-310.pyc
ADDED
|
Binary file (6.23 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/return_types.cpython-310.pyc
ADDED
|
Binary file (1.65 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/serialization.cpython-310.pyc
ADDED
|
Binary file (60.1 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/storage.cpython-310.pyc
ADDED
|
Binary file (47.1 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/torch_version.cpython-310.pyc
ADDED
|
Binary file (2.61 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/types.cpython-310.pyc
ADDED
|
Binary file (3.5 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/__pycache__/version.cpython-310.pyc
ADDED
|
Binary file (530 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_awaits/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
__all__ = ['Await']
|
| 8 |
+
|
| 9 |
+
W = TypeVar("W")
|
| 10 |
+
|
| 11 |
+
class _PyAwaitMeta(type(torch._C._Await), type(Generic)): # type: ignore[misc, no-redef]
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
class _Await(torch._C._Await, Generic[W], metaclass=_PyAwaitMeta):
|
| 15 |
+
r"""
|
| 16 |
+
Wrapper around a ``torch._C.Await`` which encapsulates delayed execution
|
| 17 |
+
of a callable. All manipulations happen with functions ``torch.jit._awaitable``,
|
| 18 |
+
``torch.jit._awaitable_wait``, ``torch.jit._awaitable_nowait``.
|
| 19 |
+
|
| 20 |
+
Torch scriptable manipulations:
|
| 21 |
+
``torch.jit._awaitable(func, *args)``
|
| 22 |
+
Creates ``Await[W]`` object, where W is return type of func.
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
``torch.jit._awaitable_wait(Await[W])``
|
| 26 |
+
Returns the result of the function, specified at ``_awaitable``, with specified arguments.
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
The result of type ``W`` of the function call. The result is owned by ``Await[W]``
|
| 30 |
+
and returned on all following ``_awaitable_wait`` calls.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
``torch.jit._awaitable_nowait(W)``
|
| 34 |
+
Returns:
|
| 35 |
+
Trivial ``Await[W]`` with specified result.
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
Only in eager mode:
|
| 39 |
+
``fn() -> Callable[Tuple[Any], W]``
|
| 40 |
+
Returns:
|
| 41 |
+
Specified at ``_awaitable`` python function ``func``.
|
| 42 |
+
|
| 43 |
+
``args() -> Tuple[Any]``
|
| 44 |
+
Returns:
|
| 45 |
+
Specified at ``_awaitable`` python args.
|
| 46 |
+
|
| 47 |
+
``is_nowait() -> _bool``
|
| 48 |
+
Returns:
|
| 49 |
+
``True`` if this object was created via ``_awaitable_nowait`` call (trivial `Await[W]`).
|
| 50 |
+
|
| 51 |
+
In eager mode ``Await[W]`` can be used as ``W`` i.e. attributes of W can be called on ``Await[W]``,
|
| 52 |
+
``_awaitable_wait()`` call will be transparently added.
|
| 53 |
+
"""
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_awaits/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.1 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__init__.py
ADDED
|
File without changes
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (230 Bytes). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/autograd.cpython-310.pyc
ADDED
|
Binary file (9 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/__pycache__/impl.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/autograd.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
from collections import namedtuple
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# NOTE [CustomOp autograd kernel indirection]
|
| 10 |
+
# We register `inner` as the autograd kernel for this custom_op.
|
| 11 |
+
# `inner` either calls the autograd formula registered by the user,
|
| 12 |
+
# or goes into an `autograd_not_implemented` kernel.
|
| 13 |
+
#
|
| 14 |
+
# The reason why this indirection exists is
|
| 15 |
+
# so that we can swap out the autograd kernel (the PyTorch dispatcher
|
| 16 |
+
# doesn't actually allow us to do this). By default, we want
|
| 17 |
+
# the `autograd_not_implemented` behavior, but then the user may come
|
| 18 |
+
# and register something that is actually a backward formula
|
| 19 |
+
def autograd_kernel_indirection(custom_op):
|
| 20 |
+
autograd_fallback = autograd_not_implemented(custom_op)
|
| 21 |
+
|
| 22 |
+
def inner(*args, **kwargs):
|
| 23 |
+
if custom_op._has_impl("autograd"):
|
| 24 |
+
kernel = custom_op._get_impl("autograd").func
|
| 25 |
+
return kernel(*args, **kwargs)
|
| 26 |
+
# As explained in NOTE ["backward", "save_for_backward", and "autograd"],
|
| 27 |
+
# after the user gives us "backward" and "save_for_backward", we generate
|
| 28 |
+
# the "autograd" impl. If the user only provided one, then we tell
|
| 29 |
+
# the user they've done something wrong.
|
| 30 |
+
if custom_op._has_impl("save_for_backward") or custom_op._has_impl("backward"):
|
| 31 |
+
missing = (
|
| 32 |
+
"save_for_backward" if custom_op._has_impl("backward") else "backward"
|
| 33 |
+
)
|
| 34 |
+
found = "save_for_backward" if missing == "backward" else "backward"
|
| 35 |
+
loc = custom_op._get_impl(found).location
|
| 36 |
+
raise RuntimeError(
|
| 37 |
+
f"We found a '{found}' registration for {custom_op} at "
|
| 38 |
+
f"{loc} but were unable to find a '{missing}' registration. "
|
| 39 |
+
f"To use the CustomOp API to register a backward formula, "
|
| 40 |
+
f"please provide us both a backward function and a "
|
| 41 |
+
f"'save for backward' function via `impl_backward` and "
|
| 42 |
+
f"`impl_save_for_backward` respectively."
|
| 43 |
+
)
|
| 44 |
+
return autograd_fallback(*args, **kwargs)
|
| 45 |
+
|
| 46 |
+
return inner
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# TODO(#101191): Use the actual C++ autograd not implemented fallback,
|
| 50 |
+
# or change the default autograd fallback to the autograd not implemented fallback.
|
| 51 |
+
def autograd_not_implemented(custom_op):
|
| 52 |
+
def kernel(*args, **kwargs):
|
| 53 |
+
if torch.is_grad_enabled() and pytree.tree_any(
|
| 54 |
+
lambda x: isinstance(x, torch.Tensor) and x.requires_grad, (args, kwargs)
|
| 55 |
+
):
|
| 56 |
+
raise RuntimeError("Autograd has not been implemented for operator")
|
| 57 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 58 |
+
return custom_op(*args, **kwargs)
|
| 59 |
+
|
| 60 |
+
return kernel
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def mark_non_differentiable(ctx, output, output_differentiability):
|
| 64 |
+
# Output types are restricted to be:
|
| 65 |
+
# - Tensor
|
| 66 |
+
# - Tensor[]
|
| 67 |
+
# - int, bool, Scalar, float
|
| 68 |
+
# See _check_can_register_backward
|
| 69 |
+
if output_differentiability is not None:
|
| 70 |
+
if not isinstance(output, tuple):
|
| 71 |
+
tuple_output = (output,)
|
| 72 |
+
else:
|
| 73 |
+
tuple_output = output # type: ignore[assignment]
|
| 74 |
+
assert len(output_differentiability) == len(tuple_output)
|
| 75 |
+
non_differentiable_tensors = []
|
| 76 |
+
for idx, (differentiable, out) in enumerate(
|
| 77 |
+
zip(output_differentiability, tuple_output)
|
| 78 |
+
):
|
| 79 |
+
if isinstance(out, torch.Tensor):
|
| 80 |
+
if not differentiable:
|
| 81 |
+
non_differentiable_tensors.append(out)
|
| 82 |
+
continue
|
| 83 |
+
if isinstance(out, list):
|
| 84 |
+
if not differentiable:
|
| 85 |
+
non_differentiable_tensors.extend(out)
|
| 86 |
+
continue
|
| 87 |
+
if differentiable:
|
| 88 |
+
raise RuntimeError(
|
| 89 |
+
f"With output_differentiability={output_differentiability}. "
|
| 90 |
+
f"At idx {idx}, we received an object of type {type(out)} that "
|
| 91 |
+
f"is not a Tensor, so it cannot have be marked as differentiable in "
|
| 92 |
+
f"output_differentiability."
|
| 93 |
+
)
|
| 94 |
+
if non_differentiable_tensors:
|
| 95 |
+
ctx.mark_non_differentiable(*non_differentiable_tensors)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def construct_autograd_kernel(
|
| 99 |
+
schema,
|
| 100 |
+
output_differentiability,
|
| 101 |
+
custom_op,
|
| 102 |
+
op_overload,
|
| 103 |
+
save_for_backward_fn,
|
| 104 |
+
backward_fn,
|
| 105 |
+
):
|
| 106 |
+
def apply(*args):
|
| 107 |
+
flat_args, spec = pytree.tree_flatten(args)
|
| 108 |
+
out_spec = None
|
| 109 |
+
|
| 110 |
+
def forward(ctx, *flat_args):
|
| 111 |
+
ctx.set_materialize_grads(True)
|
| 112 |
+
args = pytree.tree_unflatten(list(flat_args), spec)
|
| 113 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 114 |
+
output = op_overload(*args)
|
| 115 |
+
|
| 116 |
+
# We use the info about args to give better error messages in backward
|
| 117 |
+
args_info = namedtuple_args(schema, pytree.tree_map(type, args))
|
| 118 |
+
|
| 119 |
+
save_for_backward_fn_inputs = namedtuple_args(schema, args)
|
| 120 |
+
to_save = save_for_backward_fn(save_for_backward_fn_inputs, output)
|
| 121 |
+
|
| 122 |
+
save_pytree_for_backward(ctx, (to_save, args_info))
|
| 123 |
+
mark_non_differentiable(ctx, output, output_differentiability)
|
| 124 |
+
|
| 125 |
+
nonlocal out_spec
|
| 126 |
+
flat_output, out_spec = pytree.tree_flatten(output)
|
| 127 |
+
return tuple(flat_output)
|
| 128 |
+
|
| 129 |
+
def backward(ctx, *flat_grad_output):
|
| 130 |
+
assert out_spec is not None
|
| 131 |
+
grads = pytree.tree_unflatten(list(flat_grad_output), out_spec)
|
| 132 |
+
saved, args_info = unpack_saved(ctx)
|
| 133 |
+
# There is nothing on the ctx object for now, it is just there so
|
| 134 |
+
# that we can add additional things in the future.
|
| 135 |
+
inner_ctx = object()
|
| 136 |
+
if not isinstance(grads, tuple):
|
| 137 |
+
grads = (grads,)
|
| 138 |
+
grad_inputs_dict = backward_fn(inner_ctx, saved, *grads)
|
| 139 |
+
|
| 140 |
+
# Massage the grad_inputs_dict to a form acceptable by
|
| 141 |
+
# autograd.Function.
|
| 142 |
+
validate_grad_inputs_dict(grad_inputs_dict, custom_op, args_info)
|
| 143 |
+
return grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info)
|
| 144 |
+
|
| 145 |
+
generated_cls = gen_autograd_function(
|
| 146 |
+
custom_op._opname + "_customop", forward, backward
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
flat_output = generated_cls.apply(*flat_args)
|
| 150 |
+
assert out_spec is not None
|
| 151 |
+
return pytree.tree_unflatten(list(flat_output), out_spec)
|
| 152 |
+
|
| 153 |
+
return apply
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def gen_autograd_function(name, forward, backward):
|
| 157 |
+
generated_cls = type(
|
| 158 |
+
name,
|
| 159 |
+
(torch.autograd.Function,),
|
| 160 |
+
{
|
| 161 |
+
"forward": staticmethod(forward),
|
| 162 |
+
"backward": staticmethod(backward),
|
| 163 |
+
},
|
| 164 |
+
)
|
| 165 |
+
return generated_cls
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@functools.lru_cache
|
| 169 |
+
def namedtuple_args_cls(schema):
|
| 170 |
+
attribs = [arg.name for arg in schema.arguments.flat_all]
|
| 171 |
+
name = str(schema.name) + "_args"
|
| 172 |
+
# mypy doesn't support dynamic namedtuple name
|
| 173 |
+
tuple_cls = namedtuple(name, attribs) # type: ignore[misc]
|
| 174 |
+
return tuple_cls
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def namedtuple_args(schema, args):
|
| 178 |
+
assert isinstance(args, tuple)
|
| 179 |
+
tuple_cls = namedtuple_args_cls(schema)
|
| 180 |
+
return tuple_cls(*args)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def validate_grad_inputs_dict(grad_inputs_dict, forward_op, args_info):
|
| 184 |
+
def error(what):
|
| 185 |
+
backward = forward_op._get_impl("backward")
|
| 186 |
+
raise RuntimeError(
|
| 187 |
+
f"In the backward function defined for {forward_op} at "
|
| 188 |
+
f"{backward.location} using the CustomOp API, {what}"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if not isinstance(grad_inputs_dict, dict):
|
| 192 |
+
error(
|
| 193 |
+
f"expected the output of the backward function to be a dict but "
|
| 194 |
+
f"got {type(grad_inputs_dict)}"
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
expected_keys = {
|
| 198 |
+
arg.name
|
| 199 |
+
for arg in forward_op._schema.arguments.flat_all
|
| 200 |
+
if arg.type.is_tensor_like()
|
| 201 |
+
}
|
| 202 |
+
actual_keys = grad_inputs_dict.keys()
|
| 203 |
+
if expected_keys != actual_keys:
|
| 204 |
+
error(
|
| 205 |
+
f"expected the returned grad_input dict to have keys "
|
| 206 |
+
f"{expected_keys} but got {actual_keys}. The backward "
|
| 207 |
+
f"function must return a gradient (can be None) for each arg "
|
| 208 |
+
f"to the CustomOp that may be a Tensor or Sequence[Tensor]. "
|
| 209 |
+
f"Args declared to be non-Tensor-like types should not appear "
|
| 210 |
+
f"in the grad_input dict"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
for name, grad in grad_inputs_dict.items():
|
| 214 |
+
arg_info = getattr(args_info, name)
|
| 215 |
+
|
| 216 |
+
if isinstance(arg_info, list):
|
| 217 |
+
if not isinstance(grad, (tuple, list)):
|
| 218 |
+
error(
|
| 219 |
+
f"for input '{name}' expected the grad_input dict to "
|
| 220 |
+
f"hold a list of gradients but got object of type "
|
| 221 |
+
f"{type(grad)}."
|
| 222 |
+
)
|
| 223 |
+
if not len(grad) == len(arg_info):
|
| 224 |
+
error(
|
| 225 |
+
f"for input '{name}' expected the grad_input dict to "
|
| 226 |
+
f"hold a list of {len(arg_info)} gradients but got "
|
| 227 |
+
f"{len(grad)}"
|
| 228 |
+
)
|
| 229 |
+
for idx, (g, info) in enumerate(zip(grad, arg_info)):
|
| 230 |
+
if g is None:
|
| 231 |
+
continue
|
| 232 |
+
if not isinstance(g, torch.Tensor):
|
| 233 |
+
error(
|
| 234 |
+
f"for input '{name}' expected the grad_input dict to "
|
| 235 |
+
f"hold a list of None or Tensor gradients but got "
|
| 236 |
+
f"object of {type(g)} at index {idx}"
|
| 237 |
+
)
|
| 238 |
+
if not issubclass(info, torch.Tensor):
|
| 239 |
+
error(
|
| 240 |
+
f"for input '{name}', got a Tensor as the gradient "
|
| 241 |
+
f"for the {idx}-th value but expected None because "
|
| 242 |
+
f"the {idx}-th value was not a Tensor (it was "
|
| 243 |
+
f"type {arg_info}"
|
| 244 |
+
)
|
| 245 |
+
continue
|
| 246 |
+
|
| 247 |
+
if grad is None:
|
| 248 |
+
continue
|
| 249 |
+
if not isinstance(grad, torch.Tensor):
|
| 250 |
+
error(
|
| 251 |
+
f"got object of type {type(grad)} as the gradient for input "
|
| 252 |
+
f"'{name}', "
|
| 253 |
+
f"but expected the gradient to be either None or a Tensor"
|
| 254 |
+
)
|
| 255 |
+
if not issubclass(arg_info, torch.Tensor):
|
| 256 |
+
error(
|
| 257 |
+
f"got a Tensor as the gradient for input '{name}' but "
|
| 258 |
+
f"expected None as the gradient because input '{name}' "
|
| 259 |
+
f"was not a Tensor (it was type {arg_info})."
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info):
|
| 264 |
+
result = []
|
| 265 |
+
for name, arg_info in args_info._asdict().items():
|
| 266 |
+
if name not in grad_inputs_dict:
|
| 267 |
+
result.append(pytree.tree_map(lambda x: None, arg_info))
|
| 268 |
+
continue
|
| 269 |
+
result.append(grad_inputs_dict[name])
|
| 270 |
+
return tuple(pytree.tree_leaves(result))
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# Saves "stuff" (a pytree) onto the ctx object. Use unpack_saved to unpack it.
|
| 274 |
+
# autograd.Function prefers that users use ctx.save_for_backward to
|
| 275 |
+
# save Tensors (to avoid reference cycles) and for non-Tensors to go onto the
|
| 276 |
+
# ctx object.
|
| 277 |
+
def save_pytree_for_backward(ctx, stuff):
|
| 278 |
+
flat_stuff, spec = pytree.tree_flatten(stuff)
|
| 279 |
+
num_elts = len(flat_stuff)
|
| 280 |
+
tensor_idxs = [
|
| 281 |
+
idx for idx, thing in enumerate(flat_stuff) if isinstance(thing, torch.Tensor)
|
| 282 |
+
]
|
| 283 |
+
non_tensor_idxs = [
|
| 284 |
+
idx
|
| 285 |
+
for idx, thing in enumerate(flat_stuff)
|
| 286 |
+
if not isinstance(thing, torch.Tensor)
|
| 287 |
+
]
|
| 288 |
+
tensors = [thing for thing in flat_stuff if isinstance(thing, torch.Tensor)]
|
| 289 |
+
non_tensors = [thing for thing in flat_stuff if not isinstance(thing, torch.Tensor)]
|
| 290 |
+
|
| 291 |
+
ctx.spec = spec
|
| 292 |
+
ctx.num_elts = num_elts
|
| 293 |
+
ctx.save_for_backward(*tensors)
|
| 294 |
+
ctx.tensor_idxs = tensor_idxs
|
| 295 |
+
ctx.saved_non_tensors = non_tensors
|
| 296 |
+
ctx.non_tensor_idxs = non_tensor_idxs
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# Inverse operation to save_pytree_for_backward
|
| 300 |
+
def unpack_saved(ctx):
|
| 301 |
+
flat_stuff = [None] * ctx.num_elts
|
| 302 |
+
for tensor, idx in zip(ctx.saved_tensors, ctx.tensor_idxs):
|
| 303 |
+
flat_stuff[idx] = tensor
|
| 304 |
+
for non_tensor, idx in zip(ctx.saved_non_tensors, ctx.non_tensor_idxs):
|
| 305 |
+
flat_stuff[idx] = non_tensor
|
| 306 |
+
stuff = pytree.tree_unflatten(flat_stuff, ctx.spec)
|
| 307 |
+
return stuff
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_custom_op/impl.py
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import dataclasses
|
| 3 |
+
import functools
|
| 4 |
+
import inspect
|
| 5 |
+
import sys
|
| 6 |
+
import typing
|
| 7 |
+
import warnings
|
| 8 |
+
import weakref
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch._C as _C
|
| 12 |
+
import torch._library.infer_schema
|
| 13 |
+
import torch.library as library
|
| 14 |
+
from torch._library.infer_schema import infer_schema
|
| 15 |
+
from torch.library import get_ctx
|
| 16 |
+
from torchgen.model import (
|
| 17 |
+
BaseTy,
|
| 18 |
+
BaseType,
|
| 19 |
+
FunctionSchema,
|
| 20 |
+
ListType,
|
| 21 |
+
OperatorName,
|
| 22 |
+
SchemaKind,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
from .autograd import autograd_kernel_indirection, construct_autograd_kernel
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
torch._custom_op is deprecated. We shipped a production-ready version of it into torch.library.
|
| 30 |
+
Please use those APIs instead.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
__all__ = ["custom_op", "CustomOp", "get_ctx"]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
SUPPORTED_DEVICE_TYPE_TO_KEY = {
|
| 37 |
+
"cpu": "CPU",
|
| 38 |
+
"cuda": "CUDA",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
# We will not let users register CustomOps with anything that could look like
|
| 42 |
+
# PyTorch internals to avoid confusion.
|
| 43 |
+
RESERVED_NS = {
|
| 44 |
+
"prim",
|
| 45 |
+
"prims",
|
| 46 |
+
"aten",
|
| 47 |
+
"at",
|
| 48 |
+
"torch",
|
| 49 |
+
"pytorch",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def warn_deprecated():
|
| 54 |
+
warnings.warn(
|
| 55 |
+
"torch._custom_op is deprecated and will be removed in PyTorch 2.6, please "
|
| 56 |
+
"use the equivalent torch.library API instead.",
|
| 57 |
+
DeprecationWarning,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def custom_op(
|
| 62 |
+
qualname: str, manual_schema: typing.Optional[str] = None
|
| 63 |
+
) -> typing.Callable:
|
| 64 |
+
r"""
|
| 65 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 66 |
+
"""
|
| 67 |
+
warn_deprecated()
|
| 68 |
+
|
| 69 |
+
def inner(func):
|
| 70 |
+
if not inspect.isfunction(func):
|
| 71 |
+
raise ValueError(
|
| 72 |
+
f"custom_op(...)(func): Expected `func` to be a Python "
|
| 73 |
+
f"function, got: {type(func)}"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
ns, name = parse_qualname(qualname)
|
| 77 |
+
validate_namespace(ns)
|
| 78 |
+
if func.__name__ != name:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
f"custom_op(qualname='{qualname}', ...)(func): expected `func` "
|
| 81 |
+
f"to have name '{name}' but got '{func.__name__}'. "
|
| 82 |
+
f"Please either change the name of `func` or the qualname that "
|
| 83 |
+
f"is passed to `custom_op`"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
schema = (
|
| 87 |
+
infer_schema(func, mutates_args=())
|
| 88 |
+
if manual_schema is None
|
| 89 |
+
else manual_schema
|
| 90 |
+
)
|
| 91 |
+
schema_str = f"{name}{schema}"
|
| 92 |
+
function_schema = FunctionSchema.parse(schema_str)
|
| 93 |
+
validate_schema(function_schema)
|
| 94 |
+
if manual_schema is not None:
|
| 95 |
+
validate_function_matches_schema(function_schema, func)
|
| 96 |
+
|
| 97 |
+
lib = library.Library(ns, "FRAGMENT")
|
| 98 |
+
lib.define(schema_str)
|
| 99 |
+
ophandle = find_ophandle_or_throw(ns, function_schema.name)
|
| 100 |
+
result = CustomOp(
|
| 101 |
+
lib, ns, function_schema, name, ophandle, _private_access=True
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
result.__name__ = func.__name__
|
| 105 |
+
result.__module__ = func.__module__
|
| 106 |
+
result.__doc__ = func.__doc__
|
| 107 |
+
|
| 108 |
+
library.impl(lib, result._opname, "Autograd")(
|
| 109 |
+
autograd_kernel_indirection(weakref.proxy(result))
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
torch._C._dispatch_set_report_error_callback(
|
| 113 |
+
ophandle, functools.partial(report_error_callback, weakref.proxy(result))
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
return result
|
| 117 |
+
|
| 118 |
+
return inner
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# Global dictionary holding references to all CustomOp objects
|
| 122 |
+
# Yes, it keeps all CustomOps alive (see NOTE [CustomOp lifetime])
|
| 123 |
+
# Used to query the CustomOp associated with a specific C++ dispatcher operator.
|
| 124 |
+
# An example usage is FakeTensor: FakeTensor checks if a specific operator
|
| 125 |
+
# has an implementation registered via the CustomOp API.
|
| 126 |
+
# Indexed by qualname (e.g. aten::foo)
|
| 127 |
+
global_registry: dict[str, "CustomOp"] = {}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class CustomOp:
|
| 131 |
+
r"""
|
| 132 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
def __init__(
|
| 136 |
+
self, lib, cpp_ns, schema, operator_name, ophandle, *, _private_access=False
|
| 137 |
+
):
|
| 138 |
+
super().__init__()
|
| 139 |
+
warn_deprecated()
|
| 140 |
+
if not _private_access:
|
| 141 |
+
raise RuntimeError(
|
| 142 |
+
"The CustomOp constructor is private and we do not guarantee "
|
| 143 |
+
"BC for it. Please use custom_op(...) to create a CustomOp object"
|
| 144 |
+
)
|
| 145 |
+
name = f"{cpp_ns}::{operator_name}"
|
| 146 |
+
self._schema = schema
|
| 147 |
+
self._cpp_ns = cpp_ns
|
| 148 |
+
self._lib: library.Library = lib
|
| 149 |
+
self._ophandle: _C._DispatchOperatorHandle = ophandle
|
| 150 |
+
# Has the name of the op, e.g. "foo". We cache here for convenience.
|
| 151 |
+
self._opname: str = operator_name
|
| 152 |
+
# this is _opname but with namespace. e.g. "custom::foo"
|
| 153 |
+
self._qualname: str = name
|
| 154 |
+
self.__name__ = None # mypy requires this
|
| 155 |
+
# NB: Some of these impls are registered as kernels to DispatchKeys.
|
| 156 |
+
# Modifying the _impls dict directly won't do anything in that case.
|
| 157 |
+
self._impls: dict[str, typing.Optional[FuncAndLocation]] = {}
|
| 158 |
+
# See NOTE [CustomOp autograd kernel indirection]
|
| 159 |
+
self._registered_autograd_kernel_indirection = False
|
| 160 |
+
|
| 161 |
+
global_registry[self._qualname] = self
|
| 162 |
+
|
| 163 |
+
def _register_autograd_kernel_indirection(self):
|
| 164 |
+
assert not self._registered_autograd_kernel_indirection
|
| 165 |
+
self._lib.impl(
|
| 166 |
+
self._opname, autograd_kernel_indirection(weakref.proxy(self)), "Autograd"
|
| 167 |
+
)
|
| 168 |
+
self._registered_autograd_kernel_indirection = True
|
| 169 |
+
|
| 170 |
+
# Records the impl and the source location in self._impls
|
| 171 |
+
# Note that this doesn't cause torch.library to use the impl, that
|
| 172 |
+
# needs to be done in a separate self._lib.impl call.
|
| 173 |
+
def _register_impl(self, kind, func, stacklevel=2):
|
| 174 |
+
if self._has_impl(kind):
|
| 175 |
+
func_and_location = self._impls[kind]
|
| 176 |
+
assert func_and_location is not None # Pacify mypy
|
| 177 |
+
location = func_and_location.location
|
| 178 |
+
raise RuntimeError(
|
| 179 |
+
f"Attempting to register a {kind} impl for operator {self._qualname} "
|
| 180 |
+
f"that already has a {kind} impl registered from Python at "
|
| 181 |
+
f"{location}. This is not supported."
|
| 182 |
+
)
|
| 183 |
+
frame = inspect.getframeinfo(sys._getframe(stacklevel))
|
| 184 |
+
location = f"{frame.filename}:{frame.lineno}"
|
| 185 |
+
self._impls[kind] = FuncAndLocation(func, location)
|
| 186 |
+
|
| 187 |
+
def _get_impl(self, kind):
|
| 188 |
+
return self._impls[kind]
|
| 189 |
+
|
| 190 |
+
def _has_impl(self, kind):
|
| 191 |
+
return kind in self._impls
|
| 192 |
+
|
| 193 |
+
def _destroy(self):
|
| 194 |
+
# NOTE: [CustomOp lifetime]
|
| 195 |
+
# A CustomOp, once created, lives forever. The mechanism is that the
|
| 196 |
+
# global registry holds a reference to it. However, to make testing
|
| 197 |
+
# easier, we want to be able to destroy CustomOp objects.
|
| 198 |
+
# CustomOp._destroy does the job, though it leaves the CustomOp
|
| 199 |
+
# in a garbage state.
|
| 200 |
+
del self._lib
|
| 201 |
+
|
| 202 |
+
opnamespace = getattr(torch.ops, self._cpp_ns)
|
| 203 |
+
if hasattr(opnamespace, self._opname):
|
| 204 |
+
delattr(opnamespace, self._opname)
|
| 205 |
+
|
| 206 |
+
del global_registry[self._qualname]
|
| 207 |
+
|
| 208 |
+
def __repr__(self):
|
| 209 |
+
return f'<CustomOp(op="{self._qualname}")>'
|
| 210 |
+
|
| 211 |
+
def __call__(self, *args, **kwargs):
|
| 212 |
+
# Bypass torch.ops.* and directly do OperatorHandle::callBoxed.
|
| 213 |
+
# Using torch.ops.* is a bit of a pain (it can be slow and it has lifetime
|
| 214 |
+
# issues from caching operators that make testing CustomOp difficult).
|
| 215 |
+
result = _C._dispatch_call_boxed(self._ophandle, *args, **kwargs)
|
| 216 |
+
return result
|
| 217 |
+
|
| 218 |
+
def impl(
|
| 219 |
+
self,
|
| 220 |
+
device_types: typing.Union[str, typing.Iterable[str]],
|
| 221 |
+
_stacklevel=2,
|
| 222 |
+
) -> typing.Callable:
|
| 223 |
+
r"""
|
| 224 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 225 |
+
"""
|
| 226 |
+
if isinstance(device_types, str):
|
| 227 |
+
device_types = [device_types]
|
| 228 |
+
for device_type in device_types:
|
| 229 |
+
validate_device_type(device_type)
|
| 230 |
+
|
| 231 |
+
def inner(f):
|
| 232 |
+
for device_type in set(device_types):
|
| 233 |
+
self._check_doesnt_have_library_impl(device_type)
|
| 234 |
+
self._register_impl(device_type, f, stacklevel=_stacklevel)
|
| 235 |
+
dispatch_key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type]
|
| 236 |
+
library.impl(self._lib, self._opname, dispatch_key)(f)
|
| 237 |
+
return f
|
| 238 |
+
|
| 239 |
+
return inner
|
| 240 |
+
|
| 241 |
+
def _check_doesnt_have_library_impl(self, device_type):
|
| 242 |
+
if self._has_impl(device_type):
|
| 243 |
+
return
|
| 244 |
+
key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type]
|
| 245 |
+
if _C._dispatch_has_computed_kernel_for_dispatch_key(self._qualname, key):
|
| 246 |
+
raise RuntimeError(
|
| 247 |
+
f"impl(..., device_types={device_type}): the operator {self._qualname} "
|
| 248 |
+
f"already has an implementation for this device type via a "
|
| 249 |
+
f"pre-existing torch.library or TORCH_LIBRARY registration."
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
def impl_factory(self) -> typing.Callable:
|
| 253 |
+
r"""Register an implementation for a factory function."""
|
| 254 |
+
|
| 255 |
+
def inner(f):
|
| 256 |
+
self._register_impl("factory", f)
|
| 257 |
+
library.impl(self._lib, self._opname, "BackendSelect")(f)
|
| 258 |
+
return f
|
| 259 |
+
|
| 260 |
+
return inner
|
| 261 |
+
|
| 262 |
+
def impl_abstract(self, _stacklevel=2) -> typing.Callable:
|
| 263 |
+
r"""
|
| 264 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
def inner(f):
|
| 268 |
+
self._check_doesnt_have_library_meta_impl()
|
| 269 |
+
self._register_impl("abstract", f, stacklevel=_stacklevel)
|
| 270 |
+
location = self._get_impl("abstract").location
|
| 271 |
+
|
| 272 |
+
qualname = self._qualname
|
| 273 |
+
|
| 274 |
+
# Handle DispatchKey.Meta registration
|
| 275 |
+
@functools.wraps(f)
|
| 276 |
+
def f_with_ctx(*args, **kwargs):
|
| 277 |
+
def error_on_ctx():
|
| 278 |
+
raise RuntimeError(
|
| 279 |
+
f"Attempted to call get_ctx() for the meta implementation "
|
| 280 |
+
f"for {qualname}."
|
| 281 |
+
f"You have presumably called get_ctx() because the operator "
|
| 282 |
+
f"has a data-dependent output shape; if so, there is no "
|
| 283 |
+
f"such meta implementation and this error is the correct "
|
| 284 |
+
f"behavior. Otherwise, please remove the call to get_ctx() "
|
| 285 |
+
f"in the implementation registered with impl_abstract "
|
| 286 |
+
f"at {location}"
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
with torch._library.fake_impl.set_ctx_getter(error_on_ctx):
|
| 290 |
+
return f(*args, **kwargs)
|
| 291 |
+
|
| 292 |
+
self._lib.impl(self._opname, f_with_ctx, "Meta")
|
| 293 |
+
return f
|
| 294 |
+
|
| 295 |
+
return inner
|
| 296 |
+
|
| 297 |
+
def _check_can_register_backward(self):
|
| 298 |
+
def error(detail):
|
| 299 |
+
raise RuntimeError(
|
| 300 |
+
f"Cannot use torch._custom_ops APIs to register backward "
|
| 301 |
+
f"formula for {detail}. Got operator "
|
| 302 |
+
f"{self._qualname} with schema: {schema}"
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
schema = self._schema
|
| 306 |
+
if schema.kind() != SchemaKind.functional:
|
| 307 |
+
error("non-functional operator")
|
| 308 |
+
|
| 309 |
+
rets = schema.returns
|
| 310 |
+
if not schema.returns:
|
| 311 |
+
error("operator with no returns")
|
| 312 |
+
|
| 313 |
+
assert len(rets) > 0
|
| 314 |
+
is_non_mutating_view = any(
|
| 315 |
+
r.annotation is not None and not r.annotation.is_write for r in rets
|
| 316 |
+
)
|
| 317 |
+
if is_non_mutating_view:
|
| 318 |
+
error("operator that returns views")
|
| 319 |
+
|
| 320 |
+
# We make assumptions about the schema's return types.
|
| 321 |
+
allowed_return_types = {
|
| 322 |
+
BaseType(BaseTy.int): "int",
|
| 323 |
+
BaseType(BaseTy.SymInt): "SymInt",
|
| 324 |
+
BaseType(BaseTy.bool): "bool",
|
| 325 |
+
BaseType(BaseTy.float): "float",
|
| 326 |
+
BaseType(BaseTy.Tensor): "Tensor",
|
| 327 |
+
ListType(BaseType(BaseTy.Tensor), None): "List[Tensor]",
|
| 328 |
+
}
|
| 329 |
+
for ret in schema.returns:
|
| 330 |
+
if ret.type in allowed_return_types:
|
| 331 |
+
continue
|
| 332 |
+
error(
|
| 333 |
+
f"operator with return not in {list(allowed_return_types.values())} (got {ret.type})"
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def _check_doesnt_have_library_autograd_impl(self):
|
| 337 |
+
if self._registered_autograd_kernel_indirection:
|
| 338 |
+
return
|
| 339 |
+
|
| 340 |
+
if _C._dispatch_has_kernel_for_dispatch_key(
|
| 341 |
+
self._qualname, "CompositeImplicitAutograd"
|
| 342 |
+
):
|
| 343 |
+
raise RuntimeError(
|
| 344 |
+
f"impl_backward/impl_save_for_backward: the operator {self._qualname} "
|
| 345 |
+
f"already has an implementation for this device type via a "
|
| 346 |
+
f"pre-existing registration to DispatchKey::CompositeImplicitAutograd."
|
| 347 |
+
f"CompositeImplicitAutograd operators do not need an autograd formula; "
|
| 348 |
+
f"instead, the operator will decompose into its constituents and those "
|
| 349 |
+
f"can have autograd formulas defined on them."
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
# We can improve this by adding "all Autograd<BACKEND> keys", but
|
| 353 |
+
# realistically people will just be using this API for CPU/CUDA for now.
|
| 354 |
+
for key in ["Autograd", "AutogradCPU", "AutogradCUDA"]:
|
| 355 |
+
if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, key):
|
| 356 |
+
raise RuntimeError(
|
| 357 |
+
f"impl_backward/impl_save_for_backward: "
|
| 358 |
+
f"the operator {self._qualname} already has an Autograd kernel "
|
| 359 |
+
f"registered to DispatchKey::{key} vi a pre-existing "
|
| 360 |
+
f"torch.library or TORCH_LIBRARY registration. Please either "
|
| 361 |
+
f"remove those registrations or don't use the torch._custom_ops APIs"
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
def _check_doesnt_have_library_meta_impl(self):
|
| 365 |
+
if self._has_impl("abstract"):
|
| 366 |
+
return
|
| 367 |
+
|
| 368 |
+
# If the user's operator is CompositeExplicitAutograd,
|
| 369 |
+
# allow them to impl_abstract. This is being pragmatic
|
| 370 |
+
# (existing custom ops may have CompositeExplicitAutograd
|
| 371 |
+
# registration that don't work with Meta kernels, so this
|
| 372 |
+
# gives them an escape hatch).
|
| 373 |
+
if _C._dispatch_has_kernel_for_dispatch_key(
|
| 374 |
+
self._qualname, "CompositeExplicitAutograd"
|
| 375 |
+
) and not _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"):
|
| 376 |
+
return
|
| 377 |
+
|
| 378 |
+
# Otherwise, if the user's already has a Meta kernel or their
|
| 379 |
+
# op is CompositeImplicitAutograd or some other alias dispatch key,
|
| 380 |
+
# raise.
|
| 381 |
+
|
| 382 |
+
# Special case for CompositeImplicitAutograd
|
| 383 |
+
if _C._dispatch_has_kernel_for_dispatch_key(
|
| 384 |
+
self._qualname, "CompositeImplicitAutograd"
|
| 385 |
+
):
|
| 386 |
+
raise RuntimeError(
|
| 387 |
+
f"impl_abstract(...): the operator {self._qualname} "
|
| 388 |
+
f"already has an implementation for this device type via a "
|
| 389 |
+
f"pre-existing registration to DispatchKey::CompositeImplicitAutograd."
|
| 390 |
+
f"CompositeImplicitAutograd operators do not need an abstract impl; "
|
| 391 |
+
f"instead, the operator will decompose into its constituents and those "
|
| 392 |
+
f"can have abstract impls defined on them."
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"):
|
| 396 |
+
raise RuntimeError(
|
| 397 |
+
f"impl_abstract(...): the operator {self._qualname} "
|
| 398 |
+
f"already has an DispatchKey::Meta implementation via a "
|
| 399 |
+
f"pre-existing torch.library or TORCH_LIBRARY registration. "
|
| 400 |
+
f"Please either remove that registration or don't call impl_abstract."
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# NOTE ["backward", "save_for_backward", and "autograd"]
|
| 404 |
+
# As a part of the explicit autograd API, a user must provide us
|
| 405 |
+
# a "save_for_backward" function and a "backward" function.
|
| 406 |
+
# When both of these have been provided, then we automatically
|
| 407 |
+
# construct the "autograd" kernel.
|
| 408 |
+
def _register_autograd_kernel(self):
|
| 409 |
+
assert self._has_impl("backward")
|
| 410 |
+
assert self._has_impl("save_for_backward")
|
| 411 |
+
kernel = construct_autograd_kernel(
|
| 412 |
+
self._schema,
|
| 413 |
+
self._output_differentiability,
|
| 414 |
+
self,
|
| 415 |
+
get_op(self._qualname),
|
| 416 |
+
self._get_impl("save_for_backward").func,
|
| 417 |
+
self._get_impl("backward").func,
|
| 418 |
+
)
|
| 419 |
+
self._register_impl("autograd", kernel)
|
| 420 |
+
|
| 421 |
+
def impl_save_for_backward(self, _stacklevel=2):
|
| 422 |
+
r"""Register a function that tells us what to save for backward.
|
| 423 |
+
|
| 424 |
+
Please see impl_backward for more details.
|
| 425 |
+
"""
|
| 426 |
+
|
| 427 |
+
def inner(f):
|
| 428 |
+
self._check_can_register_backward()
|
| 429 |
+
self._check_doesnt_have_library_autograd_impl()
|
| 430 |
+
if not self._registered_autograd_kernel_indirection:
|
| 431 |
+
self._register_autograd_kernel_indirection()
|
| 432 |
+
self._register_impl("save_for_backward", f, stacklevel=_stacklevel)
|
| 433 |
+
if self._has_impl("backward"):
|
| 434 |
+
self._register_autograd_kernel()
|
| 435 |
+
|
| 436 |
+
return inner
|
| 437 |
+
|
| 438 |
+
def impl_backward(self, output_differentiability=None, _stacklevel=2):
|
| 439 |
+
r"""
|
| 440 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 441 |
+
"""
|
| 442 |
+
if output_differentiability is not None:
|
| 443 |
+
|
| 444 |
+
def yell():
|
| 445 |
+
raise RuntimeError(
|
| 446 |
+
f"impl_backward(output_differentiability): expected "
|
| 447 |
+
f"output_differentiability to be a list of bools with "
|
| 448 |
+
f"length equal to the number of outputs of this CustomOp "
|
| 449 |
+
f"got: {output_differentiability}"
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
if not isinstance(output_differentiability, list):
|
| 453 |
+
yell()
|
| 454 |
+
for diff in output_differentiability:
|
| 455 |
+
if not isinstance(diff, bool):
|
| 456 |
+
yell()
|
| 457 |
+
if len(self._schema.returns) != len(output_differentiability):
|
| 458 |
+
yell()
|
| 459 |
+
|
| 460 |
+
def inner(f):
|
| 461 |
+
self._check_can_register_backward()
|
| 462 |
+
self._check_doesnt_have_library_autograd_impl()
|
| 463 |
+
if not self._registered_autograd_kernel_indirection:
|
| 464 |
+
self._register_autograd_kernel_indirection()
|
| 465 |
+
self._register_impl("backward", f, stacklevel=_stacklevel)
|
| 466 |
+
self._output_differentiability = output_differentiability
|
| 467 |
+
if self._has_impl("save_for_backward"):
|
| 468 |
+
self._register_autograd_kernel()
|
| 469 |
+
|
| 470 |
+
return inner
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@dataclasses.dataclass
|
| 474 |
+
class FuncAndLocation:
|
| 475 |
+
func: typing.Callable
|
| 476 |
+
location: str
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def find_ophandle_or_throw(cpp_ns: str, operator_name: OperatorName):
|
| 480 |
+
overload_name = (
|
| 481 |
+
"" if operator_name.overload_name is None else operator_name.overload_name
|
| 482 |
+
)
|
| 483 |
+
return _C._dispatch_find_schema_or_throw(
|
| 484 |
+
f"{cpp_ns}::{str(operator_name.name)}", overload_name
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def validate_namespace(ns: str) -> None:
|
| 489 |
+
if "." in ns:
|
| 490 |
+
raise ValueError(
|
| 491 |
+
f'custom_op(..., ns="{ns}"): expected ns to not contain any . (and be a '
|
| 492 |
+
f"valid variable name)"
|
| 493 |
+
)
|
| 494 |
+
if ns in RESERVED_NS:
|
| 495 |
+
raise ValueError(
|
| 496 |
+
f"custom_op(..., ns='{ns}'): '{ns}' is a reserved namespace, "
|
| 497 |
+
f"please choose something else. "
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def validate_schema(schema: FunctionSchema) -> None:
|
| 502 |
+
if not torch._library.utils.is_functional_schema(schema):
|
| 503 |
+
raise ValueError(
|
| 504 |
+
f"custom_op only supports functional operators "
|
| 505 |
+
f"(ops that do not mutate any inputs, do not return "
|
| 506 |
+
f"views of the inputs, and has at least one return). "
|
| 507 |
+
f"Got the following non-functional schema: {schema}"
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
# For simplicity: don't allow self arguments
|
| 511 |
+
if schema.arguments.self_arg is not None:
|
| 512 |
+
raise ValueError(
|
| 513 |
+
f"custom_op does not support arguments named 'self'. Please "
|
| 514 |
+
f"rename your argument. Got: {schema}"
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def parse_qualname(qualname: str) -> tuple[str, str]:
|
| 519 |
+
names = qualname.split("::", 1)
|
| 520 |
+
if len(names) != 2:
|
| 521 |
+
raise ValueError(
|
| 522 |
+
f"Expected there to be a namespace in {qualname}, i.e. The "
|
| 523 |
+
f"operator name should look something like ns::foo"
|
| 524 |
+
)
|
| 525 |
+
if "." in names[1]:
|
| 526 |
+
raise ValueError(
|
| 527 |
+
f"The torch.custom_ops APIs do not handle overloads, "
|
| 528 |
+
f"i.e. operator names with '.' in them. "
|
| 529 |
+
f"Please name your operator something like ns::foo. "
|
| 530 |
+
f"Got: {qualname}"
|
| 531 |
+
)
|
| 532 |
+
return names[0], names[1]
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def validate_device_type(device_type: str) -> None:
|
| 536 |
+
if device_type not in SUPPORTED_DEVICE_TYPE_TO_KEY:
|
| 537 |
+
raise ValueError(
|
| 538 |
+
f"CustomOp.impl(device_types=[{device_type}, ...]): we only support device_type "
|
| 539 |
+
f"in {SUPPORTED_DEVICE_TYPE_TO_KEY.keys()}."
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def supported_param(param: inspect.Parameter) -> bool:
|
| 544 |
+
return param.kind in (
|
| 545 |
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 546 |
+
inspect.Parameter.KEYWORD_ONLY,
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def validate_function_matches_schema(
|
| 551 |
+
schema: FunctionSchema, func: typing.Callable
|
| 552 |
+
) -> None:
|
| 553 |
+
sig = inspect.signature(func)
|
| 554 |
+
|
| 555 |
+
if not all(supported_param(p) for _, p in sig.parameters.items()):
|
| 556 |
+
raise ValueError(
|
| 557 |
+
f"custom_op(..., manual_schema)(func): positional-only args, "
|
| 558 |
+
f"varargs, and kwargs are not supported. Please rewrite `func` "
|
| 559 |
+
f"to not have them. Got `func` with signature: {sig}"
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if (
|
| 563 |
+
any(
|
| 564 |
+
p.annotation is not inspect.Parameter.empty
|
| 565 |
+
for _, p in sig.parameters.items()
|
| 566 |
+
)
|
| 567 |
+
or sig.return_annotation is not inspect.Signature.empty
|
| 568 |
+
):
|
| 569 |
+
raise ValueError(
|
| 570 |
+
f"custom_op(..., manual_schema)(func): When passing in a manual "
|
| 571 |
+
f"schema, we expect `func` to have no type annotations to avoid "
|
| 572 |
+
f"ambiguity. Got `func` with signature: {sig}"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
positional = [
|
| 576 |
+
(name, param)
|
| 577 |
+
for name, param in sig.parameters.items()
|
| 578 |
+
if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
|
| 579 |
+
]
|
| 580 |
+
kwargonly = [
|
| 581 |
+
(name, param)
|
| 582 |
+
for name, param in sig.parameters.items()
|
| 583 |
+
if param.kind == inspect.Parameter.KEYWORD_ONLY
|
| 584 |
+
]
|
| 585 |
+
|
| 586 |
+
def error():
|
| 587 |
+
raise ValueError(
|
| 588 |
+
f"custom_op(..., manual_schema)(func): When passing in a manual "
|
| 589 |
+
f"schema, we expect `func`'s signature to match `manual_schema` "
|
| 590 |
+
f"(aside from type annotations). "
|
| 591 |
+
f"func's signature: {sig}, manual_schema: {schema}"
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
def error_default_args():
|
| 595 |
+
raise ValueError(
|
| 596 |
+
f"custom_op(..., manual_schema)(func): "
|
| 597 |
+
f"neither func nor manual_schema should have default "
|
| 598 |
+
f"arguments. Got "
|
| 599 |
+
f"func's signature: {sig}, manual_schema: {schema}"
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
def compare(sig_args, schema_args):
|
| 603 |
+
if len(sig_args) != len(schema_args):
|
| 604 |
+
error()
|
| 605 |
+
for (name, param), arg in zip(sig_args, schema_args):
|
| 606 |
+
if name != arg.name:
|
| 607 |
+
error()
|
| 608 |
+
if param.default is not inspect.Parameter.empty or arg.default is not None:
|
| 609 |
+
error_default_args()
|
| 610 |
+
|
| 611 |
+
compare(positional, schema.arguments.flat_positional)
|
| 612 |
+
compare(kwargonly, schema.arguments.flat_kwarg_only)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def report_error_callback(custom_op: typing.Any, key: str) -> None:
|
| 616 |
+
if key == "Undefined":
|
| 617 |
+
raise NotImplementedError(
|
| 618 |
+
f"{custom_op}: There were no Tensor inputs to this operator "
|
| 619 |
+
f"(e.g. you passed an empty list of Tensors). If your operator is a "
|
| 620 |
+
f"factory function (that is, it takes no Tensors and constructs "
|
| 621 |
+
f"a new one), then please use CustomOp.impl_factory to register "
|
| 622 |
+
f"an implementation for it"
|
| 623 |
+
)
|
| 624 |
+
if key == "Meta":
|
| 625 |
+
raise NotImplementedError(
|
| 626 |
+
f"{custom_op}: when running with device='Meta' tensors: there is no "
|
| 627 |
+
f"abstract impl registered for this CustomOp. Please register one via "
|
| 628 |
+
f"CustomOp.impl_abstract to get this CustomOp to work with Meta tensors"
|
| 629 |
+
)
|
| 630 |
+
if key in ("CPU", "CUDA"):
|
| 631 |
+
device = key.lower()
|
| 632 |
+
raise NotImplementedError(
|
| 633 |
+
f"{custom_op}: when running with device='{device}' tensors: there is no "
|
| 634 |
+
f"{device} impl registered for this CustomOp. Please register one via "
|
| 635 |
+
f"CustomOp.impl(device_type='{device}')"
|
| 636 |
+
)
|
| 637 |
+
raise NotImplementedError(
|
| 638 |
+
f"{custom_op}: No implementation for dispatch key {key}. It is likely "
|
| 639 |
+
f"that we have not added this functionality yet, please either open an "
|
| 640 |
+
f"issue or if you're feeling adventurous, use the low-level "
|
| 641 |
+
f"torch.library API"
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def custom_op_from_existing(op):
|
| 646 |
+
ns = op.namespace
|
| 647 |
+
lib = torch.library.Library(ns, "FRAGMENT")
|
| 648 |
+
name = op.name().split("::")[-1]
|
| 649 |
+
schema_str = str(op._schema)
|
| 650 |
+
# CustomOp expects the schema string without the namespace
|
| 651 |
+
schema_str = schema_str.rsplit("::", maxsplit=1)[-1]
|
| 652 |
+
schema = FunctionSchema.parse(schema_str)
|
| 653 |
+
return CustomOp(lib, ns, schema, name, op, _private_access=True)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def get_op(qualname):
|
| 657 |
+
def error_not_found():
|
| 658 |
+
raise ValueError(
|
| 659 |
+
f"Could not find the operator {qualname}. Please make sure you have "
|
| 660 |
+
f"already registered the operator and (if registered from C++) "
|
| 661 |
+
f"loaded it via torch.ops.load_library."
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
ns, name = parse_qualname(qualname)
|
| 665 |
+
if not hasattr(torch.ops, ns):
|
| 666 |
+
error_not_found()
|
| 667 |
+
opnamespace = getattr(torch.ops, ns)
|
| 668 |
+
if not hasattr(opnamespace, name):
|
| 669 |
+
error_not_found()
|
| 670 |
+
packet = getattr(opnamespace, name)
|
| 671 |
+
if not hasattr(packet, "default"):
|
| 672 |
+
error_not_found()
|
| 673 |
+
return packet.default
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def _find_custom_op(qualname, also_check_torch_library=False):
|
| 677 |
+
if qualname in global_registry:
|
| 678 |
+
return global_registry[qualname]
|
| 679 |
+
if not also_check_torch_library:
|
| 680 |
+
raise RuntimeError(
|
| 681 |
+
f'Could not find custom op "{qualname}". Did you register it via '
|
| 682 |
+
f"the torch._custom_ops API?"
|
| 683 |
+
)
|
| 684 |
+
overload = get_op(qualname)
|
| 685 |
+
result = custom_op_from_existing(overload)
|
| 686 |
+
return result
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def get_abstract_impl(qualname):
|
| 690 |
+
if qualname not in torch._custom_op.impl.global_registry:
|
| 691 |
+
return None
|
| 692 |
+
custom_op = torch._custom_op.impl.global_registry[qualname]
|
| 693 |
+
if custom_op is None:
|
| 694 |
+
return None
|
| 695 |
+
if not custom_op._has_impl("abstract"):
|
| 696 |
+
return None
|
| 697 |
+
return custom_op._get_impl("abstract").func
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def _custom_op_with_schema(qualname, schema, needs_fixed_stride_order=True):
|
| 701 |
+
ns, name = qualname.split("::")
|
| 702 |
+
schema_str = f"{name}{schema}"
|
| 703 |
+
function_schema = FunctionSchema.parse(schema_str)
|
| 704 |
+
validate_schema(function_schema)
|
| 705 |
+
tags = [torch._C.Tag.needs_fixed_stride_order] if needs_fixed_stride_order else []
|
| 706 |
+
lib = library.Library(ns, "FRAGMENT")
|
| 707 |
+
lib.define(schema_str, tags=tags)
|
| 708 |
+
ophandle = find_ophandle_or_throw(ns, function_schema.name)
|
| 709 |
+
result = CustomOp(lib, ns, function_schema, name, ophandle, _private_access=True)
|
| 710 |
+
result._register_autograd_kernel_indirection()
|
| 711 |
+
|
| 712 |
+
torch._C._dispatch_set_report_error_callback(
|
| 713 |
+
ophandle, functools.partial(report_error_callback, weakref.proxy(result))
|
| 714 |
+
)
|
| 715 |
+
return get_op(qualname)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__init__.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import inspect
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from functools import lru_cache, partial, wraps
|
| 6 |
+
from itertools import chain
|
| 7 |
+
from typing import Callable, Optional, TYPE_CHECKING, TypeVar, Union
|
| 8 |
+
from typing_extensions import ParamSpec
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from torch.export.decomp_utils import CustomDecompTable
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.library
|
| 16 |
+
from torch._ops import HigherOrderOperator, OperatorBase, OpOverload, OpOverloadPacket
|
| 17 |
+
from torch._prims_common import CustomOutParamAnnotation
|
| 18 |
+
from torch._subclasses.functional_tensor import FunctionalTensor
|
| 19 |
+
from torch.utils import _pytree as pytree
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
"decomposition_table",
|
| 24 |
+
"pre_autograd_decomposition_table",
|
| 25 |
+
"meta_table",
|
| 26 |
+
"register_decomposition",
|
| 27 |
+
"get_decompositions",
|
| 28 |
+
"core_aten_decompositions",
|
| 29 |
+
"_should_decompose_because_unsafe_op",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
_T = TypeVar("_T")
|
| 33 |
+
_P = ParamSpec("_P")
|
| 34 |
+
|
| 35 |
+
# TODO: relax key type here; torch registrations should be possible to; but
|
| 36 |
+
# right now this type is accurate
|
| 37 |
+
global_decomposition_table: dict[str, dict[torch._ops.OperatorBase, Callable]] = (
|
| 38 |
+
defaultdict(dict)
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
decomposition_table = global_decomposition_table["post_autograd"]
|
| 42 |
+
pre_autograd_decomposition_table = global_decomposition_table["pre_autograd"]
|
| 43 |
+
meta_table = global_decomposition_table["meta"]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _should_decompose_because_unsafe_op(op: torch._ops.OperatorBase) -> bool:
|
| 47 |
+
"""
|
| 48 |
+
Returns True if the op must always decompose in export/compile tracing system
|
| 49 |
+
|
| 50 |
+
In export, we always decompose certain CIA ops that are tagged with
|
| 51 |
+
maybe_aliasing_or_mutating because we statically need to know if the op is
|
| 52 |
+
mutating or not. But these CIA ops could have different behaviour in runtime.
|
| 53 |
+
|
| 54 |
+
native_batch_norm is a prim op which has a wrong schema and it needs to be replaced
|
| 55 |
+
with correct schema. But until then, we will force decompose it via this tag.
|
| 56 |
+
"""
|
| 57 |
+
if not isinstance(op, torch._ops.OpOverload):
|
| 58 |
+
return False
|
| 59 |
+
if torch.Tag.maybe_aliasing_or_mutating in op.tags:
|
| 60 |
+
return True
|
| 61 |
+
return op == torch.ops.aten.native_batch_norm.default
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _add_op_to_registry(registry, op, fn):
|
| 65 |
+
"""
|
| 66 |
+
This is an internal API for adding an op to the decomposition table.
|
| 67 |
+
|
| 68 |
+
If op is OpOverload, it will be added to the registry directly.
|
| 69 |
+
If op is OpOverloadPacket, all the valid op_overloads in the packet will be added to the registry.
|
| 70 |
+
"""
|
| 71 |
+
overloads: list[Union[torch._ops.OperatorBase]] = []
|
| 72 |
+
if isinstance(op, HigherOrderOperator):
|
| 73 |
+
# There's no concept of overloads for HigherOrderOperator
|
| 74 |
+
registry[op] = fn
|
| 75 |
+
return
|
| 76 |
+
elif isinstance(op, OpOverload):
|
| 77 |
+
overloads.append(op)
|
| 78 |
+
else:
|
| 79 |
+
assert isinstance(op, OpOverloadPacket)
|
| 80 |
+
for ol in op.overloads():
|
| 81 |
+
overloads.append(getattr(op, ol))
|
| 82 |
+
|
| 83 |
+
for op_overload in overloads:
|
| 84 |
+
if op_overload in registry:
|
| 85 |
+
raise RuntimeError(f"duplicate registrations for {op_overload}")
|
| 86 |
+
# TorchScript dumps a bunch of extra nonsense overloads
|
| 87 |
+
# which don't have corresponding dispatcher entries, we need
|
| 88 |
+
# to filter those out, e.g aten.add.float_int
|
| 89 |
+
if torch._C._dispatch_has_kernel(op_overload.name()):
|
| 90 |
+
registry[op_overload] = fn
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _convert_out_params(f):
|
| 94 |
+
out_annotation = f.__annotations__.get("out")
|
| 95 |
+
|
| 96 |
+
# If there are no out params, do not wrap the function.
|
| 97 |
+
if not out_annotation:
|
| 98 |
+
return f
|
| 99 |
+
|
| 100 |
+
# Hack to detect when out is a Tuple. There seems to be no pretty way of doing this
|
| 101 |
+
if getattr(out_annotation, "__origin__", None) is tuple:
|
| 102 |
+
sig = inspect.signature(f)
|
| 103 |
+
out_names = sig.return_annotation._fields
|
| 104 |
+
# If out is a tuple, we need to register a function that unpacks all the out
|
| 105 |
+
# elements as this is what native_functions.yaml expects
|
| 106 |
+
|
| 107 |
+
@wraps(f)
|
| 108 |
+
def _fn(*args, **kwargs):
|
| 109 |
+
out_kwargs = tuple(kwargs.pop(o, None) for o in out_names)
|
| 110 |
+
# Either all of the out kwargs are set or none of them
|
| 111 |
+
is_none = out_kwargs[0] is None
|
| 112 |
+
assert all((o is None) == is_none for o in out_kwargs)
|
| 113 |
+
return f(*args, **kwargs, out=None if is_none else out_kwargs)
|
| 114 |
+
|
| 115 |
+
out_params = [
|
| 116 |
+
inspect.Parameter(
|
| 117 |
+
o,
|
| 118 |
+
kind=inspect.Parameter.KEYWORD_ONLY,
|
| 119 |
+
default=None,
|
| 120 |
+
annotation=t,
|
| 121 |
+
)
|
| 122 |
+
for o, t in zip(out_names, out_annotation.__args__)
|
| 123 |
+
]
|
| 124 |
+
# Drop the out parameter and concatenate the new kwargs in the signature
|
| 125 |
+
params = chain((v for k, v in sig.parameters.items() if k != "out"), out_params)
|
| 126 |
+
_fn.__signature__ = inspect.Signature( # type: ignore[attr-defined]
|
| 127 |
+
parameters=params, # type: ignore[arg-type]
|
| 128 |
+
return_annotation=sig.return_annotation,
|
| 129 |
+
)
|
| 130 |
+
# Drop the out parameter and concatenate the new kwargs in the annotations
|
| 131 |
+
_fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"}
|
| 132 |
+
for o in out_params:
|
| 133 |
+
_fn.__annotations__[o.name] = o.annotation
|
| 134 |
+
|
| 135 |
+
# Propagate that this function is wrapped by `out_wrapper`
|
| 136 |
+
_fn._torch_decompositions_out_wrapper = f._torch_decompositions_out_wrapper # type: ignore[attr-defined]
|
| 137 |
+
|
| 138 |
+
return _fn
|
| 139 |
+
|
| 140 |
+
# Alternatively, there may be a single tensor out parameter with a name
|
| 141 |
+
# other than "out". This will need special treatment and is indicated by an
|
| 142 |
+
# annotation, which we will remove here so it is not exposed after wrapping.
|
| 143 |
+
custom_out_param_name = f.__annotations__.pop(CustomOutParamAnnotation, None)
|
| 144 |
+
if custom_out_param_name:
|
| 145 |
+
|
| 146 |
+
@wraps(f)
|
| 147 |
+
def _fn(*args, **kwargs):
|
| 148 |
+
out_kwarg = kwargs.pop(custom_out_param_name, None)
|
| 149 |
+
return f(*args, **kwargs, out=out_kwarg)
|
| 150 |
+
|
| 151 |
+
out_param = inspect.Parameter(
|
| 152 |
+
custom_out_param_name,
|
| 153 |
+
kind=inspect.Parameter.KEYWORD_ONLY,
|
| 154 |
+
default=None,
|
| 155 |
+
annotation=out_annotation,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# Drop the out parameter and concatenate the new kwarg in the signature
|
| 159 |
+
sig = inspect.signature(f)
|
| 160 |
+
params = chain(
|
| 161 |
+
(v for k, v in sig.parameters.items() if k != "out"), (out_param,)
|
| 162 |
+
)
|
| 163 |
+
_fn.__signature__ = inspect.Signature( # type: ignore[attr-defined]
|
| 164 |
+
parameters=params, # type: ignore[arg-type]
|
| 165 |
+
return_annotation=sig.return_annotation,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Drop the out parameter and concatenate the new kwargs in the annotations
|
| 169 |
+
_fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"}
|
| 170 |
+
_fn.__annotations__[out_param.name] = out_param.annotation
|
| 171 |
+
|
| 172 |
+
return _fn
|
| 173 |
+
|
| 174 |
+
return f
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def register_decomposition(
|
| 178 |
+
aten_op, registry=None, *, type="post_autograd", unsafe=False
|
| 179 |
+
) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
|
| 180 |
+
"""
|
| 181 |
+
A decorator to register a function as a decomposition to the Python
|
| 182 |
+
decomposition table. Use it like this::
|
| 183 |
+
|
| 184 |
+
@register_decomposition(torch.ops.aten.clamp_min)
|
| 185 |
+
def clamp_min(x):
|
| 186 |
+
return torch.clamp(self, min=min)
|
| 187 |
+
|
| 188 |
+
If you are writing a new decomposition, consider contributing it
|
| 189 |
+
directly to PyTorch in torch._decomp.decompositions.
|
| 190 |
+
|
| 191 |
+
This API is experimental; we are almost certainly going to extend
|
| 192 |
+
the API when we make decompositions eligible for use in transforms (e.g.,
|
| 193 |
+
autograd) and not just backend tracing, where we then need to know if a
|
| 194 |
+
decomposition can be used to simulate a transform.
|
| 195 |
+
|
| 196 |
+
By default, we also will register it to the Meta key of dispatcher,
|
| 197 |
+
and replace the c++ Meta implementation if there is already one.
|
| 198 |
+
|
| 199 |
+
unsafe kwarg is for reuse of this function for registering non-function
|
| 200 |
+
things
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
assert type in {"post_autograd", "pre_autograd", "meta"}
|
| 204 |
+
|
| 205 |
+
def decomposition_decorator(fn: Callable[_P, _T]) -> Callable[_P, _T]:
|
| 206 |
+
orig_fn = fn
|
| 207 |
+
if not unsafe:
|
| 208 |
+
fn = _convert_out_params(fn)
|
| 209 |
+
|
| 210 |
+
nonlocal registry
|
| 211 |
+
if registry is None:
|
| 212 |
+
registry = global_decomposition_table[type]
|
| 213 |
+
|
| 214 |
+
def register(op):
|
| 215 |
+
_add_op_to_registry(registry, op, fn)
|
| 216 |
+
|
| 217 |
+
# To handle allowing multiple aten_ops at once
|
| 218 |
+
pytree.tree_map_(register, aten_op)
|
| 219 |
+
return orig_fn
|
| 220 |
+
|
| 221 |
+
return decomposition_decorator
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def get_decompositions(
|
| 225 |
+
aten_ops: Sequence[Union[torch._ops.OperatorBase, OpOverloadPacket]],
|
| 226 |
+
type: str = "post_autograd",
|
| 227 |
+
) -> dict[torch._ops.OperatorBase, Callable]:
|
| 228 |
+
"""
|
| 229 |
+
Retrieve a dictionary of decompositions corresponding to the list of
|
| 230 |
+
operator overloads and overload packets passed as input. Overload
|
| 231 |
+
packets will include all decomposed overloads in the packet. If there is
|
| 232 |
+
no decomposition for a requested operator, it is silently ignored.
|
| 233 |
+
|
| 234 |
+
This API is experimental; we are almost certainly going to give an alternate,
|
| 235 |
+
more recommended formulation, where a user provides the set of operators
|
| 236 |
+
they know how to implement, and we provide decompositions for everything
|
| 237 |
+
not in this set.
|
| 238 |
+
"""
|
| 239 |
+
assert type in {"post_autograd", "pre_autograd", "meta"}
|
| 240 |
+
|
| 241 |
+
registry = global_decomposition_table[type]
|
| 242 |
+
packets_to_overloads = defaultdict(list)
|
| 243 |
+
for opo in registry:
|
| 244 |
+
if isinstance(opo, (OpOverload, OpOverloadPacket)):
|
| 245 |
+
packets_to_overloads[opo.overloadpacket].append(opo)
|
| 246 |
+
decompositions: dict[torch._ops.OperatorBase, Callable] = {}
|
| 247 |
+
for op in aten_ops:
|
| 248 |
+
if isinstance(op, OpOverloadPacket) and op in packets_to_overloads:
|
| 249 |
+
for op_overload in packets_to_overloads[op]:
|
| 250 |
+
decompositions[op_overload] = registry[op_overload]
|
| 251 |
+
elif isinstance(op, (torch._ops.OperatorBase)) and op in registry:
|
| 252 |
+
decompositions[op] = registry[op]
|
| 253 |
+
return decompositions
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def remove_decompositions(
|
| 257 |
+
decompositions: dict[torch._ops.OperatorBase, Callable],
|
| 258 |
+
aten_ops: Sequence[Union[OpOverload, OpOverloadPacket]],
|
| 259 |
+
) -> None:
|
| 260 |
+
"""
|
| 261 |
+
Given a dictionary of decompositions obtained from get_decompositions(), removes
|
| 262 |
+
operators associated with a list of operator overloads and overload packets passed
|
| 263 |
+
as input. If the decomposition dictionary does not contain a decomposition that is
|
| 264 |
+
specified to be removed, it is silently ignored.
|
| 265 |
+
"""
|
| 266 |
+
for op in aten_ops:
|
| 267 |
+
if isinstance(op, OpOverloadPacket):
|
| 268 |
+
for overload_name in op.overloads():
|
| 269 |
+
opo = getattr(op, overload_name)
|
| 270 |
+
decompositions.pop(opo, None)
|
| 271 |
+
elif isinstance(op, OpOverload):
|
| 272 |
+
decompositions.pop(op, None)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
# populate the table
|
| 276 |
+
import torch._decomp.decompositions
|
| 277 |
+
import torch._refs
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def core_aten_decompositions() -> "CustomDecompTable":
|
| 281 |
+
from torch.export.exported_program import default_decompositions
|
| 282 |
+
|
| 283 |
+
return default_decompositions()
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# See NOTE [Core ATen Ops]
|
| 287 |
+
#
|
| 288 |
+
# list was copied from torch/_inductor/decomposition.py
|
| 289 |
+
# excluding decompositions that results in prim ops
|
| 290 |
+
# Resulting opset of decomposition is core aten ops
|
| 291 |
+
def _core_aten_decompositions_post_autograd() -> dict[
|
| 292 |
+
torch._ops.OperatorBase, Callable
|
| 293 |
+
]:
|
| 294 |
+
aten = torch.ops.aten
|
| 295 |
+
return get_decompositions(
|
| 296 |
+
[
|
| 297 |
+
aten.addcdiv,
|
| 298 |
+
aten.addcdiv_,
|
| 299 |
+
aten.addcmul,
|
| 300 |
+
aten.addcmul_,
|
| 301 |
+
aten.addr,
|
| 302 |
+
aten.affine_grid_generator,
|
| 303 |
+
aten.alias_copy,
|
| 304 |
+
aten.all,
|
| 305 |
+
aten.aminmax,
|
| 306 |
+
aten.arange.default,
|
| 307 |
+
aten.arange.start,
|
| 308 |
+
aten.avg_pool2d_backward,
|
| 309 |
+
aten.baddbmm,
|
| 310 |
+
aten.binary_cross_entropy,
|
| 311 |
+
aten.binary_cross_entropy_backward,
|
| 312 |
+
aten.binary_cross_entropy_with_logits,
|
| 313 |
+
aten.block_diag,
|
| 314 |
+
aten.bernoulli.p,
|
| 315 |
+
aten.bernoulli.default,
|
| 316 |
+
aten.celu,
|
| 317 |
+
aten.celu_,
|
| 318 |
+
aten.channel_shuffle,
|
| 319 |
+
aten.clamp_max,
|
| 320 |
+
aten.clamp_min,
|
| 321 |
+
aten.col2im,
|
| 322 |
+
aten.count_nonzero,
|
| 323 |
+
aten.linalg_cross,
|
| 324 |
+
aten.cudnn_batch_norm,
|
| 325 |
+
aten.cudnn_batch_norm_backward,
|
| 326 |
+
aten.miopen_batch_norm_backward,
|
| 327 |
+
aten.deg2rad,
|
| 328 |
+
aten.deg2rad_,
|
| 329 |
+
aten.detach,
|
| 330 |
+
aten.diag_embed,
|
| 331 |
+
aten.diagonal_backward,
|
| 332 |
+
aten.diagonal_copy,
|
| 333 |
+
aten.dot,
|
| 334 |
+
aten.vdot,
|
| 335 |
+
aten.elu_,
|
| 336 |
+
aten.elu_backward,
|
| 337 |
+
aten._embedding_bag,
|
| 338 |
+
aten.embedding_dense_backward,
|
| 339 |
+
aten.empty_like,
|
| 340 |
+
aten._euclidean_dist.default,
|
| 341 |
+
aten.expand_as,
|
| 342 |
+
aten.expand_copy,
|
| 343 |
+
aten.eye,
|
| 344 |
+
aten.fill,
|
| 345 |
+
aten.fill_,
|
| 346 |
+
aten.floor_divide,
|
| 347 |
+
aten.frac,
|
| 348 |
+
aten.frac_,
|
| 349 |
+
aten._fused_moving_avg_obs_fq_helper,
|
| 350 |
+
aten.gelu_,
|
| 351 |
+
aten.gelu_backward,
|
| 352 |
+
aten.glu,
|
| 353 |
+
aten.glu_backward,
|
| 354 |
+
aten.hardshrink,
|
| 355 |
+
aten.hardsigmoid,
|
| 356 |
+
aten.hardsigmoid_,
|
| 357 |
+
aten.hardsigmoid_backward,
|
| 358 |
+
aten.hardswish,
|
| 359 |
+
aten.hardswish_,
|
| 360 |
+
aten.hardswish_backward,
|
| 361 |
+
aten.hardtanh_,
|
| 362 |
+
aten.hardtanh_backward,
|
| 363 |
+
aten.heaviside,
|
| 364 |
+
aten.heaviside_,
|
| 365 |
+
aten.huber_loss,
|
| 366 |
+
aten.huber_loss_backward,
|
| 367 |
+
aten.im2col,
|
| 368 |
+
aten.index_add.out,
|
| 369 |
+
aten.index_add.default,
|
| 370 |
+
aten.index_add_,
|
| 371 |
+
aten.index_copy.out,
|
| 372 |
+
aten.index_copy.default,
|
| 373 |
+
aten.index_copy_,
|
| 374 |
+
aten.index_fill.int_Scalar,
|
| 375 |
+
aten.index_fill.int_Tensor,
|
| 376 |
+
aten.index_fill.int_Scalar_out,
|
| 377 |
+
aten.index_fill.int_Tensor_out,
|
| 378 |
+
aten.index_fill_,
|
| 379 |
+
aten.isin,
|
| 380 |
+
aten.isneginf,
|
| 381 |
+
aten.isposinf,
|
| 382 |
+
aten.l1_loss,
|
| 383 |
+
aten._lazy_clone,
|
| 384 |
+
aten._test_parallel_materialize,
|
| 385 |
+
aten.leaky_relu_,
|
| 386 |
+
aten.leaky_relu_backward,
|
| 387 |
+
aten.lerp,
|
| 388 |
+
aten.lerp_,
|
| 389 |
+
aten.linspace,
|
| 390 |
+
aten.logaddexp,
|
| 391 |
+
aten.logaddexp2,
|
| 392 |
+
aten.logit,
|
| 393 |
+
aten.logit_,
|
| 394 |
+
aten.logit_backward,
|
| 395 |
+
aten.log_sigmoid_backward,
|
| 396 |
+
aten.log_sigmoid_forward,
|
| 397 |
+
aten._log_softmax_backward_data,
|
| 398 |
+
aten.logspace,
|
| 399 |
+
aten.logsumexp.default,
|
| 400 |
+
aten.masked_fill,
|
| 401 |
+
aten.masked_fill_,
|
| 402 |
+
aten.max_unpool2d,
|
| 403 |
+
aten.max_unpool3d,
|
| 404 |
+
aten.mish,
|
| 405 |
+
aten.mish_,
|
| 406 |
+
aten.mse_loss,
|
| 407 |
+
aten.mse_loss_backward,
|
| 408 |
+
aten.multi_margin_loss,
|
| 409 |
+
aten.multilabel_margin_loss_forward,
|
| 410 |
+
aten.mv,
|
| 411 |
+
aten.mvlgamma,
|
| 412 |
+
aten.mvlgamma_,
|
| 413 |
+
aten.nansum,
|
| 414 |
+
aten.nan_to_num,
|
| 415 |
+
aten.nan_to_num_,
|
| 416 |
+
aten.narrow,
|
| 417 |
+
aten.native_batch_norm_backward,
|
| 418 |
+
aten.native_dropout_backward,
|
| 419 |
+
aten.native_group_norm_backward,
|
| 420 |
+
aten.native_layer_norm_backward,
|
| 421 |
+
aten._fused_rms_norm_backward,
|
| 422 |
+
aten.new_empty,
|
| 423 |
+
aten.new_full,
|
| 424 |
+
aten.new_ones,
|
| 425 |
+
aten.new_zeros,
|
| 426 |
+
aten.nll_loss2d_forward,
|
| 427 |
+
aten.nll_loss2d_backward,
|
| 428 |
+
aten.nll_loss_backward,
|
| 429 |
+
aten.nll_loss_forward,
|
| 430 |
+
aten.norm.ScalarOpt_dtype,
|
| 431 |
+
aten.norm.Scalar,
|
| 432 |
+
aten.norm.ScalarOpt_dim_dtype,
|
| 433 |
+
aten.norm.ScalarOpt_dim,
|
| 434 |
+
aten.norm.dtype_out,
|
| 435 |
+
aten.norm.out,
|
| 436 |
+
aten.norm.names_dtype_out,
|
| 437 |
+
aten.norm.names_out,
|
| 438 |
+
aten.norm.ScalarOpt_dtype_out,
|
| 439 |
+
aten.norm.Scalar_out,
|
| 440 |
+
aten.ones,
|
| 441 |
+
aten.ones_like,
|
| 442 |
+
aten.pixel_shuffle,
|
| 443 |
+
aten.pixel_unshuffle,
|
| 444 |
+
aten._prelu_kernel,
|
| 445 |
+
aten._prelu_kernel_backward,
|
| 446 |
+
aten._reshape_alias,
|
| 447 |
+
aten.rad2deg,
|
| 448 |
+
aten.rad2deg_,
|
| 449 |
+
aten.reflection_pad1d,
|
| 450 |
+
aten.reflection_pad1d_backward,
|
| 451 |
+
aten.reflection_pad2d,
|
| 452 |
+
aten.reflection_pad2d_backward,
|
| 453 |
+
aten.reflection_pad3d,
|
| 454 |
+
aten.reflection_pad3d_backward,
|
| 455 |
+
aten.replication_pad1d,
|
| 456 |
+
aten.replication_pad2d,
|
| 457 |
+
aten.replication_pad3d,
|
| 458 |
+
aten.renorm,
|
| 459 |
+
aten.renorm_,
|
| 460 |
+
aten.replication_pad2d,
|
| 461 |
+
aten.resize_as,
|
| 462 |
+
aten.roll,
|
| 463 |
+
aten.rot90,
|
| 464 |
+
aten.rrelu_with_noise,
|
| 465 |
+
aten.rrelu_with_noise_,
|
| 466 |
+
aten.rsub,
|
| 467 |
+
aten._safe_softmax,
|
| 468 |
+
aten._scaled_dot_product_flash_attention_for_cpu.default,
|
| 469 |
+
aten.select_backward,
|
| 470 |
+
aten.select_scatter,
|
| 471 |
+
aten.sgn,
|
| 472 |
+
aten.sgn_,
|
| 473 |
+
aten.sigmoid_backward,
|
| 474 |
+
aten.silu,
|
| 475 |
+
aten.silu_,
|
| 476 |
+
aten.silu_backward.grad_input,
|
| 477 |
+
aten.sinc,
|
| 478 |
+
aten.sinc_,
|
| 479 |
+
aten.slice_backward,
|
| 480 |
+
aten.smooth_l1_loss,
|
| 481 |
+
aten.smooth_l1_loss_backward,
|
| 482 |
+
aten.soft_margin_loss,
|
| 483 |
+
aten.soft_margin_loss_backward,
|
| 484 |
+
aten._softmax_backward_data,
|
| 485 |
+
aten.softplus,
|
| 486 |
+
aten.softplus_backward,
|
| 487 |
+
aten.softshrink,
|
| 488 |
+
aten.special_entr,
|
| 489 |
+
aten.special_log_ndtr,
|
| 490 |
+
aten.special_xlog1py,
|
| 491 |
+
aten.split.Tensor,
|
| 492 |
+
aten.split_with_sizes_copy,
|
| 493 |
+
aten.squeeze_copy,
|
| 494 |
+
aten.squeeze.default,
|
| 495 |
+
aten.squeeze.dim,
|
| 496 |
+
aten.std.correction,
|
| 497 |
+
aten.std.out,
|
| 498 |
+
aten.std.correction_out,
|
| 499 |
+
aten.std.names_out,
|
| 500 |
+
aten.std.correction_names_out,
|
| 501 |
+
aten.std_mean.correction,
|
| 502 |
+
aten.std_mean.correction_out,
|
| 503 |
+
aten.stack,
|
| 504 |
+
aten.sum.default,
|
| 505 |
+
aten.sum.out,
|
| 506 |
+
aten.t,
|
| 507 |
+
aten.t_copy,
|
| 508 |
+
aten.take,
|
| 509 |
+
aten.tanh_backward,
|
| 510 |
+
aten.threshold,
|
| 511 |
+
aten.threshold_,
|
| 512 |
+
aten.threshold_backward,
|
| 513 |
+
aten.trace,
|
| 514 |
+
aten.transpose.int,
|
| 515 |
+
aten.transpose_copy,
|
| 516 |
+
aten.tril,
|
| 517 |
+
aten.tril_,
|
| 518 |
+
aten.triu,
|
| 519 |
+
aten.triu_,
|
| 520 |
+
aten.unbind,
|
| 521 |
+
aten.unfold_backward,
|
| 522 |
+
aten.unfold_copy,
|
| 523 |
+
aten._unsafe_index,
|
| 524 |
+
aten._unsafe_index_put,
|
| 525 |
+
aten._unsafe_masked_index,
|
| 526 |
+
aten._unsafe_masked_index_put_accumulate,
|
| 527 |
+
aten.unsafe_split.Tensor,
|
| 528 |
+
aten.unsafe_split_with_sizes,
|
| 529 |
+
aten.unsqueeze_copy,
|
| 530 |
+
aten._unsafe_view,
|
| 531 |
+
aten.upsample_linear1d,
|
| 532 |
+
aten.upsample_bilinear2d.out,
|
| 533 |
+
aten.upsample_trilinear3d.out,
|
| 534 |
+
aten.upsample_nearest2d_backward,
|
| 535 |
+
aten.view_as_complex,
|
| 536 |
+
aten.xlogy,
|
| 537 |
+
aten.xlogy_,
|
| 538 |
+
aten.zero,
|
| 539 |
+
aten.zero_,
|
| 540 |
+
aten.zeros,
|
| 541 |
+
aten.zeros_like,
|
| 542 |
+
aten._chunk_cat,
|
| 543 |
+
aten._weight_norm_interface,
|
| 544 |
+
]
|
| 545 |
+
)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (15.6 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-310.pyc
ADDED
|
Binary file (8.07 kB). View file
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_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 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import inspect
|
| 4 |
+
from typing import Callable, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch._decomp
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
from torch._prims_common.wrappers import _maybe_remove_out_wrapper
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
decomposition_table = torch._decomp.decomposition_table
|
| 13 |
+
decomposition_table_for_jvp: dict[torch._ops.OperatorBase, Callable] = {}
|
| 14 |
+
register_decomposition = torch._decomp.register_decomposition
|
| 15 |
+
aten = torch.ops.aten
|
| 16 |
+
|
| 17 |
+
# NOTE: [forward-mode AD decompositions mechanism]
|
| 18 |
+
#
|
| 19 |
+
# The mechanism is in VariableType,
|
| 20 |
+
# IF any inputs have forward grad
|
| 21 |
+
# AND there is no forward AD formula implemented
|
| 22 |
+
# AND the functions are actually differentiable
|
| 23 |
+
# run the decomposition
|
| 24 |
+
# See run_jit_decomposition_with_args_for_jvp
|
| 25 |
+
# We currently use python decompositions that we torchscript.
|
| 26 |
+
#
|
| 27 |
+
# Note that we would be building the backward graph at the decomposed level
|
| 28 |
+
# too, but that is OK, because we would've errored out otherwise anyway.
|
| 29 |
+
#
|
| 30 |
+
# TODO: The mechanism we are using to register decompositions doesn't
|
| 31 |
+
# seem to be exclusively used for jvp. So open question here is whether
|
| 32 |
+
# torch/csrc/jit/runtime/decomposition_registry.cpp is being used for other things.
|
| 33 |
+
# If that is the case, we may go down the decomposition path unexpectedly
|
| 34 |
+
# (and possibly produce an unintelligible error) vs erroring out earlier and
|
| 35 |
+
# printing that the forward AD formula is not implemented.
|
| 36 |
+
#
|
| 37 |
+
# The solution to this may be to have an explicitly white list control when
|
| 38 |
+
# to enable the decomposition.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def maybe_register_decomposition(op):
|
| 42 |
+
def decorator(f):
|
| 43 |
+
try:
|
| 44 |
+
return register_decomposition(op)(f)
|
| 45 |
+
except Exception:
|
| 46 |
+
return f
|
| 47 |
+
|
| 48 |
+
return decorator
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Functions where we need a special decomposition for jvp but there's another version that
|
| 52 |
+
# should be used more generally (ex. for jvp we need to recompute the mean and variance for
|
| 53 |
+
# the backwards of a normalization function. Without jvp, it should use the saved value)
|
| 54 |
+
decomposition_table_for_jvp = {}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def register_decomposition_for_jvp(fn):
|
| 58 |
+
return register_decomposition(fn, registry=decomposition_table_for_jvp)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _register_jit_decomposition_for_jvp(decomp, use_python=False):
|
| 62 |
+
if decomp in decomposition_table_for_jvp:
|
| 63 |
+
decomposition_table_used = decomposition_table_for_jvp
|
| 64 |
+
elif decomp in decomposition_table:
|
| 65 |
+
decomposition_table_used = decomposition_table
|
| 66 |
+
else:
|
| 67 |
+
raise RuntimeError(f"could not find decomposition for {decomp}")
|
| 68 |
+
decomp_fn = decomposition_table_used[decomp]
|
| 69 |
+
|
| 70 |
+
# `out_wrapper` extends a decompositions signature with
|
| 71 |
+
# an `out` parameter. However jit will use the unwrapped function's
|
| 72 |
+
# signature instead so we need to unwrap here to prevent an error
|
| 73 |
+
decomp_fn = _maybe_remove_out_wrapper(decomp_fn)
|
| 74 |
+
|
| 75 |
+
if use_python:
|
| 76 |
+
decomp_fn = torch.jit.ignore(decomp_fn)
|
| 77 |
+
sig = inspect.signature(decomp_fn)
|
| 78 |
+
|
| 79 |
+
# Create a string wrapping the function from the signature
|
| 80 |
+
# example output:
|
| 81 |
+
# def wrapped_decomp(x: torch.Tensor, y: int, z: int):
|
| 82 |
+
# return decomp_fn(x, y, z)
|
| 83 |
+
# Thanks copilot!
|
| 84 |
+
def get_function_def(sig):
|
| 85 |
+
param_def = [f"{param_str}" for param_str in sig.parameters.values()]
|
| 86 |
+
param_use = [f"{param_str}" for param_str in sig.parameters.keys()]
|
| 87 |
+
|
| 88 |
+
return f"def wrapped_decomp({', '.join(param_def)}):\n return decomp_fn({', '.join(param_use)})\n"
|
| 89 |
+
|
| 90 |
+
f_str = get_function_def(sig)
|
| 91 |
+
graph = torch.jit.CompilationUnit(f_str).wrapped_decomp.graph
|
| 92 |
+
else:
|
| 93 |
+
graph = torch.jit.script(decomp_fn).graph
|
| 94 |
+
torch.jit._register_decomposition(decomp, graph)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# The only decompositions here are temporary or hacks for the purposes of jvp
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# TODO: do these also belong here?
|
| 101 |
+
@maybe_register_decomposition(aten.trace.default)
|
| 102 |
+
def trace(self: Tensor) -> Tensor:
|
| 103 |
+
return torch.sum(torch.diag(self))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@maybe_register_decomposition(aten.log_sigmoid_forward.default)
|
| 107 |
+
def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]:
|
| 108 |
+
min = torch.minimum(self.new_zeros(()), self)
|
| 109 |
+
z = torch.exp(-torch.abs(self))
|
| 110 |
+
if self.is_cuda or self.is_xpu:
|
| 111 |
+
buffer = self.new_zeros((0,))
|
| 112 |
+
else:
|
| 113 |
+
buffer = z
|
| 114 |
+
return min - torch.log1p(z), buffer
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def recompute_mean_var(
|
| 118 |
+
input: Tensor, rstd: Tensor, inner_dim_indices: list[int], keepdim: bool
|
| 119 |
+
):
|
| 120 |
+
# for most norm decompositions, it will be the same as the core version except for here.
|
| 121 |
+
# We recompute the mean and variance so that they track gradients through input
|
| 122 |
+
|
| 123 |
+
mean = torch.mean(input, dim=inner_dim_indices, keepdim=keepdim)
|
| 124 |
+
var = torch.var(input, dim=inner_dim_indices, unbiased=False, keepdim=keepdim)
|
| 125 |
+
eps = torch.pow(1 / rstd, 2) - var # this makes me so sad inside
|
| 126 |
+
eps = eps.detach()
|
| 127 |
+
rstd = 1 / torch.sqrt(var + eps)
|
| 128 |
+
return mean, rstd
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@register_decomposition_for_jvp(aten.native_layer_norm_backward)
|
| 132 |
+
def native_layer_norm_backward(
|
| 133 |
+
grad_out: Tensor,
|
| 134 |
+
input: Tensor,
|
| 135 |
+
normalized_shape: list[int],
|
| 136 |
+
mean: Tensor,
|
| 137 |
+
rstd: Tensor,
|
| 138 |
+
weight: Optional[Tensor],
|
| 139 |
+
bias: Optional[Tensor],
|
| 140 |
+
output_mask: list[bool],
|
| 141 |
+
) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]:
|
| 142 |
+
input_shape = input.shape
|
| 143 |
+
input_ndim = input.dim()
|
| 144 |
+
|
| 145 |
+
axis = input_ndim - len(normalized_shape)
|
| 146 |
+
inner_dims = input_shape[axis:]
|
| 147 |
+
outer_dims = input_shape[:axis]
|
| 148 |
+
inner_dim_indices = list(range(axis, input_ndim))
|
| 149 |
+
outer_dim_indices = list(range(0, axis))
|
| 150 |
+
|
| 151 |
+
N = 1
|
| 152 |
+
for i in inner_dims:
|
| 153 |
+
N *= i
|
| 154 |
+
M = 1
|
| 155 |
+
for i in outer_dims:
|
| 156 |
+
M *= i
|
| 157 |
+
if M <= 0 or N <= 0:
|
| 158 |
+
return (
|
| 159 |
+
input.new_zeros(input_shape),
|
| 160 |
+
input.new_zeros(input_shape[axis:]),
|
| 161 |
+
input.new_zeros(input_shape[axis:]),
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
mean_, rstd_ = recompute_mean_var(input, rstd, inner_dim_indices, keepdim=True)
|
| 165 |
+
|
| 166 |
+
x_hat = (input - mean_) * rstd_
|
| 167 |
+
if weight is not None:
|
| 168 |
+
grad_x_hat = grad_out * weight
|
| 169 |
+
else:
|
| 170 |
+
grad_x_hat = grad_out
|
| 171 |
+
a = grad_x_hat * N
|
| 172 |
+
b = torch.sum(grad_x_hat, inner_dim_indices, True)
|
| 173 |
+
c1 = torch.mul(grad_x_hat, x_hat)
|
| 174 |
+
c2 = torch.sum(c1, inner_dim_indices, True)
|
| 175 |
+
c3 = torch.mul(x_hat, c2)
|
| 176 |
+
inner = a - b - c3
|
| 177 |
+
|
| 178 |
+
if output_mask[0]:
|
| 179 |
+
d_input: Optional[Tensor] = (rstd_ / N) * inner
|
| 180 |
+
else:
|
| 181 |
+
d_input = torch.zeros_like(input) # should be None but doesn't work with vjp
|
| 182 |
+
|
| 183 |
+
if output_mask[1] and weight is not None:
|
| 184 |
+
if len(outer_dim_indices) > 0:
|
| 185 |
+
d_weight: Optional[Tensor] = torch.sum(
|
| 186 |
+
grad_out * x_hat, outer_dim_indices, False
|
| 187 |
+
)
|
| 188 |
+
else:
|
| 189 |
+
d_weight = grad_out * x_hat
|
| 190 |
+
elif weight is not None:
|
| 191 |
+
d_weight = torch.zeros_like(weight) # should be None but doesn't work with vjp
|
| 192 |
+
else:
|
| 193 |
+
d_weight = torch.zeros(()) # should be None but doesn't work with vjp
|
| 194 |
+
|
| 195 |
+
if output_mask[2] and bias is not None:
|
| 196 |
+
if len(outer_dim_indices) > 0:
|
| 197 |
+
d_bias: Optional[Tensor] = torch.sum(grad_out, outer_dim_indices, False)
|
| 198 |
+
else:
|
| 199 |
+
d_bias = grad_out.clone()
|
| 200 |
+
elif bias is not None:
|
| 201 |
+
d_bias = torch.zeros_like(bias) # should be None but doesn't work with vjp
|
| 202 |
+
else:
|
| 203 |
+
d_bias = torch.zeros(()) # should be None but doesn't work with vjp
|
| 204 |
+
|
| 205 |
+
return (d_input, d_weight, d_bias)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def prod(x: list[int]):
|
| 209 |
+
r = 1
|
| 210 |
+
for i in x:
|
| 211 |
+
r *= i
|
| 212 |
+
return r
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@register_decomposition_for_jvp(aten.native_batch_norm_backward)
|
| 216 |
+
def native_batch_norm_backward(
|
| 217 |
+
grad_out: Tensor,
|
| 218 |
+
input: Tensor,
|
| 219 |
+
weight: Optional[Tensor],
|
| 220 |
+
running_mean: Optional[Tensor],
|
| 221 |
+
running_var: Optional[Tensor],
|
| 222 |
+
save_mean: Optional[Tensor],
|
| 223 |
+
save_invstd: Optional[Tensor],
|
| 224 |
+
train: bool,
|
| 225 |
+
eps: float,
|
| 226 |
+
output_mask: list[bool],
|
| 227 |
+
) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
|
| 228 |
+
input_shape = input.shape
|
| 229 |
+
input_rank = input.dim()
|
| 230 |
+
assert input_rank >= 2, "rank of the input must be at least 2"
|
| 231 |
+
|
| 232 |
+
axis = 1
|
| 233 |
+
num_features = prod(input_shape) / input_shape[axis] # type: ignore[arg-type]
|
| 234 |
+
mean = save_mean
|
| 235 |
+
invstd = save_invstd
|
| 236 |
+
if train:
|
| 237 |
+
assert save_mean is not None and save_invstd is not None, (
|
| 238 |
+
"when train=True, save_mean and save_invstd are required"
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
reduciton_dims = [0] + list(range(2, input.dim()))
|
| 242 |
+
assert invstd is not None # for typing
|
| 243 |
+
mean, invstd = recompute_mean_var(input, invstd, reduciton_dims, keepdim=False)
|
| 244 |
+
else:
|
| 245 |
+
assert running_mean is not None and running_var is not None
|
| 246 |
+
mean = running_mean
|
| 247 |
+
invstd = torch.rsqrt(running_var + eps)
|
| 248 |
+
|
| 249 |
+
assert invstd is not None and mean is not None
|
| 250 |
+
|
| 251 |
+
broadcast_mask = [1] * input_rank
|
| 252 |
+
broadcast_mask[axis] = input_shape[axis]
|
| 253 |
+
|
| 254 |
+
reduction_axes: list[int] = []
|
| 255 |
+
for i in range(input_rank):
|
| 256 |
+
if i != axis:
|
| 257 |
+
reduction_axes.append(i)
|
| 258 |
+
|
| 259 |
+
mean = torch.reshape(mean, broadcast_mask)
|
| 260 |
+
norm = 1.0 / num_features
|
| 261 |
+
grad_output_sum = torch.sum(grad_out, reduction_axes)
|
| 262 |
+
dot_p = torch.sum(grad_out * (input - mean), reduction_axes)
|
| 263 |
+
|
| 264 |
+
grad_mean = torch.reshape(grad_output_sum * norm, broadcast_mask)
|
| 265 |
+
proj_scale = torch.reshape(torch.mul(dot_p * norm, invstd * invstd), broadcast_mask)
|
| 266 |
+
|
| 267 |
+
if weight is None:
|
| 268 |
+
grad_scale = torch.reshape(invstd, broadcast_mask) * 1.0
|
| 269 |
+
else:
|
| 270 |
+
grad_scale = torch.reshape(invstd * weight, broadcast_mask)
|
| 271 |
+
|
| 272 |
+
if train:
|
| 273 |
+
proj = (input - mean) * proj_scale
|
| 274 |
+
grad_input = ((grad_out - proj) - grad_mean) * grad_scale
|
| 275 |
+
else:
|
| 276 |
+
grad_input = grad_out * grad_scale
|
| 277 |
+
|
| 278 |
+
if output_mask[1]:
|
| 279 |
+
grad_weight = dot_p * invstd
|
| 280 |
+
elif weight is not None:
|
| 281 |
+
grad_weight = torch.zeros_like(
|
| 282 |
+
weight
|
| 283 |
+
) # should be None but doesn't work with vjp
|
| 284 |
+
else:
|
| 285 |
+
grad_weight = torch.zeros(()) # should be None but doesn't work with vjp
|
| 286 |
+
|
| 287 |
+
if output_mask[2]:
|
| 288 |
+
grad_bias = grad_output_sum
|
| 289 |
+
else:
|
| 290 |
+
grad_bias = torch.zeros_like(
|
| 291 |
+
grad_output_sum
|
| 292 |
+
) # should be None but doesn't work with vjp
|
| 293 |
+
|
| 294 |
+
return (grad_input, grad_weight, grad_bias)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@register_decomposition_for_jvp(aten.batch_norm_backward)
|
| 298 |
+
def batch_norm_backward(
|
| 299 |
+
grad_out: Tensor,
|
| 300 |
+
input: Tensor,
|
| 301 |
+
weight: Tensor,
|
| 302 |
+
running_mean: Optional[Tensor],
|
| 303 |
+
running_var: Optional[Tensor],
|
| 304 |
+
save_mean: Optional[Tensor],
|
| 305 |
+
save_var: Optional[Tensor],
|
| 306 |
+
update: bool,
|
| 307 |
+
eps: float,
|
| 308 |
+
output_mask: list[bool],
|
| 309 |
+
reserve: Tensor,
|
| 310 |
+
) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
|
| 311 |
+
return native_batch_norm_backward(
|
| 312 |
+
grad_out,
|
| 313 |
+
input,
|
| 314 |
+
weight,
|
| 315 |
+
running_mean,
|
| 316 |
+
running_var,
|
| 317 |
+
save_mean,
|
| 318 |
+
save_var,
|
| 319 |
+
update,
|
| 320 |
+
eps,
|
| 321 |
+
output_mask,
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.trace.default, use_python=True)
|
| 326 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss_backward.default)
|
| 327 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss2d_backward.default)
|
| 328 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten._log_softmax_backward_data.default)
|
| 329 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten._softmax_backward_data.default)
|
| 330 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.log_sigmoid_forward.default)
|
| 331 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.native_layer_norm_backward.default)
|
| 332 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.native_batch_norm_backward.default)
|
| 333 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.cudnn_batch_norm_backward.default)
|
| 334 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.batch_norm_backward.default)
|
| 335 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.miopen_batch_norm_backward.default)
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import functools
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from typing import Callable
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch._decomp as decomp
|
| 9 |
+
from torch._decomp import get_decompositions
|
| 10 |
+
from torch._ops import OpOverload
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
aten = torch.ops.aten
|
| 14 |
+
|
| 15 |
+
rng_decompositions: dict[str, dict[OpOverload, Callable]] = defaultdict(dict)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def register_rng_decomposition(aten_op):
|
| 19 |
+
return decomp.register_decomposition(aten_op, rng_decompositions)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def throw_on_non_cuda(device):
|
| 23 |
+
raise RuntimeError(
|
| 24 |
+
f"You are trying to functionalize a {device.type} RNG operator but {device.type} does not "
|
| 25 |
+
f"use Philox/counter-based RNG. Therefore, functionalizing a {device.type} RNG operator is "
|
| 26 |
+
"not supported. We are discussing the possibility of a Philox-based RNG implementation for CPU."
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# TODO - We have to register many more distributions here, and also higher level
|
| 31 |
+
# ops like dropout which have fused implementation and can hide the rand inside.
|
| 32 |
+
@register_rng_decomposition(aten.rand)
|
| 33 |
+
def rand(shape, dtype=None, layout=torch.strided, device=None, pin_memory=False):
|
| 34 |
+
if device and device.type != "cuda":
|
| 35 |
+
throw_on_non_cuda(device)
|
| 36 |
+
seed, offset = PhiloxStateTracker.get_state_as_tuple()
|
| 37 |
+
dtype = dtype or torch.float32
|
| 38 |
+
out, offset_jump = torch.ops.rngprims.philox_rand(
|
| 39 |
+
shape, seed, offset, None, device, dtype
|
| 40 |
+
)
|
| 41 |
+
PhiloxStateTracker.advance_offset(offset_jump)
|
| 42 |
+
return out
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@register_rng_decomposition(aten.rand_like)
|
| 46 |
+
def rand_like(
|
| 47 |
+
x: torch.Tensor,
|
| 48 |
+
dtype=None,
|
| 49 |
+
layout=None,
|
| 50 |
+
device=None,
|
| 51 |
+
pin_memory=False,
|
| 52 |
+
memory_format=torch.preserve_format,
|
| 53 |
+
):
|
| 54 |
+
device = device or x.device
|
| 55 |
+
if device.type != "cuda":
|
| 56 |
+
throw_on_non_cuda(device)
|
| 57 |
+
dtype = dtype or x.dtype
|
| 58 |
+
seed, offset = PhiloxStateTracker.get_state_as_tuple()
|
| 59 |
+
out, offset_jump = torch.ops.rngprims.philox_rand(
|
| 60 |
+
x.shape, seed, offset, None, device, dtype
|
| 61 |
+
)
|
| 62 |
+
PhiloxStateTracker.advance_offset(offset_jump)
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class PhiloxState:
|
| 67 |
+
"""
|
| 68 |
+
Represents a PhiloxRngState - (seed, offset) where offset = base_offset +
|
| 69 |
+
relative_offset. seed and base_offset basically point to the rng state just
|
| 70 |
+
before tracing starts. relative offset tracks the totally consumed offset at
|
| 71 |
+
trace time.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self) -> None:
|
| 75 |
+
self.reset()
|
| 76 |
+
|
| 77 |
+
def reset(self):
|
| 78 |
+
self.seed = torch.tensor(())
|
| 79 |
+
self.base_offset = torch.tensor(())
|
| 80 |
+
self.relative_offset = 0
|
| 81 |
+
self.offset_advanced_alteast_once = False
|
| 82 |
+
|
| 83 |
+
def validate_state(self):
|
| 84 |
+
assert self.seed.numel() != 0 and self.base_offset.numel() != 0
|
| 85 |
+
|
| 86 |
+
def advance_offset(self, consumed_offset):
|
| 87 |
+
self.offset_advanced_alteast_once = True
|
| 88 |
+
self.relative_offset = self.relative_offset + consumed_offset
|
| 89 |
+
|
| 90 |
+
def set_state(self, seed, base_offset, relative_offset=0):
|
| 91 |
+
self.seed = seed
|
| 92 |
+
self.base_offset = base_offset
|
| 93 |
+
self.relative_offset = relative_offset
|
| 94 |
+
|
| 95 |
+
def get_state_as_tuple(self):
|
| 96 |
+
self.validate_state()
|
| 97 |
+
return (self.seed, self.base_offset + self.relative_offset)
|
| 98 |
+
|
| 99 |
+
def get_state_as_tensor(self):
|
| 100 |
+
# Only needed because we override get_rng_state.
|
| 101 |
+
self.validate_state()
|
| 102 |
+
return torch.stack([self.seed, self.base_offset + self.relative_offset])
|
| 103 |
+
|
| 104 |
+
def set_state_from_tensor(self, state):
|
| 105 |
+
# Only needed because we override set_rng_state.
|
| 106 |
+
self.seed, self.base_offset = torch.unbind(state)
|
| 107 |
+
self.relative_offset = 0
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class PhiloxStateTracker:
|
| 111 |
+
"""
|
| 112 |
+
Singleton class to track the philox rng state during AOT Autograd tracing.
|
| 113 |
+
For each aot tracing instance, AOT Autograd resets this tracker and keeps
|
| 114 |
+
track of both forward and backward offsets. At runtime, we only care about
|
| 115 |
+
the total consumed forward and backward offsets. For dynamic shapes, these
|
| 116 |
+
offsets are a function of input shapes. Therefore, the AOT generated graphs
|
| 117 |
+
have additional outputs that compute total consumed forward and backward
|
| 118 |
+
offsets.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
running_state: PhiloxState
|
| 122 |
+
fwd_state: PhiloxState
|
| 123 |
+
bwd_state: PhiloxState
|
| 124 |
+
|
| 125 |
+
def __enter__(self):
|
| 126 |
+
PhiloxStateTracker.reset()
|
| 127 |
+
return self
|
| 128 |
+
|
| 129 |
+
def __exit__(self, exc_type, exc_cal, exc_tb):
|
| 130 |
+
PhiloxStateTracker.reset()
|
| 131 |
+
|
| 132 |
+
@classmethod
|
| 133 |
+
def reset(cls):
|
| 134 |
+
cls.running_state = PhiloxState()
|
| 135 |
+
cls.fwd_state = PhiloxState()
|
| 136 |
+
cls.bwd_state = PhiloxState()
|
| 137 |
+
|
| 138 |
+
@classmethod
|
| 139 |
+
def mark_beginning_of_forward(cls):
|
| 140 |
+
# Tells the tracker to use fwd_state as the running state
|
| 141 |
+
cls.running_state = cls.fwd_state
|
| 142 |
+
|
| 143 |
+
@classmethod
|
| 144 |
+
def mark_beginning_of_backward(cls):
|
| 145 |
+
# Tells the tracker to use bwd_state as the running state
|
| 146 |
+
cls.running_state = cls.bwd_state
|
| 147 |
+
|
| 148 |
+
@classmethod
|
| 149 |
+
def record_state(cls, seed, offset, mode):
|
| 150 |
+
# Records the seed and offset tensors. These tensors are used to invoke
|
| 151 |
+
# the philox_rand functional primitives.
|
| 152 |
+
if mode == "forward":
|
| 153 |
+
cls.fwd_state.set_state(seed, offset)
|
| 154 |
+
cls.mark_beginning_of_forward()
|
| 155 |
+
else:
|
| 156 |
+
assert mode == "backward"
|
| 157 |
+
cls.bwd_state.set_state(seed, offset)
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def get_state_as_tensor(cls):
|
| 161 |
+
# The only reason this exists is because we override get_rng_state and
|
| 162 |
+
# set_rng_state during tracing. get_rng_state expects a tensor output,
|
| 163 |
+
# so return (seed, offset) tuple upset other parts of the program like
|
| 164 |
+
# ctx.saved_tensors.
|
| 165 |
+
|
| 166 |
+
# A bad consequence is that if user saves and restores rng state, we
|
| 167 |
+
# have little bit of ugliness in the generated code, where we first
|
| 168 |
+
# concat the (seed, offset) to create a tensor for get_rng_state, and
|
| 169 |
+
# then split it back to get (seed, offset) tuple in set_rng_state.
|
| 170 |
+
|
| 171 |
+
# TODO: Investigate if there is be a better way to wrap the tuple in a
|
| 172 |
+
# false Tensor object, and then desugar it later on.
|
| 173 |
+
return cls.running_state.get_state_as_tensor()
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def get_state_as_tuple(cls):
|
| 177 |
+
return cls.running_state.get_state_as_tuple()
|
| 178 |
+
|
| 179 |
+
@classmethod
|
| 180 |
+
def set_state_from_tensor(cls, x):
|
| 181 |
+
# This is only needed because we override set_rng_state. Look at the
|
| 182 |
+
# comment in get_state_from_tensor method.
|
| 183 |
+
cls.running_state.set_state_from_tensor(x)
|
| 184 |
+
|
| 185 |
+
@classmethod
|
| 186 |
+
def advance_offset(cls, consumed_offset):
|
| 187 |
+
cls.running_state.advance_offset(consumed_offset)
|
| 188 |
+
|
| 189 |
+
@classmethod
|
| 190 |
+
def get_current_relative_offset(cls):
|
| 191 |
+
return cls.running_state.relative_offset
|
| 192 |
+
|
| 193 |
+
@staticmethod
|
| 194 |
+
def multiple_of_4(offset):
|
| 195 |
+
# torch cuda rng state offset must be a multiple of 4. For inductor, as
|
| 196 |
+
# we sum up all the numel, the result might not be a multiple of 4. This
|
| 197 |
+
# method achieves that.
|
| 198 |
+
return (offset + 3) // 4 * 4
|
| 199 |
+
|
| 200 |
+
@classmethod
|
| 201 |
+
def get_updated_fwd_offset(cls):
|
| 202 |
+
# Short circuit if no rand ops were observed
|
| 203 |
+
if not cls.fwd_state.offset_advanced_alteast_once:
|
| 204 |
+
return cls.fwd_state.base_offset
|
| 205 |
+
return cls.multiple_of_4(
|
| 206 |
+
cls.fwd_state.base_offset + cls.fwd_state.relative_offset
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
@classmethod
|
| 210 |
+
def get_updated_bwd_offset(cls):
|
| 211 |
+
# Short circuit if no rand ops were observed
|
| 212 |
+
if not cls.bwd_state.offset_advanced_alteast_once:
|
| 213 |
+
return cls.bwd_state.base_offset
|
| 214 |
+
return cls.multiple_of_4(
|
| 215 |
+
cls.bwd_state.base_offset + cls.bwd_state.relative_offset
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# Adding more decompositions which eventually use rand_like inside decomps.
|
| 220 |
+
# Adding these in rng_decompositions ensures the functionalization of rand_like
|
| 221 |
+
# ops used in these decomps. The list is copied from inductor codebase, which
|
| 222 |
+
# uses it for similar purpose.
|
| 223 |
+
#
|
| 224 |
+
# Caution - These decomps do not have same accuracy as that of eager. However,
|
| 225 |
+
# we can't just disable them with a config flag like fallback_random, because
|
| 226 |
+
# for functionalization of rng ops, we have to decompose these ops.
|
| 227 |
+
extra_random_decomps = get_decompositions(
|
| 228 |
+
[
|
| 229 |
+
aten.cauchy,
|
| 230 |
+
aten.cauchy_,
|
| 231 |
+
aten.exponential,
|
| 232 |
+
aten.exponential_,
|
| 233 |
+
aten.geometric,
|
| 234 |
+
aten.geometric_,
|
| 235 |
+
aten.native_dropout,
|
| 236 |
+
aten.normal,
|
| 237 |
+
aten.normal_,
|
| 238 |
+
aten.normal_functional,
|
| 239 |
+
aten.log_normal,
|
| 240 |
+
aten.log_normal_,
|
| 241 |
+
aten.rrelu_with_noise,
|
| 242 |
+
aten.rrelu_with_noise_,
|
| 243 |
+
aten.uniform_,
|
| 244 |
+
]
|
| 245 |
+
)
|
| 246 |
+
register_extra_random_decomp = functools.partial(
|
| 247 |
+
decomp.register_decomposition, registry=extra_random_decomps
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@register_extra_random_decomp([aten.bernoulli_])
|
| 252 |
+
def bernoulli_(self, p=0.5):
|
| 253 |
+
if self.device == torch.device("cpu"):
|
| 254 |
+
return NotImplemented
|
| 255 |
+
return self.copy_(torch.rand_like(self, dtype=torch.float32) < p)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@register_extra_random_decomp([aten.bernoulli.p])
|
| 259 |
+
def bernoulli_p(self, p=0.5, *, generator=None):
|
| 260 |
+
if self.device == torch.device("cpu"):
|
| 261 |
+
return NotImplemented
|
| 262 |
+
assert generator is None
|
| 263 |
+
return torch.rand_like(self, dtype=torch.float32) < p
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
rng_decompositions.update(extra_random_decomps) # type: ignore[arg-type]
|
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torch/_dispatch/__init__.py
ADDED
|
File without changes
|