Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- llava_next/lib/libcrypto.a +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np16.gz +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.xz +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2 +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_04.npy +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy +3 -0
- parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy +3 -0
- parrot/lib/python3.10/site-packages/torch/_custom_ops.py +323 -0
- parrot/lib/python3.10/site-packages/torch/_refs/__init__.py +0 -0
- parrot/lib/python3.10/site-packages/torch/_refs/__pycache__/_conversions.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/_refs/__pycache__/fft.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/_refs/_conversions.py +119 -0
- parrot/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py +313 -0
- parrot/lib/python3.10/site-packages/torch/_refs/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/_refs/nn/__init__.py +3 -0
- parrot/lib/python3.10/site-packages/torch/_refs/nn/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py +1238 -0
- parrot/lib/python3.10/site-packages/torch/_refs/nn/functional/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/_refs/special/__init__.py +237 -0
- parrot/lib/python3.10/site-packages/torch/_refs/special/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/_vmap_internals.py +238 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__init__.py +539 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/anomaly_mode.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/forward_ad.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/function.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/functional.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/grad_mode.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/gradcheck.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/graph.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/profiler.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/profiler_legacy.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/profiler_util.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/variable.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/_functions/__init__.py +1 -0
- parrot/lib/python3.10/site-packages/torch/autograd/_functions/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/_functions/__pycache__/tensor.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/_functions/__pycache__/utils.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/torch/autograd/_functions/tensor.py +65 -0
- parrot/lib/python3.10/site-packages/torch/autograd/_functions/utils.py +63 -0
- parrot/lib/python3.10/site-packages/torch/autograd/anomaly_mode.py +120 -0
- parrot/lib/python3.10/site-packages/torch/autograd/forward_ad.py +232 -0
- parrot/lib/python3.10/site-packages/torch/autograd/function.py +843 -0
.gitattributes
CHANGED
|
@@ -343,3 +343,4 @@ parrot/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers
|
|
| 343 |
parrot/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/axes3d.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 344 |
parrot/lib/libcrypto.so.3 filter=lfs diff=lfs merge=lfs -text
|
| 345 |
llava_next/lib/python3.10/site-packages/torch/bin/nvfuser_tests filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 343 |
parrot/lib/python3.10/site-packages/mpl_toolkits/mplot3d/__pycache__/axes3d.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 344 |
parrot/lib/libcrypto.so.3 filter=lfs diff=lfs merge=lfs -text
|
| 345 |
llava_next/lib/python3.10/site-packages/torch/bin/nvfuser_tests filter=lfs diff=lfs merge=lfs -text
|
| 346 |
+
llava_next/lib/libcrypto.a filter=lfs diff=lfs merge=lfs -text
|
llava_next/lib/libcrypto.a
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:59bebb9b9a2e4af6837913a0a014f6bdc44b3c02079496f0ffc857e1dd0f87e3
|
| 3 |
+
size 11086938
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np16.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:418447e90d83486568ae3092a960b18d358230e24ac9ec38365daa99f415bd0f
|
| 3 |
+
size 769
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:89c4508e3dfbe01f801e4e739f1aded13f685941e89281c8050f0ca8aa3c97e5
|
| 3 |
+
size 986
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.xz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:efb146d450c6d061d06affb56f17384e7f64cbab9b516fcc6c4d3f8869b3e707
|
| 3 |
+
size 712
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1cbe456f5b91f5a3cb8e386838f276c30335432a351426686187761d5c34168b
|
| 3 |
+
size 1068
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6a1a9b884be654e2e3fc9a48251ecf0c6920e255c3f2ee5dd71d8252a694606
|
| 3 |
+
size 1005
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:02cf30d8b196c303662b2dd035d2a58caeb762ae3a82345ffd1274961e7f5aa0
|
| 3 |
+
size 752
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9f33bd8a21a41b729b05dac5deeb0e868f218a092b0e3fe5988094cf167217f6
|
| 3 |
+
size 673
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_04.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05
|
| 3 |
+
size 104
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c3d4cbc690d3ce9e5323a714ea546f32c01ab1710285c420184f6cdf4b26fc25
|
| 3 |
+
size 691
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8ede9a64a52b25d7db30950956c978ec0b3932b7d14acd5abc63216e64babde7
|
| 3 |
+
size 307
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809
|
| 3 |
+
size 120
|
parrot/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1
|
| 3 |
+
size 120
|
parrot/lib/python3.10/site-packages/torch/_custom_ops.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import inspect
|
| 3 |
+
|
| 4 |
+
from torch._custom_op.impl import (
|
| 5 |
+
_custom_op_with_schema,
|
| 6 |
+
_find_custom_op,
|
| 7 |
+
infer_schema,
|
| 8 |
+
parse_qualname,
|
| 9 |
+
validate_namespace,
|
| 10 |
+
)
|
| 11 |
+
from torch.library import get_ctx
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"custom_op",
|
| 15 |
+
"impl",
|
| 16 |
+
"impl_abstract",
|
| 17 |
+
"get_ctx",
|
| 18 |
+
"impl_save_for_backward",
|
| 19 |
+
"impl_backward",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def custom_op(qualname, func_or_schema=None):
|
| 24 |
+
r"""Register a new custom operator
|
| 25 |
+
|
| 26 |
+
In PyTorch, defining an op (short for "operator") is a two step-process:
|
| 27 |
+
- we need to define the op (by providing an operator name and schema)
|
| 28 |
+
- we need to implement behavior for how the operator interacts with
|
| 29 |
+
various PyTorch subsystems, like CPU/CUDA Tensors, Autograd, etc.
|
| 30 |
+
|
| 31 |
+
This entrypoint defines the custom operator (the first step)
|
| 32 |
+
you must then perform the second step by calling various
|
| 33 |
+
``impl_*`` APIs.
|
| 34 |
+
|
| 35 |
+
This API may be used as a decorator (see examples).
|
| 36 |
+
|
| 37 |
+
For a detailed guide on custom ops, please see
|
| 38 |
+
https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk
|
| 39 |
+
|
| 40 |
+
Arguments:
|
| 41 |
+
qualname (str): Should be a string that looks like
|
| 42 |
+
"namespace::operator_name". Operators in PyTorch need a namespace to
|
| 43 |
+
avoid name collisions; a given operator may only be created once.
|
| 44 |
+
If you are writing a Python library, we recommend the namespace to
|
| 45 |
+
be the name of your top-level module.
|
| 46 |
+
func_or_schema (Union[Callable, str]): Each PyTorch operator needs a
|
| 47 |
+
schema that tells PyTorch the types of the inputs/outputs.
|
| 48 |
+
If this is a Callable, we will automatically infer the schema from
|
| 49 |
+
the type annotations on the function (see examples). Otherwise,
|
| 50 |
+
if you don't want to use type annotations, you may provide us the
|
| 51 |
+
schema string.
|
| 52 |
+
|
| 53 |
+
Example::
|
| 54 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
|
| 55 |
+
>>> import torch
|
| 56 |
+
>>> import numpy as np
|
| 57 |
+
>>> from torch import Tensor
|
| 58 |
+
>>>
|
| 59 |
+
>>> # Step 1: define the custom op.
|
| 60 |
+
>>> # We need to provide the API a "prototype function"
|
| 61 |
+
>>> # (a function that returns NotImplementedError), from which
|
| 62 |
+
>>> # we will infer the types of the inputs and outputs.
|
| 63 |
+
>>> @torch._custom_ops.custom_op("mylibrary::numpy_sin")
|
| 64 |
+
>>> def numpy_sin(x: Tensor) -> Tensor:
|
| 65 |
+
>>> raise NotImplementedError
|
| 66 |
+
>>>
|
| 67 |
+
>>> # The custom op is now accessible via the torch.ops module:
|
| 68 |
+
>>> torch.ops.mylibrary.numpy_sin
|
| 69 |
+
>>>
|
| 70 |
+
>>> # Step 2: Register an implementation for various PyTorch subsystems
|
| 71 |
+
>>>
|
| 72 |
+
>>> # Register an implementation for CPU tensors
|
| 73 |
+
>>> @torch._custom_ops.impl("mylibrary::numpy_sin", device_types="cpu")
|
| 74 |
+
>>> def numpy_sin_impl_cpu(x):
|
| 75 |
+
>>> return torch.from_numpy(np.sin(x.numpy()))
|
| 76 |
+
>>>
|
| 77 |
+
>>> # Register an implementation for CUDA tensors
|
| 78 |
+
>>> @torch._custom_ops.impl("mylibrary::numpy_sin", device_types="cuda")
|
| 79 |
+
>>> def numpy_sin_impl_cuda(x):
|
| 80 |
+
>>> return torch.from_numpy(np.sin(x.cpu().numpy())).to(x.device)
|
| 81 |
+
>>>
|
| 82 |
+
>>> x = torch.randn(3)
|
| 83 |
+
>>> torch.ops.mylibrary.numpy_sin(x) # calls numpy_sin_impl_cpu
|
| 84 |
+
>>>
|
| 85 |
+
>>> x_cuda = x.cuda()
|
| 86 |
+
>>> torch.ops.mylibrary.numpy_sin(x) # calls numpy_sin_impl_cuda
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
ns, name = parse_qualname(qualname)
|
| 90 |
+
validate_namespace(ns)
|
| 91 |
+
|
| 92 |
+
def inner(func):
|
| 93 |
+
if not inspect.isfunction(func):
|
| 94 |
+
raise ValueError(
|
| 95 |
+
f"custom_op(...)(func): Expected `func` to be a Python "
|
| 96 |
+
f"function, got: {type(func)}"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
if func.__name__ != name:
|
| 100 |
+
raise ValueError(
|
| 101 |
+
f"custom_op(qualname='{qualname}', ...)(func): expected `func` "
|
| 102 |
+
f"to have name '{name}' but got '{func.__name__}'. "
|
| 103 |
+
f"Please either change the name of `func` or the qualname that "
|
| 104 |
+
f"is passed to `custom_op`"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
schema = infer_schema(func)
|
| 108 |
+
_custom_op_with_schema(qualname, schema)
|
| 109 |
+
return func
|
| 110 |
+
|
| 111 |
+
if func_or_schema is None:
|
| 112 |
+
return inner
|
| 113 |
+
if isinstance(func_or_schema, str):
|
| 114 |
+
_custom_op_with_schema(qualname, func_or_schema)
|
| 115 |
+
else:
|
| 116 |
+
return inner(func_or_schema)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def impl(qualname, *, device_types=("cpu", "cuda"), func=None):
|
| 120 |
+
r"""Register an implementation for a device type for this custom op.
|
| 121 |
+
|
| 122 |
+
If the op is passed multiple Tensor inputs with different device
|
| 123 |
+
types, it will dispatch to the registered implementation for the highest
|
| 124 |
+
priority device type among those present.
|
| 125 |
+
The supported device types, in order of priority, are {'cuda', 'cpu'}.
|
| 126 |
+
|
| 127 |
+
This API may be used as a decorator (see examples).
|
| 128 |
+
|
| 129 |
+
For a detailed guide on custom ops, please see
|
| 130 |
+
https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk
|
| 131 |
+
|
| 132 |
+
Arguments:
|
| 133 |
+
device_types (str or Iterable[str]): the device type(s) to register the function for.
|
| 134 |
+
|
| 135 |
+
Example::
|
| 136 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
|
| 137 |
+
>>> import torch
|
| 138 |
+
>>> import numpy as np
|
| 139 |
+
>>> from torch import Tensor
|
| 140 |
+
>>>
|
| 141 |
+
>>> # Step 1: define the custom op.
|
| 142 |
+
>>> # We need to provide the API a "prototype function"
|
| 143 |
+
>>> # (a function that returns NotImplementedError), from which
|
| 144 |
+
>>> # we will infer the types of the inputs and outputs.
|
| 145 |
+
>>> @torch._custom_ops.custom_op("mylibrary::numpy_cos")
|
| 146 |
+
>>> def numpy_cos(x: Tensor) -> Tensor:
|
| 147 |
+
>>> raise NotImplementedError
|
| 148 |
+
>>>
|
| 149 |
+
>>> # The custom op is now accessible via the torch.ops module:
|
| 150 |
+
>>> torch.ops.mylibrary.numpy_cos
|
| 151 |
+
>>>
|
| 152 |
+
>>> # Step 2: Register an implementation for various PyTorch subsystems
|
| 153 |
+
>>>
|
| 154 |
+
>>> # Register an implementation for CPU tensors
|
| 155 |
+
>>> @torch._custom_ops.impl("mylibrary::numpy_cos", device_types="cpu")
|
| 156 |
+
>>> def numpy_cos_impl_cpu(x):
|
| 157 |
+
>>> return torch.from_numpy(np.cos(x.numpy()))
|
| 158 |
+
>>>
|
| 159 |
+
>>> # Register an implementation for CUDA tensors
|
| 160 |
+
>>> @torch._custom_ops.impl("mylibrary::numpy_cos", device_types="cuda")
|
| 161 |
+
>>> def numpy_cos_impl_cuda(x):
|
| 162 |
+
>>> return torch.from_numpy(np.cos(x.cpu().numpy())).to(x.device)
|
| 163 |
+
>>>
|
| 164 |
+
>>> x = torch.randn(3)
|
| 165 |
+
>>> torch.ops.mylibrary.numpy_cos(x) # calls numpy_cos_impl_cpu
|
| 166 |
+
>>>
|
| 167 |
+
>>> x_cuda = x.cuda()
|
| 168 |
+
>>> torch.ops.mylibrary.numpy_cos(x) # calls numpy_cos_impl_cuda
|
| 169 |
+
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
def inner(func):
|
| 173 |
+
custom_op = _find_custom_op(qualname, also_check_torch_library=True)
|
| 174 |
+
custom_op.impl(device_types, _stacklevel=3)(func)
|
| 175 |
+
return func
|
| 176 |
+
|
| 177 |
+
if func is None:
|
| 178 |
+
return inner
|
| 179 |
+
return inner(func)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def impl_abstract(qualname, *, func=None):
|
| 183 |
+
r"""Register an abstract implementation for this operator.
|
| 184 |
+
|
| 185 |
+
An "abstract implementation" specifies the behavior of this operator on
|
| 186 |
+
Tensors that carry no data. Given some input Tensors with certain properties
|
| 187 |
+
(sizes/strides/storage_offset/device), it specifies what the properties of
|
| 188 |
+
the output Tensors are.
|
| 189 |
+
|
| 190 |
+
The abstract implementation has the same signature as the operator.
|
| 191 |
+
It is run for both FakeTensors and meta tensors. To write an abstract
|
| 192 |
+
implementation, assume that all Tensor inputs to the operator are
|
| 193 |
+
regular CPU/CUDA/Meta tensors, but they do not have storage, and
|
| 194 |
+
you are trying to return regular CPU/CUDA/Meta tensor(s) as output.
|
| 195 |
+
The abstract implementation must consist of only PyTorch operations
|
| 196 |
+
(and may not directly access the storage or data of any input or
|
| 197 |
+
intermediate Tensors).
|
| 198 |
+
|
| 199 |
+
This API may be used as a decorator (see examples).
|
| 200 |
+
|
| 201 |
+
For a detailed guide on custom ops, please see
|
| 202 |
+
https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk
|
| 203 |
+
|
| 204 |
+
Examples::
|
| 205 |
+
>>> import numpy as np
|
| 206 |
+
>>> from torch import Tensor
|
| 207 |
+
>>>
|
| 208 |
+
>>> # Example 1: an operator without data-dependent output shape
|
| 209 |
+
>>> @torch._custom_ops.custom_op("mylibrary::custom_linear")
|
| 210 |
+
>>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor:
|
| 211 |
+
>>> raise NotImplementedError
|
| 212 |
+
>>>
|
| 213 |
+
>>> @torch._custom_ops.impl_abstract("mylibrary::custom_linear")
|
| 214 |
+
>>> def custom_linear_abstract(x, weight):
|
| 215 |
+
>>> assert x.dim() == 2
|
| 216 |
+
>>> assert weight.dim() == 2
|
| 217 |
+
>>> assert bias.dim() == 1
|
| 218 |
+
>>> assert x.shape[1] == weight.shape[1]
|
| 219 |
+
>>> assert weight.shape[0] == bias.shape[0]
|
| 220 |
+
>>> assert x.device == weight.device
|
| 221 |
+
>>>
|
| 222 |
+
>>> return (x @ weight.t()) + bias
|
| 223 |
+
>>>
|
| 224 |
+
>>> # Example 2: an operator with data-dependent output shape
|
| 225 |
+
>>> @torch._custom_ops.custom_op('mylibrary::custom_nonzero')
|
| 226 |
+
>>> def custom_nonzero(x: Tensor) -> Tensor:
|
| 227 |
+
>>> ...
|
| 228 |
+
>>>
|
| 229 |
+
>>> @torch._custom_ops.impl_abstract("mylibrary::custom_nonzero")
|
| 230 |
+
>>> def custom_nonzero_abstract(x):
|
| 231 |
+
>>> # Number of nonzero-elements is data-dependent.
|
| 232 |
+
>>> # Since we cannot peek at the data in an abstract impl,
|
| 233 |
+
>>> # we use the ctx object to construct a new symint that
|
| 234 |
+
>>> # represents the data-dependent size.
|
| 235 |
+
>>> ctx = torch._custom_ops.get_ctx()
|
| 236 |
+
>>> nnz = ctx.create_unbacked_symint()
|
| 237 |
+
>>> shape = [x.dim(), nnz]
|
| 238 |
+
>>> result = x.new_empty(shape, dtype=torch.long)
|
| 239 |
+
>>> return result
|
| 240 |
+
>>>
|
| 241 |
+
>>> @torch._custom_ops.impl("mylibrary::custom_nonzero")
|
| 242 |
+
>>> def custom_nonzero_impl(x):
|
| 243 |
+
>>> x_np = to_numpy(x)
|
| 244 |
+
>>> res = np.stack(np.nonzero(x_np), axis=1)
|
| 245 |
+
>>> # unbacked symbolic ints in PyTorch must be >= 2, so we
|
| 246 |
+
>>> # constrain the range to at least 2
|
| 247 |
+
>>> if res.shape[0] <= 1:
|
| 248 |
+
>>> raise RuntimeError("not supported")
|
| 249 |
+
>>> return torch.tensor(res, device=x.device)
|
| 250 |
+
|
| 251 |
+
"""
|
| 252 |
+
import torch.library
|
| 253 |
+
|
| 254 |
+
return torch.library.register_fake(qualname, func, _stacklevel=2)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def impl_save_for_backward(qualname, *, func=None):
|
| 258 |
+
r"""Register a function that tells us what to save for backward.
|
| 259 |
+
|
| 260 |
+
Please see :func:`impl_backward` for more details.
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
def inner(func):
|
| 264 |
+
custom_op = _find_custom_op(qualname, also_check_torch_library=True)
|
| 265 |
+
custom_op.impl_save_for_backward(_stacklevel=3)(func)
|
| 266 |
+
return func
|
| 267 |
+
|
| 268 |
+
if func is None:
|
| 269 |
+
return inner
|
| 270 |
+
return inner(func)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def impl_backward(qualname, output_differentiability=None, *, func=None):
|
| 274 |
+
r"""Registers a backward formula for an operator.
|
| 275 |
+
|
| 276 |
+
In order for an operator to work with autograd, you need to register
|
| 277 |
+
a backward formula. There are two pieces to this:
|
| 278 |
+
1. You must give us a function to specify what to save for backward.
|
| 279 |
+
Call this the "save for backward" function.
|
| 280 |
+
2. You must give us a function that computes gradients. Call this the
|
| 281 |
+
"backward" function.
|
| 282 |
+
|
| 283 |
+
Use `impl_save_for_backward` to define a "save for backward" function
|
| 284 |
+
that specifies what gets saved for backward. The function should accept
|
| 285 |
+
two arguments ``(inputs, output)`` and return the quantities to be saved
|
| 286 |
+
for backward.
|
| 287 |
+
|
| 288 |
+
During runtime, when you call the operator in a forwards pass, PyTorch
|
| 289 |
+
will invoke the "save for backward" function with the inputs and output
|
| 290 |
+
of the operator.
|
| 291 |
+
|
| 292 |
+
Use `impl_backward` to define the "backward" function. The backward
|
| 293 |
+
function must accept ``(ctx, saved, *grads)``:
|
| 294 |
+
- ``ctx`` is a context object where we may provide information
|
| 295 |
+
- ``saved`` is exactly what gets returned from the "save for backward"
|
| 296 |
+
function
|
| 297 |
+
- ``grads`` is one or more gradients. The number of gradients matches
|
| 298 |
+
the number of outputs of the operator.
|
| 299 |
+
|
| 300 |
+
The backward function must return a dict that maps the name of
|
| 301 |
+
an input to the operator to its corresponding gradient. All inputs that
|
| 302 |
+
were declared to be Tensors in the operator definition must be accounted
|
| 303 |
+
for in the dict. The gradient may be a Tensor or None.
|
| 304 |
+
|
| 305 |
+
For a detailed guide on custom ops, please see
|
| 306 |
+
https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk
|
| 307 |
+
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def inner(func):
|
| 311 |
+
custom_op = _find_custom_op(qualname, also_check_torch_library=True)
|
| 312 |
+
custom_op.impl_backward(output_differentiability, _stacklevel=3)(func)
|
| 313 |
+
return func
|
| 314 |
+
|
| 315 |
+
if func is None:
|
| 316 |
+
return inner
|
| 317 |
+
return inner(func)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _destroy(qualname):
|
| 321 |
+
"""De-registers a custom op. For testing purposes only"""
|
| 322 |
+
custom_op = _find_custom_op(qualname)
|
| 323 |
+
custom_op._destroy()
|
parrot/lib/python3.10/site-packages/torch/_refs/__init__.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
parrot/lib/python3.10/site-packages/torch/_refs/__pycache__/_conversions.cpython-310.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/_refs/__pycache__/fft.cpython-310.pyc
ADDED
|
Binary file (16 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/_refs/_conversions.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch._prims_common as utils
|
| 4 |
+
|
| 5 |
+
# Utilities should come BEFORE this import
|
| 6 |
+
from torch._decomp import register_decomposition
|
| 7 |
+
|
| 8 |
+
from torch._prims_common import TensorLikeType
|
| 9 |
+
from torch._prims_common.wrappers import out_wrapper
|
| 10 |
+
from torch._refs import _broadcast_shapes
|
| 11 |
+
|
| 12 |
+
# Data conversion references.
|
| 13 |
+
#
|
| 14 |
+
# Note: this module breaks the usual _refs to torch naming scheme where
|
| 15 |
+
# _refs.foo.bar is a ref for torch.foo.bar. The following definitions are not
|
| 16 |
+
# part of _refs/__init__.py to avoid name clashes with Python builtin types
|
| 17 |
+
# (like int).
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
# dtypes
|
| 21 |
+
"bfloat16",
|
| 22 |
+
"bool",
|
| 23 |
+
"byte",
|
| 24 |
+
"cdouble",
|
| 25 |
+
"cfloat",
|
| 26 |
+
"chalf",
|
| 27 |
+
"char",
|
| 28 |
+
"double",
|
| 29 |
+
"float",
|
| 30 |
+
"half",
|
| 31 |
+
"int",
|
| 32 |
+
"long",
|
| 33 |
+
"short",
|
| 34 |
+
# misc
|
| 35 |
+
"complex",
|
| 36 |
+
"polar",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _make_conversion_method(name: str, dtype: torch.dtype):
|
| 41 |
+
def fn(
|
| 42 |
+
self: TensorLikeType, memory_format: torch.memory_format = torch.preserve_format
|
| 43 |
+
) -> TensorLikeType:
|
| 44 |
+
return self.to(dtype, memory_format=memory_format) # type: ignore[call-overload]
|
| 45 |
+
|
| 46 |
+
fn.__name__ = name
|
| 47 |
+
return fn
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
bfloat16 = _make_conversion_method("bfloat16", torch.bfloat16)
|
| 51 |
+
|
| 52 |
+
bool = _make_conversion_method("bool", torch.bool)
|
| 53 |
+
|
| 54 |
+
byte = _make_conversion_method("byte", torch.uint8)
|
| 55 |
+
|
| 56 |
+
cdouble = _make_conversion_method("cdouble", torch.cdouble)
|
| 57 |
+
|
| 58 |
+
cfloat = _make_conversion_method("cfloat", torch.cfloat)
|
| 59 |
+
|
| 60 |
+
chalf = _make_conversion_method("chalf", torch.complex32)
|
| 61 |
+
|
| 62 |
+
char = _make_conversion_method("char", torch.int8)
|
| 63 |
+
|
| 64 |
+
double = _make_conversion_method("double", torch.double)
|
| 65 |
+
|
| 66 |
+
float = _make_conversion_method("float", torch.float)
|
| 67 |
+
|
| 68 |
+
half = _make_conversion_method("half", torch.half)
|
| 69 |
+
|
| 70 |
+
int = _make_conversion_method("int", torch.int)
|
| 71 |
+
|
| 72 |
+
long = _make_conversion_method("long", torch.long)
|
| 73 |
+
|
| 74 |
+
short = _make_conversion_method("short", torch.short)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@register_decomposition(torch._ops.ops.aten.complex)
|
| 78 |
+
# Note: complex has type promotion tests disabled due to different semantics.
|
| 79 |
+
# exact_dtype is for compat with complex_check_dtype from core.
|
| 80 |
+
@out_wrapper(exact_dtype=True)
|
| 81 |
+
def complex(real: TensorLikeType, imag: TensorLikeType) -> TensorLikeType:
|
| 82 |
+
allowed_dtypes = (torch.float32, torch.float64, torch.float16)
|
| 83 |
+
torch._check(
|
| 84 |
+
real.dtype in allowed_dtypes and imag.dtype in allowed_dtypes,
|
| 85 |
+
lambda: (
|
| 86 |
+
f"Expected both inputs to be Half, Float or Double tensors but got "
|
| 87 |
+
f"{real.dtype} and {imag.dtype}"
|
| 88 |
+
),
|
| 89 |
+
)
|
| 90 |
+
torch._check(
|
| 91 |
+
real.dtype == imag.dtype,
|
| 92 |
+
lambda: (
|
| 93 |
+
f"Expected object of scalar type {real.dtype} but got "
|
| 94 |
+
f"scalar type {imag.dtype} for second argument"
|
| 95 |
+
),
|
| 96 |
+
)
|
| 97 |
+
result_dtype = utils.corresponding_complex_dtype(real.dtype) # type: ignore[arg-type]
|
| 98 |
+
common_shape = _broadcast_shapes(real.shape, imag.shape)
|
| 99 |
+
result = real.new_empty(
|
| 100 |
+
common_shape,
|
| 101 |
+
dtype=result_dtype,
|
| 102 |
+
layout=real.layout,
|
| 103 |
+
device=real.device,
|
| 104 |
+
# pin_memory=real.is_pinned(), # NYI
|
| 105 |
+
)
|
| 106 |
+
result.real = real
|
| 107 |
+
result.imag = imag
|
| 108 |
+
return result
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@register_decomposition(torch._ops.ops.aten.polar)
|
| 112 |
+
# Note: polar has type promotion tests disabled due to different semantics.
|
| 113 |
+
# exact_dtype is for compat with complex_check_dtype from core.
|
| 114 |
+
@out_wrapper(exact_dtype=True)
|
| 115 |
+
def polar(abs: TensorLikeType, angle: TensorLikeType) -> TensorLikeType:
|
| 116 |
+
result = torch.complex(abs, angle)
|
| 117 |
+
result.real = abs * torch.cos(angle)
|
| 118 |
+
result.imag = abs * torch.sin(angle)
|
| 119 |
+
return result
|
parrot/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from functools import partial
|
| 3 |
+
|
| 4 |
+
from typing import List, Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
import torch._prims as prims
|
| 9 |
+
|
| 10 |
+
import torch._prims_common as utils
|
| 11 |
+
import torch._refs as refs
|
| 12 |
+
import torch._refs.linalg as linalg
|
| 13 |
+
from torch import Tensor
|
| 14 |
+
from torch._prims_common import (
|
| 15 |
+
check_fp_or_complex,
|
| 16 |
+
check_is_matrix,
|
| 17 |
+
Dim,
|
| 18 |
+
DimsType,
|
| 19 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND,
|
| 20 |
+
IntLike,
|
| 21 |
+
NumberType,
|
| 22 |
+
TensorLikeType,
|
| 23 |
+
)
|
| 24 |
+
from torch._prims_common.wrappers import (
|
| 25 |
+
_maybe_convert_to_dtype,
|
| 26 |
+
elementwise_type_promotion_wrapper,
|
| 27 |
+
out_wrapper,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
__all__ = [
|
| 32 |
+
"diagonal",
|
| 33 |
+
"matrix_norm",
|
| 34 |
+
"norm",
|
| 35 |
+
"svd",
|
| 36 |
+
"svdvals",
|
| 37 |
+
"vector_norm",
|
| 38 |
+
"vecdot",
|
| 39 |
+
"cross",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _check_norm_dtype(dtype: Optional[torch.dtype], x_dtype: torch.dtype, fn_name: str):
|
| 44 |
+
"""
|
| 45 |
+
Checks related to the dtype kwarg in `linalg.*norm` functions
|
| 46 |
+
"""
|
| 47 |
+
if dtype is not None:
|
| 48 |
+
torch._check(
|
| 49 |
+
utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype),
|
| 50 |
+
lambda: f"{fn_name}: dtype should be floating point or complex. Got {dtype}",
|
| 51 |
+
)
|
| 52 |
+
torch._check(
|
| 53 |
+
utils.is_complex_dtype(dtype) == utils.is_complex_dtype(x_dtype),
|
| 54 |
+
lambda: "{fn_name}: dtype should be {d} for {d} inputs. Got {dtype}".format(
|
| 55 |
+
fn_name=fn_name,
|
| 56 |
+
d="complex" if utils.is_complex_dtype(x_dtype) else "real",
|
| 57 |
+
dtype=dtype,
|
| 58 |
+
),
|
| 59 |
+
)
|
| 60 |
+
torch._check(
|
| 61 |
+
utils.get_higher_dtype(dtype, x_dtype) == dtype,
|
| 62 |
+
lambda: f"{fn_name}: the dtype of the input ({x_dtype}) should be convertible "
|
| 63 |
+
"without narrowing to the specified dtype ({dtype})",
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
import operator
|
| 68 |
+
|
| 69 |
+
# Utilities should come BEFORE this import
|
| 70 |
+
from torch._decomp import register_decomposition
|
| 71 |
+
from torch._decomp.decompositions import pw_cast_for_opmath
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@register_decomposition(torch._ops.ops.aten.linalg_cross)
|
| 75 |
+
@out_wrapper()
|
| 76 |
+
@pw_cast_for_opmath
|
| 77 |
+
def cross(a: Tensor, b: Tensor, dim: int = -1):
|
| 78 |
+
torch._check(
|
| 79 |
+
a.ndim == b.ndim,
|
| 80 |
+
lambda: "linalg.cross: inputs must have the same number of dimensions.",
|
| 81 |
+
)
|
| 82 |
+
torch._check(
|
| 83 |
+
a.size(dim) == 3 and b.size(dim) == 3,
|
| 84 |
+
lambda: f"linalg.cross: inputs dim {dim} must have length 3, got {a.size(dim)} and {b.size(dim)}",
|
| 85 |
+
)
|
| 86 |
+
a, b = torch.broadcast_tensors(a, b)
|
| 87 |
+
dim = utils.canonicalize_dim(a.ndim, dim)
|
| 88 |
+
idx = torch.arange(3, device=a.device)
|
| 89 |
+
return a.index_select(dim, (idx + 1) % 3) * b.index_select(
|
| 90 |
+
dim, (idx + 2) % 3
|
| 91 |
+
) - a.index_select(dim, (idx + 2) % 3) * b.index_select(dim, (idx + 1) % 3)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def diagonal(
|
| 95 |
+
input: TensorLikeType,
|
| 96 |
+
*,
|
| 97 |
+
offset: int = 0,
|
| 98 |
+
dim1: int = -2,
|
| 99 |
+
dim2: int = -1,
|
| 100 |
+
) -> TensorLikeType:
|
| 101 |
+
return torch.diagonal(input, offset=offset, dim1=dim1, dim2=dim2)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@register_decomposition(torch._ops.ops.aten.linalg_vector_norm)
|
| 105 |
+
@out_wrapper(exact_dtype=True)
|
| 106 |
+
def vector_norm(
|
| 107 |
+
x: TensorLikeType,
|
| 108 |
+
ord: Union[float, int] = 2,
|
| 109 |
+
dim: Optional[DimsType] = None,
|
| 110 |
+
keepdim: bool = False,
|
| 111 |
+
*,
|
| 112 |
+
dtype: Optional[torch.dtype] = None,
|
| 113 |
+
) -> Tensor:
|
| 114 |
+
from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
|
| 115 |
+
|
| 116 |
+
# Checks
|
| 117 |
+
check_fp_or_complex(x.dtype, "linalg.vector_norm")
|
| 118 |
+
|
| 119 |
+
if isinstance(dim, Dim):
|
| 120 |
+
dim = [dim] # type: ignore[assignment]
|
| 121 |
+
|
| 122 |
+
if guard_size_oblivious(x.numel() == 0) and (ord < 0.0 or ord == float("inf")):
|
| 123 |
+
torch._check(
|
| 124 |
+
dim is not None and len(dim) != 0,
|
| 125 |
+
lambda: f"linalg.vector_norm cannot compute the {ord} norm on an empty tensor "
|
| 126 |
+
"because the operation does not have an identity",
|
| 127 |
+
)
|
| 128 |
+
shape = x.shape
|
| 129 |
+
assert dim is not None # mypy does not seem to be able to see through check?
|
| 130 |
+
for d in dim:
|
| 131 |
+
torch._check(
|
| 132 |
+
shape[d] != 0,
|
| 133 |
+
lambda: f"linalg.vector_norm cannot compute the {ord} norm on the "
|
| 134 |
+
f"dimension {d} because this dimension is empty and the "
|
| 135 |
+
"operation does not have an identity",
|
| 136 |
+
)
|
| 137 |
+
_check_norm_dtype(dtype, x.dtype, "linalg.vector_norm")
|
| 138 |
+
|
| 139 |
+
computation_dtype, result_dtype = utils.reduction_dtypes(
|
| 140 |
+
x, utils.REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT, dtype
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
to_result_dtype = partial(_maybe_convert_to_dtype, dtype=result_dtype)
|
| 144 |
+
|
| 145 |
+
# Implementation
|
| 146 |
+
if ord == 0.0:
|
| 147 |
+
return torch.sum(torch.ne(x, 0.0), dim=dim, keepdim=keepdim, dtype=result_dtype)
|
| 148 |
+
elif ord == float("inf"):
|
| 149 |
+
return to_result_dtype(torch.amax(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type]
|
| 150 |
+
elif ord == float("-inf"):
|
| 151 |
+
return to_result_dtype(torch.amin(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type]
|
| 152 |
+
else:
|
| 153 |
+
# From here on the computation dtype is important as the reduction is non-trivial
|
| 154 |
+
x = _maybe_convert_to_dtype(x, computation_dtype) # type: ignore[assignment]
|
| 155 |
+
reduce_sum = partial(torch.sum, dim=dim, keepdim=keepdim)
|
| 156 |
+
|
| 157 |
+
is_ord_even = ord % 2 == 0 if isinstance(ord, IntLike) else ord % 2.0 == 0.0
|
| 158 |
+
if not (is_ord_even and utils.is_float_dtype(x.dtype)):
|
| 159 |
+
x = torch.abs(x)
|
| 160 |
+
return to_result_dtype(torch.pow(reduce_sum(torch.pow(x, ord)), 1.0 / ord)) # type: ignore[return-value]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _backshift_permutation(dim0, dim1, ndim):
|
| 164 |
+
# Auxiliary function for matrix_norm
|
| 165 |
+
# Computes the permutation that moves the two given dimensions to the back
|
| 166 |
+
ret = [i for i in range(ndim) if i != dim0 and i != dim1]
|
| 167 |
+
ret.extend((dim0, dim1))
|
| 168 |
+
return ret
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _inverse_permutation(perm):
|
| 172 |
+
# Given a permutation, returns its inverse. It's equivalent to argsort on an array
|
| 173 |
+
return [i for i, j in sorted(enumerate(perm), key=operator.itemgetter(1))]
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# CompositeImplicitAutograd
|
| 177 |
+
@out_wrapper(exact_dtype=True)
|
| 178 |
+
def matrix_norm(
|
| 179 |
+
A: TensorLikeType,
|
| 180 |
+
ord: Union[float, str] = "fro",
|
| 181 |
+
dim: DimsType = (-2, -1),
|
| 182 |
+
keepdim: bool = False,
|
| 183 |
+
*,
|
| 184 |
+
dtype: Optional[torch.dtype] = None,
|
| 185 |
+
) -> TensorLikeType:
|
| 186 |
+
# shape
|
| 187 |
+
check_is_matrix(A, "linalg.matrix_norm")
|
| 188 |
+
# dim
|
| 189 |
+
dim = utils.canonicalize_dims(A.ndim, dim)
|
| 190 |
+
if isinstance(dim, Dim):
|
| 191 |
+
dim = (dim,) # type: ignore[assignment]
|
| 192 |
+
torch._check(
|
| 193 |
+
len(dim) == 2, lambda: "linalg.matrix_norm: dim must be a 2-tuple. Got {dim}"
|
| 194 |
+
)
|
| 195 |
+
torch._check(
|
| 196 |
+
dim[0] != dim[1],
|
| 197 |
+
lambda: "linalg.matrix_norm: dims must be different. Got ({dim[0]}, {dim[1]})",
|
| 198 |
+
)
|
| 199 |
+
# dtype arg
|
| 200 |
+
_check_norm_dtype(dtype, A.dtype, "linalg.matrix_norm")
|
| 201 |
+
|
| 202 |
+
if isinstance(ord, str):
|
| 203 |
+
# ord
|
| 204 |
+
torch._check(
|
| 205 |
+
ord in ("fro", "nuc"),
|
| 206 |
+
lambda: "linalg.matrix_norm: Order {ord} not supported.",
|
| 207 |
+
)
|
| 208 |
+
# dtype
|
| 209 |
+
check_fp_or_complex(
|
| 210 |
+
A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != "nuc"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
if ord == "fro":
|
| 214 |
+
return vector_norm(A, 2, dim, keepdim, dtype=dtype)
|
| 215 |
+
else: # ord == "nuc"
|
| 216 |
+
if dtype is not None:
|
| 217 |
+
A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
|
| 218 |
+
perm = _backshift_permutation(dim[0], dim[1], A.ndim)
|
| 219 |
+
result = torch.sum(svdvals(prims.transpose(A, perm)), -1, keepdim)
|
| 220 |
+
if keepdim:
|
| 221 |
+
inv_perm = _inverse_permutation(perm)
|
| 222 |
+
result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
|
| 223 |
+
return result
|
| 224 |
+
else:
|
| 225 |
+
# ord
|
| 226 |
+
abs_ord = abs(ord)
|
| 227 |
+
torch._check(
|
| 228 |
+
abs_ord in (2, 1, float("inf")),
|
| 229 |
+
lambda: "linalg.matrix_norm: Order {ord} not supported.",
|
| 230 |
+
)
|
| 231 |
+
# dtype
|
| 232 |
+
check_fp_or_complex(
|
| 233 |
+
A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != 2
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
max_min = partial(torch.amax if ord > 0.0 else torch.amin, keepdim=keepdim)
|
| 237 |
+
|
| 238 |
+
if abs_ord == 2.0:
|
| 239 |
+
if dtype is not None:
|
| 240 |
+
A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
|
| 241 |
+
perm = _backshift_permutation(dim[0], dim[1], A.ndim)
|
| 242 |
+
result = max_min(svdvals(prims.transpose(A, perm)), dim=-1)
|
| 243 |
+
if keepdim:
|
| 244 |
+
inv_perm = _inverse_permutation(perm)
|
| 245 |
+
result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
|
| 246 |
+
return result
|
| 247 |
+
else: # 1, -1, inf, -inf
|
| 248 |
+
dim0, dim1 = dim
|
| 249 |
+
if abs_ord == float("inf"):
|
| 250 |
+
dim0, dim1 = dim1, dim0
|
| 251 |
+
if not keepdim and (dim0 < dim1):
|
| 252 |
+
dim1 -= 1
|
| 253 |
+
return max_min(
|
| 254 |
+
vector_norm(A, 1.0, dim=dim0, keepdim=keepdim, dtype=dtype), dim1
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# CompositeImplicitAutograd
|
| 259 |
+
@out_wrapper(exact_dtype=True)
|
| 260 |
+
def norm(
|
| 261 |
+
A: TensorLikeType,
|
| 262 |
+
ord: Optional[Union[float, str]] = None,
|
| 263 |
+
dim: Optional[DimsType] = None,
|
| 264 |
+
keepdim: bool = False,
|
| 265 |
+
*,
|
| 266 |
+
dtype: Optional[torch.dtype] = None,
|
| 267 |
+
) -> TensorLikeType:
|
| 268 |
+
if dim is not None:
|
| 269 |
+
if isinstance(dim, Dim):
|
| 270 |
+
dim = (dim,) # type: ignore[assignment]
|
| 271 |
+
torch._check(
|
| 272 |
+
len(dim) in (1, 2),
|
| 273 |
+
lambda: "linalg.norm: If dim is specified, it must be of length 1 or 2. Got {dim}",
|
| 274 |
+
)
|
| 275 |
+
elif ord is not None:
|
| 276 |
+
torch._check(
|
| 277 |
+
A.ndim in (1, 2),
|
| 278 |
+
lambda: "linalg.norm: If dim is not specified but ord is, the input must be 1D or 2D. Got {A.ndim}D",
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
if ord is not None and (
|
| 282 |
+
(dim is not None and len(dim) == 2) or (dim is None and A.ndim == 2)
|
| 283 |
+
):
|
| 284 |
+
if dim is None:
|
| 285 |
+
dim = (0, 1)
|
| 286 |
+
return matrix_norm(A, ord, dim, keepdim, dtype=dtype)
|
| 287 |
+
else:
|
| 288 |
+
if ord is None:
|
| 289 |
+
ord = 2.0
|
| 290 |
+
return vector_norm(A, ord, dim, keepdim, dtype=dtype)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# CompositeImplicitAutograd
|
| 294 |
+
@out_wrapper("U", "S", "Vh", exact_dtype=True)
|
| 295 |
+
def svd(A: TensorLikeType, full_matrices: bool = True) -> Tuple[Tensor, Tensor, Tensor]:
|
| 296 |
+
return prims.svd(A, full_matrices=full_matrices)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# CompositeImplicitAutograd
|
| 300 |
+
@out_wrapper(exact_dtype=True)
|
| 301 |
+
def svdvals(A: TensorLikeType) -> Tensor:
|
| 302 |
+
return svd(A, full_matrices=False)[1]
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# CompositeImplicitAutograd
|
| 306 |
+
@out_wrapper()
|
| 307 |
+
@elementwise_type_promotion_wrapper(
|
| 308 |
+
type_promoting_args=("x", "y"),
|
| 309 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 310 |
+
)
|
| 311 |
+
def vecdot(x: Tensor, y: Tensor, dim: int = -1) -> Tensor:
|
| 312 |
+
check_fp_or_complex(x.dtype, "linalg.vecdot")
|
| 313 |
+
return (x.conj() * y).sum(dim=dim)
|
parrot/lib/python3.10/site-packages/torch/_refs/linalg/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (9.07 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/_refs/nn/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
__all__: List[str] = []
|
parrot/lib/python3.10/site-packages/torch/_refs/nn/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (257 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py
ADDED
|
@@ -0,0 +1,1238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
from functools import wraps
|
| 4 |
+
from typing import Callable, Optional, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch._prims as prims
|
| 8 |
+
import torch._prims_common as utils
|
| 9 |
+
import torch._refs as refs
|
| 10 |
+
from torch._decomp import register_decomposition
|
| 11 |
+
from torch._prims_common import (
|
| 12 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND,
|
| 13 |
+
NumberType,
|
| 14 |
+
ShapeType,
|
| 15 |
+
TensorLike,
|
| 16 |
+
TensorLikeType,
|
| 17 |
+
)
|
| 18 |
+
from torch._prims_common.wrappers import (
|
| 19 |
+
elementwise_type_promotion_wrapper,
|
| 20 |
+
elementwise_unary_scalar_wrapper,
|
| 21 |
+
out_wrapper,
|
| 22 |
+
)
|
| 23 |
+
from torch._refs import _make_inplace
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"alpha_dropout",
|
| 27 |
+
"celu",
|
| 28 |
+
"celu_",
|
| 29 |
+
"dropout",
|
| 30 |
+
"elu",
|
| 31 |
+
"elu_",
|
| 32 |
+
"gelu",
|
| 33 |
+
"glu",
|
| 34 |
+
"group_norm",
|
| 35 |
+
"hardshrink",
|
| 36 |
+
"hardtanh",
|
| 37 |
+
"hinge_embedding_loss",
|
| 38 |
+
"huber_loss",
|
| 39 |
+
"l1_loss",
|
| 40 |
+
"layer_norm",
|
| 41 |
+
"leaky_relu",
|
| 42 |
+
"log_softmax",
|
| 43 |
+
"margin_ranking_loss",
|
| 44 |
+
"mish",
|
| 45 |
+
"mish_",
|
| 46 |
+
"mse_loss",
|
| 47 |
+
"nll_loss",
|
| 48 |
+
"pairwise_distance",
|
| 49 |
+
"pdist",
|
| 50 |
+
"poisson_nll_loss",
|
| 51 |
+
"prelu",
|
| 52 |
+
"relu",
|
| 53 |
+
"relu6",
|
| 54 |
+
"selu",
|
| 55 |
+
"selu_",
|
| 56 |
+
"smooth_l1_loss",
|
| 57 |
+
"softmax",
|
| 58 |
+
"softmin",
|
| 59 |
+
"softplus",
|
| 60 |
+
"softshrink",
|
| 61 |
+
"tanhshrink",
|
| 62 |
+
"threshold",
|
| 63 |
+
"threshold_",
|
| 64 |
+
"triplet_margin_loss",
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
Tensor = torch.Tensor
|
| 68 |
+
aten = torch._ops.ops.aten
|
| 69 |
+
DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _dropout_helper(
|
| 73 |
+
self: TensorLikeType,
|
| 74 |
+
val: float,
|
| 75 |
+
) -> TensorLikeType:
|
| 76 |
+
"""
|
| 77 |
+
Helper function for all dropout-type operators. During training,
|
| 78 |
+
some of the elements of the input tensor are randomly masked.
|
| 79 |
+
|
| 80 |
+
Returns the masked tensor of the boolean values.
|
| 81 |
+
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
return (
|
| 85 |
+
refs._uniform_helper(
|
| 86 |
+
self.shape, low=0.0, high=1.0, dtype=torch.float32, device=self.device
|
| 87 |
+
)
|
| 88 |
+
< val
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@register_decomposition(aten.alpha_dropout)
|
| 93 |
+
def alpha_dropout(
|
| 94 |
+
self: TensorLikeType, p: float = 0.5, training: bool = False, inplace: bool = False
|
| 95 |
+
) -> TensorLikeType:
|
| 96 |
+
if inplace:
|
| 97 |
+
raise NotImplementedError
|
| 98 |
+
|
| 99 |
+
if not training:
|
| 100 |
+
return self
|
| 101 |
+
|
| 102 |
+
torch._check(
|
| 103 |
+
p <= 1 and p >= 0,
|
| 104 |
+
lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
if p == 1:
|
| 108 |
+
return torch.zeros_like(self)
|
| 109 |
+
|
| 110 |
+
if p == 0:
|
| 111 |
+
return self
|
| 112 |
+
|
| 113 |
+
dropout_mask = _dropout_helper(self, 1 - p)
|
| 114 |
+
|
| 115 |
+
# From paper: Self-Normalizing Neural Networks (https://arxiv.org/pdf/1706.02515.pdf)
|
| 116 |
+
# alpha = - SELU.alpha * SELU.scale, here
|
| 117 |
+
# SELU.alpha = 1.6732632423543772848170429916717 and
|
| 118 |
+
# SELU.scale = 1.0507009873554804934193349852946
|
| 119 |
+
alpha = -1.7580993408473766
|
| 120 |
+
|
| 121 |
+
a = 1.0 / math.sqrt((alpha * alpha * p + 1) * (1 - p))
|
| 122 |
+
b = torch.logical_not(dropout_mask)
|
| 123 |
+
b = b * (alpha * a) + alpha * a * p
|
| 124 |
+
dropout_mask = a * dropout_mask
|
| 125 |
+
|
| 126 |
+
return self * dropout_mask + b
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _inplace_wrapper(fn):
|
| 130 |
+
"""
|
| 131 |
+
Given a nn.functional non-linearity, implements its `inplace: bool` argument
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
# nb. We use the name of the first argument used in the unary references
|
| 135 |
+
@wraps(fn)
|
| 136 |
+
def _fn(a, *args, inplace=False, **kwargs):
|
| 137 |
+
if inplace:
|
| 138 |
+
torch._check(
|
| 139 |
+
"out" not in kwargs,
|
| 140 |
+
lambda: "Cannot set inplace=True and pass out= at the same time",
|
| 141 |
+
)
|
| 142 |
+
return fn(a, *args, inplace=False, out=a, **kwargs)
|
| 143 |
+
else:
|
| 144 |
+
return fn(a, *args, inplace=False, **kwargs)
|
| 145 |
+
|
| 146 |
+
return _fn
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# celu is implemented specially because it has an alpha argument
|
| 150 |
+
# celu is very similar to elu
|
| 151 |
+
@register_decomposition(aten.celu)
|
| 152 |
+
@_inplace_wrapper
|
| 153 |
+
@out_wrapper()
|
| 154 |
+
@elementwise_type_promotion_wrapper(
|
| 155 |
+
type_promoting_args=("a",),
|
| 156 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 157 |
+
)
|
| 158 |
+
def celu(
|
| 159 |
+
a: TensorLikeType, alpha: Optional[NumberType] = None, inplace: bool = False
|
| 160 |
+
) -> TensorLikeType:
|
| 161 |
+
"""
|
| 162 |
+
Reference implementation of torch.nn.functional.celu
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
if inplace:
|
| 166 |
+
raise NotImplementedError
|
| 167 |
+
|
| 168 |
+
rhs: TensorLikeType
|
| 169 |
+
if alpha is not None:
|
| 170 |
+
python_type = utils.dtype_to_type(a.dtype)
|
| 171 |
+
if not utils.is_weakly_lesser_type(type(alpha), python_type):
|
| 172 |
+
msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!"
|
| 173 |
+
raise ValueError(msg)
|
| 174 |
+
rhs = alpha * torch.expm1(torch.true_divide(a, alpha)) # type: ignore[arg-type]
|
| 175 |
+
else:
|
| 176 |
+
rhs = torch.expm1(a)
|
| 177 |
+
|
| 178 |
+
return torch.where(a > 0, a, rhs)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@_inplace_wrapper
|
| 182 |
+
@out_wrapper()
|
| 183 |
+
def dropout(
|
| 184 |
+
a: TensorLikeType, p: float = 0.5, training: bool = True, inplace: bool = False
|
| 185 |
+
) -> TensorLikeType:
|
| 186 |
+
if inplace:
|
| 187 |
+
raise NotImplementedError
|
| 188 |
+
|
| 189 |
+
if not training:
|
| 190 |
+
return a
|
| 191 |
+
|
| 192 |
+
torch._check(
|
| 193 |
+
p <= 1 and p >= 0,
|
| 194 |
+
lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
if p == 1:
|
| 198 |
+
return torch.zeros_like(a)
|
| 199 |
+
|
| 200 |
+
if p == 0:
|
| 201 |
+
return a
|
| 202 |
+
|
| 203 |
+
scale = 1 / (1 - p)
|
| 204 |
+
dropout_mask = _dropout_helper(a, 1 - p)
|
| 205 |
+
|
| 206 |
+
return a * dropout_mask * scale
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@register_decomposition(aten.elu)
|
| 210 |
+
@_inplace_wrapper
|
| 211 |
+
@out_wrapper()
|
| 212 |
+
@elementwise_type_promotion_wrapper(
|
| 213 |
+
type_promoting_args=("a",),
|
| 214 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 215 |
+
)
|
| 216 |
+
def elu(
|
| 217 |
+
a: TensorLikeType,
|
| 218 |
+
alpha: NumberType = 1.0,
|
| 219 |
+
scale: NumberType = 1.0,
|
| 220 |
+
input_scale: NumberType = 1.0,
|
| 221 |
+
inplace: bool = False,
|
| 222 |
+
) -> TensorLikeType:
|
| 223 |
+
"""
|
| 224 |
+
Reference implementation of torch.nn.functional.elu
|
| 225 |
+
"""
|
| 226 |
+
if inplace:
|
| 227 |
+
raise NotImplementedError
|
| 228 |
+
|
| 229 |
+
# nb. This should be factored out into a can_cast aux function
|
| 230 |
+
python_type = utils.dtype_to_type(a.dtype)
|
| 231 |
+
torch._check(
|
| 232 |
+
utils.is_weakly_lesser_type(type(input_scale), python_type),
|
| 233 |
+
lambda: f"input_scale argument of type {type(input_scale)} cannot be safely cast to type {python_type}!",
|
| 234 |
+
)
|
| 235 |
+
torch._check(
|
| 236 |
+
utils.is_weakly_lesser_type(type(scale), python_type),
|
| 237 |
+
lambda: f"scale argument of type {type(scale)} cannot be safely cast to type {python_type}!",
|
| 238 |
+
)
|
| 239 |
+
torch._check(
|
| 240 |
+
utils.is_weakly_lesser_type(type(alpha), python_type),
|
| 241 |
+
lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!",
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
return torch.where(a > 0, scale * a, (alpha * scale) * torch.expm1(a * input_scale))
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@register_decomposition(aten.relu)
|
| 248 |
+
@_inplace_wrapper
|
| 249 |
+
@out_wrapper()
|
| 250 |
+
@elementwise_type_promotion_wrapper(
|
| 251 |
+
type_promoting_args=("a",),
|
| 252 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 253 |
+
)
|
| 254 |
+
def relu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
|
| 255 |
+
"""
|
| 256 |
+
Reference implementation of torch.nn.functional.relu
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
if inplace:
|
| 260 |
+
raise NotImplementedError
|
| 261 |
+
|
| 262 |
+
return torch.where(torch.le(a, 0), 0, a)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def group_norm(
|
| 266 |
+
input: Tensor,
|
| 267 |
+
num_groups: int,
|
| 268 |
+
weight: Optional[Tensor] = None,
|
| 269 |
+
bias: Optional[Tensor] = None,
|
| 270 |
+
eps: float = 1e-5,
|
| 271 |
+
) -> Tensor:
|
| 272 |
+
"""
|
| 273 |
+
Reference implementation of :func:`torch.nn.functional.group_norm`.
|
| 274 |
+
"""
|
| 275 |
+
torch._check(
|
| 276 |
+
input.ndim >= 2,
|
| 277 |
+
lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}",
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
batch_size = input.shape[0]
|
| 281 |
+
num_channels = input.shape[1]
|
| 282 |
+
torch._check(
|
| 283 |
+
num_channels % num_groups == 0,
|
| 284 |
+
lambda: "Expected number of channels in input to be divisible by num_groups, "
|
| 285 |
+
+ f"but got input of shape {input.shape} and num_groups = {num_groups}",
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# input shape is (N, C, *), so we flatten all inner dimensions except (N, C)
|
| 289 |
+
flattened_inner_size = 1
|
| 290 |
+
for dim_length in input.shape[2:]:
|
| 291 |
+
flattened_inner_size *= dim_length
|
| 292 |
+
|
| 293 |
+
return torch.native_group_norm(
|
| 294 |
+
input,
|
| 295 |
+
weight,
|
| 296 |
+
bias,
|
| 297 |
+
batch_size,
|
| 298 |
+
num_channels,
|
| 299 |
+
flattened_inner_size,
|
| 300 |
+
num_groups,
|
| 301 |
+
eps,
|
| 302 |
+
)[0]
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def layer_norm(
|
| 306 |
+
input: Tensor,
|
| 307 |
+
normalized_shape: ShapeType,
|
| 308 |
+
weight: Optional[Tensor] = None,
|
| 309 |
+
bias: Optional[Tensor] = None,
|
| 310 |
+
eps: float = 1e-5,
|
| 311 |
+
) -> Tensor:
|
| 312 |
+
"""
|
| 313 |
+
Reference implementation of :func:`torch.nn.functional.layer_norm`.
|
| 314 |
+
"""
|
| 315 |
+
return torch.native_layer_norm(input, normalized_shape, weight, bias, eps)[0]
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@register_decomposition(aten.leaky_relu)
|
| 319 |
+
@_inplace_wrapper
|
| 320 |
+
@out_wrapper()
|
| 321 |
+
@elementwise_type_promotion_wrapper(
|
| 322 |
+
type_promoting_args=("a",),
|
| 323 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 324 |
+
)
|
| 325 |
+
def leaky_relu(
|
| 326 |
+
a: TensorLikeType, negative_slope: float = 0.01, inplace: bool = False
|
| 327 |
+
) -> TensorLikeType:
|
| 328 |
+
"""
|
| 329 |
+
Reference implementation of torch.nn.functional.leaky_relu
|
| 330 |
+
"""
|
| 331 |
+
|
| 332 |
+
if inplace:
|
| 333 |
+
raise NotImplementedError
|
| 334 |
+
|
| 335 |
+
python_type = utils.dtype_to_type(a.dtype)
|
| 336 |
+
if not utils.is_weakly_lesser_type(type(negative_slope), python_type):
|
| 337 |
+
msg = f"negative_slope argument of type {type(negative_slope)} cannot be safely cast to type {python_type}!"
|
| 338 |
+
raise ValueError(msg)
|
| 339 |
+
return torch.where(torch.gt(a, 0), a, torch.mul(a, negative_slope))
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
@register_decomposition(aten.mish)
|
| 343 |
+
@_inplace_wrapper
|
| 344 |
+
@out_wrapper()
|
| 345 |
+
@elementwise_type_promotion_wrapper(
|
| 346 |
+
type_promoting_args=("a",),
|
| 347 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 348 |
+
)
|
| 349 |
+
def mish(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
|
| 350 |
+
"""
|
| 351 |
+
Reference implementation of torch.nn.functional.mish
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
if inplace:
|
| 355 |
+
raise NotImplementedError
|
| 356 |
+
return a * torch.tanh(torch.nn.functional.softplus(a))
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@register_decomposition(aten.selu)
|
| 360 |
+
@_inplace_wrapper
|
| 361 |
+
@out_wrapper()
|
| 362 |
+
@elementwise_type_promotion_wrapper(
|
| 363 |
+
type_promoting_args=("a",),
|
| 364 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 365 |
+
)
|
| 366 |
+
def selu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
|
| 367 |
+
"""
|
| 368 |
+
Reference implementation of torch.nn.functional.selu
|
| 369 |
+
"""
|
| 370 |
+
if inplace:
|
| 371 |
+
raise NotImplementedError
|
| 372 |
+
|
| 373 |
+
alpha = 1.6732632423543772848170429916717
|
| 374 |
+
scale = 1.0507009873554804934193349852946
|
| 375 |
+
|
| 376 |
+
rhs = alpha * torch.expm1(a)
|
| 377 |
+
|
| 378 |
+
return scale * torch.where(a > 0, a, rhs)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
# Forwarding alias: the functional variant doesn't support the out kwarg
|
| 382 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 383 |
+
def softmax(
|
| 384 |
+
a: TensorLikeType,
|
| 385 |
+
dim: Optional[int] = None,
|
| 386 |
+
_stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
|
| 387 |
+
dtype: Optional[torch.dtype] = None,
|
| 388 |
+
) -> TensorLikeType:
|
| 389 |
+
# The error is for compat with regular PyTorch, which has this behavior
|
| 390 |
+
# deprecated. For PrimTorch, it's fine to drop support for deprecated
|
| 391 |
+
# behavior because it requires explicit opt in. This error is to inform
|
| 392 |
+
# users how to update their calls.
|
| 393 |
+
torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
|
| 394 |
+
return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 398 |
+
def softmin(
|
| 399 |
+
a: TensorLikeType,
|
| 400 |
+
dim: Optional[int] = None,
|
| 401 |
+
_stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
|
| 402 |
+
dtype: Optional[torch.dtype] = None,
|
| 403 |
+
) -> TensorLikeType:
|
| 404 |
+
# The error is for compat with regular PyTorch, which has this behavior
|
| 405 |
+
# deprecated. For PrimTorch, it's fine to drop support for deprecated
|
| 406 |
+
# behavior because it requires explicit opt in. This error is to inform
|
| 407 |
+
# users how to update their calls.
|
| 408 |
+
torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
|
| 409 |
+
return torch.softmax(a=-a, dim=dim, dtype=dtype) # type: ignore[call-overload]
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
# softplus is implemented specially because it has beta and threshold arguments
|
| 413 |
+
@register_decomposition(aten.softplus)
|
| 414 |
+
@_inplace_wrapper
|
| 415 |
+
@out_wrapper()
|
| 416 |
+
@elementwise_type_promotion_wrapper(
|
| 417 |
+
type_promoting_args=("a",),
|
| 418 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 419 |
+
)
|
| 420 |
+
def softplus(
|
| 421 |
+
a: TensorLikeType,
|
| 422 |
+
beta: Optional[NumberType] = None,
|
| 423 |
+
threshold: NumberType = 20,
|
| 424 |
+
inplace: bool = False,
|
| 425 |
+
) -> TensorLikeType:
|
| 426 |
+
"""
|
| 427 |
+
Reference implementation of torch.nn.functional.softplus
|
| 428 |
+
"""
|
| 429 |
+
|
| 430 |
+
if inplace:
|
| 431 |
+
raise NotImplementedError
|
| 432 |
+
|
| 433 |
+
rhs: TensorLikeType
|
| 434 |
+
if beta is not None:
|
| 435 |
+
python_type = utils.dtype_to_type(a.dtype)
|
| 436 |
+
if not utils.is_weakly_lesser_type(type(beta), python_type):
|
| 437 |
+
msg = f"beta argument of type {type(beta)} cannot be safely cast to type {python_type}!"
|
| 438 |
+
raise ValueError(msg)
|
| 439 |
+
scaled_input = a * beta
|
| 440 |
+
rhs = torch.true_divide(torch.log1p(torch.exp(scaled_input)), beta) # type: ignore[arg-type]
|
| 441 |
+
|
| 442 |
+
else:
|
| 443 |
+
scaled_input = a
|
| 444 |
+
rhs = torch.log1p(torch.exp(scaled_input))
|
| 445 |
+
|
| 446 |
+
return torch.where(scaled_input > threshold, a, rhs)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
@aten.hardshrink.default.py_impl(DispatchKey.Autograd)
|
| 450 |
+
@register_decomposition(aten.hardshrink)
|
| 451 |
+
@out_wrapper()
|
| 452 |
+
def hardshrink(a: TensorLikeType, lambd: float = 0.5):
|
| 453 |
+
# Formula for reference,
|
| 454 |
+
# hardshrink(x) = x if x > lambd
|
| 455 |
+
# = x if x < -lambd
|
| 456 |
+
# = 0 otherwise
|
| 457 |
+
return torch.where(torch.abs(a) <= lambd, 0, a)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
@aten.softshrink.default.py_impl(DispatchKey.Autograd)
|
| 461 |
+
@register_decomposition(aten.softshrink)
|
| 462 |
+
@out_wrapper()
|
| 463 |
+
def softshrink(a: TensorLikeType, lambd: float = 0.5):
|
| 464 |
+
# Formula for reference,
|
| 465 |
+
# softshrink(x) = x - lambd if x > lambd
|
| 466 |
+
# = x + lambd if x < -lambd
|
| 467 |
+
# = 0 otherwise
|
| 468 |
+
torch._check(
|
| 469 |
+
lambd >= 0,
|
| 470 |
+
lambda: f"lambda must be greater or equal to 0, but found to be {lambd}",
|
| 471 |
+
)
|
| 472 |
+
# We implement this in one torch.where to generate better code in the backward
|
| 473 |
+
# see https://github.com/pytorch/pytorch/pull/107052#discussion_r1293748211
|
| 474 |
+
return torch.where(torch.abs(a) > lambd, a - torch.sign(a) * lambd, 0)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
# Losses
|
| 478 |
+
def _reduction_int_to_str(reduction: int) -> str:
|
| 479 |
+
from torch._decomp.decompositions import Reduction
|
| 480 |
+
|
| 481 |
+
if reduction == Reduction.NONE.value:
|
| 482 |
+
return "none"
|
| 483 |
+
elif reduction == Reduction.MEAN.value:
|
| 484 |
+
return "mean"
|
| 485 |
+
elif reduction == Reduction.SUM.value:
|
| 486 |
+
return "sum"
|
| 487 |
+
else:
|
| 488 |
+
raise ValueError(f"{reduction} is not a valid value for reduction")
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _apply_loss_reduction(loss: TensorLikeType, reduction: str) -> TensorLikeType:
|
| 492 |
+
if reduction == "sum":
|
| 493 |
+
return torch.sum(loss)
|
| 494 |
+
elif reduction == "mean":
|
| 495 |
+
return torch.mean(loss)
|
| 496 |
+
else: # reduction == "none"
|
| 497 |
+
return loss
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _check_reduction_value(reduction: str):
|
| 501 |
+
if reduction not in ("mean", "sum", "none"):
|
| 502 |
+
raise ValueError(f"{reduction} is not a valid value for reduction")
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# This helper function maps depreciated arguments, "size_average" and "reduce"
|
| 506 |
+
# to their corresponding "reduction" string argument
|
| 507 |
+
def _get_string_reduction_arg(
|
| 508 |
+
*, size_average: Optional[bool], reduce: Optional[bool]
|
| 509 |
+
) -> str:
|
| 510 |
+
if size_average is None:
|
| 511 |
+
size_average = True
|
| 512 |
+
if reduce is None:
|
| 513 |
+
reduce = True
|
| 514 |
+
if size_average and reduce:
|
| 515 |
+
ret = "mean"
|
| 516 |
+
elif reduce:
|
| 517 |
+
ret = "sum"
|
| 518 |
+
else:
|
| 519 |
+
ret = "none"
|
| 520 |
+
return ret
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 524 |
+
@elementwise_type_promotion_wrapper(
|
| 525 |
+
type_promoting_args=("input", "target"),
|
| 526 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
|
| 527 |
+
)
|
| 528 |
+
def l1_loss(
|
| 529 |
+
input: TensorLikeType,
|
| 530 |
+
target: TensorLikeType,
|
| 531 |
+
size_average: Optional[bool] = None,
|
| 532 |
+
reduce: Optional[bool] = None,
|
| 533 |
+
reduction: str = "mean",
|
| 534 |
+
) -> TensorLikeType:
|
| 535 |
+
"""
|
| 536 |
+
Reference implementation of torch.nn.functional.l1_loss
|
| 537 |
+
"""
|
| 538 |
+
if size_average is not None or reduce is not None:
|
| 539 |
+
# TODO: Raise exception instead of converting value. This is only for
|
| 540 |
+
# primTorch since it can drop support for deprecated arguments.
|
| 541 |
+
# msg = "size_average and reduce args are deprecated, please use reduction argument."
|
| 542 |
+
reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
|
| 543 |
+
_check_reduction_value(reduction)
|
| 544 |
+
loss = torch.abs(input - target)
|
| 545 |
+
return _apply_loss_reduction(loss, reduction)
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
@elementwise_type_promotion_wrapper(
|
| 549 |
+
type_promoting_args=("input", "target"),
|
| 550 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
|
| 551 |
+
)
|
| 552 |
+
def smooth_l1_loss(
|
| 553 |
+
input: TensorLikeType,
|
| 554 |
+
target: TensorLikeType,
|
| 555 |
+
size_average: Optional[bool] = None,
|
| 556 |
+
reduce: Optional[bool] = None,
|
| 557 |
+
reduction: str = "mean",
|
| 558 |
+
beta: float = 1.0,
|
| 559 |
+
) -> TensorLikeType:
|
| 560 |
+
"""
|
| 561 |
+
Reference implementation of torch.nn.functional.smooth_l1_loss
|
| 562 |
+
"""
|
| 563 |
+
if size_average is not None or reduce is not None:
|
| 564 |
+
# TODO: Raise exception instead of converting value. This is only for
|
| 565 |
+
# primTorch since it can drop support for deprecated arguments.
|
| 566 |
+
# msg = "size_average and reduce args are deprecated, please use reduction argument."
|
| 567 |
+
reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
|
| 568 |
+
_check_reduction_value(reduction)
|
| 569 |
+
|
| 570 |
+
if beta == 0.0:
|
| 571 |
+
return torch.nn.functional.l1_loss(
|
| 572 |
+
input, target, size_average=size_average, reduce=reduce, reduction=reduction
|
| 573 |
+
)
|
| 574 |
+
else:
|
| 575 |
+
loss = torch.abs(input - target)
|
| 576 |
+
loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta)
|
| 577 |
+
return _apply_loss_reduction(loss, reduction)
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
# Forwarding alias: the functional variant doesn't support the out kwarg
|
| 581 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 582 |
+
def log_softmax(
|
| 583 |
+
a: TensorLikeType,
|
| 584 |
+
dim: Optional[int] = None,
|
| 585 |
+
_stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
|
| 586 |
+
dtype: Optional[torch.dtype] = None,
|
| 587 |
+
) -> TensorLikeType:
|
| 588 |
+
# The error is for compat with regular PyTorch, which has this behavior
|
| 589 |
+
# deprecated. For PrimTorch, it's fine to drop support for deprecated
|
| 590 |
+
# behavior because it requires explicit opt in. This error is to inform
|
| 591 |
+
# users how to update their calls.
|
| 592 |
+
torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
|
| 593 |
+
return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
@register_decomposition(aten.margin_ranking_loss)
|
| 597 |
+
def margin_ranking_loss(
|
| 598 |
+
input1: TensorLikeType,
|
| 599 |
+
input2: TensorLikeType,
|
| 600 |
+
target: TensorLikeType,
|
| 601 |
+
margin: float = 0.0,
|
| 602 |
+
reduction: str = "mean",
|
| 603 |
+
) -> TensorLikeType:
|
| 604 |
+
# loss_without_reduction = max(0, -target * (input1 - input2) + margin)
|
| 605 |
+
if input1.ndim != input2.ndim or input1.ndim != target.ndim:
|
| 606 |
+
raise RuntimeError(
|
| 607 |
+
"margin_ranking_loss : All input tensors should have same dimension but got sizes: "
|
| 608 |
+
f"input1: {input1.shape}, input2: {input2.shape}, target: {target.shape} "
|
| 609 |
+
)
|
| 610 |
+
_check_reduction_value(reduction)
|
| 611 |
+
loss = torch.clamp_min(-target * (input1 - input2) + margin, 0)
|
| 612 |
+
return _apply_loss_reduction(loss, reduction)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
@elementwise_type_promotion_wrapper(
|
| 616 |
+
type_promoting_args=("input", "target"),
|
| 617 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
|
| 618 |
+
)
|
| 619 |
+
def mse_loss(
|
| 620 |
+
input: TensorLikeType,
|
| 621 |
+
target: TensorLikeType,
|
| 622 |
+
size_average: Optional[bool] = None,
|
| 623 |
+
reduce: Optional[bool] = None,
|
| 624 |
+
reduction: str = "mean",
|
| 625 |
+
) -> TensorLikeType:
|
| 626 |
+
if size_average is not None or reduce is not None:
|
| 627 |
+
# TODO: Raise exception instead of converting value. This is only for
|
| 628 |
+
# primTorch since it can drop support for deprecated arguments.
|
| 629 |
+
# msg = "size_average and reduce args are deprecated, please use reduction argument."
|
| 630 |
+
reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
|
| 631 |
+
_check_reduction_value(reduction)
|
| 632 |
+
loss = torch.pow(input - target, 2)
|
| 633 |
+
return _apply_loss_reduction(loss, reduction)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
@register_decomposition(aten.hinge_embedding_loss)
|
| 637 |
+
def hinge_embedding_loss(
|
| 638 |
+
input: TensorLikeType,
|
| 639 |
+
target: TensorLikeType,
|
| 640 |
+
margin: float = 1.0,
|
| 641 |
+
reduction: str = "mean",
|
| 642 |
+
) -> TensorLikeType:
|
| 643 |
+
# loss_without_reduction = input if y == 1
|
| 644 |
+
# = max(0, margin - input) if y == -1
|
| 645 |
+
_check_reduction_value(reduction)
|
| 646 |
+
margin_clamp = torch.clamp_min(margin - input, 0)
|
| 647 |
+
output_margin = torch.where(target != 1, margin_clamp, 0)
|
| 648 |
+
output_self = torch.where(target != -1, input, 0)
|
| 649 |
+
loss = output_margin + output_self
|
| 650 |
+
return _apply_loss_reduction(loss, reduction)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def _nll_loss_nd(
|
| 654 |
+
input: TensorLikeType,
|
| 655 |
+
target: TensorLikeType,
|
| 656 |
+
weight: Optional[TensorLikeType],
|
| 657 |
+
reduction: str,
|
| 658 |
+
ignore_index: int,
|
| 659 |
+
) -> TensorLikeType:
|
| 660 |
+
torch._check(
|
| 661 |
+
input.ndim > 0 and input.ndim <= 3,
|
| 662 |
+
lambda: f"Expected input dimension to be either [1, 2, 3] but received {input.ndim}.",
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
torch._check(
|
| 666 |
+
(input.ndim == 1) or (input.shape[0] == target.shape[0]),
|
| 667 |
+
lambda: f"Expected input batch size {input.shape[0]} to match target batch size {target.shape[0]}.",
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
_check_reduction_value(reduction)
|
| 671 |
+
|
| 672 |
+
flat_target = torch.flatten(target)
|
| 673 |
+
ignore_classes_mask = torch.eq(flat_target, ignore_index)
|
| 674 |
+
|
| 675 |
+
# TODO: Enable data-dependent checks with debug mode
|
| 676 |
+
# TODO: This check does not work with FakeTensor inputs; See Issue #85834
|
| 677 |
+
# Explicit cast for class_check to bool; See Issue #78071
|
| 678 |
+
"""
|
| 679 |
+
from torch._subclasses.fake_tensor import FakeTensor
|
| 680 |
+
num_classes = input.shape[1] if input.ndim > 1 else input.shape[0]
|
| 681 |
+
valid_classes_mask = torch.logical_and(
|
| 682 |
+
(flat_target >= 0), (flat_target < num_classes)
|
| 683 |
+
)
|
| 684 |
+
class_check = torch.all(torch.logical_or(ignore_classes_mask, valid_classes_mask))
|
| 685 |
+
torch._check(
|
| 686 |
+
isinstance(target, FakeTensor) or bool(class_check.item()),
|
| 687 |
+
lambda: "A target class is out-of-bounds and not the ignore index.",
|
| 688 |
+
)
|
| 689 |
+
"""
|
| 690 |
+
|
| 691 |
+
ignore_class_weight = torch.scalar_tensor(0, dtype=input.dtype, device=input.device)
|
| 692 |
+
class_weight = (
|
| 693 |
+
torch.scalar_tensor(1, dtype=input.dtype, device=input.device)
|
| 694 |
+
if weight is None
|
| 695 |
+
else weight[flat_target]
|
| 696 |
+
)
|
| 697 |
+
current_weight = torch.where(
|
| 698 |
+
ignore_classes_mask,
|
| 699 |
+
ignore_class_weight,
|
| 700 |
+
class_weight,
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
if input.ndim == 1:
|
| 704 |
+
# implicit batch size = 1
|
| 705 |
+
# input (1 batch size, C classes)
|
| 706 |
+
loss = -input[target] * current_weight
|
| 707 |
+
elif input.ndim == 2:
|
| 708 |
+
# input (N batch size, C classes)
|
| 709 |
+
batch_size = input.shape[0]
|
| 710 |
+
loss = -input[torch.arange(batch_size), target] * current_weight
|
| 711 |
+
else:
|
| 712 |
+
# 3D case (N batch size, C classe, K dimensions)
|
| 713 |
+
# input (N batch size, C classes, K)
|
| 714 |
+
batch_size = input.shape[0]
|
| 715 |
+
extent = input.shape[2]
|
| 716 |
+
numel = batch_size * extent
|
| 717 |
+
indices = torch.arange(numel)
|
| 718 |
+
bdx = indices // extent
|
| 719 |
+
kdx = indices % extent
|
| 720 |
+
loss = -input[bdx, flat_target, kdx] * current_weight
|
| 721 |
+
loss = torch.reshape(loss, target.shape)
|
| 722 |
+
|
| 723 |
+
if reduction == "none":
|
| 724 |
+
return loss
|
| 725 |
+
elif reduction == "sum":
|
| 726 |
+
return torch.sum(loss)
|
| 727 |
+
else:
|
| 728 |
+
# calculate weighted mean of the loss function
|
| 729 |
+
return torch.sum(loss) / torch.sum(current_weight)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
@register_decomposition(aten.nll_loss)
|
| 733 |
+
@out_wrapper()
|
| 734 |
+
@elementwise_type_promotion_wrapper(
|
| 735 |
+
type_promoting_args=("input",),
|
| 736 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 737 |
+
)
|
| 738 |
+
def nll_loss(
|
| 739 |
+
input: TensorLikeType,
|
| 740 |
+
target: TensorLikeType,
|
| 741 |
+
weight: Optional[TensorLikeType] = None,
|
| 742 |
+
size_average: Optional[bool] = None,
|
| 743 |
+
ignore_index: int = -100,
|
| 744 |
+
reduce: Optional[bool] = None,
|
| 745 |
+
reduction: str = "mean",
|
| 746 |
+
) -> TensorLikeType:
|
| 747 |
+
"""
|
| 748 |
+
Reference implementation of torch.nn.functional.nll_loss
|
| 749 |
+
"""
|
| 750 |
+
torch._check(
|
| 751 |
+
input.ndim > 0,
|
| 752 |
+
lambda: f"Expected input tensor to have 1 or more dimensions (got {input.ndim})",
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
# TODO: raise exception instead of converting value
|
| 756 |
+
# msg = "size_average and reduce args are deprecated, please use reduction argument."
|
| 757 |
+
# Convert these options for consistency with the eager mode
|
| 758 |
+
if size_average is not None or reduce is not None:
|
| 759 |
+
reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
|
| 760 |
+
|
| 761 |
+
# The expected behavior when the target and input have zero elements:
|
| 762 |
+
# reduction = 'none' --- tensor([])
|
| 763 |
+
# reduction = 'sum' --- tensor(0.)
|
| 764 |
+
# reduction = 'mean' --- tensor(nan)
|
| 765 |
+
# Mean reduction on empty tensors produces NaN. See the discussion in
|
| 766 |
+
# https://github.com/pytorch/pytorch/pull/64572#issuecomment-926504162
|
| 767 |
+
if input.numel() == 0 and target.numel() == 0:
|
| 768 |
+
if reduction == "none":
|
| 769 |
+
return torch.zeros_like(target)
|
| 770 |
+
elif reduction == "sum":
|
| 771 |
+
return torch.empty_like(target)
|
| 772 |
+
else:
|
| 773 |
+
return torch.full_like(target, float("nan"))
|
| 774 |
+
|
| 775 |
+
# The _nll_loss_nd helper function handles the most common cases.
|
| 776 |
+
# ndim == 1 (Single Example)
|
| 777 |
+
# => Batch Size: 1, Input: (C), Target: ()
|
| 778 |
+
# ndim == 2 (k = 1)
|
| 779 |
+
# => Batch Size: N, Input: (N, C), Target: (N)
|
| 780 |
+
# ndim == 3 (k > 1)
|
| 781 |
+
# => Batch Size: N, Input: (N, C, K), Target: (N, K)
|
| 782 |
+
if input.ndim <= 3:
|
| 783 |
+
return _nll_loss_nd(input, target, weight, reduction, ignore_index)
|
| 784 |
+
|
| 785 |
+
# For ndim > 3, we reshape the input and target to 3-D case.
|
| 786 |
+
# Input (N batch-size, C classes, k-dimensions)
|
| 787 |
+
# Target (N batch-size, k-dimensions)
|
| 788 |
+
torch._check(
|
| 789 |
+
input.ndim > 0 and target.ndim > 0 and target.shape[1:] == input.shape[2:],
|
| 790 |
+
lambda: (
|
| 791 |
+
"Expected input and target to both have ndim > 0 and "
|
| 792 |
+
"target.shape[1:] == input.shape[2:], but got "
|
| 793 |
+
f"target.shape {target.shape} and input.shape {input.shape}"
|
| 794 |
+
),
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
batch_size = input.shape[0]
|
| 798 |
+
num_classes = input.shape[1]
|
| 799 |
+
out_size = [batch_size] + list(target.shape[1:])
|
| 800 |
+
|
| 801 |
+
input = torch.reshape(input, [batch_size, num_classes, -1])
|
| 802 |
+
target = torch.reshape(target, [batch_size, -1])
|
| 803 |
+
if reduction != "none":
|
| 804 |
+
return _nll_loss_nd(input, target, weight, reduction, ignore_index)
|
| 805 |
+
else:
|
| 806 |
+
result = _nll_loss_nd(input, target, weight, reduction, ignore_index)
|
| 807 |
+
# reshape flattened inner-dim to original k-dimensions
|
| 808 |
+
return torch.reshape(result, out_size)
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
# TODO: This ref supports int reduction and out kwarg to be compatible with ATen:
|
| 812 |
+
# https://github.com/pytorch/pytorch/issues/83931
|
| 813 |
+
# TODO: Could be rewritten to support complex:
|
| 814 |
+
# https://github.com/pytorch/pytorch/pull/85041
|
| 815 |
+
@register_decomposition(aten.huber_loss)
|
| 816 |
+
@out_wrapper()
|
| 817 |
+
@elementwise_type_promotion_wrapper(
|
| 818 |
+
type_promoting_args=("input", "target"),
|
| 819 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 820 |
+
)
|
| 821 |
+
def huber_loss(
|
| 822 |
+
input: TensorLikeType,
|
| 823 |
+
target: TensorLikeType,
|
| 824 |
+
reduction: Union[str, int] = "mean",
|
| 825 |
+
delta: float = 1.0,
|
| 826 |
+
) -> TensorLikeType:
|
| 827 |
+
"""
|
| 828 |
+
Reference implementation of torch.nn.functional.huber_loss
|
| 829 |
+
"""
|
| 830 |
+
if type(reduction) is int:
|
| 831 |
+
reduction = _reduction_int_to_str(reduction)
|
| 832 |
+
_check_reduction_value(reduction) # type: ignore[arg-type]
|
| 833 |
+
torch._check(
|
| 834 |
+
delta > 0,
|
| 835 |
+
lambda: "huber_loss does not support non-positive values for delta.",
|
| 836 |
+
)
|
| 837 |
+
z = (input - target).abs()
|
| 838 |
+
loss = torch.where(z < delta, 0.5 * z * z, delta * (z - 0.5 * delta))
|
| 839 |
+
return _apply_loss_reduction(loss, reduction) # type: ignore[arg-type]
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
# tanhshrink does not use _make_elementwise_unary_reference because it does not support out
|
| 843 |
+
@elementwise_unary_scalar_wrapper
|
| 844 |
+
@elementwise_type_promotion_wrapper(
|
| 845 |
+
type_promoting_args=("a",),
|
| 846 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 847 |
+
)
|
| 848 |
+
def tanhshrink(a: TensorLikeType) -> TensorLikeType:
|
| 849 |
+
"""
|
| 850 |
+
Reference implementation of torch.nn.functional.tanhshrink
|
| 851 |
+
"""
|
| 852 |
+
if not isinstance(a, TensorLike):
|
| 853 |
+
raise RuntimeError(
|
| 854 |
+
"Expected a tensor input for an elementwise unary operation!"
|
| 855 |
+
)
|
| 856 |
+
return a - torch.tanh(a)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
@register_decomposition(aten.threshold)
|
| 860 |
+
@_inplace_wrapper
|
| 861 |
+
@out_wrapper()
|
| 862 |
+
@elementwise_type_promotion_wrapper(
|
| 863 |
+
type_promoting_args=("a",),
|
| 864 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 865 |
+
)
|
| 866 |
+
def threshold(
|
| 867 |
+
a: TensorLikeType,
|
| 868 |
+
threshold: NumberType,
|
| 869 |
+
value: Union[bool, int, float],
|
| 870 |
+
inplace: bool = False,
|
| 871 |
+
) -> TensorLikeType:
|
| 872 |
+
"""
|
| 873 |
+
Reference implementation of torch.nn.functional.threshold
|
| 874 |
+
"""
|
| 875 |
+
|
| 876 |
+
if inplace:
|
| 877 |
+
raise NotImplementedError
|
| 878 |
+
|
| 879 |
+
return torch.where(a <= threshold, value, a)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 883 |
+
# No elementwise type promotion - core op doesn't explicitly type promote
|
| 884 |
+
def triplet_margin_loss(
|
| 885 |
+
anchor: TensorLikeType,
|
| 886 |
+
positive: TensorLikeType,
|
| 887 |
+
negative: TensorLikeType,
|
| 888 |
+
margin: float = 1.0,
|
| 889 |
+
p: float = 2,
|
| 890 |
+
eps: float = 1e-6,
|
| 891 |
+
swap: bool = False,
|
| 892 |
+
size_average: Optional[bool] = None,
|
| 893 |
+
reduce: Optional[bool] = None,
|
| 894 |
+
reduction: str = "mean",
|
| 895 |
+
) -> TensorLikeType:
|
| 896 |
+
if size_average is not None or reduce is not None:
|
| 897 |
+
# TODO: Raise exception instead of converting value. This is only for
|
| 898 |
+
# primTorch since it can drop support for deprecated arguments.
|
| 899 |
+
# msg = "size_average and reduce args are deprecated, please use reduction argument."
|
| 900 |
+
reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
|
| 901 |
+
|
| 902 |
+
if margin <= 0:
|
| 903 |
+
raise ValueError(f"margin must be greater than 0, got {margin}")
|
| 904 |
+
|
| 905 |
+
# torch.nn.functional.triplet_margin_with_distance_loss has no ref defined
|
| 906 |
+
# since it's a pure Python implementation. Use this helper instead.
|
| 907 |
+
return _triplet_margin_with_distance_loss(
|
| 908 |
+
anchor=anchor,
|
| 909 |
+
positive=positive,
|
| 910 |
+
negative=negative,
|
| 911 |
+
distance_function=lambda x, y: torch.pairwise_distance(x, y, p, eps),
|
| 912 |
+
margin=margin,
|
| 913 |
+
swap=swap,
|
| 914 |
+
reduction=reduction,
|
| 915 |
+
)
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
# Pure Python impl - don't register decomp and don't add a ref. Defined as a
|
| 919 |
+
# helper here since triplet_margin_loss can be nicely implemented with it.
|
| 920 |
+
def _triplet_margin_with_distance_loss(
|
| 921 |
+
anchor: TensorLikeType,
|
| 922 |
+
positive: TensorLikeType,
|
| 923 |
+
negative: TensorLikeType,
|
| 924 |
+
*,
|
| 925 |
+
distance_function: Optional[
|
| 926 |
+
Callable[[TensorLikeType, TensorLikeType], TensorLikeType]
|
| 927 |
+
] = None,
|
| 928 |
+
margin: float = 1.0,
|
| 929 |
+
swap: bool = False,
|
| 930 |
+
reduction: str = "mean",
|
| 931 |
+
) -> TensorLikeType:
|
| 932 |
+
_check_reduction_value(reduction)
|
| 933 |
+
|
| 934 |
+
a_dim = anchor.ndim
|
| 935 |
+
p_dim = positive.ndim
|
| 936 |
+
n_dim = negative.ndim
|
| 937 |
+
torch._check(
|
| 938 |
+
a_dim == p_dim and p_dim == n_dim,
|
| 939 |
+
lambda: (
|
| 940 |
+
f"The anchor, positive, and negative tensors are expected to have "
|
| 941 |
+
f"the same number of dimensions, but got: anchor {a_dim}D, "
|
| 942 |
+
f"positive {p_dim}D, and negative {n_dim}D inputs"
|
| 943 |
+
),
|
| 944 |
+
)
|
| 945 |
+
|
| 946 |
+
if distance_function is None:
|
| 947 |
+
distance_function = torch.pairwise_distance
|
| 948 |
+
|
| 949 |
+
dist_pos = distance_function(anchor, positive)
|
| 950 |
+
dist_neg = distance_function(anchor, negative)
|
| 951 |
+
# The distance swap is described in the paper "Learning shallow
|
| 952 |
+
# convolutional feature descriptors with triplet losses" by V. Balntas, E.
|
| 953 |
+
# Riba et al. If True, and if the positive example is closer to the
|
| 954 |
+
# negative example than the anchor is, swaps the positive example and the
|
| 955 |
+
# anchor in the loss computation.
|
| 956 |
+
if swap:
|
| 957 |
+
dist_swap = distance_function(positive, negative)
|
| 958 |
+
dist_neg = torch.minimum(dist_neg, dist_swap)
|
| 959 |
+
loss = torch.clamp_min(margin + dist_pos - dist_neg, 0)
|
| 960 |
+
return _apply_loss_reduction(loss, reduction)
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
@register_decomposition(aten.hardtanh)
|
| 964 |
+
@_inplace_wrapper
|
| 965 |
+
@out_wrapper()
|
| 966 |
+
@elementwise_unary_scalar_wrapper
|
| 967 |
+
@elementwise_type_promotion_wrapper(
|
| 968 |
+
type_promoting_args=("a"),
|
| 969 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 970 |
+
)
|
| 971 |
+
def hardtanh(
|
| 972 |
+
a: TensorLikeType,
|
| 973 |
+
min_val: NumberType = -1,
|
| 974 |
+
max_val: NumberType = 1,
|
| 975 |
+
inplace: bool = False,
|
| 976 |
+
) -> TensorLikeType:
|
| 977 |
+
"""
|
| 978 |
+
Reference implementation of torch.nn.functional.hardtanh
|
| 979 |
+
"""
|
| 980 |
+
if inplace:
|
| 981 |
+
raise NotImplementedError
|
| 982 |
+
if utils.is_boolean_dtype(a.dtype):
|
| 983 |
+
raise RuntimeError("Bool inputs not supported for hardtanh")
|
| 984 |
+
|
| 985 |
+
# preserve legacy behavior of boundaries not causing type promotion
|
| 986 |
+
if utils.is_integer_dtype(a.dtype):
|
| 987 |
+
min_val = int(min_val) # type: ignore[arg-type]
|
| 988 |
+
max_val = int(max_val) # type: ignore[arg-type]
|
| 989 |
+
if not (a.dtype != torch.uint8 or (min_val >= 0 and max_val >= 0)):
|
| 990 |
+
raise RuntimeError(
|
| 991 |
+
"Cannot do hardtanh on an unsigned type with negative limits"
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
if min_val > max_val: # type: ignore[operator]
|
| 995 |
+
raise ValueError("min_val cannot be greater than max_val")
|
| 996 |
+
|
| 997 |
+
return torch.clamp(a, min_val, max_val) # type: ignore[arg-type]
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
@register_decomposition(aten.gelu)
|
| 1001 |
+
@out_wrapper()
|
| 1002 |
+
@elementwise_unary_scalar_wrapper
|
| 1003 |
+
@elementwise_type_promotion_wrapper(
|
| 1004 |
+
type_promoting_args=("a",),
|
| 1005 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 1006 |
+
)
|
| 1007 |
+
def gelu(a: TensorLikeType, approximate: str = "none") -> TensorLikeType:
|
| 1008 |
+
"""
|
| 1009 |
+
Reference implementation of torch.nn.functional.gelu
|
| 1010 |
+
"""
|
| 1011 |
+
if not isinstance(a, TensorLike):
|
| 1012 |
+
raise RuntimeError(
|
| 1013 |
+
"Expected a tensor input for an elementwise unary operation!"
|
| 1014 |
+
)
|
| 1015 |
+
M_SQRT2 = 1.41421356237309504880
|
| 1016 |
+
M_SQRT1_2 = 0.70710678118654752440
|
| 1017 |
+
M_2_SQRTPI = 1.12837916709551257390
|
| 1018 |
+
if approximate == "tanh":
|
| 1019 |
+
kBeta = M_SQRT2 * M_2_SQRTPI * 0.5
|
| 1020 |
+
kKappa = 0.044715
|
| 1021 |
+
a_cube = a * a * a
|
| 1022 |
+
inner = kBeta * (a + kKappa * a_cube)
|
| 1023 |
+
return 0.5 * a * (1 + torch.tanh(inner))
|
| 1024 |
+
elif approximate == "none":
|
| 1025 |
+
kAlpha = M_SQRT1_2
|
| 1026 |
+
return a * 0.5 * (1 + torch.erf(a * kAlpha))
|
| 1027 |
+
else:
|
| 1028 |
+
raise RuntimeError("approximate argument must be either none or tanh.")
|
| 1029 |
+
|
| 1030 |
+
|
| 1031 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 1032 |
+
@elementwise_type_promotion_wrapper(
|
| 1033 |
+
type_promoting_args=("input", "target"),
|
| 1034 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 1035 |
+
)
|
| 1036 |
+
def poisson_nll_loss(
|
| 1037 |
+
input: TensorLikeType,
|
| 1038 |
+
target: TensorLikeType,
|
| 1039 |
+
log_input: bool = True,
|
| 1040 |
+
full: bool = False,
|
| 1041 |
+
size_average: Optional[bool] = None,
|
| 1042 |
+
eps: float = 1e-8,
|
| 1043 |
+
reduce: Optional[bool] = None,
|
| 1044 |
+
reduction: str = "mean",
|
| 1045 |
+
) -> TensorLikeType:
|
| 1046 |
+
"""
|
| 1047 |
+
Reference implementation of torch.nn.functional.poisson_nll_loss
|
| 1048 |
+
"""
|
| 1049 |
+
if size_average is not None or reduce is not None:
|
| 1050 |
+
# TODO: Raise exception instead of converting value. This is only for
|
| 1051 |
+
# primTorch since it can drop support for deprecated arguments.
|
| 1052 |
+
# msg = "size_average and reduce args are deprecated, please use reduction argument."
|
| 1053 |
+
reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
|
| 1054 |
+
_check_reduction_value(reduction)
|
| 1055 |
+
if log_input:
|
| 1056 |
+
loss = torch.exp(input) - target * input
|
| 1057 |
+
else:
|
| 1058 |
+
loss = input - target * torch.log(input + eps)
|
| 1059 |
+
|
| 1060 |
+
if full:
|
| 1061 |
+
stirling_term = (
|
| 1062 |
+
target * torch.log(target) - target + 0.5 * torch.log(2 * torch.pi * target)
|
| 1063 |
+
)
|
| 1064 |
+
# avoid inplace add
|
| 1065 |
+
loss = loss + stirling_term.masked_fill(target <= 1, 0)
|
| 1066 |
+
return _apply_loss_reduction(loss, reduction)
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
@register_decomposition(aten.prelu)
|
| 1070 |
+
@elementwise_type_promotion_wrapper(
|
| 1071 |
+
type_promoting_args=("a", "weight"),
|
| 1072 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 1073 |
+
)
|
| 1074 |
+
def prelu(a: TensorLikeType, weight: TensorLikeType) -> TensorLikeType:
|
| 1075 |
+
"""
|
| 1076 |
+
Reference implementation of torch.nn.functional.prelu
|
| 1077 |
+
"""
|
| 1078 |
+
torch._check(
|
| 1079 |
+
isinstance(a, TensorLike),
|
| 1080 |
+
lambda: f"prelu: Expected `a` to be tensor, but got: {type(a)}",
|
| 1081 |
+
)
|
| 1082 |
+
torch._check(
|
| 1083 |
+
isinstance(weight, TensorLike),
|
| 1084 |
+
lambda: f"prelu: Expected `weight` to be tensor, but got: {type(weight)}",
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
if weight.numel() != 1:
|
| 1088 |
+
torch._check(a.ndim > 0, lambda: "Not allow zero-dim input tensor.")
|
| 1089 |
+
channel_size = a.shape[1] if a.ndim >= 2 else 1
|
| 1090 |
+
torch._check(
|
| 1091 |
+
weight.numel() == channel_size,
|
| 1092 |
+
lambda: f"Mismatch of parameter numbers and input channel size. Found parameter numbers ="
|
| 1093 |
+
f" {weight.numel()} and channel size = {channel_size}.",
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
torch._check(
|
| 1097 |
+
weight.ndim == 0 or weight.ndim == 1,
|
| 1098 |
+
lambda: f"prelu: Expected `weight` to be a scalar or 1D tensor, but got: "
|
| 1099 |
+
f"ndim = {weight.ndim}",
|
| 1100 |
+
)
|
| 1101 |
+
if a.ndim == 0:
|
| 1102 |
+
weight = weight[0] if weight.ndim == 1 else weight
|
| 1103 |
+
else:
|
| 1104 |
+
weight = prims.broadcast_in_dim(
|
| 1105 |
+
weight, a.shape, tuple() if weight.ndim == 0 else (0 if a.ndim == 1 else 1,)
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
return torch.where(a > 0, a, a * weight)
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
@register_decomposition(aten.relu6)
|
| 1112 |
+
@_inplace_wrapper
|
| 1113 |
+
@out_wrapper()
|
| 1114 |
+
def relu6(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
|
| 1115 |
+
"""
|
| 1116 |
+
Reference implementation of torch.nn.functional.relu6
|
| 1117 |
+
"""
|
| 1118 |
+
if inplace:
|
| 1119 |
+
raise NotImplementedError
|
| 1120 |
+
|
| 1121 |
+
# See https://github.com/pytorch/pytorch/pull/81142#discussion_r918220126
|
| 1122 |
+
# It may be better to use clamp here, but we use hardtanh to replicate
|
| 1123 |
+
# the behavior of the existing implementation
|
| 1124 |
+
return torch.nn.functional.hardtanh(a, 0, 6)
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
@register_decomposition(aten.glu)
|
| 1128 |
+
@out_wrapper()
|
| 1129 |
+
@elementwise_type_promotion_wrapper(
|
| 1130 |
+
type_promoting_args=("a",),
|
| 1131 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 1132 |
+
)
|
| 1133 |
+
def glu(a: TensorLikeType, dim: int = -1) -> TensorLikeType:
|
| 1134 |
+
dim = utils.canonicalize_dims(a.ndim, dim)
|
| 1135 |
+
torch._check(
|
| 1136 |
+
a.shape[dim] % 2 == 0,
|
| 1137 |
+
lambda: f"Halving dimension must be even, but dimension {dim} is size {a.shape[dim]}",
|
| 1138 |
+
)
|
| 1139 |
+
b, c = torch.tensor_split(a, 2, dim)
|
| 1140 |
+
|
| 1141 |
+
return b * torch.sigmoid(c)
|
| 1142 |
+
|
| 1143 |
+
|
| 1144 |
+
@register_decomposition(aten.pairwise_distance)
|
| 1145 |
+
@out_wrapper()
|
| 1146 |
+
def pairwise_distance(
|
| 1147 |
+
x1: TensorLikeType,
|
| 1148 |
+
x2: TensorLikeType,
|
| 1149 |
+
p: NumberType = 2.0,
|
| 1150 |
+
eps: NumberType = 1e-6,
|
| 1151 |
+
keepdim=False,
|
| 1152 |
+
) -> TensorLikeType:
|
| 1153 |
+
return torch.linalg.vector_norm(x1 - x2 + eps, ord=p, dim=-1, keepdim=keepdim)
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
@register_decomposition(aten.pdist)
|
| 1157 |
+
@out_wrapper()
|
| 1158 |
+
@elementwise_type_promotion_wrapper(
|
| 1159 |
+
type_promoting_args=("a",),
|
| 1160 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
|
| 1161 |
+
)
|
| 1162 |
+
def pdist(a: TensorLikeType, p: float = 2) -> TensorLikeType:
|
| 1163 |
+
torch._check(a.ndim == 2, lambda: f"pdist only supports 2D tensors, got: {a.ndim}D")
|
| 1164 |
+
torch._check(p >= 0, lambda: "pdist only supports non-negative p values")
|
| 1165 |
+
# For p == 2 we can use an efficient implementation, but other values of p
|
| 1166 |
+
# require creating a much bigger tensor for an intermediate step
|
| 1167 |
+
if p == 2:
|
| 1168 |
+
aTa = torch.mm(a, a.T)
|
| 1169 |
+
aTa_diag = torch.diag(aTa)
|
| 1170 |
+
t = torch.sqrt(torch.clamp(aTa_diag + aTa_diag.unsqueeze(-1) - 2 * aTa, min=0))
|
| 1171 |
+
else:
|
| 1172 |
+
t = torch.linalg.vector_norm(a.unsqueeze(1) - a, ord=p, dim=2)
|
| 1173 |
+
i = torch.triu_indices(t.shape[0], t.shape[1], offset=1, device=a.device)
|
| 1174 |
+
return t.flatten().index_select(0, i[0] * t.shape[0] + i[1])
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
@register_decomposition(aten.pixel_shuffle)
|
| 1178 |
+
@out_wrapper()
|
| 1179 |
+
def pixel_shuffle(self: Tensor, upscale_factor: int):
|
| 1180 |
+
torch._check(
|
| 1181 |
+
self.dim() >= 3,
|
| 1182 |
+
lambda: f"pixel_shuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
|
| 1183 |
+
)
|
| 1184 |
+
batch = self.shape[:-3]
|
| 1185 |
+
C_out = self.shape[-3] // upscale_factor**2
|
| 1186 |
+
HW_out = (self.shape[-2] * upscale_factor, self.shape[-1] * upscale_factor)
|
| 1187 |
+
n = len(batch)
|
| 1188 |
+
B_dims = range(n)
|
| 1189 |
+
C_dim, r1_dim, r2_dim, H_dim, W_dim = range(n, n + 5)
|
| 1190 |
+
return (
|
| 1191 |
+
self.view(
|
| 1192 |
+
*batch,
|
| 1193 |
+
C_out,
|
| 1194 |
+
upscale_factor,
|
| 1195 |
+
upscale_factor,
|
| 1196 |
+
self.shape[-2],
|
| 1197 |
+
self.shape[-1],
|
| 1198 |
+
)
|
| 1199 |
+
.permute(*B_dims, C_dim, H_dim, r1_dim, W_dim, r2_dim)
|
| 1200 |
+
.reshape(*batch, C_out, *HW_out)
|
| 1201 |
+
.clone(memory_format=utils.suggest_memory_format(self))
|
| 1202 |
+
)
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
@register_decomposition(aten.pixel_unshuffle)
|
| 1206 |
+
@out_wrapper()
|
| 1207 |
+
def pixel_unshuffle(self: Tensor, downscale_factor: int):
|
| 1208 |
+
torch._check(
|
| 1209 |
+
self.dim() >= 3,
|
| 1210 |
+
lambda: f"pixel_unshuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
|
| 1211 |
+
)
|
| 1212 |
+
batch = self.shape[:-3]
|
| 1213 |
+
C_out = self.shape[-3] * downscale_factor**2
|
| 1214 |
+
HW_out = (self.shape[-2] // downscale_factor, self.shape[-1] // downscale_factor)
|
| 1215 |
+
n = len(batch)
|
| 1216 |
+
B_dims = range(n)
|
| 1217 |
+
C_dim, H_dim, r1_dim, W_dim, r2_dim = range(n, n + 5)
|
| 1218 |
+
return (
|
| 1219 |
+
self.view(
|
| 1220 |
+
*batch,
|
| 1221 |
+
self.shape[-3],
|
| 1222 |
+
HW_out[0],
|
| 1223 |
+
downscale_factor,
|
| 1224 |
+
HW_out[1],
|
| 1225 |
+
downscale_factor,
|
| 1226 |
+
)
|
| 1227 |
+
.permute(*B_dims, C_dim, r1_dim, r2_dim, H_dim, W_dim)
|
| 1228 |
+
.reshape(*batch, C_out, *HW_out)
|
| 1229 |
+
.clone(memory_format=utils.suggest_memory_format(self))
|
| 1230 |
+
)
|
| 1231 |
+
|
| 1232 |
+
|
| 1233 |
+
# Needed as aten.{celu_,elu_...} exist (even if they don't have the in-place kwarg)
|
| 1234 |
+
celu_ = _make_inplace(celu)
|
| 1235 |
+
elu_ = _make_inplace(elu)
|
| 1236 |
+
mish_ = _make_inplace(mish)
|
| 1237 |
+
selu_ = _make_inplace(selu)
|
| 1238 |
+
threshold_ = _make_inplace(threshold)
|
parrot/lib/python3.10/site-packages/torch/_refs/nn/functional/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (26.2 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/_refs/special/__init__.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
from typing import Optional, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch._prims as prims
|
| 7 |
+
import torch._prims_common as utils
|
| 8 |
+
import torch._refs as refs
|
| 9 |
+
|
| 10 |
+
from torch import Tensor
|
| 11 |
+
from torch._decomp import register_decomposition
|
| 12 |
+
from torch._prims_common import (
|
| 13 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND,
|
| 14 |
+
Number,
|
| 15 |
+
NumberType,
|
| 16 |
+
TensorLike,
|
| 17 |
+
TensorLikeType,
|
| 18 |
+
)
|
| 19 |
+
from torch._prims_common.wrappers import elementwise_type_promotion_wrapper, out_wrapper
|
| 20 |
+
from torch._refs import (
|
| 21 |
+
_make_alias,
|
| 22 |
+
_make_elementwise_binary_reference,
|
| 23 |
+
_make_elementwise_unary_reference,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
__all__ = [
|
| 28 |
+
"bessel_j0",
|
| 29 |
+
"bessel_j1",
|
| 30 |
+
"entr",
|
| 31 |
+
"erfcx",
|
| 32 |
+
"expit",
|
| 33 |
+
"i0e",
|
| 34 |
+
"i1",
|
| 35 |
+
"i1e",
|
| 36 |
+
"log_ndtr",
|
| 37 |
+
"logit",
|
| 38 |
+
"log_softmax",
|
| 39 |
+
"multigammaln",
|
| 40 |
+
"ndtr",
|
| 41 |
+
"ndtri",
|
| 42 |
+
"softmax",
|
| 43 |
+
"spherical_bessel_j0",
|
| 44 |
+
"xlog1py",
|
| 45 |
+
"zeta",
|
| 46 |
+
]
|
| 47 |
+
aten = torch._ops.ops.aten
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@_make_elementwise_unary_reference(
|
| 51 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 52 |
+
)
|
| 53 |
+
def bessel_j0(a: TensorLikeType) -> TensorLikeType:
|
| 54 |
+
return prims.bessel_j0(a)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@_make_elementwise_unary_reference(
|
| 58 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 59 |
+
)
|
| 60 |
+
def bessel_j1(a: TensorLikeType) -> TensorLikeType:
|
| 61 |
+
return prims.bessel_j1(a)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@register_decomposition(aten.special_entr)
|
| 65 |
+
@out_wrapper()
|
| 66 |
+
@elementwise_type_promotion_wrapper(
|
| 67 |
+
type_promoting_args=("a",),
|
| 68 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 69 |
+
)
|
| 70 |
+
def entr(a: TensorLikeType) -> TensorLikeType:
|
| 71 |
+
return torch.where(
|
| 72 |
+
torch.isnan(a),
|
| 73 |
+
a,
|
| 74 |
+
torch.where(a > 0, -a * torch.log(a), torch.where(a == 0, 0, -torch.inf)),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@register_decomposition(aten.special_erfcx)
|
| 79 |
+
@out_wrapper()
|
| 80 |
+
@elementwise_type_promotion_wrapper(
|
| 81 |
+
type_promoting_args=("a",),
|
| 82 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 83 |
+
)
|
| 84 |
+
def erfcx(a: TensorLikeType) -> TensorLikeType:
|
| 85 |
+
return prims.erfcx(a)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# alias for sigmoid
|
| 89 |
+
expit = _make_alias(torch.sigmoid, "expit")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@_make_elementwise_unary_reference(
|
| 93 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 94 |
+
)
|
| 95 |
+
def i0e(a: TensorLikeType) -> TensorLikeType:
|
| 96 |
+
return prims.bessel_i0e(a)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@_make_elementwise_unary_reference(
|
| 100 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 101 |
+
)
|
| 102 |
+
def i1(a: TensorLikeType) -> TensorLikeType:
|
| 103 |
+
return prims.bessel_i1(a)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@_make_elementwise_unary_reference(
|
| 107 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 108 |
+
)
|
| 109 |
+
def i1e(a: TensorLikeType) -> TensorLikeType:
|
| 110 |
+
return prims.bessel_i1e(a)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@register_decomposition(aten.special_log_ndtr)
|
| 114 |
+
@out_wrapper()
|
| 115 |
+
@elementwise_type_promotion_wrapper(
|
| 116 |
+
type_promoting_args=("a",),
|
| 117 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 118 |
+
)
|
| 119 |
+
def log_ndtr(a: TensorLikeType) -> TensorLikeType:
|
| 120 |
+
# Note: M_SQRT1_2 is the value of 1 / sqrt(2)
|
| 121 |
+
M_SQRT1_2 = 0.707106781186547524400844362104849039
|
| 122 |
+
t = a * M_SQRT1_2
|
| 123 |
+
return torch.where(
|
| 124 |
+
a < 1.0,
|
| 125 |
+
torch.log(torch.special.erfcx(-t) / 2) - t * t,
|
| 126 |
+
torch.log1p(-torch.erfc(t) / 2),
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@register_decomposition(aten.logit)
|
| 131 |
+
@out_wrapper()
|
| 132 |
+
@elementwise_type_promotion_wrapper(
|
| 133 |
+
type_promoting_args=("self",),
|
| 134 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 135 |
+
)
|
| 136 |
+
def logit(self: TensorLikeType, eps: Optional[float] = None) -> TensorLikeType:
|
| 137 |
+
if eps is None:
|
| 138 |
+
eps = -1.0
|
| 139 |
+
lo = eps
|
| 140 |
+
hi = 1 - eps
|
| 141 |
+
self = torch.clamp(self, lo, hi)
|
| 142 |
+
return torch.log(torch.true_divide(self, torch.sub(1, self)))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@register_decomposition(aten.special_xlog1py)
|
| 146 |
+
@out_wrapper()
|
| 147 |
+
@elementwise_type_promotion_wrapper(
|
| 148 |
+
type_promoting_args=("a", "b"),
|
| 149 |
+
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 150 |
+
)
|
| 151 |
+
def xlog1py(a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]):
|
| 152 |
+
torch._check(
|
| 153 |
+
isinstance(a, TensorLike) or isinstance(b, TensorLike),
|
| 154 |
+
lambda: 'Expected either argument a or b to be a Tensor"',
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Operations like eq and log do not handle scalar values, so we convert them to scalar_tensors.
|
| 158 |
+
if isinstance(a, TensorLike) and isinstance(b, Number):
|
| 159 |
+
b = refs.scalar_tensor(b, dtype=a.dtype, device=a.device)
|
| 160 |
+
elif isinstance(b, TensorLike) and isinstance(a, Number):
|
| 161 |
+
a = refs.scalar_tensor(a, dtype=b.dtype, device=b.device)
|
| 162 |
+
|
| 163 |
+
# mypy: expected "Tensor"
|
| 164 |
+
assert isinstance(a, TensorLike)
|
| 165 |
+
assert isinstance(b, TensorLike)
|
| 166 |
+
rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log1p(b)))
|
| 167 |
+
return torch.where(torch.isnan(b), float("nan"), rhs)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@register_decomposition(aten.mvlgamma)
|
| 171 |
+
@out_wrapper()
|
| 172 |
+
@elementwise_type_promotion_wrapper(
|
| 173 |
+
type_promoting_args=("a",),
|
| 174 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 175 |
+
)
|
| 176 |
+
def multigammaln(a: TensorLikeType, p: int) -> TensorLikeType:
|
| 177 |
+
c = 0.25 * p * (p - 1) * math.log(math.pi)
|
| 178 |
+
b = 0.5 * torch.arange(start=(1 - p), end=1, step=1, dtype=a.dtype, device=a.device)
|
| 179 |
+
return torch.sum(torch.lgamma(a.unsqueeze(-1) + b), dim=-1) + c
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@register_decomposition(aten.special_ndtr)
|
| 183 |
+
@out_wrapper()
|
| 184 |
+
@elementwise_type_promotion_wrapper(
|
| 185 |
+
type_promoting_args=("a",),
|
| 186 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 187 |
+
)
|
| 188 |
+
def ndtr(a: TensorLikeType) -> TensorLikeType:
|
| 189 |
+
# Note: M_SQRT1_2 is the value of 1 / sqrt(2)
|
| 190 |
+
M_SQRT1_2 = 0.707106781186547524400844362104849039
|
| 191 |
+
a_sqrt_2 = a * M_SQRT1_2
|
| 192 |
+
return (1 + torch.erf(a_sqrt_2)) * 0.5
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@register_decomposition(aten.special_ndtri)
|
| 196 |
+
@out_wrapper()
|
| 197 |
+
@elementwise_type_promotion_wrapper(
|
| 198 |
+
type_promoting_args=("a",),
|
| 199 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 200 |
+
)
|
| 201 |
+
def ndtri(a: TensorLikeType) -> TensorLikeType:
|
| 202 |
+
return prims.ndtri(a)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# Forwarding alias: the special variant doesn't support the out kwarg
|
| 206 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 207 |
+
def log_softmax(
|
| 208 |
+
a: TensorLikeType,
|
| 209 |
+
dim: int,
|
| 210 |
+
dtype: Optional[torch.dtype] = None,
|
| 211 |
+
) -> TensorLikeType:
|
| 212 |
+
return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# Forwarding alias: the special variant doesn't support the out kwarg
|
| 216 |
+
# CompositeImplicitAutograd - don't register decomp
|
| 217 |
+
def softmax(
|
| 218 |
+
a: TensorLikeType,
|
| 219 |
+
dim: int,
|
| 220 |
+
dtype: Optional[torch.dtype] = None,
|
| 221 |
+
) -> TensorLikeType:
|
| 222 |
+
return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@_make_elementwise_unary_reference(
|
| 226 |
+
ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 227 |
+
)
|
| 228 |
+
def spherical_bessel_j0(a: TensorLikeType) -> TensorLikeType:
|
| 229 |
+
return prims.spherical_bessel_j0(a)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# TODO: add docstring
|
| 233 |
+
@_make_elementwise_binary_reference(
|
| 234 |
+
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
|
| 235 |
+
)
|
| 236 |
+
def zeta(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
|
| 237 |
+
return prims.zeta(a, b)
|
parrot/lib/python3.10/site-packages/torch/_refs/special/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (5.08 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/_vmap_internals.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
from typing import Any, Callable, List, Optional, Tuple, Union
|
| 4 |
+
from typing_extensions import deprecated
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch.utils._pytree import _broadcast_to_and_flatten, tree_flatten, tree_unflatten
|
| 9 |
+
|
| 10 |
+
in_dims_t = Union[int, Tuple]
|
| 11 |
+
out_dims_t = Union[int, Tuple[int, ...]]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Checks that all args-to-be-batched have the same batch dim size
|
| 15 |
+
def _validate_and_get_batch_size(
|
| 16 |
+
flat_in_dims: List[Optional[int]], flat_args: List
|
| 17 |
+
) -> int:
|
| 18 |
+
batch_sizes = [
|
| 19 |
+
arg.size(in_dim)
|
| 20 |
+
for in_dim, arg in zip(flat_in_dims, flat_args)
|
| 21 |
+
if in_dim is not None
|
| 22 |
+
]
|
| 23 |
+
if batch_sizes and any(size != batch_sizes[0] for size in batch_sizes):
|
| 24 |
+
raise ValueError(
|
| 25 |
+
f"vmap: Expected all tensors to have the same size in the mapped "
|
| 26 |
+
f"dimension, got sizes {batch_sizes} for the mapped dimension"
|
| 27 |
+
)
|
| 28 |
+
return batch_sizes[0]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _num_outputs(batched_outputs: Union[Tensor, Tuple[Tensor, ...]]) -> int:
|
| 32 |
+
if isinstance(batched_outputs, tuple):
|
| 33 |
+
return len(batched_outputs)
|
| 34 |
+
return 1
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# If value is a tuple, check it has length `num_elements`.
|
| 38 |
+
# If value is not a tuple, make a tuple with `value` repeated `num_elements` times
|
| 39 |
+
def _as_tuple(
|
| 40 |
+
value: Any, num_elements: int, error_message_lambda: Callable[[], str]
|
| 41 |
+
) -> Tuple:
|
| 42 |
+
if not isinstance(value, tuple):
|
| 43 |
+
return (value,) * num_elements
|
| 44 |
+
if len(value) != num_elements:
|
| 45 |
+
raise ValueError(error_message_lambda())
|
| 46 |
+
return value
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Creates BatchedTensors for every Tensor in arg that should be batched.
|
| 50 |
+
# Returns the (potentially) batched arguments and the batch_size.
|
| 51 |
+
def _create_batched_inputs(
|
| 52 |
+
in_dims: in_dims_t, args: Tuple, vmap_level: int, func: Callable
|
| 53 |
+
) -> Tuple[Tuple, int]:
|
| 54 |
+
if not isinstance(in_dims, int) and not isinstance(in_dims, tuple):
|
| 55 |
+
raise ValueError(
|
| 56 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 57 |
+
f"expected `in_dims` to be int or a (potentially nested) tuple "
|
| 58 |
+
f"matching the structure of inputs, got: {type(in_dims)}."
|
| 59 |
+
)
|
| 60 |
+
if len(args) == 0:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
f"vmap({_get_name(func)})(<inputs>): got no inputs. Maybe you forgot to add "
|
| 63 |
+
f"inputs, or you are trying to vmap over a function with no inputs. "
|
| 64 |
+
f"The latter is unsupported."
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
flat_args, args_spec = tree_flatten(args)
|
| 68 |
+
flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec)
|
| 69 |
+
if flat_in_dims is None:
|
| 70 |
+
raise ValueError(
|
| 71 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 72 |
+
f"in_dims is not compatible with the structure of `inputs`. "
|
| 73 |
+
f"in_dims has structure {tree_flatten(in_dims)[1]} but inputs "
|
| 74 |
+
f"has structure {args_spec}."
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
for arg, in_dim in zip(flat_args, flat_in_dims):
|
| 78 |
+
if not isinstance(in_dim, int) and in_dim is not None:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 81 |
+
f"Got in_dim={in_dim} for an input but in_dim must be either "
|
| 82 |
+
f"an integer dimension or None."
|
| 83 |
+
)
|
| 84 |
+
if isinstance(in_dim, int) and not isinstance(arg, Tensor):
|
| 85 |
+
raise ValueError(
|
| 86 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 87 |
+
f"Got in_dim={in_dim} for an input but the input is of type "
|
| 88 |
+
f"{type(arg)}. We cannot vmap over non-Tensor arguments, "
|
| 89 |
+
f"please use None as the respective in_dim"
|
| 90 |
+
)
|
| 91 |
+
if in_dim is not None and (in_dim < 0 or in_dim >= arg.dim()):
|
| 92 |
+
raise ValueError(
|
| 93 |
+
f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): "
|
| 94 |
+
f"Got in_dim={in_dim} for some input, but that input is a Tensor "
|
| 95 |
+
f"of dimensionality {arg.dim()} so expected in_dim to satisfy "
|
| 96 |
+
f"0 <= in_dim < {arg.dim()}."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args)
|
| 100 |
+
# See NOTE [Ignored _remove_batch_dim, _add_batch_dim]
|
| 101 |
+
batched_inputs = [
|
| 102 |
+
arg if in_dim is None else torch._add_batch_dim(arg, in_dim, vmap_level)
|
| 103 |
+
for in_dim, arg in zip(flat_in_dims, flat_args)
|
| 104 |
+
]
|
| 105 |
+
return tree_unflatten(batched_inputs, args_spec), batch_size
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Undos the batching (and any batch dimensions) associated with the `vmap_level`.
|
| 109 |
+
def _unwrap_batched(
|
| 110 |
+
batched_outputs: Union[Tensor, Tuple[Tensor, ...]],
|
| 111 |
+
out_dims: out_dims_t,
|
| 112 |
+
vmap_level: int,
|
| 113 |
+
batch_size: int,
|
| 114 |
+
func: Callable,
|
| 115 |
+
allow_none_pass_through: bool = False,
|
| 116 |
+
) -> Tuple:
|
| 117 |
+
num_outputs = _num_outputs(batched_outputs)
|
| 118 |
+
out_dims_as_tuple = _as_tuple(
|
| 119 |
+
out_dims,
|
| 120 |
+
num_outputs,
|
| 121 |
+
lambda: f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must "
|
| 122 |
+
f"have one dim per output (got {num_outputs} outputs) of {_get_name(func)}.",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# NOTE [Ignored _remove_batch_dim, _add_batch_dim]
|
| 126 |
+
# There is something wrong with our type bindings for functions that begin
|
| 127 |
+
# with '_', see #40397.
|
| 128 |
+
if isinstance(batched_outputs, Tensor):
|
| 129 |
+
out_dim = out_dims_as_tuple[0]
|
| 130 |
+
return torch._remove_batch_dim(batched_outputs, vmap_level, batch_size, out_dim) # type: ignore[return-value]
|
| 131 |
+
if allow_none_pass_through:
|
| 132 |
+
return tuple(
|
| 133 |
+
(
|
| 134 |
+
torch._remove_batch_dim(out, vmap_level, batch_size, out_dim)
|
| 135 |
+
if out is not None
|
| 136 |
+
else None
|
| 137 |
+
)
|
| 138 |
+
for out, out_dim in zip(batched_outputs, out_dims_as_tuple)
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
return tuple(
|
| 142 |
+
torch._remove_batch_dim(out, vmap_level, batch_size, out_dim)
|
| 143 |
+
for out, out_dim in zip(batched_outputs, out_dims_as_tuple)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# Checks that `fn` returned one or more Tensors and nothing else.
|
| 148 |
+
# NB: A python function that return multiple arguments returns a single tuple,
|
| 149 |
+
# so we are effectively checking that `outputs` is a single Tensor or a tuple of
|
| 150 |
+
# Tensors.
|
| 151 |
+
def _validate_outputs(outputs: Any, func: Callable) -> None:
|
| 152 |
+
if isinstance(outputs, Tensor):
|
| 153 |
+
return
|
| 154 |
+
if not isinstance(outputs, tuple):
|
| 155 |
+
raise ValueError(
|
| 156 |
+
f"vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return "
|
| 157 |
+
f"Tensors, got type {type(outputs)} as the return."
|
| 158 |
+
)
|
| 159 |
+
for idx, output in enumerate(outputs):
|
| 160 |
+
if isinstance(output, Tensor):
|
| 161 |
+
continue
|
| 162 |
+
raise ValueError(
|
| 163 |
+
f"vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return "
|
| 164 |
+
f"Tensors, got type {type(output)} for return {idx}."
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _check_out_dims_is_int_or_int_tuple(out_dims: out_dims_t, func: Callable) -> None:
|
| 169 |
+
if isinstance(out_dims, int):
|
| 170 |
+
return
|
| 171 |
+
if not isinstance(out_dims, tuple) or not all(
|
| 172 |
+
isinstance(out_dim, int) for out_dim in out_dims
|
| 173 |
+
):
|
| 174 |
+
raise ValueError(
|
| 175 |
+
f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be "
|
| 176 |
+
f"an int or a tuple of int representing where in the outputs the "
|
| 177 |
+
f"vmapped dimension should appear."
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _get_name(func: Callable):
|
| 182 |
+
if hasattr(func, "__name__"):
|
| 183 |
+
return func.__name__
|
| 184 |
+
|
| 185 |
+
# Not all callables have __name__, in fact, only static functions/methods do.
|
| 186 |
+
# A callable created via functools.partial or an nn.Module, to name some
|
| 187 |
+
# examples, don't have a __name__.
|
| 188 |
+
return repr(func)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors,
|
| 192 |
+
# sends those into func, and then unwraps the output BatchedTensors. Operations
|
| 193 |
+
# on BatchedTensors perform the batched operations that the user is asking for.
|
| 194 |
+
@deprecated(
|
| 195 |
+
"Please use `torch.vmap` instead of `torch._vmap_internals.vmap`.",
|
| 196 |
+
category=FutureWarning,
|
| 197 |
+
)
|
| 198 |
+
def vmap(func: Callable, in_dims: in_dims_t = 0, out_dims: out_dims_t = 0) -> Callable:
|
| 199 |
+
"""
|
| 200 |
+
Please use torch.vmap instead of this API.
|
| 201 |
+
"""
|
| 202 |
+
return _vmap(func, in_dims, out_dims)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# A version of vmap but without the initial "experimental prototype" warning
|
| 206 |
+
def _vmap(
|
| 207 |
+
func: Callable,
|
| 208 |
+
in_dims: in_dims_t = 0,
|
| 209 |
+
out_dims: out_dims_t = 0,
|
| 210 |
+
allow_none_pass_through: bool = False,
|
| 211 |
+
) -> Callable:
|
| 212 |
+
# The `allow_none_pass_through` argument is a temporary workaround may be removed.
|
| 213 |
+
# Currently it enables us to wrap the call in `autograd.grad` to the autograd engine,
|
| 214 |
+
# which may return None if any of the inputs are unused. See the issue discussing this:
|
| 215 |
+
# https://github.com/facebookresearch/functorch/issues/159.
|
| 216 |
+
@functools.wraps(func)
|
| 217 |
+
def wrapped(*args):
|
| 218 |
+
_check_out_dims_is_int_or_int_tuple(out_dims, func)
|
| 219 |
+
vmap_level = torch._C._vmapmode_increment_nesting()
|
| 220 |
+
try:
|
| 221 |
+
batched_inputs, batch_size = _create_batched_inputs(
|
| 222 |
+
in_dims, args, vmap_level, func
|
| 223 |
+
)
|
| 224 |
+
batched_outputs = func(*batched_inputs)
|
| 225 |
+
if not allow_none_pass_through:
|
| 226 |
+
_validate_outputs(batched_outputs, func)
|
| 227 |
+
return _unwrap_batched(
|
| 228 |
+
batched_outputs,
|
| 229 |
+
out_dims,
|
| 230 |
+
vmap_level,
|
| 231 |
+
batch_size,
|
| 232 |
+
func,
|
| 233 |
+
allow_none_pass_through=allow_none_pass_through,
|
| 234 |
+
)
|
| 235 |
+
finally:
|
| 236 |
+
torch._C._vmapmode_decrement_nesting()
|
| 237 |
+
|
| 238 |
+
return wrapped
|
parrot/lib/python3.10/site-packages/torch/autograd/__init__.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""
|
| 3 |
+
``torch.autograd`` provides classes and functions implementing automatic
|
| 4 |
+
differentiation of arbitrary scalar valued functions. It requires minimal
|
| 5 |
+
changes to the existing code - you only need to declare :class:`Tensor` s
|
| 6 |
+
for which gradients should be computed with the ``requires_grad=True`` keyword.
|
| 7 |
+
As of now, we only support autograd for floating point :class:`Tensor` types (
|
| 8 |
+
half, float, double and bfloat16) and complex :class:`Tensor` types (cfloat, cdouble).
|
| 9 |
+
"""
|
| 10 |
+
import warnings
|
| 11 |
+
from typing import Any, Callable, cast, List, Optional, Sequence, Tuple, Union
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from torch.types import _size, _TensorOrTensors, _TensorOrTensorsOrGradEdge
|
| 16 |
+
from .. import _vmap_internals
|
| 17 |
+
from ..overrides import handle_torch_function, has_torch_function, is_tensor_like
|
| 18 |
+
from . import forward_ad, functional, graph
|
| 19 |
+
from .anomaly_mode import detect_anomaly, set_detect_anomaly
|
| 20 |
+
from .function import Function, NestedIOFunction
|
| 21 |
+
from .grad_mode import (
|
| 22 |
+
_force_original_view_tracking,
|
| 23 |
+
_unsafe_preserve_version_counter,
|
| 24 |
+
enable_grad,
|
| 25 |
+
inference_mode,
|
| 26 |
+
no_grad,
|
| 27 |
+
set_grad_enabled,
|
| 28 |
+
set_multithreading_enabled,
|
| 29 |
+
)
|
| 30 |
+
from .gradcheck import gradcheck, gradgradcheck
|
| 31 |
+
from .graph import _engine_run_backward
|
| 32 |
+
|
| 33 |
+
from .variable import Variable
|
| 34 |
+
|
| 35 |
+
__all__ = [
|
| 36 |
+
"Variable",
|
| 37 |
+
"Function",
|
| 38 |
+
"backward",
|
| 39 |
+
"grad_mode",
|
| 40 |
+
"NestedIOFunction",
|
| 41 |
+
"detect_anomaly",
|
| 42 |
+
"enable_grad",
|
| 43 |
+
"grad",
|
| 44 |
+
"gradcheck",
|
| 45 |
+
"gradgradcheck",
|
| 46 |
+
"inference_mode",
|
| 47 |
+
"no_grad",
|
| 48 |
+
"set_detect_anomaly",
|
| 49 |
+
"set_grad_enabled",
|
| 50 |
+
"set_multithreading_enabled",
|
| 51 |
+
"variable",
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
_OptionalTensor = Optional[torch.Tensor]
|
| 55 |
+
_ShapeorNestedShape = Union[_size, Sequence[_size], torch.Tensor]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _calculate_shape(
|
| 59 |
+
output: torch.Tensor, grad: torch.Tensor, is_grads_batched: bool
|
| 60 |
+
) -> Tuple[_ShapeorNestedShape, _ShapeorNestedShape]:
|
| 61 |
+
# is_same_size ensures that both tensors are either nested or non nested
|
| 62 |
+
# circular import
|
| 63 |
+
from torch.nested._internal.nested_tensor import NestedTensor
|
| 64 |
+
|
| 65 |
+
if output.is_nested and not isinstance(output, NestedTensor):
|
| 66 |
+
if is_grads_batched:
|
| 67 |
+
raise RuntimeError("Batched grads are not supported with Nested Tensor.")
|
| 68 |
+
out_shape = output._nested_tensor_size()
|
| 69 |
+
grad_shape = grad._nested_tensor_size()
|
| 70 |
+
|
| 71 |
+
return out_shape, grad_shape
|
| 72 |
+
|
| 73 |
+
reg_out_shape = output.shape
|
| 74 |
+
reg_grad_shape = grad.shape if not is_grads_batched else grad.shape[1:]
|
| 75 |
+
return reg_out_shape, reg_grad_shape
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _make_grads(
|
| 79 |
+
outputs: Sequence[torch.Tensor],
|
| 80 |
+
grads: Sequence[_OptionalTensor],
|
| 81 |
+
is_grads_batched: bool,
|
| 82 |
+
) -> Tuple[_OptionalTensor, ...]:
|
| 83 |
+
new_grads: List[_OptionalTensor] = []
|
| 84 |
+
for out, grad in zip(outputs, grads):
|
| 85 |
+
if isinstance(grad, torch.Tensor):
|
| 86 |
+
from torch.fx.experimental.symbolic_shapes import expect_true, sym_eq
|
| 87 |
+
|
| 88 |
+
first_grad = grad if not is_grads_batched else grad[0]
|
| 89 |
+
# TODO: We can remove this conditional once we uniformly use
|
| 90 |
+
# singleton int to represent jagged dimension, so that size() call
|
| 91 |
+
# on nested tensor works
|
| 92 |
+
if out.is_nested or first_grad.is_nested:
|
| 93 |
+
shape_matches = torch.is_same_size(out, first_grad)
|
| 94 |
+
else:
|
| 95 |
+
# We need to do a regular size check, without going through
|
| 96 |
+
# the operator, to be able to handle unbacked symints
|
| 97 |
+
# (expect_true ensures we can deal with unbacked)
|
| 98 |
+
shape_matches = expect_true(sym_eq(out.size(), first_grad.size()))
|
| 99 |
+
if not shape_matches:
|
| 100 |
+
out_shape, grad_shape = _calculate_shape(
|
| 101 |
+
out, first_grad, is_grads_batched
|
| 102 |
+
)
|
| 103 |
+
if is_grads_batched:
|
| 104 |
+
raise RuntimeError(
|
| 105 |
+
"If `is_grads_batched=True`, we interpret the first "
|
| 106 |
+
"dimension of each grad_output as the batch dimension. "
|
| 107 |
+
"The sizes of the remaining dimensions are expected to match "
|
| 108 |
+
"the shape of corresponding output, but a mismatch "
|
| 109 |
+
"was detected: grad_output["
|
| 110 |
+
+ str(grads.index(grad))
|
| 111 |
+
+ "] has a shape of "
|
| 112 |
+
+ str(grad_shape)
|
| 113 |
+
+ " and output["
|
| 114 |
+
+ str(outputs.index(out))
|
| 115 |
+
+ "] has a shape of "
|
| 116 |
+
+ str(out_shape)
|
| 117 |
+
+ ". "
|
| 118 |
+
"If you only want some tensors in `grad_output` to be considered "
|
| 119 |
+
"batched, consider using vmap."
|
| 120 |
+
)
|
| 121 |
+
else:
|
| 122 |
+
raise RuntimeError(
|
| 123 |
+
"Mismatch in shape: grad_output["
|
| 124 |
+
+ str(grads.index(grad))
|
| 125 |
+
+ "] has a shape of "
|
| 126 |
+
+ str(grad_shape)
|
| 127 |
+
+ " and output["
|
| 128 |
+
+ str(outputs.index(out))
|
| 129 |
+
+ "] has a shape of "
|
| 130 |
+
+ str(out_shape)
|
| 131 |
+
+ "."
|
| 132 |
+
)
|
| 133 |
+
if out.dtype.is_complex != grad.dtype.is_complex:
|
| 134 |
+
raise RuntimeError(
|
| 135 |
+
"For complex Tensors, both grad_output and output"
|
| 136 |
+
" are required to have the same dtype."
|
| 137 |
+
" Mismatch in dtype: grad_output["
|
| 138 |
+
+ str(grads.index(grad))
|
| 139 |
+
+ "] has a dtype of "
|
| 140 |
+
+ str(grad.dtype)
|
| 141 |
+
+ " and output["
|
| 142 |
+
+ str(outputs.index(out))
|
| 143 |
+
+ "] has a dtype of "
|
| 144 |
+
+ str(out.dtype)
|
| 145 |
+
+ "."
|
| 146 |
+
)
|
| 147 |
+
new_grads.append(grad)
|
| 148 |
+
elif grad is None:
|
| 149 |
+
if out.requires_grad:
|
| 150 |
+
if out.numel() != 1:
|
| 151 |
+
raise RuntimeError(
|
| 152 |
+
"grad can be implicitly created only for scalar outputs"
|
| 153 |
+
)
|
| 154 |
+
if not out.dtype.is_floating_point:
|
| 155 |
+
msg = (
|
| 156 |
+
"grad can be implicitly created only for real scalar outputs"
|
| 157 |
+
f" but got {out.dtype}"
|
| 158 |
+
)
|
| 159 |
+
raise RuntimeError(msg)
|
| 160 |
+
new_grads.append(
|
| 161 |
+
torch.ones_like(out, memory_format=torch.preserve_format)
|
| 162 |
+
)
|
| 163 |
+
else:
|
| 164 |
+
new_grads.append(None)
|
| 165 |
+
else:
|
| 166 |
+
raise TypeError(
|
| 167 |
+
"gradients can be either Tensors or None, but got "
|
| 168 |
+
+ type(grad).__name__
|
| 169 |
+
)
|
| 170 |
+
return tuple(new_grads)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _tensor_or_tensors_to_tuple(
|
| 174 |
+
tensors: Optional[_TensorOrTensors], length: int
|
| 175 |
+
) -> Tuple[_OptionalTensor, ...]:
|
| 176 |
+
if tensors is None:
|
| 177 |
+
return (None,) * length
|
| 178 |
+
if isinstance(tensors, torch.Tensor):
|
| 179 |
+
return (tensors,)
|
| 180 |
+
return tuple(tensors)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def backward(
|
| 184 |
+
tensors: _TensorOrTensors,
|
| 185 |
+
grad_tensors: Optional[_TensorOrTensors] = None,
|
| 186 |
+
retain_graph: Optional[bool] = None,
|
| 187 |
+
create_graph: bool = False,
|
| 188 |
+
grad_variables: Optional[_TensorOrTensors] = None,
|
| 189 |
+
inputs: Optional[_TensorOrTensorsOrGradEdge] = None,
|
| 190 |
+
) -> None:
|
| 191 |
+
r"""Computes the sum of gradients of given tensors with respect to graph
|
| 192 |
+
leaves.
|
| 193 |
+
|
| 194 |
+
The graph is differentiated using the chain rule. If any of ``tensors``
|
| 195 |
+
are non-scalar (i.e. their data has more than one element) and require
|
| 196 |
+
gradient, then the Jacobian-vector product would be computed, in this
|
| 197 |
+
case the function additionally requires specifying ``grad_tensors``.
|
| 198 |
+
It should be a sequence of matching length, that contains the "vector"
|
| 199 |
+
in the Jacobian-vector product, usually the gradient of the differentiated
|
| 200 |
+
function w.r.t. corresponding tensors (``None`` is an acceptable value for
|
| 201 |
+
all tensors that don't need gradient tensors).
|
| 202 |
+
|
| 203 |
+
This function accumulates gradients in the leaves - you might need to zero
|
| 204 |
+
``.grad`` attributes or set them to ``None`` before calling it.
|
| 205 |
+
See :ref:`Default gradient layouts<default-grad-layouts>`
|
| 206 |
+
for details on the memory layout of accumulated gradients.
|
| 207 |
+
|
| 208 |
+
.. note::
|
| 209 |
+
Using this method with ``create_graph=True`` will create a reference cycle
|
| 210 |
+
between the parameter and its gradient which can cause a memory leak.
|
| 211 |
+
We recommend using ``autograd.grad`` when creating the graph to avoid this.
|
| 212 |
+
If you have to use this function, make sure to reset the ``.grad`` fields of your
|
| 213 |
+
parameters to ``None`` after use to break the cycle and avoid the leak.
|
| 214 |
+
|
| 215 |
+
.. note::
|
| 216 |
+
|
| 217 |
+
If you run any forward ops, create ``grad_tensors``, and/or call ``backward``
|
| 218 |
+
in a user-specified CUDA stream context, see
|
| 219 |
+
:ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.
|
| 220 |
+
|
| 221 |
+
.. note::
|
| 222 |
+
|
| 223 |
+
When ``inputs`` are provided and a given input is not a leaf,
|
| 224 |
+
the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients).
|
| 225 |
+
It is an implementation detail on which the user should not rely.
|
| 226 |
+
See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
tensors (Sequence[Tensor] or Tensor): Tensors of which the derivative will be
|
| 230 |
+
computed.
|
| 231 |
+
grad_tensors (Sequence[Tensor or None] or Tensor, optional): The "vector" in
|
| 232 |
+
the Jacobian-vector product, usually gradients w.r.t. each element of
|
| 233 |
+
corresponding tensors. None values can be specified for scalar Tensors or
|
| 234 |
+
ones that don't require grad. If a None value would be acceptable for all
|
| 235 |
+
grad_tensors, then this argument is optional.
|
| 236 |
+
retain_graph (bool, optional): If ``False``, the graph used to compute the grad
|
| 237 |
+
will be freed. Note that in nearly all cases setting this option to ``True``
|
| 238 |
+
is not needed and often can be worked around in a much more efficient
|
| 239 |
+
way. Defaults to the value of ``create_graph``.
|
| 240 |
+
create_graph (bool, optional): If ``True``, graph of the derivative will
|
| 241 |
+
be constructed, allowing to compute higher order derivative products.
|
| 242 |
+
Defaults to ``False``.
|
| 243 |
+
inputs (Sequence[Tensor] or Tensor or Sequence[GradientEdge], optional): Inputs w.r.t. which the gradient
|
| 244 |
+
be will accumulated into ``.grad``. All other Tensors will be ignored. If
|
| 245 |
+
not provided, the gradient is accumulated into all the leaf Tensors that
|
| 246 |
+
were used to compute the :attr:`tensors`.
|
| 247 |
+
"""
|
| 248 |
+
if torch._C._are_functorch_transforms_active():
|
| 249 |
+
raise RuntimeError(
|
| 250 |
+
"backward() called inside a functorch transform. This is not "
|
| 251 |
+
"supported, please use functorch.grad or functorch.vjp instead "
|
| 252 |
+
"or call backward() outside of functorch transforms."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
if grad_variables is not None:
|
| 256 |
+
warnings.warn(
|
| 257 |
+
"`grad_variables` is deprecated. Use `grad_tensors` instead.",
|
| 258 |
+
FutureWarning,
|
| 259 |
+
stacklevel=2,
|
| 260 |
+
)
|
| 261 |
+
if grad_tensors is None:
|
| 262 |
+
grad_tensors = grad_variables
|
| 263 |
+
else:
|
| 264 |
+
raise RuntimeError(
|
| 265 |
+
"`grad_tensors` and `grad_variables` (deprecated) "
|
| 266 |
+
"arguments both passed to `backward()`. Please only "
|
| 267 |
+
"use `grad_tensors`."
|
| 268 |
+
)
|
| 269 |
+
if inputs is not None and len(inputs) == 0:
|
| 270 |
+
raise RuntimeError("`inputs` argument to `backward()` cannot be empty.")
|
| 271 |
+
|
| 272 |
+
tensors = (tensors,) if isinstance(tensors, torch.Tensor) else tuple(tensors)
|
| 273 |
+
inputs = (
|
| 274 |
+
(inputs,)
|
| 275 |
+
if isinstance(inputs, (torch.Tensor, graph.GradientEdge))
|
| 276 |
+
else tuple(inputs)
|
| 277 |
+
if inputs is not None
|
| 278 |
+
else tuple()
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
grad_tensors_ = _tensor_or_tensors_to_tuple(grad_tensors, len(tensors))
|
| 282 |
+
grad_tensors_ = _make_grads(tensors, grad_tensors_, is_grads_batched=False)
|
| 283 |
+
if retain_graph is None:
|
| 284 |
+
retain_graph = create_graph
|
| 285 |
+
|
| 286 |
+
# The reason we repeat the same comment below is that
|
| 287 |
+
# some Python versions print out the first line of a multi-line function
|
| 288 |
+
# calls in the traceback and some print out the last line
|
| 289 |
+
_engine_run_backward(
|
| 290 |
+
tensors,
|
| 291 |
+
grad_tensors_,
|
| 292 |
+
retain_graph,
|
| 293 |
+
create_graph,
|
| 294 |
+
inputs,
|
| 295 |
+
allow_unreachable=True,
|
| 296 |
+
accumulate_grad=True,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def grad(
|
| 301 |
+
outputs: _TensorOrTensors,
|
| 302 |
+
inputs: _TensorOrTensorsOrGradEdge,
|
| 303 |
+
grad_outputs: Optional[_TensorOrTensors] = None,
|
| 304 |
+
retain_graph: Optional[bool] = None,
|
| 305 |
+
create_graph: bool = False,
|
| 306 |
+
only_inputs: bool = True,
|
| 307 |
+
allow_unused: Optional[bool] = None,
|
| 308 |
+
is_grads_batched: bool = False,
|
| 309 |
+
materialize_grads: bool = False,
|
| 310 |
+
) -> Tuple[torch.Tensor, ...]:
|
| 311 |
+
r"""Computes and returns the sum of gradients of outputs with respect to
|
| 312 |
+
the inputs.
|
| 313 |
+
|
| 314 |
+
``grad_outputs`` should be a sequence of length matching ``output``
|
| 315 |
+
containing the "vector" in vector-Jacobian product, usually the pre-computed
|
| 316 |
+
gradients w.r.t. each of the outputs. If an output doesn't require_grad,
|
| 317 |
+
then the gradient can be ``None``).
|
| 318 |
+
|
| 319 |
+
.. note::
|
| 320 |
+
|
| 321 |
+
If you run any forward ops, create ``grad_outputs``, and/or call ``grad``
|
| 322 |
+
in a user-specified CUDA stream context, see
|
| 323 |
+
:ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.
|
| 324 |
+
|
| 325 |
+
.. note::
|
| 326 |
+
|
| 327 |
+
``only_inputs`` argument is deprecated and is ignored now (defaults to ``True``).
|
| 328 |
+
To accumulate gradient for other parts of the graph, please use
|
| 329 |
+
``torch.autograd.backward``.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
outputs (sequence of Tensor): outputs of the differentiated function.
|
| 333 |
+
inputs (sequence of Tensor or GradientEdge): Inputs w.r.t. which the gradient will be
|
| 334 |
+
returned (and not accumulated into ``.grad``).
|
| 335 |
+
grad_outputs (sequence of Tensor): The "vector" in the vector-Jacobian product.
|
| 336 |
+
Usually gradients w.r.t. each output. None values can be specified for scalar
|
| 337 |
+
Tensors or ones that don't require grad. If a None value would be acceptable
|
| 338 |
+
for all grad_tensors, then this argument is optional. Default: None.
|
| 339 |
+
retain_graph (bool, optional): If ``False``, the graph used to compute the grad
|
| 340 |
+
will be freed. Note that in nearly all cases setting this option to ``True``
|
| 341 |
+
is not needed and often can be worked around in a much more efficient
|
| 342 |
+
way. Defaults to the value of ``create_graph``.
|
| 343 |
+
create_graph (bool, optional): If ``True``, graph of the derivative will
|
| 344 |
+
be constructed, allowing to compute higher order derivative products.
|
| 345 |
+
Default: ``False``.
|
| 346 |
+
allow_unused (Optional[bool], optional): If ``False``, specifying inputs
|
| 347 |
+
that were not used when computing outputs (and therefore their grad is
|
| 348 |
+
always zero) is an error. Defaults to the value of ``materialize_grads``.
|
| 349 |
+
is_grads_batched (bool, optional): If ``True``, the first dimension of each
|
| 350 |
+
tensor in ``grad_outputs`` will be interpreted as the batch dimension.
|
| 351 |
+
Instead of computing a single vector-Jacobian product, we compute a
|
| 352 |
+
batch of vector-Jacobian products for each "vector" in the batch.
|
| 353 |
+
We use the vmap prototype feature as the backend to vectorize calls
|
| 354 |
+
to the autograd engine so that this computation can be performed in a
|
| 355 |
+
single call. This should lead to performance improvements when compared
|
| 356 |
+
to manually looping and performing backward multiple times. Note that
|
| 357 |
+
due to this feature being experimental, there may be performance
|
| 358 |
+
cliffs. Please use ``torch._C._debug_only_display_vmap_fallback_warnings(True)``
|
| 359 |
+
to show any performance warnings and file an issue on github if warnings exist
|
| 360 |
+
for your use case. Defaults to ``False``.
|
| 361 |
+
materialize_grads (bool, optional): If ``True``, set the gradient for unused inputs
|
| 362 |
+
to zero instead of None. This is useful when computing higher-order derivatives.
|
| 363 |
+
If ``materialize_grads`` is ``True`` and ``allow_unused`` is ``False``, an error
|
| 364 |
+
will be raised. Defaults to ``False``.
|
| 365 |
+
|
| 366 |
+
"""
|
| 367 |
+
if materialize_grads and allow_unused is False:
|
| 368 |
+
raise ValueError(
|
| 369 |
+
"Expected allow_unused to be True or not passed when materialize_grads=True, "
|
| 370 |
+
"but got: allow_unused=False."
|
| 371 |
+
)
|
| 372 |
+
if allow_unused is None:
|
| 373 |
+
allow_unused = materialize_grads
|
| 374 |
+
t_outputs = cast(
|
| 375 |
+
Tuple[torch.Tensor, ...],
|
| 376 |
+
(outputs,) if is_tensor_like(outputs) else tuple(outputs),
|
| 377 |
+
)
|
| 378 |
+
if is_tensor_like(inputs) or isinstance(inputs, graph.GradientEdge):
|
| 379 |
+
inputs = cast(_TensorOrTensorsOrGradEdge, (inputs,))
|
| 380 |
+
else:
|
| 381 |
+
inputs = tuple(inputs)
|
| 382 |
+
t_inputs = tuple(i for i in inputs if is_tensor_like(i))
|
| 383 |
+
overridable_args = t_outputs + t_inputs
|
| 384 |
+
if has_torch_function(overridable_args):
|
| 385 |
+
return handle_torch_function(
|
| 386 |
+
grad,
|
| 387 |
+
overridable_args,
|
| 388 |
+
t_outputs,
|
| 389 |
+
inputs,
|
| 390 |
+
grad_outputs=grad_outputs,
|
| 391 |
+
retain_graph=retain_graph,
|
| 392 |
+
create_graph=create_graph,
|
| 393 |
+
only_inputs=only_inputs,
|
| 394 |
+
allow_unused=allow_unused,
|
| 395 |
+
is_grads_batched=is_grads_batched,
|
| 396 |
+
materialize_grads=materialize_grads,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
if not only_inputs:
|
| 400 |
+
warnings.warn(
|
| 401 |
+
"only_inputs argument is deprecated and is ignored now "
|
| 402 |
+
"(defaults to True). To accumulate gradient for other "
|
| 403 |
+
"parts of the graph, please use torch.autograd.backward.",
|
| 404 |
+
FutureWarning,
|
| 405 |
+
stacklevel=2,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
grad_outputs_ = _tensor_or_tensors_to_tuple(grad_outputs, len(t_outputs))
|
| 409 |
+
grad_outputs_ = _make_grads(
|
| 410 |
+
t_outputs, grad_outputs_, is_grads_batched=is_grads_batched
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
if retain_graph is None:
|
| 414 |
+
retain_graph = create_graph
|
| 415 |
+
|
| 416 |
+
# The reason we repeat the same comment several times below is because
|
| 417 |
+
# some Python versions print out the first line of multi-line function
|
| 418 |
+
# calls in the traceback and some print out the last line
|
| 419 |
+
if is_grads_batched:
|
| 420 |
+
|
| 421 |
+
def vjp(gO):
|
| 422 |
+
return _engine_run_backward(
|
| 423 |
+
t_outputs,
|
| 424 |
+
gO,
|
| 425 |
+
retain_graph,
|
| 426 |
+
create_graph,
|
| 427 |
+
inputs,
|
| 428 |
+
allow_unused,
|
| 429 |
+
accumulate_grad=False,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
result = _vmap_internals._vmap(vjp, 0, 0, allow_none_pass_through=True)(
|
| 433 |
+
grad_outputs_
|
| 434 |
+
)
|
| 435 |
+
else:
|
| 436 |
+
result = _engine_run_backward(
|
| 437 |
+
t_outputs,
|
| 438 |
+
grad_outputs_,
|
| 439 |
+
retain_graph,
|
| 440 |
+
create_graph,
|
| 441 |
+
inputs,
|
| 442 |
+
allow_unused,
|
| 443 |
+
accumulate_grad=False,
|
| 444 |
+
)
|
| 445 |
+
if materialize_grads:
|
| 446 |
+
if any(
|
| 447 |
+
result[i] is None and not is_tensor_like(inputs[i])
|
| 448 |
+
for i in range(len(inputs))
|
| 449 |
+
):
|
| 450 |
+
raise RuntimeError(
|
| 451 |
+
"materialize_grads cannot be used when the given input is a GradientEdge"
|
| 452 |
+
)
|
| 453 |
+
result = tuple(
|
| 454 |
+
output
|
| 455 |
+
if output is not None
|
| 456 |
+
else torch.zeros_like(input, requires_grad=True)
|
| 457 |
+
for (output, input) in zip(result, inputs)
|
| 458 |
+
)
|
| 459 |
+
return result
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
# This function applies in case of gradient checkpointing for memory
|
| 463 |
+
# optimization. Currently, gradient checkpointing is supported only if the
|
| 464 |
+
# execution engine is invoked through torch.autograd.backward() and its
|
| 465 |
+
# inputs argument is not passed. It is not supported for torch.autograd.grad().
|
| 466 |
+
# This is because if inputs are specified, the gradient won't be calculated for
|
| 467 |
+
# anything else e.g. model parameters like weights, bias etc.
|
| 468 |
+
#
|
| 469 |
+
# This function returns whether the checkpointing is valid i.e. torch.autograd.backward
|
| 470 |
+
# or not i.e. torch.autograd.grad. The implementation works by maintaining a thread
|
| 471 |
+
# local variable in torch/csrc/autograd/engine.cpp which looks at the NodeTask
|
| 472 |
+
# in the stack and before a NodeTask is executed in evaluate_function, it
|
| 473 |
+
# checks for whether reentrant backwards is imperative or not.
|
| 474 |
+
# See https://github.com/pytorch/pytorch/pull/4594 for more discussion/context
|
| 475 |
+
def _is_checkpoint_valid():
|
| 476 |
+
return Variable._execution_engine.is_checkpoint_valid()
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def variable(*args, **kwargs):
|
| 480 |
+
raise RuntimeError(
|
| 481 |
+
"torch.autograd.variable(...) is deprecated, use torch.tensor(...) instead"
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
# Monkey patching variable.Variable to fix FX codegen. FX generates a call by roughly doing
|
| 486 |
+
# f"{fn.__module__}.{fn.__name__}(...). This yields torch.autograd.variable.Variable(...) in the
|
| 487 |
+
# output of an FX graph. Unfortunately the module name torch.autograd.variable is shadowed by the
|
| 488 |
+
# deprecated function - variable(...).
|
| 489 |
+
variable.Variable = Variable # type: ignore[attr-defined]
|
| 490 |
+
|
| 491 |
+
if not torch._C._autograd_init():
|
| 492 |
+
raise RuntimeError("autograd initialization failed")
|
| 493 |
+
|
| 494 |
+
# Import all native method/classes
|
| 495 |
+
from torch._C._autograd import (
|
| 496 |
+
_add_metadata_json,
|
| 497 |
+
_disable_profiler,
|
| 498 |
+
_disable_profiler_legacy,
|
| 499 |
+
_enable_profiler,
|
| 500 |
+
_enable_profiler_legacy,
|
| 501 |
+
_enable_record_function,
|
| 502 |
+
_get_sequence_nr,
|
| 503 |
+
_kineto_step,
|
| 504 |
+
_KinetoEvent,
|
| 505 |
+
_pop_saved_tensors_default_hooks,
|
| 506 |
+
_prepare_profiler,
|
| 507 |
+
_profiler_enabled,
|
| 508 |
+
_ProfilerResult,
|
| 509 |
+
_push_saved_tensors_default_hooks,
|
| 510 |
+
_record_function_with_args_enter,
|
| 511 |
+
_record_function_with_args_exit,
|
| 512 |
+
_set_empty_test_observer,
|
| 513 |
+
_supported_activities,
|
| 514 |
+
DeviceType,
|
| 515 |
+
kineto_available,
|
| 516 |
+
ProfilerEvent,
|
| 517 |
+
SavedTensor,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
from torch._C._profiler import ProfilerActivity, ProfilerConfig, ProfilerState
|
| 521 |
+
|
| 522 |
+
from . import profiler
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def _register_py_tensor_class_for_device(device, cls):
|
| 526 |
+
if not isinstance(cls, type):
|
| 527 |
+
raise RuntimeError("cls isn't a typeinfo object")
|
| 528 |
+
torch._C._register_py_class_for_device(device, cls)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
is_multithreading_enabled = torch._C._is_multithreading_enabled
|
| 532 |
+
torch._C._add_docstr(
|
| 533 |
+
is_multithreading_enabled, "Returns True if multithreading is currently enabled."
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
is_view_replay_enabled = torch._C._is_view_replay_enabled
|
| 537 |
+
torch._C._add_docstr(
|
| 538 |
+
is_view_replay_enabled, "Returns True if view-replay is currently enabled."
|
| 539 |
+
)
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/anomaly_mode.cpython-310.pyc
ADDED
|
Binary file (5.51 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/forward_ad.cpython-310.pyc
ADDED
|
Binary file (7.26 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/function.cpython-310.pyc
ADDED
|
Binary file (32.2 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/functional.cpython-310.pyc
ADDED
|
Binary file (36 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/grad_mode.cpython-310.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/gradcheck.cpython-310.pyc
ADDED
|
Binary file (61.1 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/graph.cpython-310.pyc
ADDED
|
Binary file (26.6 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/profiler.cpython-310.pyc
ADDED
|
Binary file (37.1 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/profiler_legacy.cpython-310.pyc
ADDED
|
Binary file (7.81 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/profiler_util.cpython-310.pyc
ADDED
|
Binary file (29.3 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/__pycache__/variable.cpython-310.pyc
ADDED
|
Binary file (829 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/_functions/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .tensor import * # noqa: F403
|
parrot/lib/python3.10/site-packages/torch/autograd/_functions/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (200 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/_functions/__pycache__/tensor.cpython-310.pyc
ADDED
|
Binary file (2.21 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/_functions/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (1.49 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/torch/autograd/_functions/tensor.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from functools import reduce
|
| 4 |
+
from typing_extensions import deprecated
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch._utils
|
| 8 |
+
from ..function import Function
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Type(Function):
|
| 12 |
+
@staticmethod
|
| 13 |
+
@deprecated(
|
| 14 |
+
"`torch.autograd._functions.Type` is deprecated as of PyTorch 2.1, "
|
| 15 |
+
"please use `torch.tensor.to(dtype=dtype)` instead.",
|
| 16 |
+
category=FutureWarning,
|
| 17 |
+
)
|
| 18 |
+
def forward(ctx, i, dest_type):
|
| 19 |
+
ctx.input_type = type(i)
|
| 20 |
+
ctx.input_device = -1 if not i.is_cuda else i.get_device()
|
| 21 |
+
return i.type(dest_type)
|
| 22 |
+
|
| 23 |
+
@staticmethod
|
| 24 |
+
def backward(ctx, grad_output):
|
| 25 |
+
if ctx.input_device == -1:
|
| 26 |
+
return grad_output.type(ctx.input_type), None
|
| 27 |
+
else:
|
| 28 |
+
with torch.cuda.device(ctx.input_device):
|
| 29 |
+
return grad_output.type(ctx.input_type), None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# TODO: deprecate this
|
| 33 |
+
class Resize(Function):
|
| 34 |
+
@staticmethod
|
| 35 |
+
def forward(ctx, tensor, sizes):
|
| 36 |
+
ctx.sizes = sizes
|
| 37 |
+
ctx.numel = reduce(operator.mul, sizes, 1)
|
| 38 |
+
if tensor.numel() != ctx.numel:
|
| 39 |
+
raise RuntimeError(
|
| 40 |
+
(
|
| 41 |
+
"requested resize to {} ({} elements in total), "
|
| 42 |
+
"but the given tensor has a size of {} ({} elements). "
|
| 43 |
+
"autograd's resize can only change the shape of a given "
|
| 44 |
+
"tensor, while preserving the number of elements. "
|
| 45 |
+
).format(
|
| 46 |
+
"x".join(map(str, sizes)),
|
| 47 |
+
ctx.numel,
|
| 48 |
+
"x".join(map(str, tensor.size())),
|
| 49 |
+
tensor.numel(),
|
| 50 |
+
)
|
| 51 |
+
)
|
| 52 |
+
ctx.input_sizes = tensor.size()
|
| 53 |
+
if tensor.is_quantized:
|
| 54 |
+
tensor.copy_(tensor)
|
| 55 |
+
return tensor.contiguous().view(*sizes)
|
| 56 |
+
if tensor.is_contiguous():
|
| 57 |
+
result = tensor.new(tensor).contiguous().view(*sizes)
|
| 58 |
+
return result
|
| 59 |
+
else:
|
| 60 |
+
return tensor.contiguous().view(*sizes)
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def backward(ctx, grad_output):
|
| 64 |
+
assert grad_output.numel() == ctx.numel
|
| 65 |
+
return grad_output.contiguous().view(ctx.input_sizes), None
|
parrot/lib/python3.10/site-packages/torch/autograd/_functions/utils.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from functools import reduce
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def maybe_view(tensor, size, check_same_size=True):
|
| 7 |
+
if check_same_size and tensor.size() == size:
|
| 8 |
+
return tensor
|
| 9 |
+
return tensor.contiguous().view(size)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def maybe_unexpand(tensor, old_size, check_same_size=True):
|
| 13 |
+
if check_same_size and tensor.size() == old_size:
|
| 14 |
+
return tensor
|
| 15 |
+
num_unsqueezed = tensor.dim() - len(old_size)
|
| 16 |
+
expanded_dims = [
|
| 17 |
+
dim
|
| 18 |
+
for dim, (expanded, original) in enumerate(
|
| 19 |
+
zip(tensor.size()[num_unsqueezed:], old_size)
|
| 20 |
+
)
|
| 21 |
+
if expanded != original
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
for _ in range(num_unsqueezed):
|
| 25 |
+
tensor = tensor.sum(0, keepdim=False)
|
| 26 |
+
for dim in expanded_dims:
|
| 27 |
+
tensor = tensor.sum(dim, keepdim=True)
|
| 28 |
+
return tensor
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Check whether the op enable broadcasting, and whether it is supported by ONNX.
|
| 32 |
+
# If dims1 and dims2 are different, then broadcast is True.
|
| 33 |
+
# We always assume the combination of dims1 and dims2 is broadcastable.
|
| 34 |
+
# The following types of broadcasting are supported in ONNX:
|
| 35 |
+
# 1) Only one element in dims2, such as dims2 = [1, 1]
|
| 36 |
+
# 2) dims2 is suffix of dims1, such as dims1 = [2, 3, 4], and dims2 = [3, 4]
|
| 37 |
+
# Details can be found here: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Gemm
|
| 38 |
+
def check_onnx_broadcast(dims1, dims2):
|
| 39 |
+
broadcast = False
|
| 40 |
+
supported = True
|
| 41 |
+
len1 = len(dims1)
|
| 42 |
+
len2 = len(dims2)
|
| 43 |
+
numel1 = reduce(operator.mul, dims1)
|
| 44 |
+
numel2 = reduce(operator.mul, dims2)
|
| 45 |
+
if len1 < len2:
|
| 46 |
+
broadcast = True
|
| 47 |
+
if numel2 != 1:
|
| 48 |
+
supported = False
|
| 49 |
+
elif len1 > len2:
|
| 50 |
+
broadcast = True
|
| 51 |
+
if numel2 != 1 and dims1[len1 - len2 :] != dims2:
|
| 52 |
+
supported = False
|
| 53 |
+
else:
|
| 54 |
+
if dims1 != dims2:
|
| 55 |
+
broadcast = True
|
| 56 |
+
if numel2 != 1:
|
| 57 |
+
supported = False
|
| 58 |
+
|
| 59 |
+
if not supported:
|
| 60 |
+
raise ValueError(
|
| 61 |
+
f"Numpy style broadcasting is not supported in ONNX. Input dims are: {dims1}, {dims2}"
|
| 62 |
+
)
|
| 63 |
+
return broadcast
|
parrot/lib/python3.10/site-packages/torch/autograd/anomaly_mode.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
__all__ = ["detect_anomaly", "set_detect_anomaly"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class detect_anomaly:
|
| 10 |
+
r"""Context-manager that enable anomaly detection for the autograd engine.
|
| 11 |
+
|
| 12 |
+
This does two things:
|
| 13 |
+
|
| 14 |
+
- Running the forward pass with detection enabled will allow the backward
|
| 15 |
+
pass to print the traceback of the forward operation that created the failing
|
| 16 |
+
backward function.
|
| 17 |
+
- If ``check_nan`` is ``True``, any backward computation that generate "nan"
|
| 18 |
+
value will raise an error. Default ``True``.
|
| 19 |
+
|
| 20 |
+
.. warning::
|
| 21 |
+
This mode should be enabled only for debugging as the different tests
|
| 22 |
+
will slow down your program execution.
|
| 23 |
+
|
| 24 |
+
Example:
|
| 25 |
+
|
| 26 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_ANOMALY)
|
| 27 |
+
>>> import torch
|
| 28 |
+
>>> from torch import autograd
|
| 29 |
+
>>> class MyFunc(autograd.Function):
|
| 30 |
+
... @staticmethod
|
| 31 |
+
... def forward(ctx, inp):
|
| 32 |
+
... return inp.clone()
|
| 33 |
+
... @staticmethod
|
| 34 |
+
... def backward(ctx, gO):
|
| 35 |
+
... # Error during the backward pass
|
| 36 |
+
... raise RuntimeError("Some error in backward")
|
| 37 |
+
... return gO.clone()
|
| 38 |
+
>>> def run_fn(a):
|
| 39 |
+
... out = MyFunc.apply(a)
|
| 40 |
+
... return out.sum()
|
| 41 |
+
>>> inp = torch.rand(10, 10, requires_grad=True)
|
| 42 |
+
>>> out = run_fn(inp)
|
| 43 |
+
>>> out.backward()
|
| 44 |
+
Traceback (most recent call last):
|
| 45 |
+
File "<stdin>", line 1, in <module>
|
| 46 |
+
File "/your/pytorch/install/torch/_tensor.py", line 93, in backward
|
| 47 |
+
torch.autograd.backward(self, gradient, retain_graph, create_graph)
|
| 48 |
+
File "/your/pytorch/install/torch/autograd/__init__.py", line 90, in backward
|
| 49 |
+
allow_unreachable=True) # allow_unreachable flag
|
| 50 |
+
File "/your/pytorch/install/torch/autograd/function.py", line 76, in apply
|
| 51 |
+
return self._forward_cls.backward(self, *args)
|
| 52 |
+
File "<stdin>", line 8, in backward
|
| 53 |
+
RuntimeError: Some error in backward
|
| 54 |
+
>>> with autograd.detect_anomaly():
|
| 55 |
+
... inp = torch.rand(10, 10, requires_grad=True)
|
| 56 |
+
... out = run_fn(inp)
|
| 57 |
+
... out.backward()
|
| 58 |
+
Traceback of forward call that caused the error:
|
| 59 |
+
File "tmp.py", line 53, in <module>
|
| 60 |
+
out = run_fn(inp)
|
| 61 |
+
File "tmp.py", line 44, in run_fn
|
| 62 |
+
out = MyFunc.apply(a)
|
| 63 |
+
Traceback (most recent call last):
|
| 64 |
+
File "<stdin>", line 4, in <module>
|
| 65 |
+
File "/your/pytorch/install/torch/_tensor.py", line 93, in backward
|
| 66 |
+
torch.autograd.backward(self, gradient, retain_graph, create_graph)
|
| 67 |
+
File "/your/pytorch/install/torch/autograd/__init__.py", line 90, in backward
|
| 68 |
+
allow_unreachable=True) # allow_unreachable flag
|
| 69 |
+
File "/your/pytorch/install/torch/autograd/function.py", line 76, in apply
|
| 70 |
+
return self._forward_cls.backward(self, *args)
|
| 71 |
+
File "<stdin>", line 8, in backward
|
| 72 |
+
RuntimeError: Some error in backward
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(self, check_nan=True) -> None:
|
| 77 |
+
self.prev = torch.is_anomaly_enabled()
|
| 78 |
+
self.check_nan = check_nan
|
| 79 |
+
self.prev_check_nan = torch.is_anomaly_check_nan_enabled()
|
| 80 |
+
warnings.warn(
|
| 81 |
+
"Anomaly Detection has been enabled. "
|
| 82 |
+
"This mode will increase the runtime "
|
| 83 |
+
"and should only be enabled for debugging.",
|
| 84 |
+
stacklevel=2,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def __enter__(self) -> None:
|
| 88 |
+
torch.set_anomaly_enabled(True, self.check_nan)
|
| 89 |
+
|
| 90 |
+
def __exit__(self, *args: object) -> None:
|
| 91 |
+
torch.set_anomaly_enabled(self.prev, self.prev_check_nan)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class set_detect_anomaly:
|
| 95 |
+
r"""Context-manager that sets the anomaly detection for the autograd engine on or off.
|
| 96 |
+
|
| 97 |
+
``set_detect_anomaly`` will enable or disable the autograd anomaly detection
|
| 98 |
+
based on its argument :attr:`mode`.
|
| 99 |
+
It can be used as a context-manager or as a function.
|
| 100 |
+
|
| 101 |
+
See ``detect_anomaly`` above for details of the anomaly detection behaviour.
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
mode (bool): Flag whether to enable anomaly detection (``True``),
|
| 105 |
+
or disable (``False``).
|
| 106 |
+
check_nan (bool): Flag whether to raise an error when the backward
|
| 107 |
+
generate "nan"
|
| 108 |
+
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
def __init__(self, mode: bool, check_nan: bool = True) -> None:
|
| 112 |
+
self.prev = torch.is_anomaly_enabled()
|
| 113 |
+
self.prev_check_nan = torch.is_anomaly_check_nan_enabled()
|
| 114 |
+
torch.set_anomaly_enabled(mode, check_nan)
|
| 115 |
+
|
| 116 |
+
def __enter__(self) -> None:
|
| 117 |
+
pass
|
| 118 |
+
|
| 119 |
+
def __exit__(self, *args: object) -> None:
|
| 120 |
+
torch.set_anomaly_enabled(self.prev, self.prev_check_nan)
|
parrot/lib/python3.10/site-packages/torch/autograd/forward_ad.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import os
|
| 3 |
+
from collections import namedtuple
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from .grad_mode import _DecoratorContextManager
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"UnpackedDualTensor",
|
| 12 |
+
"enter_dual_level",
|
| 13 |
+
"exit_dual_level",
|
| 14 |
+
"make_dual",
|
| 15 |
+
"unpack_dual",
|
| 16 |
+
"dual_level",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
# Global variable used to make the python API simpler to use
|
| 20 |
+
_current_level = -1
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def enter_dual_level():
|
| 24 |
+
r"""Enter a new forward grad level.
|
| 25 |
+
|
| 26 |
+
This level can be used to make and unpack dual Tensors to compute
|
| 27 |
+
forward gradients.
|
| 28 |
+
|
| 29 |
+
This function also updates the current level that is used by default
|
| 30 |
+
by the other functions in this API.
|
| 31 |
+
"""
|
| 32 |
+
global _current_level
|
| 33 |
+
new_level = torch._C._enter_dual_level()
|
| 34 |
+
if new_level != _current_level + 1:
|
| 35 |
+
raise RuntimeError(
|
| 36 |
+
"Entering a new forward AD level but the current level "
|
| 37 |
+
"is not valid. Make sure you did not modified it directly."
|
| 38 |
+
)
|
| 39 |
+
_current_level = new_level
|
| 40 |
+
return new_level
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def exit_dual_level(*, level=None):
|
| 44 |
+
r"""Exit a forward grad level.
|
| 45 |
+
|
| 46 |
+
This function deletes all the gradients associated with this
|
| 47 |
+
level. Only deleting the latest entered level is allowed.
|
| 48 |
+
|
| 49 |
+
This function also updates the current level that is used by default
|
| 50 |
+
by the other functions in this API.
|
| 51 |
+
"""
|
| 52 |
+
global _current_level
|
| 53 |
+
if level is None:
|
| 54 |
+
level = _current_level
|
| 55 |
+
if level != _current_level:
|
| 56 |
+
raise RuntimeError(
|
| 57 |
+
"Trying to exit a forward AD level that was not the last one "
|
| 58 |
+
"that was created. This is not supported."
|
| 59 |
+
)
|
| 60 |
+
torch._C._exit_dual_level(level=level)
|
| 61 |
+
_current_level = level - 1
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _maybe_load_decompositions():
|
| 65 |
+
if os.environ.get("PYTORCH_JIT", "1") == "1" and __debug__:
|
| 66 |
+
from torch._decomp import decompositions_for_jvp # noqa: F401
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def make_dual(tensor, tangent, *, level=None):
|
| 70 |
+
r"""Associate a tensor value with its tangent to create a "dual tensor" for forward AD gradient computation.
|
| 71 |
+
|
| 72 |
+
The result is a new tensor aliased to :attr:`tensor` with :attr:`tangent` embedded
|
| 73 |
+
as an attribute as-is if it has the same storage layout or copied otherwise.
|
| 74 |
+
The tangent attribute can be recovered with :func:`unpack_dual`.
|
| 75 |
+
|
| 76 |
+
This function is backward differentiable.
|
| 77 |
+
|
| 78 |
+
Given a function `f` whose jacobian is `J`, it allows one to compute the Jacobian-vector product (`jvp`)
|
| 79 |
+
between `J` and a given vector `v` as follows.
|
| 80 |
+
|
| 81 |
+
Example::
|
| 82 |
+
|
| 83 |
+
>>> # xdoctest: +SKIP("Undefined variables")
|
| 84 |
+
>>> with dual_level():
|
| 85 |
+
... inp = make_dual(x, v)
|
| 86 |
+
... out = f(inp)
|
| 87 |
+
... y, jvp = unpack_dual(out)
|
| 88 |
+
|
| 89 |
+
Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
|
| 90 |
+
for detailed steps on how to use this API.
|
| 91 |
+
|
| 92 |
+
"""
|
| 93 |
+
# See NOTE: [forward-mode AD decompositions mechanism]
|
| 94 |
+
#
|
| 95 |
+
# Import from torch._decomp import decompositions_for_jvp to register
|
| 96 |
+
# decompositions for jvp to the jit registry
|
| 97 |
+
#
|
| 98 |
+
# FIXME: We specify that __debug__ must be True because
|
| 99 |
+
# if python is run with -OO or -O flags (i.e., __debug__ is False), we encounter the
|
| 100 |
+
# following error:
|
| 101 |
+
#
|
| 102 |
+
# Return value was annotated as having type Tuple[NoneType, NoneType] but is actually of
|
| 103 |
+
# type Tuple[Tensor, Tensor]:
|
| 104 |
+
# File ".../torch/_decomp/__init__.py", line 1585
|
| 105 |
+
# else:
|
| 106 |
+
# buffer = z
|
| 107 |
+
# return min - torch.log1p(z), buffer
|
| 108 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
|
| 109 |
+
_maybe_load_decompositions()
|
| 110 |
+
|
| 111 |
+
if level is None:
|
| 112 |
+
level = _current_level
|
| 113 |
+
|
| 114 |
+
if level < 0:
|
| 115 |
+
raise RuntimeError(
|
| 116 |
+
"Trying to create a dual Tensor for forward AD but no level "
|
| 117 |
+
"exists, make sure to enter_dual_level() first."
|
| 118 |
+
)
|
| 119 |
+
if not (tensor.is_floating_point() or tensor.is_complex()):
|
| 120 |
+
raise ValueError(
|
| 121 |
+
f"Expected primal to be floating point or complex, but got: {tensor.dtype}"
|
| 122 |
+
)
|
| 123 |
+
if not (tangent.is_floating_point() or tangent.is_complex()):
|
| 124 |
+
raise ValueError(
|
| 125 |
+
f"Expected tangent to be floating point or complex, but got: {tangent.dtype}"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
return torch._VF._make_dual(tensor, tangent, level=level)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
_UnpackedDualTensor = namedtuple("_UnpackedDualTensor", ["primal", "tangent"])
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class UnpackedDualTensor(_UnpackedDualTensor):
|
| 135 |
+
r"""Namedtuple returned by :func:`unpack_dual` containing the primal and tangent components of the dual tensor.
|
| 136 |
+
|
| 137 |
+
See :func:`unpack_dual` for more details.
|
| 138 |
+
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def unpack_dual(tensor, *, level=None):
|
| 145 |
+
r"""Unpack a "dual tensor" to get both its Tensor value and its forward AD gradient.
|
| 146 |
+
|
| 147 |
+
The result is a namedtuple ``(primal, tangent)`` where ``primal`` is a view of
|
| 148 |
+
:attr:`tensor`'s primal and ``tangent`` is :attr:`tensor`'s tangent as-is.
|
| 149 |
+
Neither of these tensors can be dual tensor of level :attr:`level`.
|
| 150 |
+
|
| 151 |
+
This function is backward differentiable.
|
| 152 |
+
|
| 153 |
+
Example::
|
| 154 |
+
|
| 155 |
+
>>> # xdoctest: +SKIP("Undefined variables")
|
| 156 |
+
>>> with dual_level():
|
| 157 |
+
... inp = make_dual(x, x_t)
|
| 158 |
+
... out = f(inp)
|
| 159 |
+
... y, jvp = unpack_dual(out)
|
| 160 |
+
... jvp = unpack_dual(out).tangent
|
| 161 |
+
|
| 162 |
+
Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
|
| 163 |
+
for detailed steps on how to use this API.
|
| 164 |
+
"""
|
| 165 |
+
if level is None:
|
| 166 |
+
level = _current_level
|
| 167 |
+
|
| 168 |
+
if level < 0:
|
| 169 |
+
return UnpackedDualTensor(tensor, None)
|
| 170 |
+
|
| 171 |
+
primal, dual = torch._VF._unpack_dual(tensor, level=level)
|
| 172 |
+
|
| 173 |
+
return UnpackedDualTensor(primal, dual)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class dual_level(_DecoratorContextManager):
|
| 177 |
+
r"""Context-manager for forward AD, where all forward AD computation must occur within the ``dual_level`` context.
|
| 178 |
+
|
| 179 |
+
.. Note::
|
| 180 |
+
|
| 181 |
+
The ``dual_level`` context appropriately enters and exit the dual level to
|
| 182 |
+
controls the current forward AD level, which is used by default by the other
|
| 183 |
+
functions in this API.
|
| 184 |
+
|
| 185 |
+
We currently don't plan to support nested ``dual_level`` contexts, however, so
|
| 186 |
+
only a single forward AD level is supported. To compute higher-order
|
| 187 |
+
forward grads, one can use :func:`torch.func.jvp`.
|
| 188 |
+
|
| 189 |
+
Example::
|
| 190 |
+
|
| 191 |
+
>>> # xdoctest: +SKIP("Undefined variables")
|
| 192 |
+
>>> x = torch.tensor([1])
|
| 193 |
+
>>> x_t = torch.tensor([1])
|
| 194 |
+
>>> with dual_level():
|
| 195 |
+
... inp = make_dual(x, x_t)
|
| 196 |
+
... # Do computations with inp
|
| 197 |
+
... out = your_fn(inp)
|
| 198 |
+
... _, grad = unpack_dual(out)
|
| 199 |
+
>>> grad is None
|
| 200 |
+
False
|
| 201 |
+
>>> # After exiting the level, the grad is deleted
|
| 202 |
+
>>> _, grad_after = unpack_dual(out)
|
| 203 |
+
>>> grad is None
|
| 204 |
+
True
|
| 205 |
+
|
| 206 |
+
Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
|
| 207 |
+
for detailed steps on how to use this API.
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
def __enter__(self):
|
| 211 |
+
return enter_dual_level()
|
| 212 |
+
|
| 213 |
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
| 214 |
+
exit_dual_level()
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
# Private helper functions
|
| 218 |
+
_is_fwd_grad_enabled = torch._C._is_fwd_grad_enabled
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# Private helper function to enable or disable fwd grad.
|
| 222 |
+
# If you're a user and want to use this, please file an issue to discuss the use case.
|
| 223 |
+
class _set_fwd_grad_enabled(_DecoratorContextManager):
|
| 224 |
+
def __init__(self, mode: bool) -> None:
|
| 225 |
+
self.prev = _is_fwd_grad_enabled()
|
| 226 |
+
torch._C._set_fwd_grad_enabled(mode)
|
| 227 |
+
|
| 228 |
+
def __enter__(self) -> None:
|
| 229 |
+
pass
|
| 230 |
+
|
| 231 |
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
| 232 |
+
torch._C._set_fwd_grad_enabled(self.prev)
|
parrot/lib/python3.10/site-packages/torch/autograd/function.py
ADDED
|
@@ -0,0 +1,843 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import inspect
|
| 4 |
+
import itertools
|
| 5 |
+
import warnings
|
| 6 |
+
from collections import OrderedDict
|
| 7 |
+
from typing import Any, List, Optional, Tuple
|
| 8 |
+
from typing_extensions import deprecated
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch._C as _C
|
| 12 |
+
import torch._functorch as _functorch
|
| 13 |
+
import torch.utils.hooks as hooks
|
| 14 |
+
from torch._C import _functions
|
| 15 |
+
from torch._functorch.autograd_function import custom_function_call
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"FunctionCtx",
|
| 19 |
+
"BackwardCFunction",
|
| 20 |
+
"FunctionMeta",
|
| 21 |
+
"Function",
|
| 22 |
+
"once_differentiable",
|
| 23 |
+
"InplaceFunction",
|
| 24 |
+
"NestedIOFunction",
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# Unique id provider for each class inheriting from Function
|
| 28 |
+
# This is incremented in FunctionMeta during class definition
|
| 29 |
+
AUTOGRAD_FUNCTION_COUNTER = itertools.count()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# Formerly known as: _ContextMethodMixin
|
| 33 |
+
class FunctionCtx:
|
| 34 |
+
def save_for_backward(self, *tensors: torch.Tensor):
|
| 35 |
+
r"""Save given tensors for a future call to :func:`~Function.backward`.
|
| 36 |
+
|
| 37 |
+
``save_for_backward`` should be called at most once, in either the
|
| 38 |
+
:func:`setup_context` or :func:`forward` methods, and only with tensors.
|
| 39 |
+
|
| 40 |
+
All tensors intended to be used in the backward pass should be saved
|
| 41 |
+
with ``save_for_backward`` (as opposed to directly on ``ctx``) to prevent
|
| 42 |
+
incorrect gradients and memory leaks, and enable the application of saved
|
| 43 |
+
tensor hooks. See :class:`torch.autograd.graph.saved_tensors_hooks`.
|
| 44 |
+
|
| 45 |
+
Note that if intermediary tensors, tensors that are neither inputs
|
| 46 |
+
nor outputs of :func:`forward`, are saved for backward, your custom Function
|
| 47 |
+
may not support double backward.
|
| 48 |
+
Custom Functions that do not support double backward should decorate their
|
| 49 |
+
:func:`backward` method with ``@once_differentiable`` so that performing
|
| 50 |
+
double backward raises an error. If you'd like to support double backward,
|
| 51 |
+
you can either recompute intermediaries based on the inputs during backward
|
| 52 |
+
or return the intermediaries as the outputs of the custom Function. See the
|
| 53 |
+
`double backward tutorial <https://pytorch.org/tutorials/intermediate/custom_function_double_backward_tutorial.html>`_
|
| 54 |
+
for more details.
|
| 55 |
+
|
| 56 |
+
In :func:`backward`, saved tensors can be accessed through the :attr:`saved_tensors`
|
| 57 |
+
attribute. Before returning them to the user, a check is made to ensure
|
| 58 |
+
they weren't used in any in-place operation that modified their content.
|
| 59 |
+
|
| 60 |
+
Arguments can also be ``None``. This is a no-op.
|
| 61 |
+
|
| 62 |
+
See :ref:`extending-autograd` for more details on how to use this method.
|
| 63 |
+
|
| 64 |
+
Example::
|
| 65 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
|
| 66 |
+
>>> class Func(Function):
|
| 67 |
+
>>> @staticmethod
|
| 68 |
+
>>> def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int):
|
| 69 |
+
>>> w = x * z
|
| 70 |
+
>>> out = x * y + y * z + w * y
|
| 71 |
+
>>> ctx.save_for_backward(x, y, w, out)
|
| 72 |
+
>>> ctx.z = z # z is not a tensor
|
| 73 |
+
>>> return out
|
| 74 |
+
>>>
|
| 75 |
+
>>> @staticmethod
|
| 76 |
+
>>> @once_differentiable
|
| 77 |
+
>>> def backward(ctx, grad_out):
|
| 78 |
+
>>> x, y, w, out = ctx.saved_tensors
|
| 79 |
+
>>> z = ctx.z
|
| 80 |
+
>>> gx = grad_out * (y + y * z)
|
| 81 |
+
>>> gy = grad_out * (x + z + w)
|
| 82 |
+
>>> gz = None
|
| 83 |
+
>>> return gx, gy, gz
|
| 84 |
+
>>>
|
| 85 |
+
>>> a = torch.tensor(1., requires_grad=True, dtype=torch.double)
|
| 86 |
+
>>> b = torch.tensor(2., requires_grad=True, dtype=torch.double)
|
| 87 |
+
>>> c = 4
|
| 88 |
+
>>> d = Func.apply(a, b, c)
|
| 89 |
+
|
| 90 |
+
"""
|
| 91 |
+
self.to_save = tensors
|
| 92 |
+
|
| 93 |
+
def save_for_forward(self, *tensors: torch.Tensor):
|
| 94 |
+
r"""Save given tensors for a future call to :func:`~Function.jvp`.
|
| 95 |
+
|
| 96 |
+
``save_for_forward`` should be called at most once, in either the
|
| 97 |
+
:func:`setup_context` or :func:`forward` methods, and all arguments
|
| 98 |
+
should be tensors.
|
| 99 |
+
|
| 100 |
+
In :func:`jvp`, saved objects can be accessed through the :attr:`saved_tensors`
|
| 101 |
+
attribute.
|
| 102 |
+
|
| 103 |
+
Arguments can also be ``None``. This is a no-op.
|
| 104 |
+
|
| 105 |
+
See :ref:`extending-autograd` for more details on how to use this method.
|
| 106 |
+
|
| 107 |
+
Example::
|
| 108 |
+
>>> # xdoctest: +SKIP
|
| 109 |
+
>>> class Func(torch.autograd.Function):
|
| 110 |
+
>>> @staticmethod
|
| 111 |
+
>>> def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int):
|
| 112 |
+
>>> ctx.save_for_backward(x, y)
|
| 113 |
+
>>> ctx.save_for_forward(x, y)
|
| 114 |
+
>>> ctx.z = z
|
| 115 |
+
>>> return x * y * z
|
| 116 |
+
>>>
|
| 117 |
+
>>> @staticmethod
|
| 118 |
+
>>> def jvp(ctx, x_t, y_t, _):
|
| 119 |
+
>>> x, y = ctx.saved_tensors
|
| 120 |
+
>>> z = ctx.z
|
| 121 |
+
>>> return z * (y * x_t + x * y_t)
|
| 122 |
+
>>>
|
| 123 |
+
>>> @staticmethod
|
| 124 |
+
>>> def vjp(ctx, grad_out):
|
| 125 |
+
>>> x, y = ctx.saved_tensors
|
| 126 |
+
>>> z = ctx.z
|
| 127 |
+
>>> return z * grad_out * y, z * grad_out * x, None
|
| 128 |
+
>>>
|
| 129 |
+
>>> a = torch.tensor(1., requires_grad=True, dtype=torch.double)
|
| 130 |
+
>>> t = torch.tensor(1., dtype=torch.double)
|
| 131 |
+
>>> b = torch.tensor(2., requires_grad=True, dtype=torch.double)
|
| 132 |
+
>>> c = 4
|
| 133 |
+
>>>
|
| 134 |
+
>>> with fwAD.dual_level():
|
| 135 |
+
>>> a_dual = fwAD.make_dual(a, t)
|
| 136 |
+
>>> d = Func.apply(a_dual, b, c)
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
for tensor in tensors:
|
| 140 |
+
assert isinstance(tensor, torch.Tensor) or tensor is None, (
|
| 141 |
+
"save_for_forward expects all arguments to be tensors; you should "
|
| 142 |
+
"save non-tensors as attributes on ctx."
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
self.saved_for_forward = tensors
|
| 146 |
+
|
| 147 |
+
def mark_dirty(self, *args: torch.Tensor):
|
| 148 |
+
r"""Mark given tensors as modified in an in-place operation.
|
| 149 |
+
|
| 150 |
+
This should be called at most once, in either the :func:`setup_context`
|
| 151 |
+
or :func:`forward` methods, and all arguments should be inputs.
|
| 152 |
+
|
| 153 |
+
Every tensor that's been modified in-place in a call to :func:`forward`
|
| 154 |
+
should be given to this function, to ensure correctness of our checks.
|
| 155 |
+
It doesn't matter whether the function is called before or after
|
| 156 |
+
modification.
|
| 157 |
+
|
| 158 |
+
Examples::
|
| 159 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
|
| 160 |
+
>>> class Inplace(Function):
|
| 161 |
+
>>> @staticmethod
|
| 162 |
+
>>> def forward(ctx, x):
|
| 163 |
+
>>> x_npy = x.numpy() # x_npy shares storage with x
|
| 164 |
+
>>> x_npy += 1
|
| 165 |
+
>>> ctx.mark_dirty(x)
|
| 166 |
+
>>> return x
|
| 167 |
+
>>>
|
| 168 |
+
>>> @staticmethod
|
| 169 |
+
>>> @once_differentiable
|
| 170 |
+
>>> def backward(ctx, grad_output):
|
| 171 |
+
>>> return grad_output
|
| 172 |
+
>>>
|
| 173 |
+
>>> a = torch.tensor(1., requires_grad=True, dtype=torch.double).clone()
|
| 174 |
+
>>> b = a * a
|
| 175 |
+
>>> Inplace.apply(a) # This would lead to wrong gradients!
|
| 176 |
+
>>> # but the engine would not know unless we mark_dirty
|
| 177 |
+
>>> # xdoctest: +SKIP
|
| 178 |
+
>>> b.backward() # RuntimeError: one of the variables needed for gradient
|
| 179 |
+
>>> # computation has been modified by an inplace operation
|
| 180 |
+
|
| 181 |
+
"""
|
| 182 |
+
self.dirty_tensors = args
|
| 183 |
+
|
| 184 |
+
@deprecated(
|
| 185 |
+
"`mark_shared_storage` is deprecated. "
|
| 186 |
+
"Tensors with shared storages are automatically tracked. "
|
| 187 |
+
"Note that calls to `set_()` are not tracked",
|
| 188 |
+
category=FutureWarning,
|
| 189 |
+
)
|
| 190 |
+
def mark_shared_storage(self, *pairs):
|
| 191 |
+
pass
|
| 192 |
+
|
| 193 |
+
def mark_non_differentiable(self, *args: torch.Tensor):
|
| 194 |
+
r"""Mark outputs as non-differentiable.
|
| 195 |
+
|
| 196 |
+
This should be called at most once, in either the :func:`setup_context`
|
| 197 |
+
or :func:`forward` methods, and all arguments should be tensor outputs.
|
| 198 |
+
|
| 199 |
+
This will mark outputs as not requiring gradients, increasing the
|
| 200 |
+
efficiency of backward computation. You still need to accept a gradient
|
| 201 |
+
for each output in :meth:`~Function.backward`, but it's always going to
|
| 202 |
+
be a zero tensor with the same shape as the shape of a corresponding
|
| 203 |
+
output.
|
| 204 |
+
|
| 205 |
+
This is used e.g. for indices returned from a sort. See example::
|
| 206 |
+
>>> class Func(Function):
|
| 207 |
+
>>> @staticmethod
|
| 208 |
+
>>> def forward(ctx, x):
|
| 209 |
+
>>> sorted, idx = x.sort()
|
| 210 |
+
>>> ctx.mark_non_differentiable(idx)
|
| 211 |
+
>>> ctx.save_for_backward(x, idx)
|
| 212 |
+
>>> return sorted, idx
|
| 213 |
+
>>>
|
| 214 |
+
>>> @staticmethod
|
| 215 |
+
>>> @once_differentiable
|
| 216 |
+
>>> def backward(ctx, g1, g2): # still need to accept g2
|
| 217 |
+
>>> x, idx = ctx.saved_tensors
|
| 218 |
+
>>> grad_input = torch.zeros_like(x)
|
| 219 |
+
>>> grad_input.index_add_(0, idx, g1)
|
| 220 |
+
>>> return grad_input
|
| 221 |
+
|
| 222 |
+
"""
|
| 223 |
+
self.non_differentiable = args
|
| 224 |
+
|
| 225 |
+
def set_materialize_grads(self, value: bool):
|
| 226 |
+
r"""Set whether to materialize grad tensors. Default is ``True``.
|
| 227 |
+
|
| 228 |
+
This should be called only from either the :func:`setup_context` or
|
| 229 |
+
:func:`forward` methods.
|
| 230 |
+
|
| 231 |
+
If ``True``, undefined grad tensors will be expanded to tensors full of zeros
|
| 232 |
+
prior to calling the :func:`backward` and :func:`jvp` methods.
|
| 233 |
+
|
| 234 |
+
Example::
|
| 235 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
|
| 236 |
+
>>> class SimpleFunc(Function):
|
| 237 |
+
>>> @staticmethod
|
| 238 |
+
>>> def forward(ctx, x):
|
| 239 |
+
>>> return x.clone(), x.clone()
|
| 240 |
+
>>>
|
| 241 |
+
>>> @staticmethod
|
| 242 |
+
>>> @once_differentiable
|
| 243 |
+
>>> def backward(ctx, g1, g2):
|
| 244 |
+
>>> return g1 + g2 # No check for None necessary
|
| 245 |
+
>>>
|
| 246 |
+
>>> # We modify SimpleFunc to handle non-materialized grad outputs
|
| 247 |
+
>>> class Func(Function):
|
| 248 |
+
>>> @staticmethod
|
| 249 |
+
>>> def forward(ctx, x):
|
| 250 |
+
>>> ctx.set_materialize_grads(False)
|
| 251 |
+
>>> ctx.save_for_backward(x)
|
| 252 |
+
>>> return x.clone(), x.clone()
|
| 253 |
+
>>>
|
| 254 |
+
>>> @staticmethod
|
| 255 |
+
>>> @once_differentiable
|
| 256 |
+
>>> def backward(ctx, g1, g2):
|
| 257 |
+
>>> x, = ctx.saved_tensors
|
| 258 |
+
>>> grad_input = torch.zeros_like(x)
|
| 259 |
+
>>> if g1 is not None: # We must check for None now
|
| 260 |
+
>>> grad_input += g1
|
| 261 |
+
>>> if g2 is not None:
|
| 262 |
+
>>> grad_input += g2
|
| 263 |
+
>>> return grad_input
|
| 264 |
+
>>>
|
| 265 |
+
>>> a = torch.tensor(1., requires_grad=True)
|
| 266 |
+
>>> b, _ = Func.apply(a) # induces g2 to be undefined
|
| 267 |
+
|
| 268 |
+
"""
|
| 269 |
+
self.materialize_grads = value
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# DO NOT USE: This is only defined to be able to load old serialized models
|
| 273 |
+
_ContextMethodMixin = FunctionCtx
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class _HookMixin:
|
| 277 |
+
@staticmethod
|
| 278 |
+
def _register_hook(backward_hooks, hook):
|
| 279 |
+
if backward_hooks is None:
|
| 280 |
+
backward_hooks = OrderedDict()
|
| 281 |
+
handle = hooks.RemovableHandle(backward_hooks)
|
| 282 |
+
backward_hooks[handle.id] = hook
|
| 283 |
+
return backward_hooks, handle
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class BackwardCFunction(_C._FunctionBase, FunctionCtx, _HookMixin):
|
| 287 |
+
r"""
|
| 288 |
+
This class is used for internal autograd work. Do not use.
|
| 289 |
+
"""
|
| 290 |
+
|
| 291 |
+
def apply(self, *args):
|
| 292 |
+
r"""
|
| 293 |
+
Apply method used when executing this Node during the backward
|
| 294 |
+
"""
|
| 295 |
+
# _forward_cls is defined by derived class
|
| 296 |
+
# The user should define either backward or vjp but never both.
|
| 297 |
+
backward_fn = self._forward_cls.backward # type: ignore[attr-defined]
|
| 298 |
+
vjp_fn = self._forward_cls.vjp # type: ignore[attr-defined]
|
| 299 |
+
if backward_fn is not Function.backward and vjp_fn is not Function.vjp:
|
| 300 |
+
raise RuntimeError(
|
| 301 |
+
"Implementing both 'backward' and 'vjp' for a custom "
|
| 302 |
+
"Function is not allowed. You should only implement one "
|
| 303 |
+
"of them."
|
| 304 |
+
)
|
| 305 |
+
user_fn = vjp_fn if vjp_fn is not Function.vjp else backward_fn
|
| 306 |
+
return user_fn(self, *args)
|
| 307 |
+
|
| 308 |
+
def apply_jvp(self, *args):
|
| 309 |
+
r"""
|
| 310 |
+
Apply method used when executing forward mode AD during the forward
|
| 311 |
+
"""
|
| 312 |
+
# _forward_cls is defined by derived class
|
| 313 |
+
return self._forward_cls.jvp(self, *args) # type: ignore[attr-defined]
|
| 314 |
+
|
| 315 |
+
def _compiled_autograd_key(self):
|
| 316 |
+
return self._forward_cls._compiled_autograd_key(self) # type: ignore[attr-defined]
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class FunctionMeta(type):
|
| 320 |
+
"""Function metaclass.
|
| 321 |
+
|
| 322 |
+
This metaclass sets up the following properties:
|
| 323 |
+
_backward_cls: The Function class corresponding to the differentiated
|
| 324 |
+
version of this function (which is generated on the fly by this
|
| 325 |
+
metaclass).
|
| 326 |
+
"""
|
| 327 |
+
|
| 328 |
+
def __init__(cls, name, bases, attrs):
|
| 329 |
+
backward_fn = type(
|
| 330 |
+
name + "Backward", (BackwardCFunction,), {"_forward_cls": cls}
|
| 331 |
+
)
|
| 332 |
+
backward_fn._autograd_function_id = next(AUTOGRAD_FUNCTION_COUNTER) # type: ignore[attr-defined]
|
| 333 |
+
backward_fn._compiled_autograd_should_lift = attrs.get( # type: ignore[attr-defined]
|
| 334 |
+
"_compiled_autograd_should_lift", True
|
| 335 |
+
)
|
| 336 |
+
cls._backward_cls = backward_fn
|
| 337 |
+
|
| 338 |
+
super().__init__(name, bases, attrs)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class _SingleLevelFunction(
|
| 342 |
+
_C._FunctionBase, FunctionCtx, _HookMixin, metaclass=FunctionMeta
|
| 343 |
+
):
|
| 344 |
+
@staticmethod
|
| 345 |
+
def forward(*args: Any, **kwargs: Any) -> Any:
|
| 346 |
+
r"""Define the forward of the custom autograd Function.
|
| 347 |
+
|
| 348 |
+
This function is to be overridden by all subclasses.
|
| 349 |
+
There are two ways to define forward:
|
| 350 |
+
|
| 351 |
+
Usage 1 (Combined forward and ctx)::
|
| 352 |
+
|
| 353 |
+
@staticmethod
|
| 354 |
+
def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any:
|
| 355 |
+
pass
|
| 356 |
+
|
| 357 |
+
- It must accept a context ctx as the first argument, followed by any
|
| 358 |
+
number of arguments (tensors or other types).
|
| 359 |
+
- See :ref:`combining-forward-context` for more details
|
| 360 |
+
|
| 361 |
+
Usage 2 (Separate forward and ctx)::
|
| 362 |
+
|
| 363 |
+
@staticmethod
|
| 364 |
+
def forward(*args: Any, **kwargs: Any) -> Any:
|
| 365 |
+
pass
|
| 366 |
+
|
| 367 |
+
@staticmethod
|
| 368 |
+
def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None:
|
| 369 |
+
pass
|
| 370 |
+
|
| 371 |
+
- The forward no longer accepts a ctx argument.
|
| 372 |
+
- Instead, you must also override the :meth:`torch.autograd.Function.setup_context`
|
| 373 |
+
staticmethod to handle setting up the ``ctx`` object.
|
| 374 |
+
``output`` is the output of the forward, ``inputs`` are a Tuple of inputs
|
| 375 |
+
to the forward.
|
| 376 |
+
- See :ref:`extending-autograd` for more details
|
| 377 |
+
|
| 378 |
+
The context can be used to store arbitrary data that can be then
|
| 379 |
+
retrieved during the backward pass. Tensors should not be stored
|
| 380 |
+
directly on `ctx` (though this is not currently enforced for
|
| 381 |
+
backward compatibility). Instead, tensors should be saved either with
|
| 382 |
+
:func:`ctx.save_for_backward` if they are intended to be used in
|
| 383 |
+
``backward`` (equivalently, ``vjp``) or :func:`ctx.save_for_forward`
|
| 384 |
+
if they are intended to be used for in ``jvp``.
|
| 385 |
+
"""
|
| 386 |
+
raise NotImplementedError(
|
| 387 |
+
"You must implement the forward function for custom autograd.Function."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
@staticmethod
|
| 391 |
+
def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> Any:
|
| 392 |
+
r"""There are two ways to define the forward pass of an autograd.Function.
|
| 393 |
+
|
| 394 |
+
Either:
|
| 395 |
+
|
| 396 |
+
1. Override forward with the signature ``forward(ctx, *args, **kwargs)``.
|
| 397 |
+
``setup_context`` is not overridden. Setting up the ctx for backward
|
| 398 |
+
happens inside the ``forward``.
|
| 399 |
+
2. Override forward with the signature ``forward(*args, **kwargs)`` and
|
| 400 |
+
override ``setup_context``. Setting up the ctx for backward happens
|
| 401 |
+
inside ``setup_context`` (as opposed to inside the ``forward``)
|
| 402 |
+
|
| 403 |
+
See :meth:`torch.autograd.Function.forward` and :ref:`extending-autograd` for more details.
|
| 404 |
+
"""
|
| 405 |
+
raise NotImplementedError("setup_context is not implemented.")
|
| 406 |
+
|
| 407 |
+
@staticmethod
|
| 408 |
+
def backward(ctx: Any, *grad_outputs: Any) -> Any:
|
| 409 |
+
r"""Define a formula for differentiating the operation with backward mode automatic differentiation.
|
| 410 |
+
|
| 411 |
+
This function is to be overridden by all subclasses.
|
| 412 |
+
(Defining this function is equivalent to defining the ``vjp`` function.)
|
| 413 |
+
|
| 414 |
+
It must accept a context :attr:`ctx` as the first argument, followed by
|
| 415 |
+
as many outputs as the :func:`forward` returned (None will be passed in
|
| 416 |
+
for non tensor outputs of the forward function),
|
| 417 |
+
and it should return as many tensors, as there were inputs to
|
| 418 |
+
:func:`forward`. Each argument is the gradient w.r.t the given output,
|
| 419 |
+
and each returned value should be the gradient w.r.t. the
|
| 420 |
+
corresponding input. If an input is not a Tensor or is a Tensor not
|
| 421 |
+
requiring grads, you can just pass None as a gradient for that input.
|
| 422 |
+
|
| 423 |
+
The context can be used to retrieve tensors saved during the forward
|
| 424 |
+
pass. It also has an attribute :attr:`ctx.needs_input_grad` as a tuple
|
| 425 |
+
of booleans representing whether each input needs gradient. E.g.,
|
| 426 |
+
:func:`backward` will have ``ctx.needs_input_grad[0] = True`` if the
|
| 427 |
+
first input to :func:`forward` needs gradient computed w.r.t. the
|
| 428 |
+
output.
|
| 429 |
+
"""
|
| 430 |
+
raise NotImplementedError(
|
| 431 |
+
"You must implement either the backward or vjp method for "
|
| 432 |
+
"your custom autograd.Function to use it with backward "
|
| 433 |
+
"mode AD."
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
# vjp and backward are alias of each other
|
| 437 |
+
vjp = backward
|
| 438 |
+
|
| 439 |
+
@staticmethod
|
| 440 |
+
def jvp(ctx: Any, *grad_inputs: Any) -> Any:
|
| 441 |
+
r"""Define a formula for differentiating the operation with forward mode automatic differentiation.
|
| 442 |
+
|
| 443 |
+
This function is to be overridden by all subclasses.
|
| 444 |
+
It must accept a context :attr:`ctx` as the first argument, followed by
|
| 445 |
+
as many inputs as the :func:`forward` got (None will be passed in
|
| 446 |
+
for non tensor inputs of the forward function),
|
| 447 |
+
and it should return as many tensors as there were outputs to
|
| 448 |
+
:func:`forward`. Each argument is the gradient w.r.t the given input,
|
| 449 |
+
and each returned value should be the gradient w.r.t. the
|
| 450 |
+
corresponding output. If an output is not a Tensor or the function is not
|
| 451 |
+
differentiable with respect to that output, you can just pass None as a
|
| 452 |
+
gradient for that input.
|
| 453 |
+
|
| 454 |
+
You can use the :attr:`ctx` object to pass any value from the forward to this
|
| 455 |
+
functions.
|
| 456 |
+
"""
|
| 457 |
+
raise NotImplementedError(
|
| 458 |
+
"You must implement the jvp function for custom "
|
| 459 |
+
"autograd.Function to use it with forward mode AD."
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class Function(_SingleLevelFunction):
|
| 464 |
+
r"""Base class to create custom `autograd.Function`.
|
| 465 |
+
|
| 466 |
+
To create a custom `autograd.Function`, subclass this class and implement
|
| 467 |
+
the :meth:`forward` and :meth:`backward` static methods. Then, to use your custom
|
| 468 |
+
op in the forward pass, call the class method ``apply``. Do not call
|
| 469 |
+
:meth:`forward` directly.
|
| 470 |
+
|
| 471 |
+
To ensure correctness and best performance, make sure you are calling the
|
| 472 |
+
correct methods on ``ctx`` and validating your backward function using
|
| 473 |
+
:func:`torch.autograd.gradcheck`.
|
| 474 |
+
|
| 475 |
+
See :ref:`extending-autograd` for more details on how to use this class.
|
| 476 |
+
|
| 477 |
+
Examples::
|
| 478 |
+
|
| 479 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
|
| 480 |
+
>>> class Exp(Function):
|
| 481 |
+
>>> @staticmethod
|
| 482 |
+
>>> def forward(ctx, i):
|
| 483 |
+
>>> result = i.exp()
|
| 484 |
+
>>> ctx.save_for_backward(result)
|
| 485 |
+
>>> return result
|
| 486 |
+
>>>
|
| 487 |
+
>>> @staticmethod
|
| 488 |
+
>>> def backward(ctx, grad_output):
|
| 489 |
+
>>> result, = ctx.saved_tensors
|
| 490 |
+
>>> return grad_output * result
|
| 491 |
+
>>>
|
| 492 |
+
>>> # Use it by calling the apply method:
|
| 493 |
+
>>> # xdoctest: +SKIP
|
| 494 |
+
>>> output = Exp.apply(input)
|
| 495 |
+
"""
|
| 496 |
+
|
| 497 |
+
def __init__(self, *args, **kwargs):
|
| 498 |
+
warnings.warn(
|
| 499 |
+
f"{self.__class__} should not be instantiated. Methods on autograd functions"
|
| 500 |
+
"are all static, so you should invoke them on the class itself. "
|
| 501 |
+
"Instantiating an autograd function will raise an "
|
| 502 |
+
"error in a future version of PyTorch.",
|
| 503 |
+
DeprecationWarning,
|
| 504 |
+
stacklevel=2,
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
def __call__(self, *args, **kwargs):
|
| 508 |
+
raise RuntimeError(
|
| 509 |
+
"Legacy autograd function with non-static forward method is deprecated. "
|
| 510 |
+
"Please use new-style autograd function with static forward method. "
|
| 511 |
+
"(Example: https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function)"
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
"""
|
| 515 |
+
Bool that specifies if PyTorch should attempt to autogenerate
|
| 516 |
+
:func:`torch.vmap` support for this autograd.Function. You may set this to
|
| 517 |
+
True only if this autograd.Function's forward, backward, and jvp (if they
|
| 518 |
+
exist) are written using PyTorch operations; otherwise, please override
|
| 519 |
+
:meth:`torch.autograd.Function.vmap` to add support for :func:`torch.vmap`.
|
| 520 |
+
|
| 521 |
+
Please see :ref:`func-autograd-function` for more details.
|
| 522 |
+
"""
|
| 523 |
+
generate_vmap_rule = False
|
| 524 |
+
|
| 525 |
+
@staticmethod
|
| 526 |
+
def vmap(info, in_dims, *args):
|
| 527 |
+
r"""Define the behavior for this autograd.Function underneath :func:`torch.vmap`.
|
| 528 |
+
|
| 529 |
+
For a :func:`torch.autograd.Function` to support
|
| 530 |
+
:func:`torch.vmap`, you must either override this static method, or set
|
| 531 |
+
``generate_vmap_rule`` to ``True`` (you may not do both).
|
| 532 |
+
|
| 533 |
+
If you choose to override this staticmethod: it must accept
|
| 534 |
+
|
| 535 |
+
- an ``info`` object as the first argument. ``info.batch_size``
|
| 536 |
+
specifies the size of the dimension being vmapped over,
|
| 537 |
+
while ``info.randomness`` is the randomness option passed to
|
| 538 |
+
:func:`torch.vmap`.
|
| 539 |
+
- an ``in_dims`` tuple as the second argument.
|
| 540 |
+
For each arg in ``args``, ``in_dims`` has a corresponding
|
| 541 |
+
``Optional[int]``. It is ``None`` if the arg is not a Tensor or if
|
| 542 |
+
the arg is not being vmapped over, otherwise, it is an integer
|
| 543 |
+
specifying what dimension of the Tensor is being vmapped over.
|
| 544 |
+
- ``*args``, which is the same as the args to :meth:`~Function.forward`.
|
| 545 |
+
|
| 546 |
+
The return of the vmap staticmethod is a tuple of ``(output, out_dims)``.
|
| 547 |
+
Similar to ``in_dims``, ``out_dims`` should be of the same structure as
|
| 548 |
+
``output`` and contain one ``out_dim`` per output that specifies if the
|
| 549 |
+
output has the vmapped dimension and what index it is in.
|
| 550 |
+
|
| 551 |
+
Please see :ref:`func-autograd-function` for more details.
|
| 552 |
+
"""
|
| 553 |
+
raise NotImplementedError(
|
| 554 |
+
"To use autograd.Function with vmap, you must either override the "
|
| 555 |
+
"vmap staticmethod or set generate_vmap_rule=True."
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
@classmethod
|
| 559 |
+
def apply(cls, *args, **kwargs):
|
| 560 |
+
def bind_default_args(func, *args, **kwargs):
|
| 561 |
+
signature = inspect.signature(func)
|
| 562 |
+
bound_args = signature.bind(*args, **kwargs)
|
| 563 |
+
bound_args.apply_defaults()
|
| 564 |
+
|
| 565 |
+
return bound_args.args
|
| 566 |
+
|
| 567 |
+
is_setup_ctx_defined = _is_setup_context_defined(cls.setup_context)
|
| 568 |
+
if is_setup_ctx_defined:
|
| 569 |
+
args = bind_default_args(cls.forward, *args, **kwargs)
|
| 570 |
+
|
| 571 |
+
if not torch._C._are_functorch_transforms_active():
|
| 572 |
+
# See NOTE: [functorch vjp and autograd interaction]
|
| 573 |
+
args = _functorch.utils.unwrap_dead_wrappers(args)
|
| 574 |
+
return super().apply(*args, **kwargs) # type: ignore[misc]
|
| 575 |
+
|
| 576 |
+
if not is_setup_ctx_defined:
|
| 577 |
+
raise RuntimeError(
|
| 578 |
+
"In order to use an autograd.Function with functorch transforms "
|
| 579 |
+
"(vmap, grad, jvp, jacrev, ...), it must override the setup_context "
|
| 580 |
+
"staticmethod. For more details, please see "
|
| 581 |
+
"https://pytorch.org/docs/main/notes/extending.func.html"
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
return custom_function_call(cls, *args, **kwargs)
|
| 585 |
+
|
| 586 |
+
@staticmethod
|
| 587 |
+
def _compiled_autograd_key(ctx):
|
| 588 |
+
return (ctx._autograd_function_id,)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def _is_setup_context_defined(fn):
|
| 592 |
+
return fn != _SingleLevelFunction.setup_context
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def once_differentiable(fn):
|
| 596 |
+
@functools.wraps(fn)
|
| 597 |
+
def wrapper(ctx, *args):
|
| 598 |
+
with torch.no_grad():
|
| 599 |
+
outputs = fn(ctx, *args)
|
| 600 |
+
|
| 601 |
+
if not torch.is_grad_enabled():
|
| 602 |
+
return outputs
|
| 603 |
+
|
| 604 |
+
# If any of the inputs have requires_grad=True, we force the outputs
|
| 605 |
+
# to have requires_grad=True but point to a grad_fn which throws an
|
| 606 |
+
# error message during (double) back-propagation.
|
| 607 |
+
# XXX: this is only an approximation of requires_grad - there's no way
|
| 608 |
+
# to figure out if fn didn't use ctx.saved_tensors and as a result
|
| 609 |
+
# some Tensors might require grad, even if no args do.
|
| 610 |
+
# Unfortunately, this leads to unexpected error messages ("no nodes
|
| 611 |
+
# require computing gradients"), but I don't have a better idea.
|
| 612 |
+
# These functions would raise an error in backward anyway.
|
| 613 |
+
requires_grad = any(
|
| 614 |
+
isinstance(arg, torch.Tensor) and arg.requires_grad for arg in args
|
| 615 |
+
)
|
| 616 |
+
if not requires_grad:
|
| 617 |
+
return outputs
|
| 618 |
+
|
| 619 |
+
if not isinstance(outputs, tuple):
|
| 620 |
+
outputs = (outputs,)
|
| 621 |
+
|
| 622 |
+
err_fn = _functions.DelayedError(
|
| 623 |
+
b"trying to differentiate twice a function that was marked "
|
| 624 |
+
b"with @once_differentiable",
|
| 625 |
+
len(outputs),
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
# Create aliases of each output that has requires_grad=True. We need
|
| 629 |
+
# at least one of the inputs to err_fn to require grad so that the
|
| 630 |
+
# output will have a grad_fn.
|
| 631 |
+
def fake_requires_grad(var):
|
| 632 |
+
if var is not None:
|
| 633 |
+
var = var.detach()
|
| 634 |
+
var.requires_grad = True
|
| 635 |
+
return var
|
| 636 |
+
|
| 637 |
+
return err_fn(*[fake_requires_grad(v) for v in outputs])
|
| 638 |
+
|
| 639 |
+
return wrapper
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
class InplaceFunction(Function):
|
| 643 |
+
r"""
|
| 644 |
+
This class is here only for backward compatibility reasons.
|
| 645 |
+
Use :class:`Function` instead of this for any new use case.
|
| 646 |
+
"""
|
| 647 |
+
|
| 648 |
+
def __init__(self, inplace=False):
|
| 649 |
+
super().__init__()
|
| 650 |
+
self.inplace = inplace
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def _nested_map(condition, fn, condition_msg=None):
|
| 654 |
+
def _map(obj):
|
| 655 |
+
if condition(obj):
|
| 656 |
+
return fn(obj)
|
| 657 |
+
elif obj is None:
|
| 658 |
+
return None
|
| 659 |
+
elif isinstance(obj, (list, tuple)):
|
| 660 |
+
mapped = (_map(x) for x in obj)
|
| 661 |
+
if hasattr(obj, "_fields"):
|
| 662 |
+
# obj is namedtuple
|
| 663 |
+
return type(obj)(*mapped)
|
| 664 |
+
return type(obj)(mapped)
|
| 665 |
+
elif isinstance(obj, dict):
|
| 666 |
+
return {x: _map(obj[x]) for x in obj}
|
| 667 |
+
else:
|
| 668 |
+
raise ValueError(
|
| 669 |
+
"Auto nesting doesn't know how to process "
|
| 670 |
+
"an input object of type "
|
| 671 |
+
+ torch.typename(obj)
|
| 672 |
+
+ (
|
| 673 |
+
". Accepted types: " + condition_msg + ", or lists/tuples of them"
|
| 674 |
+
if condition_msg
|
| 675 |
+
else ""
|
| 676 |
+
)
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
return _map
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def _jit_unwrap_structured(obj):
|
| 683 |
+
if hasattr(obj, "_jit_unwrap"):
|
| 684 |
+
return obj._jit_unwrap()
|
| 685 |
+
return obj
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def _iter_filter(condition, allow_unknown=False, condition_msg=None, conversion=None):
|
| 689 |
+
def _iter(obj):
|
| 690 |
+
if conversion is not None:
|
| 691 |
+
obj = conversion(obj)
|
| 692 |
+
if condition(obj):
|
| 693 |
+
yield obj
|
| 694 |
+
elif obj is None:
|
| 695 |
+
return
|
| 696 |
+
elif isinstance(obj, (list, tuple)):
|
| 697 |
+
for o in obj:
|
| 698 |
+
yield from _iter(o)
|
| 699 |
+
elif isinstance(obj, dict):
|
| 700 |
+
# We only accept primitive key types, so we needn't inspect them
|
| 701 |
+
for o in obj.values():
|
| 702 |
+
yield from _iter(o)
|
| 703 |
+
elif allow_unknown:
|
| 704 |
+
yield obj
|
| 705 |
+
else:
|
| 706 |
+
raise ValueError(
|
| 707 |
+
"Auto nesting doesn't know how to process "
|
| 708 |
+
"an input object of type "
|
| 709 |
+
+ torch.typename(obj)
|
| 710 |
+
+ (
|
| 711 |
+
". Accepted types: " + condition_msg + ", or lists/tuples of them"
|
| 712 |
+
if condition_msg
|
| 713 |
+
else ""
|
| 714 |
+
)
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
return _iter
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def _unflatten(input, proto):
|
| 721 |
+
# unflatten a list or tuple input into a nested list/tuple structure
|
| 722 |
+
# specified by proto
|
| 723 |
+
def unflatten_helper(input, proto):
|
| 724 |
+
res: List[Optional[torch.Tensor]] = []
|
| 725 |
+
if hasattr(proto, "_jit_wrap"):
|
| 726 |
+
return proto._jit_wrap(input)
|
| 727 |
+
if not isinstance(proto, (list, tuple)):
|
| 728 |
+
return input[0], input[1:]
|
| 729 |
+
for e in proto:
|
| 730 |
+
if e is None:
|
| 731 |
+
res.append(e)
|
| 732 |
+
else:
|
| 733 |
+
res_e, input = unflatten_helper(input, e)
|
| 734 |
+
res.append(res_e)
|
| 735 |
+
return type(proto)(res), input
|
| 736 |
+
|
| 737 |
+
return unflatten_helper(input, proto)[0]
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
_iter_jit_values = _iter_filter(
|
| 741 |
+
lambda o: o is None or isinstance(o, torch._C.Value),
|
| 742 |
+
condition_msg="jit's Values or None",
|
| 743 |
+
)
|
| 744 |
+
_iter_tensors = _iter_filter(
|
| 745 |
+
lambda x: isinstance(x, torch.Tensor),
|
| 746 |
+
condition_msg="Tensors",
|
| 747 |
+
conversion=_jit_unwrap_structured,
|
| 748 |
+
)
|
| 749 |
+
_iter_tensors_permissive = _iter_filter(
|
| 750 |
+
lambda x: isinstance(x, torch.Tensor),
|
| 751 |
+
allow_unknown=True,
|
| 752 |
+
condition_msg="Tensors (permissive)",
|
| 753 |
+
)
|
| 754 |
+
_iter_None_tensors = _iter_filter(
|
| 755 |
+
lambda o: o is None or isinstance(o, torch.Tensor), condition_msg="Tensors or None"
|
| 756 |
+
)
|
| 757 |
+
_map_tensor_data = _nested_map(
|
| 758 |
+
lambda x: isinstance(x, torch.Tensor), lambda o: o.data, condition_msg="Tensors"
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
class NestedIOFunction(Function):
|
| 763 |
+
r"""
|
| 764 |
+
This class is here only for backward compatibility reasons.
|
| 765 |
+
Use :class:`Function` instead of this for any new use case.
|
| 766 |
+
"""
|
| 767 |
+
# The 'type: ignore' statements are needed here because these functions are declared as '@staticmethod' in the
|
| 768 |
+
# superclass (Function) but are instance methods here, which mypy reports as incompatible.
|
| 769 |
+
|
| 770 |
+
def _do_forward(self, *input):
|
| 771 |
+
self._nested_input = input
|
| 772 |
+
flat_input = tuple(_iter_tensors(input))
|
| 773 |
+
flat_output = super()._do_forward(*flat_input) # type: ignore[misc]
|
| 774 |
+
nested_output = self._nested_output
|
| 775 |
+
nested_tensors = _unflatten(flat_output, self._nested_output)
|
| 776 |
+
return nested_tensors
|
| 777 |
+
|
| 778 |
+
def _do_backward(self, gradients, retain_variables):
|
| 779 |
+
self.retain_variables = retain_variables
|
| 780 |
+
result = super()._do_backward(gradients, retain_variables) # type: ignore[misc]
|
| 781 |
+
if not retain_variables:
|
| 782 |
+
del self._nested_output
|
| 783 |
+
del self._to_save_nested
|
| 784 |
+
return result
|
| 785 |
+
|
| 786 |
+
def backward(self, *gradients: Any) -> Any: # type: ignore[override]
|
| 787 |
+
r"""
|
| 788 |
+
Shared backward utility.
|
| 789 |
+
"""
|
| 790 |
+
nested_gradients = _unflatten(gradients, self._nested_output)
|
| 791 |
+
result = self.backward_extended(*nested_gradients) # type: ignore[func-returns-value]
|
| 792 |
+
return tuple(_iter_None_tensors(result))
|
| 793 |
+
|
| 794 |
+
__call__ = _do_forward
|
| 795 |
+
|
| 796 |
+
def forward(self, *args: Any) -> Any: # type: ignore[override]
|
| 797 |
+
r"""
|
| 798 |
+
Shared forward utility.
|
| 799 |
+
"""
|
| 800 |
+
nested_tensors = _map_tensor_data(self._nested_input)
|
| 801 |
+
result = self.forward_extended(*nested_tensors) # type: ignore[func-returns-value]
|
| 802 |
+
del self._nested_input
|
| 803 |
+
self._nested_output = result
|
| 804 |
+
return tuple(_iter_tensors(result))
|
| 805 |
+
|
| 806 |
+
def save_for_backward(self, *args: Any) -> None:
|
| 807 |
+
r"""
|
| 808 |
+
See :meth:`Function.save_for_backward`.
|
| 809 |
+
"""
|
| 810 |
+
self.to_save = tuple(_iter_tensors(args))
|
| 811 |
+
self._to_save_nested = args
|
| 812 |
+
|
| 813 |
+
@property
|
| 814 |
+
def saved_tensors(self):
|
| 815 |
+
r"""
|
| 816 |
+
See :meth:`Function.saved_tensors`.
|
| 817 |
+
"""
|
| 818 |
+
flat_tensors = super().saved_tensors # type: ignore[misc]
|
| 819 |
+
return _unflatten(flat_tensors, self._to_save_nested)
|
| 820 |
+
|
| 821 |
+
def mark_dirty(self, *args: Any, **kwargs: Any) -> None:
|
| 822 |
+
r"""
|
| 823 |
+
See :meth:`Function.mark_dirty`.
|
| 824 |
+
"""
|
| 825 |
+
self.dirty_tensors = tuple(_iter_tensors((args, kwargs)))
|
| 826 |
+
|
| 827 |
+
def mark_non_differentiable(self, *args: Any, **kwargs: Any) -> None:
|
| 828 |
+
r"""
|
| 829 |
+
See :meth:`Function.mark_non_differentiable`.
|
| 830 |
+
"""
|
| 831 |
+
self.non_differentiable = tuple(_iter_tensors((args, kwargs)))
|
| 832 |
+
|
| 833 |
+
def forward_extended(self, *input: Any) -> None:
|
| 834 |
+
r"""
|
| 835 |
+
User defined forward.
|
| 836 |
+
"""
|
| 837 |
+
raise NotImplementedError
|
| 838 |
+
|
| 839 |
+
def backward_extended(self, *grad_output: Any) -> None:
|
| 840 |
+
r"""
|
| 841 |
+
User defined backward.
|
| 842 |
+
"""
|
| 843 |
+
raise NotImplementedError
|