Sumitwarrior7 commited on
Commit
0511a45
·
verified ·
1 Parent(s): ccfdb32

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.10/site-packages/torch/_C_flatbuffer/__init__.pyi +11 -0
  2. .venv/lib/python3.10/site-packages/torch/_awaits/__init__.py +54 -0
  3. .venv/lib/python3.10/site-packages/torch/_dispatch/__init__.py +0 -0
  4. .venv/lib/python3.10/site-packages/torch/_dispatch/python.py +204 -0
  5. .venv/lib/python3.10/site-packages/torch/_refs/__init__.py +0 -0
  6. .venv/lib/python3.10/site-packages/torch/_refs/_conversions.py +119 -0
  7. .venv/lib/python3.10/site-packages/torch/_refs/fft.py +596 -0
  8. .venv/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py +436 -0
  9. .venv/lib/python3.10/site-packages/torch/_refs/nn/__init__.py +1 -0
  10. .venv/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py +1297 -0
  11. .venv/lib/python3.10/site-packages/torch/_refs/special/__init__.py +240 -0
  12. .venv/lib/python3.10/site-packages/torch/_vendor/__init__.py +0 -0
  13. .venv/lib/python3.10/site-packages/torch/_vendor/packaging/__init__.py +15 -0
  14. .venv/lib/python3.10/site-packages/torch/_vendor/packaging/_structures.py +61 -0
  15. .venv/lib/python3.10/site-packages/torch/_vendor/packaging/version.py +563 -0
  16. .venv/lib/python3.10/site-packages/torch/amp/__init__.py +9 -0
  17. .venv/lib/python3.10/site-packages/torch/amp/autocast_mode.py +529 -0
  18. .venv/lib/python3.10/site-packages/torch/amp/grad_scaler.py +714 -0
  19. .venv/lib/python3.10/site-packages/torch/ao/__init__.py +31 -0
  20. .venv/lib/python3.10/site-packages/torch/ao/nn/__init__.py +35 -0
  21. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/__init__.py +41 -0
  22. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/modules/__init__.py +41 -0
  23. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/modules/fused.py +319 -0
  24. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/__init__.py +1 -0
  25. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/__init__.py +32 -0
  26. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/conv_fused.py +971 -0
  27. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_fused.py +199 -0
  28. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_relu.py +74 -0
  29. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/__init__.py +15 -0
  30. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py +1 -0
  31. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py +6 -0
  32. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py +72 -0
  33. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py +18 -0
  34. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py +113 -0
  35. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py +153 -0
  36. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py +289 -0
  37. .venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/linear_relu.py +198 -0
  38. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/__init__.py +1 -0
  39. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/__init__.py +1 -0
  40. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/modules/__init__.py +4 -0
  41. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/modules/linear.py +40 -0
  42. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/__init__.py +13 -0
  43. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/conv.py +318 -0
  44. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/embedding_ops.py +265 -0
  45. .venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/linear.py +99 -0
  46. .venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/__init__.py +1 -0
  47. .venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/__init__.py +9 -0
  48. .venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/activation.py +623 -0
  49. .venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/rnn.py +618 -0
  50. .venv/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py +39 -0
.venv/lib/python3.10/site-packages/torch/_C_flatbuffer/__init__.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from torch._C import LiteScriptModule, ScriptModule
3
+
4
+ def _load_mobile_module_from_file(filename: str): ...
5
+ def _load_mobile_module_from_bytes(bytes_: bytes): ...
6
+ def _load_jit_module_from_file(filename: str): ...
7
+ def _load_jit_module_from_bytes(bytes_: bytes): ...
8
+ def _save_mobile_module(m: LiteScriptModule, filename: str): ...
9
+ def _save_jit_module(m: ScriptModule, filename: str): ...
10
+ def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ...
11
+ def _save_jit_module_to_bytes(m: ScriptModule) -> bytes: ...
.venv/lib/python3.10/site-packages/torch/_awaits/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Generic, TypeVar
4
+
5
+ import torch
6
+
7
+ # pyrefly: ignore [bad-dunder-all]
8
+ __all__ = ['Await']
9
+
10
+ W = TypeVar("W")
11
+
12
+ class _PyAwaitMeta(type(torch._C._Await), type(Generic)): # type: ignore[misc, no-redef]
13
+ pass
14
+
15
+ class _Await(torch._C._Await, Generic[W], metaclass=_PyAwaitMeta):
16
+ r"""
17
+ Wrapper around a ``torch._C.Await`` which encapsulates delayed execution
18
+ of a callable. All manipulations happen with functions ``torch.jit._awaitable``,
19
+ ``torch.jit._awaitable_wait``, ``torch.jit._awaitable_nowait``.
20
+
21
+ Torch scriptable manipulations:
22
+ ``torch.jit._awaitable(func, *args)``
23
+ Creates ``Await[W]`` object, where W is return type of func.
24
+
25
+ Returns:
26
+ ``torch.jit._awaitable_wait(Await[W])``
27
+ Returns the result of the function, specified at ``_awaitable``, with specified arguments.
28
+
29
+ Returns:
30
+ The result of type ``W`` of the function call. The result is owned by ``Await[W]``
31
+ and returned on all following ``_awaitable_wait`` calls.
32
+
33
+
34
+ ``torch.jit._awaitable_nowait(W)``
35
+ Returns:
36
+ Trivial ``Await[W]`` with specified result.
37
+
38
+
39
+ Only in eager mode:
40
+ ``fn() -> Callable[Tuple[Any], W]``
41
+ Returns:
42
+ Specified at ``_awaitable`` python function ``func``.
43
+
44
+ ``args() -> Tuple[Any]``
45
+ Returns:
46
+ Specified at ``_awaitable`` python args.
47
+
48
+ ``is_nowait() -> _bool``
49
+ Returns:
50
+ ``True`` if this object was created via ``_awaitable_nowait`` call (trivial `Await[W]`).
51
+
52
+ In eager mode ``Await[W]`` can be used as ``W`` i.e. attributes of W can be called on ``Await[W]``,
53
+ ``_awaitable_wait()`` call will be transparently added.
54
+ """
.venv/lib/python3.10/site-packages/torch/_dispatch/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_dispatch/python.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import unittest.mock
3
+ from collections.abc import Callable, Generator, Iterator
4
+ from contextlib import contextmanager
5
+ from typing import TypeVar, Union
6
+ from typing_extensions import ParamSpec
7
+
8
+ import torch
9
+ import torch._C
10
+ import torch._ops
11
+ import torch.utils._python_dispatch
12
+ import torch.utils._pytree as pytree
13
+ from torch._C import DispatchKey
14
+
15
+
16
+ __all__ = ["enable_python_dispatcher", "no_python_dispatcher", "enable_pre_dispatch"]
17
+
18
+ no_python_dispatcher = torch._C._DisablePythonDispatcher
19
+ enable_python_dispatcher = torch._C._EnablePythonDispatcher
20
+ enable_pre_dispatch = torch._C._EnablePreDispatch
21
+
22
+ CROSSREF_FUNCTIONALIZE = False
23
+
24
+ _P = ParamSpec("_P")
25
+ _T = TypeVar("_T")
26
+ _R = TypeVar("_R")
27
+
28
+
29
+ def all_py_loaded_overloads() -> Iterator[torch._ops.OpOverload]:
30
+ """
31
+ Warning: the set of overloads this will report is very subtle. It is precisely
32
+ the set of torch.ops functions that have actually been accessed from Python
33
+ (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT
34
+ from the set of registered operators, which will in general be a larger set,
35
+ as this would include all operators which we ran C++ static initializers or
36
+ Python operator registration on. This does not eagerly populate the list on
37
+ torch.ops.aten; this list is lazy!
38
+
39
+ In other words, this is good for traversing over everything that has an
40
+ OpOverload object allocated in Python. We use it for cache invalidation, but
41
+ don't rely on this list being complete.
42
+
43
+ Note that even if we did report all C++ registered overloads, this isn't guaranteed
44
+ to be complete either, as a subsequent lazy load of a library which triggers more
45
+ registrations could add more things to the set.
46
+ """
47
+ for ns in torch.ops:
48
+ packets = getattr(torch.ops, ns)
49
+ for op_name in packets:
50
+ packet = getattr(packets, op_name)
51
+ for overload in packet:
52
+ yield getattr(packet, overload)
53
+
54
+
55
+ @contextmanager
56
+ def suspend_functionalization() -> Generator[None, None, None]:
57
+ f_tls = torch._C._dispatch_tls_is_dispatch_key_included(
58
+ torch._C.DispatchKey.Functionalize
59
+ )
60
+ f_rv = torch._C._functionalization_reapply_views_tls()
61
+ if f_tls:
62
+ torch._disable_functionalization()
63
+ try:
64
+ yield
65
+ finally:
66
+ if f_tls:
67
+ torch._enable_functionalization(reapply_views=f_rv)
68
+
69
+
70
+ def check_tensor_metadata_matches(
71
+ nv: torch.Tensor, rv: torch.Tensor, desc: Callable[[], str]
72
+ ) -> None:
73
+ if not callable(desc):
74
+ raise AssertionError(f"desc must be callable, got {type(desc)}")
75
+ if nv.size() != rv.size():
76
+ raise AssertionError(f"{desc()}: sizes {nv.size()} != {rv.size()}")
77
+ if nv.dtype != rv.dtype:
78
+ raise AssertionError(f"{desc()}: dtype {nv.dtype} != {rv.dtype}")
79
+ same_strides, idx = torch._prims_common.check_significant_strides(
80
+ nv, rv, only_cuda=False
81
+ )
82
+ if not same_strides:
83
+ raise AssertionError(
84
+ f"{desc()}: strides {nv.stride()} != {rv.stride()} (mismatch at index {idx})"
85
+ )
86
+
87
+
88
+ def check_metadata_matches(n: object, r: object, desc: Callable[[], str]) -> None:
89
+ if not callable(desc):
90
+ raise AssertionError(f"desc must be callable, got {type(desc)}")
91
+ n_vals, _n_spec = pytree.tree_flatten(n)
92
+ r_vals, _r_spec = pytree.tree_flatten(r)
93
+ # TODO: test the specs match; empirically sometimes we have a tuple
94
+ # on one side and a list on the other
95
+ if len(n_vals) != len(r_vals):
96
+ raise AssertionError(f"{len(n_vals)} != {len(r_vals)}")
97
+ for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals):
98
+ if not isinstance(rv, torch.Tensor):
99
+ continue
100
+ check_tensor_metadata_matches(nv, rv, lambda: f"{desc()} output {i}")
101
+
102
+
103
+ class Lit:
104
+ def __init__(self, s: str) -> None:
105
+ self.s = s
106
+
107
+ def __repr__(self) -> str:
108
+ return self.s
109
+
110
+
111
+ def _fmt(a: object) -> object:
112
+ if isinstance(a, torch.Tensor):
113
+ return Lit(
114
+ f"torch.empty_strided({tuple(a.size())}, {a.stride()}, dtype={a.dtype})"
115
+ )
116
+ else:
117
+ return a
118
+
119
+
120
+ def make_crossref_functionalize(
121
+ op: torch._ops.OpOverload[_P, _T], final_key: DispatchKey
122
+ ) -> Union[Callable[_P, _T], DispatchKey]:
123
+ from torch._subclasses.fake_tensor import FakeTensorMode
124
+
125
+ # This case is pretty weird, suppress it for now
126
+ if op is torch.ops.aten.lift_fresh.default:
127
+ return final_key
128
+
129
+ def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T:
130
+ fake_mode = FakeTensorMode()
131
+
132
+ def fakeify_defun(t: _R) -> _R | torch._subclasses.fake_tensor.FakeTensor:
133
+ if isinstance(t, torch.Tensor):
134
+ if torch._is_functional_tensor(t):
135
+ r = torch._from_functional_tensor(t)
136
+ # NB: This assumes that the inner tensor sizes/strides match
137
+ # the outer tensor sizes/strides. This doesn't necessarily have to
138
+ # be the case, see discussion at
139
+ # https://github.com/pytorch/pytorch/pull/87610/files/401ddeda1d769bedc88a12de332c7357b60e51a4#r1007264456
140
+ if t.size() != r.size():
141
+ raise AssertionError(f"size mismatch: {t.size()} != {r.size()}")
142
+ if t.stride() != r.stride():
143
+ raise AssertionError(
144
+ f"stride mismatch: {t.stride()} != {r.stride()}"
145
+ )
146
+ else:
147
+ r = t
148
+ # TODO: suppress guards
149
+ return fake_mode.from_tensor(r)
150
+ return t
151
+
152
+ def maybe_detach(t: _R) -> _R | torch.Tensor:
153
+ if isinstance(t, torch.Tensor):
154
+ return t.detach()
155
+ else:
156
+ return t
157
+
158
+ # TODO: This probably does the wrong thing if you're running other
159
+ # substantive modes with the normal op outside here
160
+ with (
161
+ torch.utils._python_dispatch._disable_current_modes(),
162
+ suspend_functionalization(),
163
+ ):
164
+ f_args, f_kwargs = pytree.tree_map(fakeify_defun, (args, kwargs))
165
+ orig_f_args, orig_f_kwargs = pytree.tree_map(
166
+ maybe_detach, (f_args, f_kwargs)
167
+ )
168
+ with fake_mode:
169
+ f_r = op(*f_args, **f_kwargs) # pyrefly: ignore [invalid-param-spec]
170
+ r = op._op_dk(final_key, *args, **kwargs)
171
+
172
+ def desc() -> str:
173
+ fmt_args = ", ".join(
174
+ itertools.chain(
175
+ (repr(pytree.tree_map(_fmt, a)) for a in orig_f_args),
176
+ (
177
+ f"{k}={pytree.tree_map(_fmt, v)}"
178
+ for k, v in orig_f_kwargs.items()
179
+ ),
180
+ )
181
+ )
182
+ return f"{op}({fmt_args})"
183
+
184
+ check_metadata_matches(f_r, r, desc)
185
+ return r
186
+
187
+ return handler
188
+
189
+
190
+ # NB: enabling this is slow, don't do it in a hot loop. This is purely
191
+ # for debugging purposes.
192
+ @contextmanager
193
+ def enable_crossref_functionalize() -> Generator[None, None, None]:
194
+ for op in all_py_loaded_overloads():
195
+ op._uncache_dispatch(torch._C.DispatchKey.Functionalize)
196
+ try:
197
+ with (
198
+ enable_python_dispatcher(),
199
+ unittest.mock.patch("torch._dispatch.python.CROSSREF_FUNCTIONALIZE", True),
200
+ ):
201
+ yield
202
+ finally:
203
+ for op in all_py_loaded_overloads():
204
+ op._uncache_dispatch(torch._C.DispatchKey.Functionalize)
.venv/lib/python3.10/site-packages/torch/_refs/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/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
+ from torch._prims_common import TensorLikeType
8
+ from torch._prims_common.wrappers import out_wrapper
9
+ from torch._refs import _broadcast_shapes
10
+
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
.venv/lib/python3.10/site-packages/torch/_refs/fft.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections.abc import Iterable, Sequence
3
+ from typing import Literal, NamedTuple, Optional, Union
4
+
5
+ import torch
6
+ import torch._prims as prims
7
+ import torch._prims_common as utils
8
+ from torch._decomp import register_decomposition
9
+ from torch._prims_common import DimsType, ShapeType, TensorLikeType
10
+ from torch._prims_common.wrappers import _maybe_convert_to_dtype, out_wrapper
11
+
12
+
13
+ __all__ = [
14
+ # Transforms
15
+ "fft",
16
+ "fft2",
17
+ "fftn",
18
+ "hfft",
19
+ "hfft2",
20
+ "hfftn",
21
+ "rfft",
22
+ "rfft2",
23
+ "rfftn",
24
+ "ifft",
25
+ "ifft2",
26
+ "ifftn",
27
+ "ihfft",
28
+ "ihfft2",
29
+ "ihfftn",
30
+ "irfft",
31
+ "irfft2",
32
+ "irfftn",
33
+ # Helpers
34
+ "fftshift",
35
+ "ifftshift",
36
+ ]
37
+
38
+ NormType = Union[None, Literal["forward", "backward", "ortho"]]
39
+ _NORM_VALUES = {None, "forward", "backward", "ortho"}
40
+ aten = torch._ops.ops.aten
41
+
42
+
43
+ def _apply_norm(
44
+ x: TensorLikeType, norm: NormType, signal_numel: int, forward: bool
45
+ ) -> TensorLikeType:
46
+ """Apply normalization to the un-normalized FFT result"""
47
+ torch._check(norm in _NORM_VALUES, lambda: f"Invalid normalization mode: {norm}")
48
+
49
+ if norm == "ortho":
50
+ return x * (1 / math.sqrt(signal_numel))
51
+
52
+ normalize = (not forward and (norm is None or norm == "backward")) or (
53
+ forward and norm == "forward"
54
+ )
55
+ return x * (1 / signal_numel) if normalize else x
56
+
57
+
58
+ def _promote_type_fft(
59
+ dtype: torch.dtype, require_complex: bool, device: torch.device
60
+ ) -> torch.dtype:
61
+ """Helper to promote a dtype to one supported by the FFT primitives"""
62
+ if dtype.is_complex:
63
+ return dtype
64
+
65
+ # Promote integral to default float type
66
+ if not dtype.is_floating_point:
67
+ dtype = torch.get_default_dtype()
68
+
69
+ allowed_types = [torch.float32, torch.float64]
70
+ maybe_support_half = device.type in ["cuda", "meta"]
71
+
72
+ if maybe_support_half:
73
+ allowed_types.append(torch.float16)
74
+ torch._check(dtype in allowed_types, lambda: f"Unsupported dtype {dtype}")
75
+
76
+ if require_complex:
77
+ dtype = utils.corresponding_complex_dtype(dtype)
78
+
79
+ return dtype
80
+
81
+
82
+ def _maybe_promote_tensor_fft(
83
+ t: TensorLikeType, require_complex: bool = False
84
+ ) -> TensorLikeType:
85
+ """Helper to promote a tensor to a dtype supported by the FFT primitives"""
86
+ cur_type = t.dtype
87
+ new_type = _promote_type_fft(cur_type, require_complex, t.device)
88
+ return _maybe_convert_to_dtype(t, new_type) # type: ignore[return-value]
89
+
90
+
91
+ def _resize_fft_input(
92
+ x: TensorLikeType, dims: tuple[int, ...], sizes: tuple[int, ...]
93
+ ) -> TensorLikeType:
94
+ """
95
+ Fixes the shape of x such that x.size(dims[i]) == sizes[i],
96
+ either by zero-padding, or by slicing x starting from 0.
97
+ """
98
+ if len(dims) != len(sizes):
99
+ raise AssertionError(
100
+ f"dims and sizes must have the same length, got {len(dims)} and {len(sizes)}"
101
+ )
102
+ must_copy = False
103
+ x_sizes = x.shape
104
+ pad_amount = [0] * len(x_sizes) * 2
105
+ for i in range(len(dims)):
106
+ if sizes[i] == -1:
107
+ continue
108
+
109
+ if x_sizes[dims[i]] < sizes[i]:
110
+ must_copy = True
111
+ pad_idx = len(pad_amount) - 2 * dims[i] - 1
112
+
113
+ pad_amount[pad_idx] = sizes[i] - x_sizes[dims[i]]
114
+
115
+ if x_sizes[dims[i]] > sizes[i]:
116
+ x = x.narrow(dims[i], 0, sizes[i])
117
+
118
+ return torch.constant_pad_nd(x, pad_amount) if must_copy else x
119
+
120
+
121
+ def _fft_c2r(
122
+ func_name: str,
123
+ input: TensorLikeType,
124
+ n: Optional[int],
125
+ dim: int,
126
+ norm: NormType,
127
+ forward: bool,
128
+ ) -> TensorLikeType:
129
+ """Common code for performing any complex to real FFT (irfft or hfft)"""
130
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
131
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
132
+ last_dim_size = n if n is not None else 2 * (input.shape[dim] - 1)
133
+ torch._check(
134
+ last_dim_size >= 1,
135
+ lambda: f"Invalid number of data points ({last_dim_size}) specified",
136
+ )
137
+
138
+ if n is not None:
139
+ input = _resize_fft_input(input, dims=dims, sizes=(last_dim_size // 2 + 1,))
140
+
141
+ if forward:
142
+ input = torch.conj(input)
143
+
144
+ output = prims.fft_c2r(input, dim=dims, last_dim_size=last_dim_size)
145
+ return _apply_norm(output, norm=norm, signal_numel=last_dim_size, forward=forward)
146
+
147
+
148
+ def _fft_r2c(
149
+ func_name: str,
150
+ input: TensorLikeType,
151
+ n: Optional[int],
152
+ dim: int,
153
+ norm: NormType,
154
+ forward: bool,
155
+ onesided: bool,
156
+ ) -> TensorLikeType:
157
+ """Common code for performing any real to complex FFT (rfft or ihfft)"""
158
+ torch._check(
159
+ not input.dtype.is_complex,
160
+ lambda: f"{func_name} expects a floating point input tensor, but got {input.dtype}",
161
+ )
162
+ input = _maybe_promote_tensor_fft(input)
163
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
164
+ dim_size = n if n is not None else input.shape[dim]
165
+ torch._check(
166
+ dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified"
167
+ )
168
+
169
+ if n is not None:
170
+ input = _resize_fft_input(input, dims, (n,))
171
+
172
+ ret = prims.fft_r2c(input, dim=dims, onesided=onesided)
173
+ ret = _apply_norm(ret, norm, dim_size, forward)
174
+ return ret if forward else torch.conj(ret)
175
+
176
+
177
+ def _fft_c2c(
178
+ func_name: str,
179
+ input: TensorLikeType,
180
+ n: Optional[int],
181
+ dim: int,
182
+ norm: NormType,
183
+ forward: bool,
184
+ ) -> TensorLikeType:
185
+ """Common code for performing any complex to complex FFT (fft or ifft)"""
186
+ torch._check(
187
+ input.dtype.is_complex,
188
+ lambda: f"{func_name} expects a complex input tensor, but got {input.dtype}",
189
+ )
190
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
191
+ dim_size = n if n is not None else input.shape[dim]
192
+ torch._check(
193
+ dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified"
194
+ )
195
+
196
+ if n is not None:
197
+ input = _resize_fft_input(input, dims, (n,))
198
+
199
+ ret = prims.fft_c2c(input, dim=dims, forward=forward)
200
+ return _apply_norm(ret, norm, dim_size, forward)
201
+
202
+
203
+ @register_decomposition(aten.fft_fft)
204
+ @out_wrapper()
205
+ def fft(
206
+ input: TensorLikeType,
207
+ n: Optional[int] = None,
208
+ dim: int = -1,
209
+ norm: NormType = None,
210
+ ) -> TensorLikeType:
211
+ if input.dtype.is_complex:
212
+ return _fft_c2c("fft", input, n, dim, norm, forward=True)
213
+ else:
214
+ return _fft_r2c("fft", input, n, dim, norm, forward=True, onesided=False)
215
+
216
+
217
+ @register_decomposition(aten.fft_ifft)
218
+ @out_wrapper()
219
+ def ifft(
220
+ input: TensorLikeType,
221
+ n: Optional[int] = None,
222
+ dim: int = -1,
223
+ norm: NormType = None,
224
+ ) -> TensorLikeType:
225
+ if input.dtype.is_complex:
226
+ return _fft_c2c("ifft", input, n, dim, norm, forward=False)
227
+ else:
228
+ return _fft_r2c("ifft", input, n, dim, norm, forward=False, onesided=False)
229
+
230
+
231
+ @register_decomposition(aten.fft_rfft)
232
+ @out_wrapper()
233
+ def rfft(
234
+ input: TensorLikeType,
235
+ n: Optional[int] = None,
236
+ dim: int = -1,
237
+ norm: NormType = None,
238
+ ) -> TensorLikeType:
239
+ return _fft_r2c("rfft", input, n, dim, norm, forward=True, onesided=True)
240
+
241
+
242
+ @register_decomposition(aten.fft_irfft)
243
+ @out_wrapper()
244
+ def irfft(
245
+ input: TensorLikeType,
246
+ n: Optional[int] = None,
247
+ dim: int = -1,
248
+ norm: NormType = None,
249
+ ) -> TensorLikeType:
250
+ return _fft_c2r("irfft", input, n, dim, norm, forward=False)
251
+
252
+
253
+ @register_decomposition(aten.fft_hfft)
254
+ @out_wrapper()
255
+ def hfft(
256
+ input: TensorLikeType,
257
+ n: Optional[int] = None,
258
+ dim: int = -1,
259
+ norm: NormType = None,
260
+ ) -> TensorLikeType:
261
+ return _fft_c2r("hfft", input, n, dim, norm, forward=True)
262
+
263
+
264
+ @register_decomposition(aten.fft_ihfft)
265
+ @out_wrapper()
266
+ def ihfft(
267
+ input: TensorLikeType,
268
+ n: Optional[int] = None,
269
+ dim: int = -1,
270
+ norm: NormType = None,
271
+ ) -> TensorLikeType:
272
+ return _fft_r2c("ihfft", input, n, dim, norm, forward=False, onesided=True)
273
+
274
+
275
+ class _ShapeAndDims(NamedTuple):
276
+ shape: tuple[int, ...]
277
+ dims: tuple[int, ...]
278
+
279
+
280
+ def _canonicalize_fft_shape_and_dim_args(
281
+ input: TensorLikeType, shape: Optional[ShapeType], dim: Optional[DimsType]
282
+ ) -> _ShapeAndDims:
283
+ """Convert the shape and dim arguments into a canonical form where neither are optional"""
284
+ input_dim = input.ndim
285
+ input_sizes = input.shape
286
+
287
+ if dim is not None:
288
+ if not isinstance(dim, Sequence):
289
+ dim = (dim,)
290
+ ret_dims = utils.canonicalize_dims(input_dim, dim, wrap_scalar=False)
291
+
292
+ # Check dims are unique
293
+ torch._check(
294
+ len(set(ret_dims)) == len(ret_dims), lambda: "FFT dims must be unique"
295
+ )
296
+
297
+ if shape is not None:
298
+ if not isinstance(shape, Sequence):
299
+ shape = (shape,)
300
+
301
+ # Has shape, might have dim
302
+ torch._check(
303
+ dim is None or len(dim) == len(shape),
304
+ lambda: "When given, dim and shape arguments must have the same length",
305
+ )
306
+ transform_ndim = len(shape)
307
+
308
+ torch._check(
309
+ transform_ndim <= input_dim,
310
+ lambda: f"Got shape with {transform_ndim} values but input tensor "
311
+ f"only has {input_dim} dimensions.",
312
+ )
313
+
314
+ # If shape is given, dims defaults to the last len(shape) dimensions
315
+ if dim is None:
316
+ ret_dims = tuple(range(input_dim - transform_ndim, input_dim))
317
+
318
+ # Translate any -1 values in shape to the default length
319
+ ret_shape = tuple(
320
+ s if s != -1 else input_sizes[d]
321
+ for (s, d) in zip(shape, ret_dims) # type: ignore[possibly-undefined]
322
+ )
323
+ elif dim is None:
324
+ # No shape, no dim
325
+ ret_dims = tuple(range(input_dim))
326
+ ret_shape = tuple(input_sizes)
327
+ else:
328
+ # No shape, has dim
329
+ ret_shape = tuple(input_sizes[d] for d in ret_dims) # type: ignore[possibly-undefined]
330
+
331
+ for n in ret_shape:
332
+ torch._check(n > 0, lambda: f"Invalid number of data points ({n}) specified")
333
+
334
+ return _ShapeAndDims(shape=ret_shape, dims=ret_dims) # type: ignore[possibly-undefined]
335
+
336
+
337
+ def _prod(xs: Iterable[int]) -> int:
338
+ """Compute product of a list"""
339
+ prod = 1
340
+ for x in xs:
341
+ prod *= x
342
+ return prod
343
+
344
+
345
+ def _fftn_c2c(
346
+ function_name: str,
347
+ input: TensorLikeType,
348
+ shape: tuple[int, ...],
349
+ dim: tuple[int, ...],
350
+ norm: NormType,
351
+ forward: bool,
352
+ ) -> TensorLikeType:
353
+ """Common code for n-dimensional complex to complex FFTs (fftn or ifftn)"""
354
+ torch._check(
355
+ input.dtype.is_complex,
356
+ lambda: f"{function_name} expects a complex input tensor, "
357
+ f"but got {input.dtype}",
358
+ )
359
+ x = _resize_fft_input(input, dim, shape)
360
+ output = prims.fft_c2c(x, dim=dim, forward=forward)
361
+ return _apply_norm(output, norm=norm, signal_numel=_prod(shape), forward=forward)
362
+
363
+
364
+ @register_decomposition(aten.fft_fftn)
365
+ @out_wrapper()
366
+ def fftn(
367
+ input: TensorLikeType,
368
+ s: Optional[ShapeType] = None,
369
+ dim: Optional[DimsType] = None,
370
+ norm: NormType = None,
371
+ ) -> TensorLikeType:
372
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
373
+ x = _maybe_promote_tensor_fft(input, require_complex=True)
374
+ return _fftn_c2c("fftn", x, shape, dim, norm, forward=True)
375
+
376
+
377
+ @register_decomposition(aten.fft_ifftn)
378
+ @out_wrapper()
379
+ def ifftn(
380
+ input: TensorLikeType,
381
+ s: Optional[ShapeType] = None,
382
+ dim: Optional[DimsType] = None,
383
+ norm: NormType = None,
384
+ ) -> TensorLikeType:
385
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
386
+ x = _maybe_promote_tensor_fft(input, require_complex=True)
387
+ return _fftn_c2c("ifftn", x, shape, dim, norm, forward=False)
388
+
389
+
390
+ @register_decomposition(aten.fft_rfftn)
391
+ @out_wrapper()
392
+ def rfftn(
393
+ input: TensorLikeType,
394
+ s: Optional[ShapeType] = None,
395
+ dim: Optional[DimsType] = None,
396
+ norm: NormType = None,
397
+ ) -> TensorLikeType:
398
+ torch._check(
399
+ not input.dtype.is_complex,
400
+ lambda: f"rfftn expects a real-valued input tensor, but got {input.dtype}",
401
+ )
402
+ shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim)
403
+ input = _maybe_promote_tensor_fft(input, require_complex=False)
404
+ input = _resize_fft_input(input, dim, shape)
405
+ out = prims.fft_r2c(input, dim=dim, onesided=True)
406
+ return _apply_norm(out, norm=norm, signal_numel=_prod(shape), forward=True)
407
+
408
+
409
+ @register_decomposition(aten.fft_ihfftn)
410
+ @out_wrapper()
411
+ def ihfftn(
412
+ input: TensorLikeType,
413
+ s: Optional[ShapeType] = None,
414
+ dim: Optional[DimsType] = None,
415
+ norm: NormType = None,
416
+ ) -> TensorLikeType:
417
+ torch._check(
418
+ not input.dtype.is_complex,
419
+ lambda: f"ihfftn expects a real-valued input tensor, but got {input.dtype}",
420
+ )
421
+ shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim)
422
+ torch._check(len(shape) > 0, lambda: "ihfftn must transform at least one axis")
423
+ input = _maybe_promote_tensor_fft(input, require_complex=False)
424
+ input = _resize_fft_input(input, dim, shape)
425
+
426
+ tmp = prims.fft_r2c(input, dim=dim[-1:], onesided=True)
427
+
428
+ if len(dim) == 1:
429
+ tmp = _apply_norm(tmp, norm=norm, signal_numel=shape[0], forward=False)
430
+ return prims.conj(tmp)
431
+
432
+ tmp = prims.conj_physical(tmp)
433
+ tmp = prims.fft_c2c(tmp, dim=dim[:-1], forward=False)
434
+ return _apply_norm(tmp, norm=norm, signal_numel=_prod(shape), forward=False)
435
+
436
+
437
+ class _CanonicalizeC2rReturn(NamedTuple):
438
+ shape: tuple[int, ...]
439
+ dim: tuple[int, ...]
440
+ last_dim_size: int
441
+
442
+
443
+ def _canonicalize_fft_c2r_shape_and_dim_args(
444
+ fname: str,
445
+ input: TensorLikeType,
446
+ s: Optional[ShapeType],
447
+ dim: Optional[DimsType],
448
+ ) -> _CanonicalizeC2rReturn:
449
+ """Canonicalize shape and dim arguments for n-dimensional c2r transforms,
450
+ as well as calculating the last_dim_size which is shape[dim[-1]] for the output"""
451
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
452
+ torch._check(len(shape) > 0, lambda: f"{fname} must transform at least one axis")
453
+
454
+ if s is None or s[-1] == -1:
455
+ last_dim_size = 2 * (input.shape[dim[-1]] - 1)
456
+ else:
457
+ last_dim_size = shape[-1]
458
+
459
+ torch._check(
460
+ last_dim_size >= 1,
461
+ lambda: f"Invalid number of data points ({last_dim_size}) specified",
462
+ )
463
+
464
+ shape_list = list(shape)
465
+ shape_list[-1] = last_dim_size // 2 + 1
466
+ return _CanonicalizeC2rReturn(
467
+ shape=tuple(shape_list), dim=dim, last_dim_size=last_dim_size
468
+ )
469
+
470
+
471
+ @register_decomposition(aten.fft_irfftn)
472
+ @out_wrapper()
473
+ def irfftn(
474
+ input: TensorLikeType,
475
+ s: Optional[ShapeType] = None,
476
+ dim: Optional[DimsType] = None,
477
+ norm: NormType = None,
478
+ ) -> TensorLikeType:
479
+ shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args(
480
+ "irfftn", input, s, dim
481
+ )
482
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
483
+ input = _resize_fft_input(input, dim, shape)
484
+ out = prims.fft_c2r(input, dim=dim, last_dim_size=last_dim_size)
485
+ return _apply_norm(out, norm, _prod(out.shape[d] for d in dim), forward=False)
486
+
487
+
488
+ @register_decomposition(aten.fft_hfftn)
489
+ @out_wrapper()
490
+ def hfftn(
491
+ input: TensorLikeType,
492
+ s: Optional[ShapeType] = None,
493
+ dim: Optional[DimsType] = None,
494
+ norm: NormType = None,
495
+ ) -> TensorLikeType:
496
+ shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args(
497
+ "hfftn", input, s, dim
498
+ )
499
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
500
+ input = _resize_fft_input(input, dim, shape)
501
+
502
+ tmp = prims.fft_c2c(input, dim=dim[:-1], forward=True) if len(dim) > 1 else input
503
+ tmp = _apply_norm(tmp, norm, _prod(shape[:-1]), forward=True)
504
+ tmp = prims.conj_physical(tmp)
505
+ out = prims.fft_c2r(tmp, dim=dim[-1:], last_dim_size=last_dim_size)
506
+ return _apply_norm(out, norm, last_dim_size, forward=True)
507
+
508
+
509
+ @register_decomposition(aten.fft_fft2)
510
+ @out_wrapper()
511
+ def fft2(
512
+ input: TensorLikeType,
513
+ s: Optional[ShapeType] = None,
514
+ dim: Optional[DimsType] = (-2, -1),
515
+ norm: NormType = None,
516
+ ) -> TensorLikeType:
517
+ return torch.fft.fftn(input, s=s, dim=dim, norm=norm)
518
+
519
+
520
+ @register_decomposition(aten.fft_ifft2)
521
+ @out_wrapper()
522
+ def ifft2(
523
+ input: TensorLikeType,
524
+ s: Optional[ShapeType] = None,
525
+ dim: Optional[DimsType] = (-2, -1),
526
+ norm: NormType = None,
527
+ ) -> TensorLikeType:
528
+ return torch.fft.ifftn(input, s=s, dim=dim, norm=norm)
529
+
530
+
531
+ @register_decomposition(aten.fft_rfft2)
532
+ @out_wrapper()
533
+ def rfft2(
534
+ input: TensorLikeType,
535
+ s: Optional[ShapeType] = None,
536
+ dim: Optional[DimsType] = (-2, -1),
537
+ norm: NormType = None,
538
+ ) -> TensorLikeType:
539
+ return torch.fft.rfftn(input, s=s, dim=dim, norm=norm)
540
+
541
+
542
+ @register_decomposition(aten.fft_irfft2)
543
+ @out_wrapper()
544
+ def irfft2(
545
+ input: TensorLikeType,
546
+ s: Optional[ShapeType] = None,
547
+ dim: Optional[DimsType] = (-2, -1),
548
+ norm: NormType = None,
549
+ ) -> TensorLikeType:
550
+ return torch.fft.irfftn(input, s=s, dim=dim, norm=norm)
551
+
552
+
553
+ @register_decomposition(aten.fft_hfft2)
554
+ @out_wrapper()
555
+ def hfft2(
556
+ input: TensorLikeType,
557
+ s: Optional[ShapeType] = None,
558
+ dim: Optional[DimsType] = (-2, -1),
559
+ norm: NormType = None,
560
+ ) -> TensorLikeType:
561
+ return torch.fft.hfftn(input, s=s, dim=dim, norm=norm)
562
+
563
+
564
+ @register_decomposition(aten.fft_ihfft2)
565
+ @out_wrapper()
566
+ def ihfft2(
567
+ input: TensorLikeType,
568
+ s: Optional[ShapeType] = None,
569
+ dim: Optional[DimsType] = (-2, -1),
570
+ norm: NormType = None,
571
+ ) -> TensorLikeType:
572
+ return torch.fft.ihfftn(input, s=s, dim=dim, norm=norm)
573
+
574
+
575
+ def _default_alldims(dim: Optional[DimsType], x: TensorLikeType) -> list[int]:
576
+ """Convert Optional[DimsType] to a simple list, defaulting to all dimensions"""
577
+ if dim is None:
578
+ return list(range(x.ndim))
579
+ elif not isinstance(dim, Sequence):
580
+ return [dim]
581
+ else:
582
+ return list(dim)
583
+
584
+
585
+ @register_decomposition(aten.fft_fftshift)
586
+ def fftshift(input: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType:
587
+ dims = _default_alldims(dim, input)
588
+ shift = [input.shape[d] // 2 for d in dims]
589
+ return torch.roll(input, shift, dims)
590
+
591
+
592
+ @register_decomposition(aten.fft_ifftshift)
593
+ def ifftshift(input: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType:
594
+ dims = _default_alldims(dim, input)
595
+ shift = [(input.shape[d] + 1) // 2 for d in dims]
596
+ return torch.roll(input, shift, dims)
.venv/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ from functools import partial
4
+ from typing import 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
+ import torch._refs.linalg as linalg
11
+ from torch import Tensor
12
+ from torch._prims_common import (
13
+ check_fp_or_complex,
14
+ check_is_matrix,
15
+ Dim,
16
+ DimsType,
17
+ ELEMENTWISE_TYPE_PROMOTION_KIND,
18
+ IntLike,
19
+ TensorLikeType,
20
+ )
21
+ from torch._prims_common.wrappers import (
22
+ _maybe_convert_to_dtype,
23
+ elementwise_type_promotion_wrapper,
24
+ out_wrapper,
25
+ )
26
+
27
+
28
+ __all__ = [
29
+ "diagonal",
30
+ "matrix_norm",
31
+ "norm",
32
+ "svd",
33
+ "svdvals",
34
+ "vector_norm",
35
+ "vecdot",
36
+ "cross",
37
+ ]
38
+
39
+
40
+ def _check_norm_dtype(dtype: Optional[torch.dtype], x_dtype: torch.dtype, fn_name: str):
41
+ """
42
+ Checks related to the dtype kwarg in `linalg.*norm` functions
43
+ """
44
+ if dtype is not None:
45
+ torch._check(
46
+ utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype),
47
+ lambda: f"{fn_name}: dtype should be floating point or complex. Got {dtype}",
48
+ )
49
+ torch._check(
50
+ utils.is_complex_dtype(dtype) == utils.is_complex_dtype(x_dtype),
51
+ lambda: "{fn_name}: dtype should be {d} for {d} inputs. Got {dtype}".format(
52
+ fn_name=fn_name,
53
+ d="complex" if utils.is_complex_dtype(x_dtype) else "real",
54
+ dtype=dtype,
55
+ ),
56
+ )
57
+ torch._check(
58
+ utils.get_higher_dtype(dtype, x_dtype) == dtype,
59
+ lambda: f"{fn_name}: the dtype of the input ({x_dtype}) should be convertible "
60
+ f"without narrowing to the specified dtype ({dtype})",
61
+ )
62
+
63
+
64
+ import operator
65
+
66
+ # Utilities should come BEFORE this import
67
+ from torch._decomp import register_decomposition
68
+ from torch._decomp.decompositions import pw_cast_for_opmath
69
+
70
+
71
+ @register_decomposition(torch._ops.ops.aten.linalg_cross)
72
+ @out_wrapper()
73
+ @pw_cast_for_opmath
74
+ def cross(a: Tensor, b: Tensor, dim: int = -1):
75
+ torch._check(
76
+ a.ndim == b.ndim,
77
+ lambda: "linalg.cross: inputs must have the same number of dimensions.",
78
+ )
79
+ torch._check(
80
+ a.size(dim) == 3 and b.size(dim) == 3,
81
+ lambda: f"linalg.cross: inputs dim {dim} must have length 3, got {a.size(dim)} and {b.size(dim)}",
82
+ )
83
+ a, b = torch.broadcast_tensors(a, b)
84
+ dim = utils.canonicalize_dim(a.ndim, dim)
85
+ idx = torch.arange(3, device=a.device)
86
+ return a.index_select(dim, (idx + 1) % 3) * b.index_select(
87
+ dim, (idx + 2) % 3
88
+ ) - a.index_select(dim, (idx + 2) % 3) * b.index_select(dim, (idx + 1) % 3)
89
+
90
+
91
+ def diagonal(
92
+ input: TensorLikeType,
93
+ *,
94
+ offset: int = 0,
95
+ dim1: int = -2,
96
+ dim2: int = -1,
97
+ ) -> TensorLikeType:
98
+ return torch.diagonal(input, offset=offset, dim1=dim1, dim2=dim2)
99
+
100
+
101
+ def _check_vector_norm_args(
102
+ x: TensorLikeType, ord: Union[float, int] = 2, dim: Optional[DimsType] = None
103
+ ):
104
+ from torch.fx.experimental.symbolic_shapes import sym_or
105
+
106
+ if not (ord < 0.0 or ord == float("inf")):
107
+ return
108
+
109
+ torch._check(
110
+ sym_or(
111
+ x.numel() != 0,
112
+ not isinstance(dim, IntLike) and dim is not None and len(dim) != 0,
113
+ ),
114
+ lambda: f"linalg.vector_norm cannot compute the {ord} norm on an empty tensor "
115
+ "because the operation does not have an identity",
116
+ )
117
+
118
+ shape = x.shape
119
+ if dim is not None and not isinstance(dim, IntLike):
120
+ for d in dim:
121
+ torch._check(
122
+ sym_or(x.numel() != 0, d < len(shape) and d >= 0 and shape[d] != 0),
123
+ lambda: f"linalg.vector_norm cannot compute the {ord} norm on the "
124
+ f"dimension {d} because this dimension is empty and the "
125
+ "operation does not have an identity",
126
+ )
127
+
128
+
129
+ @register_decomposition(torch._ops.ops.aten.linalg_vector_norm)
130
+ @out_wrapper(exact_dtype=True)
131
+ def vector_norm(
132
+ x: TensorLikeType,
133
+ ord: Union[float, int] = 2,
134
+ dim: Optional[DimsType] = None,
135
+ keepdim: bool = False,
136
+ *,
137
+ dtype: Optional[torch.dtype] = None,
138
+ ) -> Tensor:
139
+ from torch.fx.experimental.symbolic_shapes import guard_or_false
140
+
141
+ check_fp_or_complex(x.dtype, "linalg.vector_norm")
142
+
143
+ if isinstance(dim, Dim):
144
+ dim = [dim] # type: ignore[assignment]
145
+
146
+ _check_vector_norm_args(x, ord, dim)
147
+
148
+ _check_norm_dtype(dtype, x.dtype, "linalg.vector_norm")
149
+
150
+ computation_dtype, result_dtype = utils.reduction_dtypes(
151
+ x, utils.REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT, dtype
152
+ )
153
+
154
+ to_result_dtype = partial(_maybe_convert_to_dtype, dtype=result_dtype)
155
+
156
+ # Implementation
157
+ if ord == 0.0:
158
+ return torch.sum(torch.ne(x, 0.0), dim=dim, keepdim=keepdim, dtype=result_dtype)
159
+ elif ord == float("inf"):
160
+ return to_result_dtype(torch.amax(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type]
161
+ elif ord == float("-inf"):
162
+ return to_result_dtype(torch.amin(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type]
163
+ else:
164
+ # From here on the computation dtype is important as the reduction is non-trivial
165
+ x = _maybe_convert_to_dtype(x, computation_dtype) # type: ignore[assignment]
166
+ reduce_sum = partial(torch.sum, dim=dim, keepdim=keepdim)
167
+
168
+ is_ord_even = ord % 2 == 0 if isinstance(ord, IntLike) else ord % 2.0 == 0.0
169
+ if dim == []:
170
+ dim = None
171
+
172
+ if (dim is None and x.numel() == 1) or (
173
+ dim is not None
174
+ and (x.ndim > 0 and all(guard_or_false(x.shape[d] == 1) for d in dim))
175
+ ):
176
+ if x.ndim > 64:
177
+ raise RuntimeError(
178
+ f"Received a tensor with {x.ndim} dimensions, but only tensors with up to 64 dims are supported!"
179
+ )
180
+ x = torch.abs(x)
181
+ if keepdim or x.ndim == 0:
182
+ return to_result_dtype(x).contiguous()
183
+ elif dim is None:
184
+ return to_result_dtype(x).flatten()[0]
185
+ else:
186
+ new_shape = [s for d, s in enumerate(x.shape) if d not in dim]
187
+ return to_result_dtype(x.view(new_shape)).contiguous()
188
+
189
+ if not (is_ord_even and utils.is_float_dtype(x.dtype)):
190
+ x = torch.abs(x)
191
+ return to_result_dtype(torch.pow(reduce_sum(torch.pow(x, ord)), 1.0 / ord)) # type: ignore[return-value]
192
+
193
+
194
+ def _backshift_permutation(dim0, dim1, ndim):
195
+ # Auxiliary function for matrix_norm
196
+ # Computes the permutation that moves the two given dimensions to the back
197
+ ret = [i for i in range(ndim) if i != dim0 and i != dim1]
198
+ ret.extend((dim0, dim1))
199
+ return ret
200
+
201
+
202
+ def _inverse_permutation(perm):
203
+ # Given a permutation, returns its inverse. It's equivalent to argsort on an array
204
+ return [i for i, j in sorted(enumerate(perm), key=operator.itemgetter(1))]
205
+
206
+
207
+ # CompositeImplicitAutograd
208
+ @out_wrapper(exact_dtype=True)
209
+ def matrix_norm(
210
+ A: TensorLikeType,
211
+ ord: Union[float, str] = "fro",
212
+ dim: DimsType = (-2, -1),
213
+ keepdim: bool = False,
214
+ *,
215
+ dtype: Optional[torch.dtype] = None,
216
+ ) -> TensorLikeType:
217
+ # shape
218
+ check_is_matrix(A, "linalg.matrix_norm")
219
+ # dim
220
+
221
+ dim = utils.canonicalize_dims(A.ndim, dim)
222
+ if isinstance(dim, Dim):
223
+ dim = (dim,) # type: ignore[assignment]
224
+ torch._check(
225
+ len(dim) == 2, lambda: f"linalg.matrix_norm: dim must be a 2-tuple. Got {dim}"
226
+ )
227
+ torch._check(
228
+ # pyrefly: ignore [bad-index]
229
+ dim[0] != dim[1],
230
+ # pyrefly: ignore [bad-index, index-error]
231
+ # pyrefly: ignore [bad-index, index-error]
232
+ lambda: f"linalg.matrix_norm: dims must be different. Got ({dim[0]}, {dim[1]})",
233
+ )
234
+ # dtype arg
235
+ _check_norm_dtype(dtype, A.dtype, "linalg.matrix_norm")
236
+
237
+ if isinstance(ord, str):
238
+ # ord
239
+ torch._check(
240
+ ord in ("fro", "nuc"),
241
+ lambda: f"linalg.matrix_norm: Order {ord} not supported.",
242
+ )
243
+ # dtype
244
+ check_fp_or_complex(
245
+ A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != "nuc"
246
+ )
247
+
248
+ if ord == "fro":
249
+ return vector_norm(A, 2, dim, keepdim, dtype=dtype)
250
+ else: # ord == "nuc"
251
+ if dtype is not None:
252
+ A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
253
+ # pyrefly: ignore [bad-index, index-error]
254
+ perm = _backshift_permutation(dim[0], dim[1], A.ndim)
255
+ result = torch.sum(svdvals(prims.transpose(A, perm)), -1, keepdim)
256
+ if keepdim:
257
+ inv_perm = _inverse_permutation(perm)
258
+ result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
259
+ return result
260
+ else:
261
+ # ord
262
+ abs_ord = abs(ord)
263
+ torch._check(
264
+ abs_ord in (2, 1, float("inf")),
265
+ lambda: f"linalg.matrix_norm: Order {ord} not supported.",
266
+ )
267
+ # dtype
268
+ check_fp_or_complex(
269
+ A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != 2
270
+ )
271
+
272
+ max_min = partial(torch.amax if ord > 0.0 else torch.amin, keepdim=keepdim)
273
+
274
+ def _max_min_wrapper(A, dim):
275
+ # pyrefly: ignore [unsupported-operation]
276
+ if A.size(dim) == 0 and ord > 0.0:
277
+ new_size = list(A.size())
278
+ if keepdim:
279
+ new_size[dim] = 1
280
+ else:
281
+ del new_size[dim]
282
+ return torch.zeros(new_size, dtype=A.dtype, device=A.device)
283
+ else:
284
+ return max_min(A, dim)
285
+
286
+ if abs_ord == 2.0:
287
+ if dtype is not None:
288
+ A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
289
+ # pyrefly: ignore [bad-index, index-error]
290
+ perm = _backshift_permutation(dim[0], dim[1], A.ndim)
291
+ result = _max_min_wrapper(svdvals(prims.transpose(A, perm)), dim=-1)
292
+ if keepdim:
293
+ inv_perm = _inverse_permutation(perm)
294
+ result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
295
+ return result
296
+ else: # 1, -1, inf, -inf
297
+ # pyrefly: ignore [bad-unpacking]
298
+ dim0, dim1 = dim
299
+ if abs_ord == float("inf"):
300
+ dim0, dim1 = dim1, dim0
301
+ if not keepdim and (dim0 < dim1):
302
+ dim1 -= 1
303
+ return _max_min_wrapper(
304
+ vector_norm(A, 1.0, dim=dim0, keepdim=keepdim, dtype=dtype), dim1
305
+ )
306
+
307
+
308
+ # CompositeImplicitAutograd
309
+ @out_wrapper(exact_dtype=True)
310
+ def norm(
311
+ A: TensorLikeType,
312
+ ord: Optional[Union[float, str]] = None,
313
+ dim: Optional[DimsType] = None,
314
+ keepdim: bool = False,
315
+ *,
316
+ dtype: Optional[torch.dtype] = None,
317
+ ) -> TensorLikeType:
318
+ if dim is not None:
319
+ if isinstance(dim, Dim):
320
+ dim = (dim,) # type: ignore[assignment]
321
+ torch._check(
322
+ len(dim) in (1, 2),
323
+ lambda: f"linalg.norm: If dim is specified, it must be of length 1 or 2. Got {dim}",
324
+ )
325
+ elif ord is not None:
326
+ torch._check(
327
+ A.ndim in (1, 2),
328
+ lambda: f"linalg.norm: If dim is not specified but ord is, the input must be 1D or 2D. Got {A.ndim}D",
329
+ )
330
+
331
+ if ord is not None and (
332
+ (dim is not None and len(dim) == 2) or (dim is None and A.ndim == 2)
333
+ ):
334
+ if dim is None:
335
+ dim = (0, 1)
336
+ return matrix_norm(A, ord, dim, keepdim, dtype=dtype)
337
+ else:
338
+ if ord is None:
339
+ ord = 2.0
340
+ return vector_norm(A, ord, dim, keepdim, dtype=dtype) # type: ignore[arg-type]
341
+
342
+
343
+ # CompositeImplicitAutograd
344
+ @out_wrapper("U", "S", "Vh", exact_dtype=True)
345
+ def svd(A: TensorLikeType, full_matrices: bool = True) -> tuple[Tensor, Tensor, Tensor]:
346
+ return prims.svd(A, full_matrices=full_matrices)
347
+
348
+
349
+ # CompositeImplicitAutograd
350
+ @out_wrapper(exact_dtype=True)
351
+ def svdvals(A: TensorLikeType) -> Tensor:
352
+ return svd(A, full_matrices=False)[1]
353
+
354
+
355
+ # CompositeImplicitAutograd
356
+ @out_wrapper()
357
+ @elementwise_type_promotion_wrapper(
358
+ type_promoting_args=("x", "y"),
359
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
360
+ )
361
+ def vecdot(x: Tensor, y: Tensor, dim: int = -1) -> Tensor:
362
+ check_fp_or_complex(x.dtype, "linalg.vecdot")
363
+ return (x.conj() * y).sum(dim=dim)
364
+
365
+
366
+ def _pivots_to_permutation(pivots, shape, *, inverse=False):
367
+ perm = torch.empty(shape, dtype=torch.int32, device=pivots.device)
368
+ perm[..., :] = torch.arange(shape[-1], dtype=torch.int32, device=pivots.device)
369
+ indices = range(shape[-1])
370
+ if inverse:
371
+ indices = reversed(indices)
372
+
373
+ if len(shape) > 1:
374
+ for i in indices:
375
+ j_s = pivots[..., i]
376
+ perm_i = perm[..., i].clone()
377
+ j_idx = torch.meshgrid(
378
+ *[torch.arange(s, device=perm.device) for s in j_s.shape], indexing="ij"
379
+ ) + (j_s,)
380
+ perm_j = perm[j_idx]
381
+ perm.index_put_(j_idx, perm_i)
382
+ perm[..., i].copy_(perm_j)
383
+
384
+ else:
385
+ for i in indices:
386
+ j = pivots[i]
387
+ perm_i = perm[i].clone()
388
+ perm_j = perm[j].clone()
389
+ perm[i].copy_(perm_j)
390
+ perm[j].copy_(perm_i)
391
+
392
+ return perm
393
+
394
+
395
+ def _apply_pivots(a, pivots, shape, *, inverse=False):
396
+ perm = _pivots_to_permutation(pivots - 1, shape, inverse=inverse)
397
+
398
+ if len(shape) == 1:
399
+ return a[perm, :]
400
+ else:
401
+ idx = torch.meshgrid(
402
+ *[torch.arange(s, device=a.device) for s in perm.shape], indexing="ij"
403
+ )[:-1] + (perm, slice(None))
404
+ return a[idx]
405
+
406
+
407
+ def linalg_lu_solve_out_mps(LU, pivots, B, *, left=True, adjoint=False, out):
408
+ if out.numel() == 0:
409
+ return
410
+
411
+ if not left:
412
+ adjoint = not adjoint
413
+ B = B.mH
414
+
415
+ if adjoint:
416
+ lu_ = LU.mH
417
+ x = torch.linalg.solve_triangular(lu_, B, left=True, upper=False)
418
+ x = torch.linalg.solve_triangular(
419
+ lu_, x, left=True, upper=True, unitriangular=True
420
+ )
421
+ x = _apply_pivots(x, pivots, LU.shape[:-1], inverse=True)
422
+ else:
423
+ x = _apply_pivots(B, pivots, LU.shape[:-1])
424
+ x = torch.linalg.solve_triangular(
425
+ LU, x, left=True, upper=False, unitriangular=True
426
+ )
427
+ x = torch.linalg.solve_triangular(LU, x, left=True, upper=True)
428
+
429
+ if not left:
430
+ x = x.mH
431
+
432
+ out.copy_(x)
433
+
434
+
435
+ mps_lib = torch.library.Library("aten", "IMPL", "MPS") # noqa: TOR901
436
+ mps_lib.impl("aten::linalg_lu_solve.out", linalg_lu_solve_out_mps)
.venv/lib/python3.10/site-packages/torch/_refs/nn/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __all__: list[str] = []
.venv/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py ADDED
@@ -0,0 +1,1297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import math
4
+ from collections.abc import Callable
5
+ from functools import wraps
6
+ from typing import Concatenate, Optional, TypeVar, Union
7
+ from typing_extensions import ParamSpec
8
+
9
+ import torch
10
+ import torch._prims as prims
11
+ import torch._prims_common as utils
12
+ import torch._refs as refs
13
+ from torch._decomp import register_decomposition
14
+ from torch._prims_common import (
15
+ ELEMENTWISE_TYPE_PROMOTION_KIND,
16
+ NumberType,
17
+ ShapeType,
18
+ TensorLike,
19
+ TensorLikeType,
20
+ )
21
+ from torch._prims_common.wrappers import (
22
+ elementwise_type_promotion_wrapper,
23
+ elementwise_unary_scalar_wrapper,
24
+ out_wrapper,
25
+ )
26
+ from torch._refs import _make_inplace
27
+
28
+
29
+ __all__ = [
30
+ "alpha_dropout",
31
+ "celu",
32
+ "celu_",
33
+ "channel_shuffle",
34
+ "dropout",
35
+ "elu",
36
+ "elu_",
37
+ "gelu",
38
+ "glu",
39
+ "group_norm",
40
+ "hardshrink",
41
+ "hardtanh",
42
+ "hinge_embedding_loss",
43
+ "huber_loss",
44
+ "l1_loss",
45
+ "layer_norm",
46
+ "leaky_relu",
47
+ "log_softmax",
48
+ "margin_ranking_loss",
49
+ "mish",
50
+ "mish_",
51
+ "mse_loss",
52
+ "nll_loss",
53
+ "pairwise_distance",
54
+ "pdist",
55
+ "poisson_nll_loss",
56
+ "prelu",
57
+ "relu",
58
+ "relu6",
59
+ "selu",
60
+ "selu_",
61
+ "smooth_l1_loss",
62
+ "softmax",
63
+ "softmin",
64
+ "softplus",
65
+ "softshrink",
66
+ "tanhshrink",
67
+ "threshold",
68
+ "threshold_",
69
+ "triplet_margin_loss",
70
+ ]
71
+
72
+ _T = TypeVar("_T")
73
+ _P = ParamSpec("_P")
74
+
75
+ Tensor = torch.Tensor
76
+ aten = torch._ops.ops.aten
77
+ DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined]
78
+
79
+
80
+ def _dropout_helper(
81
+ self: TensorLikeType,
82
+ val: float,
83
+ ) -> TensorLikeType:
84
+ """
85
+ Helper function for all dropout-type operators. During training,
86
+ some of the elements of the input tensor are randomly masked.
87
+
88
+ Returns the masked tensor of the boolean values.
89
+
90
+ """
91
+
92
+ return (
93
+ refs._uniform_helper(
94
+ self.shape,
95
+ low=0.0,
96
+ high=1.0,
97
+ dtype=torch.float32,
98
+ device=self.device,
99
+ stride=self.stride(),
100
+ )
101
+ < val
102
+ )
103
+
104
+
105
+ @register_decomposition(aten.alpha_dropout)
106
+ def alpha_dropout(
107
+ self: TensorLikeType, p: float = 0.5, training: bool = False, inplace: bool = False
108
+ ) -> TensorLikeType:
109
+ if inplace:
110
+ raise NotImplementedError
111
+
112
+ if not training:
113
+ return self
114
+
115
+ torch._check(
116
+ p <= 1 and p >= 0,
117
+ lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
118
+ )
119
+
120
+ if p == 1:
121
+ return torch.zeros_like(self)
122
+
123
+ if p == 0:
124
+ return self
125
+
126
+ dropout_mask = _dropout_helper(self, 1 - p)
127
+
128
+ # From paper: Self-Normalizing Neural Networks (https://arxiv.org/pdf/1706.02515.pdf)
129
+ # alpha = - SELU.alpha * SELU.scale, here
130
+ # SELU.alpha = 1.6732632423543772848170429916717 and
131
+ # SELU.scale = 1.0507009873554804934193349852946
132
+ alpha = -1.7580993408473766
133
+
134
+ a = 1.0 / math.sqrt((alpha * alpha * p + 1) * (1 - p))
135
+ b = torch.logical_not(dropout_mask)
136
+ b = b * (alpha * a) + alpha * a * p
137
+ dropout_mask = a * dropout_mask
138
+
139
+ return self * dropout_mask + b
140
+
141
+
142
+ def _inplace_wrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]:
143
+ """
144
+ Given a nn.functional non-linearity, implements its `inplace: bool` argument
145
+ """
146
+
147
+ # nb. We use the name of the first argument used in the unary references
148
+ @wraps(fn)
149
+ def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T:
150
+ a = args[0]
151
+ if "inplace" not in kwargs:
152
+ kwargs["inplace"] = False
153
+
154
+ if kwargs["inplace"]:
155
+ torch._check(
156
+ "out" not in kwargs,
157
+ lambda: "Cannot set inplace=True and pass out= at the same time",
158
+ )
159
+ kwargs["inplace"] = False
160
+ kwargs["out"] = a
161
+ return fn(*args, **kwargs)
162
+ else:
163
+ return fn(*args, **kwargs)
164
+
165
+ return _fn
166
+
167
+
168
+ # celu is implemented specially because it has an alpha argument
169
+ # celu is very similar to elu
170
+ @register_decomposition(aten.celu)
171
+ @_inplace_wrapper
172
+ @out_wrapper()
173
+ @elementwise_type_promotion_wrapper(
174
+ type_promoting_args=("a",),
175
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
176
+ )
177
+ def celu(
178
+ a: TensorLikeType, alpha: Optional[NumberType] = None, inplace: bool = False
179
+ ) -> TensorLikeType:
180
+ """
181
+ Reference implementation of torch.nn.functional.celu
182
+ """
183
+
184
+ if inplace:
185
+ raise NotImplementedError
186
+
187
+ rhs: TensorLikeType
188
+ if alpha is not None:
189
+ python_type = utils.dtype_to_type(a.dtype)
190
+ if not utils.is_weakly_lesser_type(type(alpha), python_type):
191
+ msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!"
192
+ raise ValueError(msg)
193
+ rhs = alpha * torch.expm1(torch.true_divide(a, alpha)) # type: ignore[arg-type]
194
+ else:
195
+ rhs = torch.expm1(a)
196
+
197
+ return torch.where(a > 0, a, rhs)
198
+
199
+
200
+ @_inplace_wrapper
201
+ @out_wrapper()
202
+ def dropout(
203
+ a: TensorLikeType, p: float = 0.5, training: bool = True, inplace: bool = False
204
+ ) -> TensorLikeType:
205
+ if inplace:
206
+ raise NotImplementedError
207
+
208
+ if not training:
209
+ return a
210
+
211
+ torch._check(
212
+ p <= 1 and p >= 0,
213
+ lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
214
+ )
215
+
216
+ if p == 1:
217
+ return torch.zeros_like(a)
218
+
219
+ if p == 0:
220
+ return a
221
+
222
+ scale = 1 / (1 - p)
223
+ dropout_mask = _dropout_helper(a, 1 - p)
224
+
225
+ return a * dropout_mask * scale
226
+
227
+
228
+ @register_decomposition(aten.elu)
229
+ @_inplace_wrapper
230
+ @out_wrapper()
231
+ @elementwise_type_promotion_wrapper(
232
+ type_promoting_args=("a",),
233
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
234
+ )
235
+ def elu(
236
+ a: TensorLikeType,
237
+ alpha: NumberType = 1.0,
238
+ scale: NumberType = 1.0,
239
+ input_scale: NumberType = 1.0,
240
+ inplace: bool = False,
241
+ ) -> TensorLikeType:
242
+ """
243
+ Reference implementation of torch.nn.functional.elu
244
+ """
245
+ if inplace:
246
+ raise NotImplementedError
247
+
248
+ # nb. This should be factored out into a can_cast aux function
249
+ python_type = utils.dtype_to_type(a.dtype)
250
+ torch._check(
251
+ utils.is_weakly_lesser_type(type(input_scale), python_type),
252
+ lambda: f"input_scale argument of type {type(input_scale)} cannot be safely cast to type {python_type}!",
253
+ )
254
+ torch._check(
255
+ utils.is_weakly_lesser_type(type(scale), python_type),
256
+ lambda: f"scale argument of type {type(scale)} cannot be safely cast to type {python_type}!",
257
+ )
258
+ torch._check(
259
+ utils.is_weakly_lesser_type(type(alpha), python_type),
260
+ lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!",
261
+ )
262
+
263
+ return torch.where(a > 0, scale * a, (alpha * scale) * torch.expm1(a * input_scale))
264
+
265
+
266
+ @register_decomposition(aten.relu)
267
+ @_inplace_wrapper
268
+ @out_wrapper()
269
+ @elementwise_type_promotion_wrapper(
270
+ type_promoting_args=("a",),
271
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
272
+ )
273
+ def relu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
274
+ """
275
+ Reference implementation of torch.nn.functional.relu
276
+ """
277
+
278
+ if inplace:
279
+ raise NotImplementedError
280
+
281
+ return torch.where(torch.le(a, 0), 0, a)
282
+
283
+
284
+ @register_decomposition(aten.channel_shuffle)
285
+ @out_wrapper()
286
+ def channel_shuffle(input: TensorLikeType, groups: int) -> TensorLikeType:
287
+ """
288
+ Reference implementation of :func:`torch.nn.functional.channel_shuffle`.
289
+ """
290
+ from torch._meta_registrations import device_hint
291
+
292
+ torch._check(
293
+ input.dim() > 2,
294
+ lambda: f"channel_shuffle expects input with > 2 dims, but got input with sizes {list(input.size())}",
295
+ )
296
+ c = input.shape[1]
297
+ torch._check(
298
+ groups > 0,
299
+ lambda: f"Number of groups to divide channels in must be positive. Value of groups:{groups}",
300
+ )
301
+ torch._check(
302
+ (c % groups) == 0,
303
+ lambda: f"Number of channels must be divisible by groups. Got {c} channels and {groups} groups.",
304
+ )
305
+ n = input.shape[0]
306
+ cg = c // groups
307
+ dhw = input.shape[2:]
308
+
309
+ if input.numel() == 0 or (
310
+ device_hint(input) == "cuda" and (groups == 1 or groups == c)
311
+ ):
312
+ return input.view(input.shape)
313
+
314
+ return (
315
+ input.reshape(n, groups, cg, *dhw)
316
+ .transpose(1, 2)
317
+ .reshape(input.shape)
318
+ .contiguous()
319
+ )
320
+
321
+
322
+ def group_norm(
323
+ input: Tensor,
324
+ num_groups: int,
325
+ weight: Optional[Tensor] = None,
326
+ bias: Optional[Tensor] = None,
327
+ eps: float = 1e-5,
328
+ ) -> Tensor:
329
+ """
330
+ Reference implementation of :func:`torch.nn.functional.group_norm`.
331
+ """
332
+ torch._check(
333
+ input.ndim >= 2,
334
+ lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}",
335
+ )
336
+
337
+ batch_size = input.shape[0]
338
+ num_channels = input.shape[1]
339
+ torch._check(
340
+ num_channels % num_groups == 0,
341
+ lambda: "Expected number of channels in input to be divisible by num_groups, "
342
+ + f"but got input of shape {input.shape} and num_groups = {num_groups}",
343
+ )
344
+
345
+ # input shape is (N, C, *), so we flatten all inner dimensions except (N, C)
346
+ flattened_inner_size = 1
347
+ for dim_length in input.shape[2:]:
348
+ flattened_inner_size *= dim_length
349
+
350
+ return torch.native_group_norm(
351
+ input,
352
+ weight,
353
+ bias,
354
+ batch_size,
355
+ num_channels,
356
+ flattened_inner_size,
357
+ num_groups,
358
+ eps,
359
+ )[0]
360
+
361
+
362
+ def layer_norm(
363
+ input: Tensor,
364
+ normalized_shape: ShapeType,
365
+ weight: Optional[Tensor] = None,
366
+ bias: Optional[Tensor] = None,
367
+ eps: float = 1e-5,
368
+ ) -> Tensor:
369
+ """
370
+ Reference implementation of :func:`torch.nn.functional.layer_norm`.
371
+ """
372
+ return torch.native_layer_norm(input, normalized_shape, weight, bias, eps)[0]
373
+
374
+
375
+ @register_decomposition(aten.leaky_relu)
376
+ @_inplace_wrapper
377
+ @out_wrapper()
378
+ @elementwise_type_promotion_wrapper(
379
+ type_promoting_args=("a",),
380
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
381
+ )
382
+ def leaky_relu(
383
+ a: TensorLikeType, negative_slope: float = 0.01, inplace: bool = False
384
+ ) -> TensorLikeType:
385
+ """
386
+ Reference implementation of torch.nn.functional.leaky_relu
387
+ """
388
+
389
+ if inplace:
390
+ raise NotImplementedError
391
+
392
+ python_type = utils.dtype_to_type(a.dtype)
393
+ if not utils.is_weakly_lesser_type(type(negative_slope), python_type):
394
+ msg = f"negative_slope argument of type {type(negative_slope)} cannot be safely cast to type {python_type}!"
395
+ raise ValueError(msg)
396
+ return torch.where(torch.gt(a, 0), a, torch.mul(a, negative_slope))
397
+
398
+
399
+ @register_decomposition(aten.mish)
400
+ @_inplace_wrapper
401
+ @out_wrapper()
402
+ @elementwise_type_promotion_wrapper(
403
+ type_promoting_args=("a",),
404
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
405
+ )
406
+ def mish(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
407
+ """
408
+ Reference implementation of torch.nn.functional.mish
409
+ """
410
+
411
+ if inplace:
412
+ raise NotImplementedError
413
+ return a * torch.tanh(torch.nn.functional.softplus(a))
414
+
415
+
416
+ @register_decomposition(aten.selu)
417
+ @_inplace_wrapper
418
+ @out_wrapper()
419
+ @elementwise_type_promotion_wrapper(
420
+ type_promoting_args=("a",),
421
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
422
+ )
423
+ def selu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
424
+ """
425
+ Reference implementation of torch.nn.functional.selu
426
+ """
427
+ if inplace:
428
+ raise NotImplementedError
429
+
430
+ alpha = 1.6732632423543772848170429916717
431
+ scale = 1.0507009873554804934193349852946
432
+
433
+ rhs = alpha * torch.expm1(a)
434
+
435
+ return scale * torch.where(a > 0, a, rhs)
436
+
437
+
438
+ # Forwarding alias: the functional variant doesn't support the out kwarg
439
+ # CompositeImplicitAutograd - don't register decomp
440
+ def softmax(
441
+ a: TensorLikeType,
442
+ dim: Optional[int] = None,
443
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
444
+ dtype: Optional[torch.dtype] = None,
445
+ ) -> TensorLikeType:
446
+ # The error is for compat with regular PyTorch, which has this behavior
447
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
448
+ # behavior because it requires explicit opt in. This error is to inform
449
+ # users how to update their calls.
450
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
451
+ return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
452
+
453
+
454
+ # CompositeImplicitAutograd - don't register decomp
455
+ def softmin(
456
+ a: TensorLikeType,
457
+ dim: Optional[int] = None,
458
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
459
+ dtype: Optional[torch.dtype] = None,
460
+ ) -> TensorLikeType:
461
+ # The error is for compat with regular PyTorch, which has this behavior
462
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
463
+ # behavior because it requires explicit opt in. This error is to inform
464
+ # users how to update their calls.
465
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
466
+ return torch.softmax(a=-a, dim=dim, dtype=dtype) # type: ignore[call-overload]
467
+
468
+
469
+ # softplus is implemented specially because it has beta and threshold arguments
470
+ @register_decomposition(aten.softplus)
471
+ @_inplace_wrapper
472
+ @out_wrapper()
473
+ @elementwise_type_promotion_wrapper(
474
+ type_promoting_args=("a",),
475
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
476
+ )
477
+ def softplus(
478
+ a: TensorLikeType,
479
+ beta: Optional[NumberType] = None,
480
+ threshold: NumberType = 20,
481
+ inplace: bool = False,
482
+ ) -> TensorLikeType:
483
+ """
484
+ Reference implementation of torch.nn.functional.softplus
485
+ """
486
+
487
+ if inplace:
488
+ raise NotImplementedError
489
+
490
+ rhs: TensorLikeType
491
+ if beta is not None:
492
+ python_type = utils.dtype_to_type(a.dtype)
493
+ if not utils.is_weakly_lesser_type(type(beta), python_type):
494
+ msg = f"beta argument of type {type(beta)} cannot be safely cast to type {python_type}!"
495
+ raise ValueError(msg)
496
+ scaled_input = a * beta
497
+ rhs = torch.true_divide(torch.log1p(torch.exp(scaled_input)), beta) # type: ignore[arg-type]
498
+
499
+ else:
500
+ scaled_input = a
501
+ rhs = torch.log1p(torch.exp(scaled_input))
502
+
503
+ return torch.where(scaled_input > threshold, a, rhs)
504
+
505
+
506
+ @aten.hardshrink.default.py_impl(DispatchKey.Autograd)
507
+ @register_decomposition(aten.hardshrink)
508
+ @out_wrapper()
509
+ def hardshrink(a: TensorLikeType, lambd: float = 0.5):
510
+ # Formula for reference,
511
+ # hardshrink(x) = x if x > lambd
512
+ # = x if x < -lambd
513
+ # = 0 otherwise
514
+ return torch.where(torch.abs(a) <= lambd, 0, a)
515
+
516
+
517
+ @aten.softshrink.default.py_impl(DispatchKey.Autograd)
518
+ @register_decomposition(aten.softshrink)
519
+ @out_wrapper()
520
+ def softshrink(a: TensorLikeType, lambd: float = 0.5):
521
+ # Formula for reference,
522
+ # softshrink(x) = x - lambd if x > lambd
523
+ # = x + lambd if x < -lambd
524
+ # = 0 otherwise
525
+ torch._check(
526
+ 0 <= lambd <= torch.finfo(a.dtype).max,
527
+ lambda: f"lambda must be in range [0, {torch.finfo(a.dtype).max}] for input dtype {a.dtype}, but found {lambd}",
528
+ )
529
+ # We implement this in one torch.where to generate better code in the backward
530
+ # see https://github.com/pytorch/pytorch/pull/107052#discussion_r1293748211
531
+ # We multiply by 0 for dealing with nans
532
+ return torch.where(torch.abs(a) > lambd, a - torch.sign(a) * lambd, a * 0)
533
+
534
+
535
+ # Losses
536
+ def _reduction_int_to_str(reduction: int) -> str:
537
+ from torch._decomp.decompositions import Reduction
538
+
539
+ if reduction == Reduction.NONE.value:
540
+ return "none"
541
+ elif reduction == Reduction.MEAN.value:
542
+ return "mean"
543
+ elif reduction == Reduction.SUM.value:
544
+ return "sum"
545
+ else:
546
+ raise ValueError(f"{reduction} is not a valid value for reduction")
547
+
548
+
549
+ def _apply_loss_reduction(loss: TensorLikeType, reduction: str) -> TensorLikeType:
550
+ if reduction == "sum":
551
+ return torch.sum(loss)
552
+ elif reduction == "mean":
553
+ return torch.mean(loss)
554
+ else: # reduction == "none"
555
+ return loss
556
+
557
+
558
+ def _check_reduction_value(reduction: str):
559
+ if reduction not in ("mean", "sum", "none"):
560
+ raise ValueError(f"{reduction} is not a valid value for reduction")
561
+
562
+
563
+ # This helper function maps depreciated arguments, "size_average" and "reduce"
564
+ # to their corresponding "reduction" string argument
565
+ def _get_string_reduction_arg(
566
+ *, size_average: Optional[bool], reduce: Optional[bool]
567
+ ) -> str:
568
+ if size_average is None:
569
+ size_average = True
570
+ if reduce is None:
571
+ reduce = True
572
+ if size_average and reduce:
573
+ ret = "mean"
574
+ elif reduce:
575
+ ret = "sum"
576
+ else:
577
+ ret = "none"
578
+ return ret
579
+
580
+
581
+ # CompositeImplicitAutograd - don't register decomp
582
+ @elementwise_type_promotion_wrapper(
583
+ type_promoting_args=("input", "target"),
584
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
585
+ )
586
+ def l1_loss(
587
+ input: TensorLikeType,
588
+ target: TensorLikeType,
589
+ size_average: Optional[bool] = None,
590
+ reduce: Optional[bool] = None,
591
+ reduction: str = "mean",
592
+ ) -> TensorLikeType:
593
+ """
594
+ Reference implementation of torch.nn.functional.l1_loss
595
+ """
596
+ if size_average is not None or reduce is not None:
597
+ # TODO: Raise exception instead of converting value. This is only for
598
+ # primTorch since it can drop support for deprecated arguments.
599
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
600
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
601
+ _check_reduction_value(reduction)
602
+ loss = torch.abs(input - target)
603
+ return _apply_loss_reduction(loss, reduction)
604
+
605
+
606
+ @elementwise_type_promotion_wrapper(
607
+ type_promoting_args=("input", "target"),
608
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
609
+ )
610
+ def smooth_l1_loss(
611
+ input: TensorLikeType,
612
+ target: TensorLikeType,
613
+ size_average: Optional[bool] = None,
614
+ reduce: Optional[bool] = None,
615
+ reduction: str = "mean",
616
+ beta: float = 1.0,
617
+ ) -> TensorLikeType:
618
+ """
619
+ Reference implementation of torch.nn.functional.smooth_l1_loss
620
+ """
621
+ if size_average is not None or reduce is not None:
622
+ # TODO: Raise exception instead of converting value. This is only for
623
+ # primTorch since it can drop support for deprecated arguments.
624
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
625
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
626
+ _check_reduction_value(reduction)
627
+
628
+ if beta == 0.0:
629
+ return torch.nn.functional.l1_loss(
630
+ input, target, size_average=size_average, reduce=reduce, reduction=reduction
631
+ )
632
+ else:
633
+ loss = torch.abs(input - target)
634
+
635
+ loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta)
636
+ return _apply_loss_reduction(loss, reduction)
637
+
638
+
639
+ # Forwarding alias: the functional variant doesn't support the out kwarg
640
+ # CompositeImplicitAutograd - don't register decomp
641
+ def log_softmax(
642
+ a: TensorLikeType,
643
+ dim: Optional[int] = None,
644
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
645
+ dtype: Optional[torch.dtype] = None,
646
+ ) -> TensorLikeType:
647
+ # The error is for compat with regular PyTorch, which has this behavior
648
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
649
+ # behavior because it requires explicit opt in. This error is to inform
650
+ # users how to update their calls.
651
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
652
+ return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
653
+
654
+
655
+ @register_decomposition(aten.margin_ranking_loss)
656
+ def margin_ranking_loss(
657
+ input1: TensorLikeType,
658
+ input2: TensorLikeType,
659
+ target: TensorLikeType,
660
+ margin: float = 0.0,
661
+ reduction: str = "mean",
662
+ ) -> TensorLikeType:
663
+ # loss_without_reduction = max(0, -target * (input1 - input2) + margin)
664
+ if input1.ndim != input2.ndim or input1.ndim != target.ndim:
665
+ raise RuntimeError(
666
+ "margin_ranking_loss : All input tensors should have same dimension but got sizes: "
667
+ f"input1: {input1.shape}, input2: {input2.shape}, target: {target.shape} "
668
+ )
669
+ _check_reduction_value(reduction)
670
+ loss = torch.clamp_min(-target * (input1 - input2) + margin, 0)
671
+ return _apply_loss_reduction(loss, reduction)
672
+
673
+
674
+ @elementwise_type_promotion_wrapper(
675
+ type_promoting_args=("input", "target"),
676
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
677
+ )
678
+ def mse_loss(
679
+ input: TensorLikeType,
680
+ target: TensorLikeType,
681
+ size_average: Optional[bool] = None,
682
+ reduce: Optional[bool] = None,
683
+ reduction: str = "mean",
684
+ ) -> TensorLikeType:
685
+ if size_average is not None or reduce is not None:
686
+ # TODO: Raise exception instead of converting value. This is only for
687
+ # primTorch since it can drop support for deprecated arguments.
688
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
689
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
690
+ _check_reduction_value(reduction)
691
+ loss = torch.pow(input - target, 2)
692
+ return _apply_loss_reduction(loss, reduction)
693
+
694
+
695
+ @register_decomposition(aten.hinge_embedding_loss)
696
+ def hinge_embedding_loss(
697
+ input: TensorLikeType,
698
+ target: TensorLikeType,
699
+ margin: float = 1.0,
700
+ reduction: str = "mean",
701
+ ) -> TensorLikeType:
702
+ # loss_without_reduction = input if y == 1
703
+ # = max(0, margin - input) if y == -1
704
+ _check_reduction_value(reduction)
705
+ margin_clamp = torch.clamp_min(margin - input, 0)
706
+ output_margin = torch.where(target != 1, margin_clamp, 0)
707
+ output_self = torch.where(target != -1, input, 0)
708
+ loss = output_margin + output_self
709
+ return _apply_loss_reduction(loss, reduction)
710
+
711
+
712
+ def _nll_loss_nd(
713
+ input: TensorLikeType,
714
+ target: TensorLikeType,
715
+ weight: Optional[TensorLikeType],
716
+ reduction: str,
717
+ ignore_index: int,
718
+ ) -> TensorLikeType:
719
+ torch._check(
720
+ input.ndim > 0 and input.ndim <= 3,
721
+ lambda: f"Expected input dimension to be either [1, 2, 3] but received {input.ndim}.",
722
+ )
723
+
724
+ torch._check(
725
+ (input.ndim == 1) or (input.shape[0] == target.shape[0]),
726
+ lambda: f"Expected input batch size {input.shape[0]} to match target batch size {target.shape[0]}.",
727
+ )
728
+
729
+ _check_reduction_value(reduction)
730
+
731
+ flat_target = torch.flatten(target)
732
+ ignore_classes_mask = torch.eq(flat_target, ignore_index)
733
+
734
+ # TODO: Enable data-dependent checks with debug mode
735
+ # TODO: This check does not work with FakeTensor inputs; See Issue #85834
736
+ # Explicit cast for class_check to bool; See Issue #78071
737
+ """
738
+ from torch._subclasses.fake_tensor import FakeTensor
739
+ num_classes = input.shape[1] if input.ndim > 1 else input.shape[0]
740
+ valid_classes_mask = torch.logical_and(
741
+ (flat_target >= 0), (flat_target < num_classes)
742
+ )
743
+ class_check = torch.all(torch.logical_or(ignore_classes_mask, valid_classes_mask))
744
+ torch._check(
745
+ isinstance(target, FakeTensor) or bool(class_check.item()),
746
+ lambda: "A target class is out-of-bounds and not the ignore index.",
747
+ )
748
+ """
749
+
750
+ ignore_class_weight = torch.scalar_tensor(0, dtype=input.dtype, device=input.device)
751
+ class_weight = (
752
+ torch.scalar_tensor(1, dtype=input.dtype, device=input.device)
753
+ if weight is None
754
+ else weight[flat_target]
755
+ )
756
+ current_weight = torch.where(
757
+ ignore_classes_mask,
758
+ ignore_class_weight,
759
+ class_weight,
760
+ )
761
+
762
+ if input.ndim == 1:
763
+ # implicit batch size = 1
764
+ # input (1 batch size, C classes)
765
+ loss = -input[target] * current_weight
766
+ elif input.ndim == 2:
767
+ # input (N batch size, C classes)
768
+ batch_size = input.shape[0]
769
+ loss = -input[torch.arange(batch_size), target] * current_weight
770
+ else:
771
+ # 3D case (N batch size, C classes, K dimensions)
772
+ # input (N batch size, C classes, K)
773
+ batch_size = input.shape[0]
774
+ extent = input.shape[2]
775
+ numel = batch_size * extent
776
+ indices = torch.arange(numel)
777
+ bdx = indices // extent
778
+ kdx = indices % extent
779
+ loss = -input[bdx, flat_target, kdx] * current_weight
780
+ loss = torch.reshape(loss, target.shape)
781
+
782
+ if reduction == "none":
783
+ return loss
784
+ elif reduction == "sum":
785
+ return torch.sum(loss)
786
+ else:
787
+ # calculate weighted mean of the loss function
788
+ return torch.sum(loss) / torch.sum(current_weight)
789
+
790
+
791
+ @register_decomposition(aten.nll_loss)
792
+ @out_wrapper()
793
+ @elementwise_type_promotion_wrapper(
794
+ type_promoting_args=("input",),
795
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
796
+ )
797
+ def nll_loss(
798
+ input: TensorLikeType,
799
+ target: TensorLikeType,
800
+ weight: Optional[TensorLikeType] = None,
801
+ size_average: Optional[bool] = None,
802
+ ignore_index: int = -100,
803
+ reduce: Optional[bool] = None,
804
+ reduction: str = "mean",
805
+ ) -> TensorLikeType:
806
+ """
807
+ Reference implementation of torch.nn.functional.nll_loss
808
+ """
809
+ torch._check(
810
+ input.ndim > 0,
811
+ lambda: f"Expected input tensor to have 1 or more dimensions (got {input.ndim})",
812
+ )
813
+
814
+ # TODO: raise exception instead of converting value
815
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
816
+ # Convert these options for consistency with the eager mode
817
+ if size_average is not None or reduce is not None:
818
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
819
+
820
+ # The expected behavior when the target and input have zero elements:
821
+ # reduction = 'none' --- tensor([])
822
+ # reduction = 'sum' --- tensor(0.)
823
+ # reduction = 'mean' --- tensor(nan)
824
+ # Mean reduction on empty tensors produces NaN. See the discussion in
825
+ # https://github.com/pytorch/pytorch/pull/64572#issuecomment-926504162
826
+ if input.numel() == 0 and target.numel() == 0:
827
+ if reduction == "none":
828
+ return torch.zeros_like(target)
829
+ elif reduction == "sum":
830
+ return torch.empty_like(target)
831
+ else:
832
+ return torch.full_like(target, float("nan"))
833
+
834
+ # The _nll_loss_nd helper function handles the most common cases.
835
+ # ndim == 1 (Single Example)
836
+ # => Batch Size: 1, Input: (C), Target: ()
837
+ # ndim == 2 (k = 1)
838
+ # => Batch Size: N, Input: (N, C), Target: (N)
839
+ # ndim == 3 (k > 1)
840
+ # => Batch Size: N, Input: (N, C, K), Target: (N, K)
841
+ if input.ndim <= 3:
842
+ return _nll_loss_nd(input, target, weight, reduction, ignore_index)
843
+
844
+ # For ndim > 3, we reshape the input and target to 3-D case.
845
+ # Input (N batch-size, C classes, k-dimensions)
846
+ # Target (N batch-size, k-dimensions)
847
+ torch._check(
848
+ input.ndim > 0 and target.ndim > 0 and target.shape[1:] == input.shape[2:],
849
+ lambda: (
850
+ "Expected input and target to both have ndim > 0 and "
851
+ "target.shape[1:] == input.shape[2:], but got "
852
+ f"target.shape {target.shape} and input.shape {input.shape}"
853
+ ),
854
+ )
855
+
856
+ batch_size = input.shape[0]
857
+ num_classes = input.shape[1]
858
+ out_size = [batch_size] + list(target.shape[1:])
859
+
860
+ input = torch.reshape(input, [batch_size, num_classes, -1])
861
+ target = torch.reshape(target, [batch_size, -1])
862
+ if reduction != "none":
863
+ return _nll_loss_nd(input, target, weight, reduction, ignore_index)
864
+ else:
865
+ result = _nll_loss_nd(input, target, weight, reduction, ignore_index)
866
+ # reshape flattened inner-dim to original k-dimensions
867
+ return torch.reshape(result, out_size)
868
+
869
+
870
+ # TODO: This ref supports int reduction and out kwarg to be compatible with ATen:
871
+ # https://github.com/pytorch/pytorch/issues/83931
872
+ # TODO: Could be rewritten to support complex:
873
+ # https://github.com/pytorch/pytorch/pull/85041
874
+ @register_decomposition(aten.huber_loss)
875
+ @out_wrapper()
876
+ @elementwise_type_promotion_wrapper(
877
+ type_promoting_args=("input", "target"),
878
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
879
+ )
880
+ def huber_loss(
881
+ input: TensorLikeType,
882
+ target: TensorLikeType,
883
+ reduction: Union[str, int] = "mean",
884
+ delta: float = 1.0,
885
+ ) -> TensorLikeType:
886
+ """
887
+ Reference implementation of torch.nn.functional.huber_loss
888
+ """
889
+ if type(reduction) is int:
890
+ reduction = _reduction_int_to_str(reduction)
891
+ _check_reduction_value(reduction) # type: ignore[arg-type]
892
+ torch._check(
893
+ delta > 0,
894
+ lambda: "huber_loss does not support non-positive values for delta.",
895
+ )
896
+ z = (input - target).abs()
897
+ loss = torch.where(z < delta, 0.5 * z * z, delta * (z - 0.5 * delta))
898
+ return _apply_loss_reduction(loss, reduction) # type: ignore[arg-type]
899
+
900
+
901
+ # tanhshrink does not use _make_elementwise_unary_reference because it does not support out
902
+ @elementwise_unary_scalar_wrapper
903
+ @elementwise_type_promotion_wrapper(
904
+ type_promoting_args=("a",),
905
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
906
+ )
907
+ def tanhshrink(a: TensorLikeType) -> TensorLikeType:
908
+ """
909
+ Reference implementation of torch.nn.functional.tanhshrink
910
+ """
911
+ if not isinstance(a, TensorLike):
912
+ raise RuntimeError(
913
+ "Expected a tensor input for an elementwise unary operation!"
914
+ )
915
+ return a - torch.tanh(a)
916
+
917
+
918
+ @register_decomposition(aten.threshold)
919
+ @_inplace_wrapper
920
+ @out_wrapper()
921
+ @elementwise_type_promotion_wrapper(
922
+ type_promoting_args=("a",),
923
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
924
+ )
925
+ def threshold(
926
+ a: TensorLikeType,
927
+ threshold: NumberType,
928
+ value: Union[bool, int, float],
929
+ inplace: bool = False,
930
+ ) -> TensorLikeType:
931
+ """
932
+ Reference implementation of torch.nn.functional.threshold
933
+ """
934
+
935
+ if inplace:
936
+ raise NotImplementedError
937
+
938
+ return torch.where(a <= threshold, value, a)
939
+
940
+
941
+ # CompositeImplicitAutograd - don't register decomp
942
+ # No elementwise type promotion - core op doesn't explicitly type promote
943
+ def triplet_margin_loss(
944
+ anchor: TensorLikeType,
945
+ positive: TensorLikeType,
946
+ negative: TensorLikeType,
947
+ margin: float = 1.0,
948
+ p: float = 2,
949
+ eps: float = 1e-6,
950
+ swap: bool = False,
951
+ size_average: Optional[bool] = None,
952
+ reduce: Optional[bool] = None,
953
+ reduction: str = "mean",
954
+ ) -> TensorLikeType:
955
+ if size_average is not None or reduce is not None:
956
+ # TODO: Raise exception instead of converting value. This is only for
957
+ # primTorch since it can drop support for deprecated arguments.
958
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
959
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
960
+
961
+ if margin <= 0:
962
+ raise ValueError(f"margin must be greater than 0, got {margin}")
963
+
964
+ # torch.nn.functional.triplet_margin_with_distance_loss has no ref defined
965
+ # since it's a pure Python implementation. Use this helper instead.
966
+ return _triplet_margin_with_distance_loss(
967
+ anchor=anchor,
968
+ positive=positive,
969
+ negative=negative,
970
+ distance_function=lambda x, y: torch.pairwise_distance(x, y, p, eps),
971
+ margin=margin,
972
+ swap=swap,
973
+ reduction=reduction,
974
+ )
975
+
976
+
977
+ # Pure Python impl - don't register decomp and don't add a ref. Defined as a
978
+ # helper here since triplet_margin_loss can be nicely implemented with it.
979
+ def _triplet_margin_with_distance_loss(
980
+ anchor: TensorLikeType,
981
+ positive: TensorLikeType,
982
+ negative: TensorLikeType,
983
+ *,
984
+ distance_function: Optional[
985
+ Callable[[TensorLikeType, TensorLikeType], TensorLikeType]
986
+ ] = None,
987
+ margin: float = 1.0,
988
+ swap: bool = False,
989
+ reduction: str = "mean",
990
+ ) -> TensorLikeType:
991
+ _check_reduction_value(reduction)
992
+
993
+ a_dim = anchor.ndim
994
+ p_dim = positive.ndim
995
+ n_dim = negative.ndim
996
+ torch._check(
997
+ a_dim == p_dim and p_dim == n_dim,
998
+ lambda: (
999
+ f"The anchor, positive, and negative tensors are expected to have "
1000
+ f"the same number of dimensions, but got: anchor {a_dim}D, "
1001
+ f"positive {p_dim}D, and negative {n_dim}D inputs"
1002
+ ),
1003
+ )
1004
+
1005
+ if distance_function is None:
1006
+ distance_function = torch.pairwise_distance
1007
+
1008
+ dist_pos = distance_function(anchor, positive)
1009
+ dist_neg = distance_function(anchor, negative)
1010
+ # The distance swap is described in the paper "Learning shallow
1011
+ # convolutional feature descriptors with triplet losses" by V. Balntas, E.
1012
+ # Riba et al. If True, and if the positive example is closer to the
1013
+ # negative example than the anchor is, swaps the positive example and the
1014
+ # anchor in the loss computation.
1015
+ if swap:
1016
+ dist_swap = distance_function(positive, negative)
1017
+ dist_neg = torch.minimum(dist_neg, dist_swap)
1018
+ loss = torch.clamp_min(margin + dist_pos - dist_neg, 0)
1019
+ return _apply_loss_reduction(loss, reduction)
1020
+
1021
+
1022
+ @register_decomposition(aten.hardtanh)
1023
+ @_inplace_wrapper
1024
+ @out_wrapper()
1025
+ @elementwise_unary_scalar_wrapper
1026
+ @elementwise_type_promotion_wrapper(
1027
+ type_promoting_args=("a"),
1028
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1029
+ )
1030
+ def hardtanh(
1031
+ a: TensorLikeType,
1032
+ min_val: NumberType = -1,
1033
+ max_val: NumberType = 1,
1034
+ inplace: bool = False,
1035
+ ) -> TensorLikeType:
1036
+ """
1037
+ Reference implementation of torch.nn.functional.hardtanh
1038
+ """
1039
+ if inplace:
1040
+ raise NotImplementedError
1041
+ if utils.is_boolean_dtype(a.dtype):
1042
+ raise RuntimeError("Bool inputs not supported for hardtanh")
1043
+
1044
+ # preserve legacy behavior of boundaries not causing type promotion
1045
+ if utils.is_integer_dtype(a.dtype):
1046
+ min_val = int(min_val) # type: ignore[arg-type]
1047
+ max_val = int(max_val) # type: ignore[arg-type]
1048
+ if not (a.dtype != torch.uint8 or (min_val >= 0 and max_val >= 0)):
1049
+ raise RuntimeError(
1050
+ "Cannot do hardtanh on an unsigned type with negative limits"
1051
+ )
1052
+
1053
+ if min_val > max_val: # type: ignore[operator]
1054
+ raise ValueError("min_val cannot be greater than max_val")
1055
+
1056
+ return torch.clamp(a, min_val, max_val) # type: ignore[arg-type]
1057
+
1058
+
1059
+ @register_decomposition(aten.gelu)
1060
+ @out_wrapper()
1061
+ @elementwise_unary_scalar_wrapper
1062
+ @elementwise_type_promotion_wrapper(
1063
+ type_promoting_args=("a",),
1064
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1065
+ )
1066
+ def gelu(a: TensorLikeType, approximate: str = "none") -> TensorLikeType:
1067
+ """
1068
+ Reference implementation of torch.nn.functional.gelu
1069
+ """
1070
+ if not isinstance(a, TensorLike):
1071
+ raise RuntimeError(
1072
+ "Expected a tensor input for an elementwise unary operation!"
1073
+ )
1074
+ M_SQRT2 = 1.41421356237309504880
1075
+ M_SQRT1_2 = 0.70710678118654752440
1076
+ M_2_SQRTPI = 1.12837916709551257390
1077
+ if approximate == "tanh":
1078
+ kBeta = M_SQRT2 * M_2_SQRTPI * 0.5
1079
+ kKappa = 0.044715
1080
+ a_cube = a * a * a
1081
+ inner = kBeta * (a + kKappa * a_cube)
1082
+ return 0.5 * a * (1 + torch.tanh(inner))
1083
+ elif approximate == "none":
1084
+ kAlpha = M_SQRT1_2
1085
+ return a * 0.5 * (1 + torch.erf(a * kAlpha))
1086
+ else:
1087
+ raise RuntimeError("approximate argument must be either none or tanh.")
1088
+
1089
+
1090
+ # CompositeImplicitAutograd - don't register decomp
1091
+ @elementwise_type_promotion_wrapper(
1092
+ type_promoting_args=("input", "target"),
1093
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
1094
+ )
1095
+ def poisson_nll_loss(
1096
+ input: TensorLikeType,
1097
+ target: TensorLikeType,
1098
+ log_input: bool = True,
1099
+ full: bool = False,
1100
+ size_average: Optional[bool] = None,
1101
+ eps: float = 1e-8,
1102
+ reduce: Optional[bool] = None,
1103
+ reduction: str = "mean",
1104
+ ) -> TensorLikeType:
1105
+ """
1106
+ Reference implementation of torch.nn.functional.poisson_nll_loss
1107
+ """
1108
+ if size_average is not None or reduce is not None:
1109
+ # TODO: Raise exception instead of converting value. This is only for
1110
+ # primTorch since it can drop support for deprecated arguments.
1111
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
1112
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
1113
+ _check_reduction_value(reduction)
1114
+ if log_input:
1115
+ loss = torch.exp(input) - target * input
1116
+ else:
1117
+ loss = input - target * torch.log(input + eps)
1118
+
1119
+ if full:
1120
+ stirling_term = (
1121
+ target * torch.log(target) - target + 0.5 * torch.log(2 * torch.pi * target)
1122
+ )
1123
+ # avoid inplace add
1124
+ loss = loss + stirling_term.masked_fill(target <= 1, 0)
1125
+ return _apply_loss_reduction(loss, reduction)
1126
+
1127
+
1128
+ @register_decomposition(aten.prelu)
1129
+ @elementwise_type_promotion_wrapper(
1130
+ type_promoting_args=("a", "weight"),
1131
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1132
+ )
1133
+ def prelu(a: TensorLikeType, weight: TensorLikeType) -> TensorLikeType:
1134
+ """
1135
+ Reference implementation of torch.nn.functional.prelu
1136
+ """
1137
+ torch._check(
1138
+ isinstance(a, TensorLike),
1139
+ lambda: f"prelu: Expected `a` to be tensor, but got: {type(a)}",
1140
+ )
1141
+ torch._check(
1142
+ isinstance(weight, TensorLike),
1143
+ lambda: f"prelu: Expected `weight` to be tensor, but got: {type(weight)}",
1144
+ )
1145
+
1146
+ if weight.numel() != 1:
1147
+ torch._check(a.ndim > 0, lambda: "Not allow zero-dim input tensor.")
1148
+ channel_size = a.shape[1] if a.ndim >= 2 else 1
1149
+ torch._check(
1150
+ weight.numel() == channel_size,
1151
+ lambda: f"Mismatch of parameter numbers and input channel size. Found parameter numbers ="
1152
+ f" {weight.numel()} and channel size = {channel_size}.",
1153
+ )
1154
+
1155
+ torch._check(
1156
+ weight.ndim == 0 or weight.ndim == 1,
1157
+ lambda: f"prelu: Expected `weight` to be a scalar or 1D tensor, but got: "
1158
+ f"ndim = {weight.ndim}",
1159
+ )
1160
+ if a.ndim == 0:
1161
+ weight = weight[0] if weight.ndim == 1 else weight
1162
+ else:
1163
+ weight = prims.broadcast_in_dim(
1164
+ weight, a.shape, () if weight.ndim == 0 else (0 if a.ndim == 1 else 1,)
1165
+ )
1166
+
1167
+ return torch.where(a > 0, a, a * weight)
1168
+
1169
+
1170
+ @register_decomposition(aten.relu6)
1171
+ @_inplace_wrapper
1172
+ @out_wrapper()
1173
+ def relu6(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
1174
+ """
1175
+ Reference implementation of torch.nn.functional.relu6
1176
+ """
1177
+ if inplace:
1178
+ raise NotImplementedError
1179
+
1180
+ # See https://github.com/pytorch/pytorch/pull/81142#discussion_r918220126
1181
+ # It may be better to use clamp here, but we use hardtanh to replicate
1182
+ # the behavior of the existing implementation
1183
+ return torch.nn.functional.hardtanh(a, 0, 6)
1184
+
1185
+
1186
+ @register_decomposition(aten.glu)
1187
+ @out_wrapper()
1188
+ @elementwise_type_promotion_wrapper(
1189
+ type_promoting_args=("a",),
1190
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1191
+ )
1192
+ def glu(a: TensorLikeType, dim: int = -1) -> TensorLikeType:
1193
+ dim = utils.canonicalize_dims(a.ndim, dim)
1194
+ torch._check(
1195
+ a.shape[dim] % 2 == 0,
1196
+ lambda: f"Halving dimension must be even, but dimension {dim} is size {a.shape[dim]}",
1197
+ )
1198
+ b, c = torch.tensor_split(a, 2, dim)
1199
+
1200
+ return b * torch.sigmoid(c)
1201
+
1202
+
1203
+ @register_decomposition(aten.pairwise_distance)
1204
+ @out_wrapper()
1205
+ def pairwise_distance(
1206
+ x1: TensorLikeType,
1207
+ x2: TensorLikeType,
1208
+ p: NumberType = 2.0,
1209
+ eps: NumberType = 1e-6,
1210
+ keepdim=False,
1211
+ ) -> TensorLikeType:
1212
+ return torch.linalg.vector_norm(x1 - x2 + eps, ord=p, dim=-1, keepdim=keepdim)
1213
+
1214
+
1215
+ @register_decomposition(aten.pdist)
1216
+ @out_wrapper()
1217
+ @elementwise_type_promotion_wrapper(
1218
+ type_promoting_args=("a",),
1219
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1220
+ )
1221
+ def pdist(a: TensorLikeType, p: float = 2) -> TensorLikeType:
1222
+ torch._check(a.ndim == 2, lambda: f"pdist only supports 2D tensors, got: {a.ndim}D")
1223
+ torch._check(p >= 0, lambda: "pdist only supports non-negative p values")
1224
+ # For p == 2 we can use an efficient implementation, but other values of p
1225
+ # require creating a much bigger tensor for an intermediate step
1226
+ if p == 2:
1227
+ aTa = torch.mm(a, a.T)
1228
+ aTa_diag = torch.diag(aTa)
1229
+ t = torch.sqrt(torch.clamp(aTa_diag + aTa_diag.unsqueeze(-1) - 2 * aTa, min=0))
1230
+ else:
1231
+ t = torch.linalg.vector_norm(a.unsqueeze(1) - a, ord=p, dim=2)
1232
+ i = torch.triu_indices(t.shape[0], t.shape[1], offset=1, device=a.device)
1233
+ return t.flatten().index_select(0, i[0] * t.shape[0] + i[1])
1234
+
1235
+
1236
+ @register_decomposition(aten.pixel_shuffle)
1237
+ @out_wrapper()
1238
+ def pixel_shuffle(self: Tensor, upscale_factor: int):
1239
+ torch._check(
1240
+ self.dim() >= 3,
1241
+ lambda: f"pixel_shuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
1242
+ )
1243
+ batch = self.shape[:-3]
1244
+ C_out = self.shape[-3] // upscale_factor**2
1245
+ HW_out = (self.shape[-2] * upscale_factor, self.shape[-1] * upscale_factor)
1246
+ n = len(batch)
1247
+ B_dims = range(n)
1248
+ C_dim, r1_dim, r2_dim, H_dim, W_dim = range(n, n + 5)
1249
+ return (
1250
+ self.view(
1251
+ *batch,
1252
+ C_out,
1253
+ upscale_factor,
1254
+ upscale_factor,
1255
+ self.shape[-2],
1256
+ self.shape[-1],
1257
+ )
1258
+ .permute(*B_dims, C_dim, H_dim, r1_dim, W_dim, r2_dim)
1259
+ .reshape(*batch, C_out, *HW_out)
1260
+ .clone(memory_format=utils.suggest_memory_format(self))
1261
+ )
1262
+
1263
+
1264
+ @register_decomposition(aten.pixel_unshuffle)
1265
+ @out_wrapper()
1266
+ def pixel_unshuffle(self: Tensor, downscale_factor: int):
1267
+ torch._check(
1268
+ self.dim() >= 3,
1269
+ lambda: f"pixel_unshuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
1270
+ )
1271
+ batch = self.shape[:-3]
1272
+ C_out = self.shape[-3] * downscale_factor**2
1273
+ HW_out = (self.shape[-2] // downscale_factor, self.shape[-1] // downscale_factor)
1274
+ n = len(batch)
1275
+ B_dims = range(n)
1276
+ C_dim, H_dim, r1_dim, W_dim, r2_dim = range(n, n + 5)
1277
+ return (
1278
+ self.view(
1279
+ *batch,
1280
+ self.shape[-3],
1281
+ HW_out[0],
1282
+ downscale_factor,
1283
+ HW_out[1],
1284
+ downscale_factor,
1285
+ )
1286
+ .permute(*B_dims, C_dim, r1_dim, r2_dim, H_dim, W_dim)
1287
+ .reshape(*batch, C_out, *HW_out)
1288
+ .clone(memory_format=utils.suggest_memory_format(self))
1289
+ )
1290
+
1291
+
1292
+ # Needed as aten.{celu_,elu_...} exist (even if they don't have the in-place kwarg)
1293
+ celu_ = _make_inplace(celu)
1294
+ elu_ = _make_inplace(elu)
1295
+ mish_ = _make_inplace(mish)
1296
+ selu_ = _make_inplace(selu)
1297
+ threshold_ = _make_inplace(threshold)
.venv/lib/python3.10/site-packages/torch/_refs/special/__init__.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from torch import Tensor
10
+ from torch._decomp import register_decomposition
11
+ from torch._prims_common import (
12
+ ELEMENTWISE_TYPE_PROMOTION_KIND,
13
+ Number,
14
+ NumberType,
15
+ TensorLike,
16
+ TensorLikeType,
17
+ )
18
+ from torch._prims_common.wrappers import elementwise_type_promotion_wrapper, out_wrapper
19
+ from torch._refs import (
20
+ _make_alias,
21
+ _make_elementwise_binary_reference,
22
+ _make_elementwise_unary_reference,
23
+ )
24
+
25
+
26
+ __all__ = [
27
+ "bessel_j0",
28
+ "bessel_j1",
29
+ "entr",
30
+ "erfcx",
31
+ "expit",
32
+ "i0e",
33
+ "i1",
34
+ "i1e",
35
+ "log_ndtr",
36
+ "logit",
37
+ "log_softmax",
38
+ "multigammaln",
39
+ "ndtr",
40
+ "ndtri",
41
+ "softmax",
42
+ "spherical_bessel_j0",
43
+ "xlog1py",
44
+ "zeta",
45
+ ]
46
+ aten = torch._ops.ops.aten
47
+
48
+
49
+ @_make_elementwise_unary_reference(
50
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
51
+ )
52
+ def bessel_j0(a: TensorLikeType) -> TensorLikeType:
53
+ return prims.bessel_j0(a)
54
+
55
+
56
+ @_make_elementwise_unary_reference(
57
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
58
+ )
59
+ def bessel_j1(a: TensorLikeType) -> TensorLikeType:
60
+ return prims.bessel_j1(a)
61
+
62
+
63
+ @register_decomposition(aten.special_entr)
64
+ @out_wrapper()
65
+ @elementwise_type_promotion_wrapper(
66
+ type_promoting_args=("a",),
67
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
68
+ )
69
+ def entr(a: TensorLikeType) -> TensorLikeType:
70
+ return torch.where(
71
+ torch.isnan(a),
72
+ a,
73
+ torch.where(a > 0, -a * torch.log(a), torch.where(a == 0, 0, -torch.inf)),
74
+ )
75
+
76
+
77
+ @register_decomposition(aten.special_erfcx)
78
+ @out_wrapper()
79
+ @elementwise_type_promotion_wrapper(
80
+ type_promoting_args=("a",),
81
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
82
+ )
83
+ def erfcx(a: TensorLikeType) -> TensorLikeType:
84
+ return prims.erfcx(a)
85
+
86
+
87
+ # alias for sigmoid
88
+ expit = _make_alias(torch.sigmoid, "expit")
89
+
90
+
91
+ @_make_elementwise_unary_reference(
92
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
93
+ )
94
+ def i0e(a: TensorLikeType) -> TensorLikeType:
95
+ return prims.bessel_i0e(a)
96
+
97
+
98
+ @_make_elementwise_unary_reference(
99
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
100
+ )
101
+ def i1(a: TensorLikeType) -> TensorLikeType:
102
+ return prims.bessel_i1(a)
103
+
104
+
105
+ @_make_elementwise_unary_reference(
106
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
107
+ )
108
+ def i1e(a: TensorLikeType) -> TensorLikeType:
109
+ return prims.bessel_i1e(a)
110
+
111
+
112
+ @register_decomposition(aten.special_log_ndtr)
113
+ @out_wrapper()
114
+ @elementwise_type_promotion_wrapper(
115
+ type_promoting_args=("a",),
116
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
117
+ )
118
+ def log_ndtr(a: TensorLikeType) -> TensorLikeType:
119
+ # Note: M_SQRT1_2 is the value of 1 / sqrt(2)
120
+ M_SQRT1_2 = 0.707106781186547524400844362104849039
121
+ t = a * M_SQRT1_2
122
+ return torch.where(
123
+ a < 1.0,
124
+ torch.log(torch.special.erfcx(-t) / 2) - t * t,
125
+ torch.log1p(-torch.erfc(t) / 2),
126
+ )
127
+
128
+
129
+ @register_decomposition(aten.logit)
130
+ @out_wrapper()
131
+ @elementwise_type_promotion_wrapper(
132
+ type_promoting_args=("self",),
133
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
134
+ )
135
+ def logit(self: TensorLikeType, eps: Optional[float] = None) -> TensorLikeType:
136
+ if eps is None:
137
+ eps = -1.0
138
+ lo = eps
139
+ hi = 1 - eps
140
+ self = torch.where(self < lo, lo, torch.where(self > hi, hi, self))
141
+ return torch.log(torch.true_divide(self, torch.sub(1, self)))
142
+
143
+
144
+ @register_decomposition(aten.special_xlog1py)
145
+ @out_wrapper()
146
+ @elementwise_type_promotion_wrapper(
147
+ type_promoting_args=("a", "b"),
148
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
149
+ )
150
+ def xlog1py(a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]):
151
+ torch._check(
152
+ isinstance(a, TensorLike) or isinstance(b, TensorLike),
153
+ lambda: 'Expected either argument a or b to be a Tensor"',
154
+ )
155
+
156
+ # Operations like eq and log do not handle scalar values, so we convert them to scalar_tensors.
157
+ if isinstance(a, TensorLike) and isinstance(b, Number):
158
+ # pyrefly: ignore [bad-argument-type]
159
+ b = refs.scalar_tensor(b, dtype=a.dtype, device=a.device)
160
+ elif isinstance(b, TensorLike) and isinstance(a, Number):
161
+ # pyrefly: ignore [bad-argument-type]
162
+ a = refs.scalar_tensor(a, dtype=b.dtype, device=b.device)
163
+
164
+ # mypy: expected "Tensor"
165
+ if not isinstance(a, TensorLike):
166
+ raise AssertionError(f"a must be TensorLike, got {type(a)}")
167
+ if not isinstance(b, TensorLike):
168
+ raise AssertionError(f"b must be TensorLike, got {type(b)}")
169
+ rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log1p(b)))
170
+ return torch.where(torch.isnan(b), float("nan"), rhs)
171
+
172
+
173
+ @register_decomposition(aten.mvlgamma)
174
+ @out_wrapper()
175
+ @elementwise_type_promotion_wrapper(
176
+ type_promoting_args=("a",),
177
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
178
+ )
179
+ def multigammaln(a: TensorLikeType, p: int) -> TensorLikeType:
180
+ c = 0.25 * p * (p - 1) * math.log(math.pi)
181
+ b = 0.5 * torch.arange(start=(1 - p), end=1, step=1, dtype=a.dtype, device=a.device)
182
+ return torch.sum(torch.lgamma(a.unsqueeze(-1) + b), dim=-1) + c
183
+
184
+
185
+ @register_decomposition(aten.special_ndtr)
186
+ @out_wrapper()
187
+ @elementwise_type_promotion_wrapper(
188
+ type_promoting_args=("a",),
189
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
190
+ )
191
+ def ndtr(a: TensorLikeType) -> TensorLikeType:
192
+ # Note: M_SQRT1_2 is the value of 1 / sqrt(2)
193
+ M_SQRT1_2 = 0.707106781186547524400844362104849039
194
+ a_sqrt_2 = a * M_SQRT1_2
195
+ return (1 + torch.erf(a_sqrt_2)) * 0.5
196
+
197
+
198
+ @register_decomposition(aten.special_ndtri)
199
+ @out_wrapper()
200
+ @elementwise_type_promotion_wrapper(
201
+ type_promoting_args=("a",),
202
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
203
+ )
204
+ def ndtri(a: TensorLikeType) -> TensorLikeType:
205
+ return prims.ndtri(a)
206
+
207
+
208
+ # Forwarding alias: the special variant doesn't support the out kwarg
209
+ # CompositeImplicitAutograd - don't register decomp
210
+ def log_softmax(
211
+ a: TensorLikeType,
212
+ dim: int,
213
+ dtype: Optional[torch.dtype] = None,
214
+ ) -> TensorLikeType:
215
+ return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
216
+
217
+
218
+ # Forwarding alias: the special variant doesn't support the out kwarg
219
+ # CompositeImplicitAutograd - don't register decomp
220
+ def softmax(
221
+ a: TensorLikeType,
222
+ dim: int,
223
+ dtype: Optional[torch.dtype] = None,
224
+ ) -> TensorLikeType:
225
+ return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
226
+
227
+
228
+ @_make_elementwise_unary_reference(
229
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
230
+ )
231
+ def spherical_bessel_j0(a: TensorLikeType) -> TensorLikeType:
232
+ return prims.spherical_bessel_j0(a)
233
+
234
+
235
+ # TODO: add docstring
236
+ @_make_elementwise_binary_reference(
237
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
238
+ )
239
+ def zeta(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
240
+ return prims.zeta(a, b)
.venv/lib/python3.10/site-packages/torch/_vendor/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_vendor/packaging/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __title__ = "packaging"
6
+ __summary__ = "Core utilities for Python packages"
7
+ __uri__ = "https://github.com/pypa/packaging"
8
+
9
+ __version__ = "23.2"
10
+
11
+ __author__ = "Donald Stufft and individual contributors"
12
+ __email__ = "donald@stufft.io"
13
+
14
+ __license__ = "BSD-2-Clause or Apache-2.0"
15
+ __copyright__ = "2014 %s" % __author__
.venv/lib/python3.10/site-packages/torch/_vendor/packaging/_structures.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+
6
+ class InfinityType:
7
+ def __repr__(self) -> str:
8
+ return "Infinity"
9
+
10
+ def __hash__(self) -> int:
11
+ return hash(repr(self))
12
+
13
+ def __lt__(self, other: object) -> bool:
14
+ return False
15
+
16
+ def __le__(self, other: object) -> bool:
17
+ return False
18
+
19
+ def __eq__(self, other: object) -> bool:
20
+ return isinstance(other, self.__class__)
21
+
22
+ def __gt__(self, other: object) -> bool:
23
+ return True
24
+
25
+ def __ge__(self, other: object) -> bool:
26
+ return True
27
+
28
+ def __neg__(self: object) -> "NegativeInfinityType":
29
+ return NegativeInfinity
30
+
31
+
32
+ Infinity = InfinityType()
33
+
34
+
35
+ class NegativeInfinityType:
36
+ def __repr__(self) -> str:
37
+ return "-Infinity"
38
+
39
+ def __hash__(self) -> int:
40
+ return hash(repr(self))
41
+
42
+ def __lt__(self, other: object) -> bool:
43
+ return True
44
+
45
+ def __le__(self, other: object) -> bool:
46
+ return True
47
+
48
+ def __eq__(self, other: object) -> bool:
49
+ return isinstance(other, self.__class__)
50
+
51
+ def __gt__(self, other: object) -> bool:
52
+ return False
53
+
54
+ def __ge__(self, other: object) -> bool:
55
+ return False
56
+
57
+ def __neg__(self: object) -> InfinityType:
58
+ return Infinity
59
+
60
+
61
+ NegativeInfinity = NegativeInfinityType()
.venv/lib/python3.10/site-packages/torch/_vendor/packaging/version.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+ """
5
+ .. testsetup::
6
+
7
+ from packaging.version import parse, Version
8
+ """
9
+
10
+ import itertools
11
+ import re
12
+ from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union
13
+
14
+ from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
15
+
16
+ __all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
17
+
18
+ LocalType = Tuple[Union[int, str], ...]
19
+
20
+ CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]
21
+ CmpLocalType = Union[
22
+ NegativeInfinityType,
23
+ Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],
24
+ ]
25
+ CmpKey = Tuple[
26
+ int,
27
+ Tuple[int, ...],
28
+ CmpPrePostDevType,
29
+ CmpPrePostDevType,
30
+ CmpPrePostDevType,
31
+ CmpLocalType,
32
+ ]
33
+ VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
34
+
35
+
36
+ class _Version(NamedTuple):
37
+ epoch: int
38
+ release: Tuple[int, ...]
39
+ dev: Optional[Tuple[str, int]]
40
+ pre: Optional[Tuple[str, int]]
41
+ post: Optional[Tuple[str, int]]
42
+ local: Optional[LocalType]
43
+
44
+
45
+ def parse(version: str) -> "Version":
46
+ """Parse the given version string.
47
+
48
+ >>> parse('1.0.dev1')
49
+ <Version('1.0.dev1')>
50
+
51
+ :param version: The version string to parse.
52
+ :raises InvalidVersion: When the version string is not a valid version.
53
+ """
54
+ return Version(version)
55
+
56
+
57
+ class InvalidVersion(ValueError):
58
+ """Raised when a version string is not a valid version.
59
+
60
+ >>> Version("invalid")
61
+ Traceback (most recent call last):
62
+ ...
63
+ packaging.version.InvalidVersion: Invalid version: 'invalid'
64
+ """
65
+
66
+
67
+ class _BaseVersion:
68
+ _key: Tuple[Any, ...]
69
+
70
+ def __hash__(self) -> int:
71
+ return hash(self._key)
72
+
73
+ # Please keep the duplicated `isinstance` check
74
+ # in the six comparisons hereunder
75
+ # unless you find a way to avoid adding overhead function calls.
76
+ def __lt__(self, other: "_BaseVersion") -> bool:
77
+ if not isinstance(other, _BaseVersion):
78
+ return NotImplemented
79
+
80
+ return self._key < other._key
81
+
82
+ def __le__(self, other: "_BaseVersion") -> bool:
83
+ if not isinstance(other, _BaseVersion):
84
+ return NotImplemented
85
+
86
+ return self._key <= other._key
87
+
88
+ def __eq__(self, other: object) -> bool:
89
+ if not isinstance(other, _BaseVersion):
90
+ return NotImplemented
91
+
92
+ return self._key == other._key
93
+
94
+ def __ge__(self, other: "_BaseVersion") -> bool:
95
+ if not isinstance(other, _BaseVersion):
96
+ return NotImplemented
97
+
98
+ return self._key >= other._key
99
+
100
+ def __gt__(self, other: "_BaseVersion") -> bool:
101
+ if not isinstance(other, _BaseVersion):
102
+ return NotImplemented
103
+
104
+ return self._key > other._key
105
+
106
+ def __ne__(self, other: object) -> bool:
107
+ if not isinstance(other, _BaseVersion):
108
+ return NotImplemented
109
+
110
+ return self._key != other._key
111
+
112
+
113
+ # Deliberately not anchored to the start and end of the string, to make it
114
+ # easier for 3rd party code to reuse
115
+ _VERSION_PATTERN = r"""
116
+ v?
117
+ (?:
118
+ (?:(?P<epoch>[0-9]+)!)? # epoch
119
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
120
+ (?P<pre> # pre-release
121
+ [-_\.]?
122
+ (?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)
123
+ [-_\.]?
124
+ (?P<pre_n>[0-9]+)?
125
+ )?
126
+ (?P<post> # post release
127
+ (?:-(?P<post_n1>[0-9]+))
128
+ |
129
+ (?:
130
+ [-_\.]?
131
+ (?P<post_l>post|rev|r)
132
+ [-_\.]?
133
+ (?P<post_n2>[0-9]+)?
134
+ )
135
+ )?
136
+ (?P<dev> # dev release
137
+ [-_\.]?
138
+ (?P<dev_l>dev)
139
+ [-_\.]?
140
+ (?P<dev_n>[0-9]+)?
141
+ )?
142
+ )
143
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
144
+ """
145
+
146
+ VERSION_PATTERN = _VERSION_PATTERN
147
+ """
148
+ A string containing the regular expression used to match a valid version.
149
+
150
+ The pattern is not anchored at either end, and is intended for embedding in larger
151
+ expressions (for example, matching a version number as part of a file name). The
152
+ regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
153
+ flags set.
154
+
155
+ :meta hide-value:
156
+ """
157
+
158
+
159
+ class Version(_BaseVersion):
160
+ """This class abstracts handling of a project's versions.
161
+
162
+ A :class:`Version` instance is comparison aware and can be compared and
163
+ sorted using the standard Python interfaces.
164
+
165
+ >>> v1 = Version("1.0a5")
166
+ >>> v2 = Version("1.0")
167
+ >>> v1
168
+ <Version('1.0a5')>
169
+ >>> v2
170
+ <Version('1.0')>
171
+ >>> v1 < v2
172
+ True
173
+ >>> v1 == v2
174
+ False
175
+ >>> v1 > v2
176
+ False
177
+ >>> v1 >= v2
178
+ False
179
+ >>> v1 <= v2
180
+ True
181
+ """
182
+
183
+ _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
184
+ _key: CmpKey
185
+
186
+ def __init__(self, version: str) -> None:
187
+ """Initialize a Version object.
188
+
189
+ :param version:
190
+ The string representation of a version which will be parsed and normalized
191
+ before use.
192
+ :raises InvalidVersion:
193
+ If the ``version`` does not conform to PEP 440 in any way then this
194
+ exception will be raised.
195
+ """
196
+
197
+ # Validate the version and parse it into pieces
198
+ match = self._regex.search(version)
199
+ if not match:
200
+ raise InvalidVersion(f"Invalid version: '{version}'")
201
+
202
+ # Store the parsed out pieces of the version
203
+ self._version = _Version(
204
+ epoch=int(match.group("epoch")) if match.group("epoch") else 0,
205
+ release=tuple(int(i) for i in match.group("release").split(".")),
206
+ pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
207
+ post=_parse_letter_version(
208
+ match.group("post_l"), match.group("post_n1") or match.group("post_n2")
209
+ ),
210
+ dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
211
+ local=_parse_local_version(match.group("local")),
212
+ )
213
+
214
+ # Generate a key which will be used for sorting
215
+ self._key = _cmpkey(
216
+ self._version.epoch,
217
+ self._version.release,
218
+ self._version.pre,
219
+ self._version.post,
220
+ self._version.dev,
221
+ self._version.local,
222
+ )
223
+
224
+ def __repr__(self) -> str:
225
+ """A representation of the Version that shows all internal state.
226
+
227
+ >>> Version('1.0.0')
228
+ <Version('1.0.0')>
229
+ """
230
+ return f"<Version('{self}')>"
231
+
232
+ def __str__(self) -> str:
233
+ """A string representation of the version that can be rounded-tripped.
234
+
235
+ >>> str(Version("1.0a5"))
236
+ '1.0a5'
237
+ """
238
+ parts = []
239
+
240
+ # Epoch
241
+ if self.epoch != 0:
242
+ parts.append(f"{self.epoch}!")
243
+
244
+ # Release segment
245
+ parts.append(".".join(str(x) for x in self.release))
246
+
247
+ # Pre-release
248
+ if self.pre is not None:
249
+ parts.append("".join(str(x) for x in self.pre))
250
+
251
+ # Post-release
252
+ if self.post is not None:
253
+ parts.append(f".post{self.post}")
254
+
255
+ # Development release
256
+ if self.dev is not None:
257
+ parts.append(f".dev{self.dev}")
258
+
259
+ # Local version segment
260
+ if self.local is not None:
261
+ parts.append(f"+{self.local}")
262
+
263
+ return "".join(parts)
264
+
265
+ @property
266
+ def epoch(self) -> int:
267
+ """The epoch of the version.
268
+
269
+ >>> Version("2.0.0").epoch
270
+ 0
271
+ >>> Version("1!2.0.0").epoch
272
+ 1
273
+ """
274
+ return self._version.epoch
275
+
276
+ @property
277
+ def release(self) -> Tuple[int, ...]:
278
+ """The components of the "release" segment of the version.
279
+
280
+ >>> Version("1.2.3").release
281
+ (1, 2, 3)
282
+ >>> Version("2.0.0").release
283
+ (2, 0, 0)
284
+ >>> Version("1!2.0.0.post0").release
285
+ (2, 0, 0)
286
+
287
+ Includes trailing zeroes but not the epoch or any pre-release / development /
288
+ post-release suffixes.
289
+ """
290
+ return self._version.release
291
+
292
+ @property
293
+ def pre(self) -> Optional[Tuple[str, int]]:
294
+ """The pre-release segment of the version.
295
+
296
+ >>> print(Version("1.2.3").pre)
297
+ None
298
+ >>> Version("1.2.3a1").pre
299
+ ('a', 1)
300
+ >>> Version("1.2.3b1").pre
301
+ ('b', 1)
302
+ >>> Version("1.2.3rc1").pre
303
+ ('rc', 1)
304
+ """
305
+ return self._version.pre
306
+
307
+ @property
308
+ def post(self) -> Optional[int]:
309
+ """The post-release number of the version.
310
+
311
+ >>> print(Version("1.2.3").post)
312
+ None
313
+ >>> Version("1.2.3.post1").post
314
+ 1
315
+ """
316
+ return self._version.post[1] if self._version.post else None
317
+
318
+ @property
319
+ def dev(self) -> Optional[int]:
320
+ """The development number of the version.
321
+
322
+ >>> print(Version("1.2.3").dev)
323
+ None
324
+ >>> Version("1.2.3.dev1").dev
325
+ 1
326
+ """
327
+ return self._version.dev[1] if self._version.dev else None
328
+
329
+ @property
330
+ def local(self) -> Optional[str]:
331
+ """The local version segment of the version.
332
+
333
+ >>> print(Version("1.2.3").local)
334
+ None
335
+ >>> Version("1.2.3+abc").local
336
+ 'abc'
337
+ """
338
+ if self._version.local:
339
+ return ".".join(str(x) for x in self._version.local)
340
+ else:
341
+ return None
342
+
343
+ @property
344
+ def public(self) -> str:
345
+ """The public portion of the version.
346
+
347
+ >>> Version("1.2.3").public
348
+ '1.2.3'
349
+ >>> Version("1.2.3+abc").public
350
+ '1.2.3'
351
+ >>> Version("1.2.3+abc.dev1").public
352
+ '1.2.3'
353
+ """
354
+ return str(self).split("+", 1)[0]
355
+
356
+ @property
357
+ def base_version(self) -> str:
358
+ """The "base version" of the version.
359
+
360
+ >>> Version("1.2.3").base_version
361
+ '1.2.3'
362
+ >>> Version("1.2.3+abc").base_version
363
+ '1.2.3'
364
+ >>> Version("1!1.2.3+abc.dev1").base_version
365
+ '1!1.2.3'
366
+
367
+ The "base version" is the public version of the project without any pre or post
368
+ release markers.
369
+ """
370
+ parts = []
371
+
372
+ # Epoch
373
+ if self.epoch != 0:
374
+ parts.append(f"{self.epoch}!")
375
+
376
+ # Release segment
377
+ parts.append(".".join(str(x) for x in self.release))
378
+
379
+ return "".join(parts)
380
+
381
+ @property
382
+ def is_prerelease(self) -> bool:
383
+ """Whether this version is a pre-release.
384
+
385
+ >>> Version("1.2.3").is_prerelease
386
+ False
387
+ >>> Version("1.2.3a1").is_prerelease
388
+ True
389
+ >>> Version("1.2.3b1").is_prerelease
390
+ True
391
+ >>> Version("1.2.3rc1").is_prerelease
392
+ True
393
+ >>> Version("1.2.3dev1").is_prerelease
394
+ True
395
+ """
396
+ return self.dev is not None or self.pre is not None
397
+
398
+ @property
399
+ def is_postrelease(self) -> bool:
400
+ """Whether this version is a post-release.
401
+
402
+ >>> Version("1.2.3").is_postrelease
403
+ False
404
+ >>> Version("1.2.3.post1").is_postrelease
405
+ True
406
+ """
407
+ return self.post is not None
408
+
409
+ @property
410
+ def is_devrelease(self) -> bool:
411
+ """Whether this version is a development release.
412
+
413
+ >>> Version("1.2.3").is_devrelease
414
+ False
415
+ >>> Version("1.2.3.dev1").is_devrelease
416
+ True
417
+ """
418
+ return self.dev is not None
419
+
420
+ @property
421
+ def major(self) -> int:
422
+ """The first item of :attr:`release` or ``0`` if unavailable.
423
+
424
+ >>> Version("1.2.3").major
425
+ 1
426
+ """
427
+ return self.release[0] if len(self.release) >= 1 else 0
428
+
429
+ @property
430
+ def minor(self) -> int:
431
+ """The second item of :attr:`release` or ``0`` if unavailable.
432
+
433
+ >>> Version("1.2.3").minor
434
+ 2
435
+ >>> Version("1").minor
436
+ 0
437
+ """
438
+ return self.release[1] if len(self.release) >= 2 else 0
439
+
440
+ @property
441
+ def micro(self) -> int:
442
+ """The third item of :attr:`release` or ``0`` if unavailable.
443
+
444
+ >>> Version("1.2.3").micro
445
+ 3
446
+ >>> Version("1").micro
447
+ 0
448
+ """
449
+ return self.release[2] if len(self.release) >= 3 else 0
450
+
451
+
452
+ def _parse_letter_version(
453
+ letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
454
+ ) -> Optional[Tuple[str, int]]:
455
+
456
+ if letter:
457
+ # We consider there to be an implicit 0 in a pre-release if there is
458
+ # not a numeral associated with it.
459
+ if number is None:
460
+ number = 0
461
+
462
+ # We normalize any letters to their lower case form
463
+ letter = letter.lower()
464
+
465
+ # We consider some words to be alternate spellings of other words and
466
+ # in those cases we want to normalize the spellings to our preferred
467
+ # spelling.
468
+ if letter == "alpha":
469
+ letter = "a"
470
+ elif letter == "beta":
471
+ letter = "b"
472
+ elif letter in ["c", "pre", "preview"]:
473
+ letter = "rc"
474
+ elif letter in ["rev", "r"]:
475
+ letter = "post"
476
+
477
+ return letter, int(number)
478
+ if not letter and number:
479
+ # We assume if we are given a number, but we are not given a letter
480
+ # then this is using the implicit post release syntax (e.g. 1.0-1)
481
+ letter = "post"
482
+
483
+ return letter, int(number)
484
+
485
+ return None
486
+
487
+
488
+ _local_version_separators = re.compile(r"[\._-]")
489
+
490
+
491
+ def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
492
+ """
493
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
494
+ """
495
+ if local is not None:
496
+ return tuple(
497
+ part.lower() if not part.isdigit() else int(part)
498
+ for part in _local_version_separators.split(local)
499
+ )
500
+ return None
501
+
502
+
503
+ def _cmpkey(
504
+ epoch: int,
505
+ release: Tuple[int, ...],
506
+ pre: Optional[Tuple[str, int]],
507
+ post: Optional[Tuple[str, int]],
508
+ dev: Optional[Tuple[str, int]],
509
+ local: Optional[LocalType],
510
+ ) -> CmpKey:
511
+
512
+ # When we compare a release version, we want to compare it with all of the
513
+ # trailing zeros removed. So we'll use a reverse the list, drop all the now
514
+ # leading zeros until we come to something non zero, then take the rest
515
+ # re-reverse it back into the correct order and make it a tuple and use
516
+ # that for our sorting key.
517
+ _release = tuple(
518
+ reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
519
+ )
520
+
521
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
522
+ # We'll do this by abusing the pre segment, but we _only_ want to do this
523
+ # if there is not a pre or a post segment. If we have one of those then
524
+ # the normal sorting rules will handle this case correctly.
525
+ if pre is None and post is None and dev is not None:
526
+ _pre: CmpPrePostDevType = NegativeInfinity
527
+ # Versions without a pre-release (except as noted above) should sort after
528
+ # those with one.
529
+ elif pre is None:
530
+ _pre = Infinity
531
+ else:
532
+ _pre = pre
533
+
534
+ # Versions without a post segment should sort before those with one.
535
+ if post is None:
536
+ _post: CmpPrePostDevType = NegativeInfinity
537
+
538
+ else:
539
+ _post = post
540
+
541
+ # Versions without a development segment should sort after those with one.
542
+ if dev is None:
543
+ _dev: CmpPrePostDevType = Infinity
544
+
545
+ else:
546
+ _dev = dev
547
+
548
+ if local is None:
549
+ # Versions without a local segment should sort before those with one.
550
+ _local: CmpLocalType = NegativeInfinity
551
+ else:
552
+ # Versions with a local segment need that segment parsed to implement
553
+ # the sorting rules in PEP440.
554
+ # - Alpha numeric segments sort before numeric segments
555
+ # - Alpha numeric segments sort lexicographically
556
+ # - Numeric segments sort numerically
557
+ # - Shorter versions sort before longer versions when the prefixes
558
+ # match exactly
559
+ _local = tuple(
560
+ (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
561
+ )
562
+
563
+ return epoch, _release, _pre, _post, _dev, _local
.venv/lib/python3.10/site-packages/torch/amp/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from .autocast_mode import (
2
+ _enter_autocast,
3
+ _exit_autocast,
4
+ autocast,
5
+ custom_bwd,
6
+ custom_fwd,
7
+ is_autocast_available,
8
+ )
9
+ from .grad_scaler import GradScaler
.venv/lib/python3.10/site-packages/torch/amp/autocast_mode.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import functools
4
+ import warnings
5
+ from typing import Any, Optional
6
+
7
+ import torch
8
+ from torch.types import _dtype
9
+
10
+
11
+ try:
12
+ import numpy as np
13
+
14
+ HAS_NUMPY = True
15
+ except ModuleNotFoundError:
16
+ HAS_NUMPY = False
17
+ np = None # type: ignore[assignment]
18
+
19
+ __all__ = [
20
+ "autocast_decorator",
21
+ "autocast",
22
+ "is_autocast_available",
23
+ "custom_fwd",
24
+ "custom_bwd",
25
+ ]
26
+
27
+
28
+ def is_autocast_available(device_type: str) -> bool:
29
+ r"""
30
+ Return a bool indicating if autocast is available on :attr:`device_type`.
31
+
32
+ Args:
33
+ device_type(str): Device type to use. Possible values are: 'cuda', 'cpu', 'mtia', 'maia', 'xpu', and so on.
34
+ The type is the same as the `type` attribute of a :class:`torch.device`.
35
+ Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
36
+ """
37
+ return torch._C._is_autocast_available(device_type)
38
+
39
+
40
+ def autocast_decorator(autocast_instance, func):
41
+ @functools.wraps(func)
42
+ def decorate_autocast(*args, **kwargs):
43
+ with autocast_instance:
44
+ return func(*args, **kwargs)
45
+
46
+ decorate_autocast.__script_unsupported = ( # type: ignore[attr-defined]
47
+ "@autocast() decorator is not supported in script mode"
48
+ )
49
+ return decorate_autocast
50
+
51
+
52
+ class autocast:
53
+ r"""
54
+ Instances of :class:`autocast` serve as context managers or decorators that
55
+ allow regions of your script to run in mixed precision.
56
+
57
+ In these regions, ops run in an op-specific dtype chosen by autocast
58
+ to improve performance while maintaining accuracy.
59
+ See the :ref:`Autocast Op Reference<autocast-op-reference>` for details.
60
+
61
+ When entering an autocast-enabled region, Tensors may be any type.
62
+ You should not call ``half()`` or ``bfloat16()`` on your model(s) or inputs when using autocasting.
63
+
64
+ :class:`autocast` should wrap only the forward pass(es) of your network, including the loss
65
+ computation(s). Backward passes under autocast are not recommended.
66
+ Backward ops run in the same type that autocast used for corresponding forward ops.
67
+
68
+ Example for CUDA Devices::
69
+
70
+ # Creates model and optimizer in default precision
71
+ model = Net().cuda()
72
+ optimizer = optim.SGD(model.parameters(), ...)
73
+
74
+ for input, target in data:
75
+ optimizer.zero_grad()
76
+
77
+ # Enables autocasting for the forward pass (model + loss)
78
+ with torch.autocast(device_type="cuda"):
79
+ output = model(input)
80
+ loss = loss_fn(output, target)
81
+
82
+ # Exits the context manager before backward()
83
+ loss.backward()
84
+ optimizer.step()
85
+
86
+ See the :ref:`Automatic Mixed Precision examples<amp-examples>` for usage (along with gradient scaling)
87
+ in more complex scenarios (e.g., gradient penalty, multiple models/losses, custom autograd functions).
88
+
89
+ :class:`autocast` can also be used as a decorator, e.g., on the ``forward`` method of your model::
90
+
91
+ class AutocastModel(nn.Module):
92
+ ...
93
+
94
+ @torch.autocast(device_type="cuda")
95
+ def forward(self, input): ...
96
+
97
+ Floating-point Tensors produced in an autocast-enabled region may be ``float16``.
98
+ After returning to an autocast-disabled region, using them with floating-point
99
+ Tensors of different dtypes may cause type mismatch errors. If so, cast the Tensor(s)
100
+ produced in the autocast region back to ``float32`` (or other dtype if desired).
101
+ If a Tensor from the autocast region is already ``float32``, the cast is a no-op,
102
+ and incurs no additional overhead.
103
+ CUDA Example::
104
+
105
+ # Creates some tensors in default dtype (here assumed to be float32)
106
+ a_float32 = torch.rand((8, 8), device="cuda")
107
+ b_float32 = torch.rand((8, 8), device="cuda")
108
+ c_float32 = torch.rand((8, 8), device="cuda")
109
+ d_float32 = torch.rand((8, 8), device="cuda")
110
+
111
+ with torch.autocast(device_type="cuda"):
112
+ # torch.mm is on autocast's list of ops that should run in float16.
113
+ # Inputs are float32, but the op runs in float16 and produces float16 output.
114
+ # No manual casts are required.
115
+ e_float16 = torch.mm(a_float32, b_float32)
116
+ # Also handles mixed input types
117
+ f_float16 = torch.mm(d_float32, e_float16)
118
+
119
+ # After exiting autocast, calls f_float16.float() to use with d_float32
120
+ g_float32 = torch.mm(d_float32, f_float16.float())
121
+
122
+ CPU Training Example::
123
+
124
+ # Creates model and optimizer in default precision
125
+ model = Net()
126
+ optimizer = optim.SGD(model.parameters(), ...)
127
+
128
+ for epoch in epochs:
129
+ for input, target in data:
130
+ optimizer.zero_grad()
131
+
132
+ # Runs the forward pass with autocasting.
133
+ with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
134
+ output = model(input)
135
+ loss = loss_fn(output, target)
136
+
137
+ loss.backward()
138
+ optimizer.step()
139
+
140
+
141
+ CPU Inference Example::
142
+
143
+ # Creates model in default precision
144
+ model = Net().eval()
145
+
146
+ with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
147
+ for input in data:
148
+ # Runs the forward pass with autocasting.
149
+ output = model(input)
150
+
151
+ CPU Inference Example with Jit Trace::
152
+
153
+ class TestModel(nn.Module):
154
+ def __init__(self, input_size, num_classes):
155
+ super().__init__()
156
+ self.fc1 = nn.Linear(input_size, num_classes)
157
+
158
+ def forward(self, x):
159
+ return self.fc1(x)
160
+
161
+
162
+ input_size = 2
163
+ num_classes = 2
164
+ model = TestModel(input_size, num_classes).eval()
165
+
166
+ # For now, we suggest to disable the Jit Autocast Pass,
167
+ # As the issue: https://github.com/pytorch/pytorch/issues/75956
168
+ torch._C._jit_set_autocast_mode(False)
169
+
170
+ with torch.cpu.amp.autocast(cache_enabled=False):
171
+ model = torch.jit.trace(model, torch.randn(1, input_size))
172
+ model = torch.jit.freeze(model)
173
+ # Models Run
174
+ for _ in range(3):
175
+ model(torch.randn(1, input_size))
176
+
177
+ Type mismatch errors *in* an autocast-enabled region are a bug; if this is what you observe,
178
+ please file an issue.
179
+
180
+ ``autocast(enabled=False)`` subregions can be nested in autocast-enabled regions.
181
+ Locally disabling autocast can be useful, for example, if you want to force a subregion
182
+ to run in a particular ``dtype``. Disabling autocast gives you explicit control over
183
+ the execution type. In the subregion, inputs from the surrounding region
184
+ should be cast to ``dtype`` before use::
185
+
186
+ # Creates some tensors in default dtype (here assumed to be float32)
187
+ a_float32 = torch.rand((8, 8), device="cuda")
188
+ b_float32 = torch.rand((8, 8), device="cuda")
189
+ c_float32 = torch.rand((8, 8), device="cuda")
190
+ d_float32 = torch.rand((8, 8), device="cuda")
191
+
192
+ with torch.autocast(device_type="cuda"):
193
+ e_float16 = torch.mm(a_float32, b_float32)
194
+ with torch.autocast(device_type="cuda", enabled=False):
195
+ # Calls e_float16.float() to ensure float32 execution
196
+ # (necessary because e_float16 was created in an autocasted region)
197
+ f_float32 = torch.mm(c_float32, e_float16.float())
198
+
199
+ # No manual casts are required when re-entering the autocast-enabled region.
200
+ # torch.mm again runs in float16 and produces float16 output, regardless of input types.
201
+ g_float16 = torch.mm(d_float32, f_float32)
202
+
203
+ The autocast state is thread-local. If you want it enabled in a new thread, the context manager or decorator
204
+ must be invoked in that thread. This affects :class:`torch.nn.DataParallel` and
205
+ :class:`torch.nn.parallel.DistributedDataParallel` when used with more than one GPU per process
206
+ (see :ref:`Working with Multiple GPUs<amp-multigpu>`).
207
+
208
+ Args:
209
+ device_type(str, required): Device type to use. Possible values are: 'cuda', 'cpu', 'mtia', 'maia', 'xpu', and 'hpu'.
210
+ The type is the same as the `type` attribute of a :class:`torch.device`.
211
+ Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
212
+ enabled(bool, optional): Whether autocasting should be enabled in the region.
213
+ Default: ``True``
214
+ dtype(torch_dtype, optional): Data type for ops run in autocast. It uses the default value
215
+ (``torch.float16`` for CUDA and ``torch.bfloat16`` for CPU), given by
216
+ :func:`~torch.get_autocast_dtype`, if :attr:`dtype` is ``None``.
217
+ Default: ``None``
218
+ cache_enabled(bool, optional): Whether the weight cache inside autocast should be enabled.
219
+ Default: ``True``
220
+ """
221
+
222
+ def __init__(
223
+ self,
224
+ device_type: str,
225
+ dtype: Optional[_dtype] = None,
226
+ enabled: bool = True,
227
+ cache_enabled: Optional[bool] = None,
228
+ ):
229
+ if not isinstance(device_type, str):
230
+ raise ValueError(
231
+ f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
232
+ )
233
+ self.fast_dtype = (
234
+ torch.get_autocast_dtype(device_type) if dtype is None else dtype
235
+ )
236
+ if torch._jit_internal.is_scripting():
237
+ self._enabled = enabled
238
+ self.device = device_type
239
+ if self.fast_dtype is None:
240
+ raise AssertionError("fast_dtype must not be None in scripting mode")
241
+ return
242
+ self.device = device_type
243
+ if not is_autocast_available(self.device):
244
+ raise RuntimeError(
245
+ f"User specified an unsupported autocast device_type '{self.device}'"
246
+ )
247
+
248
+ device_supported_dtypes = [torch.bfloat16, torch.float16]
249
+
250
+ self.custom_backend_name = torch._C._get_privateuse1_backend_name()
251
+ if self.device == self.custom_backend_name:
252
+ necessary_funcs = [
253
+ "get_amp_supported_dtype",
254
+ ]
255
+ message = f"Tried to use AMP with the `{self.custom_backend_name}` backend, but the backend has not "
256
+ message += "registered a module or the module miss some necessary funcs. The backend should register "
257
+ message += "a module by `torch._register_device_module`, and the module must have these funcs: \n"
258
+ message += "`get_amp_supported_dtype() -> List[torch.dtype]`. \n"
259
+
260
+ if not hasattr(torch, self.custom_backend_name):
261
+ raise AssertionError(message)
262
+ self.custom_device_mod = getattr(torch, self.custom_backend_name)
263
+ for func in necessary_funcs:
264
+ if not hasattr(self.custom_device_mod, func):
265
+ raise AssertionError(
266
+ message + f"But the func `{func}` is missing. \n"
267
+ )
268
+ device_supported_dtypes = self.custom_device_mod.get_amp_supported_dtype()
269
+
270
+ self._cache_enabled = (
271
+ torch.is_autocast_cache_enabled()
272
+ if cache_enabled is None
273
+ else cache_enabled
274
+ )
275
+
276
+ device_name = (
277
+ self.device
278
+ if self.device == self.custom_backend_name
279
+ else self.device.upper()
280
+ )
281
+ if enabled:
282
+ # Special case for CUDA AMP and bfloat16 support
283
+ if self.device == "cuda":
284
+ if torch.cuda.amp.common.amp_definitely_not_available():
285
+ warnings.warn(
286
+ "CUDA is not available or torch_xla is imported. Disabling autocast.",
287
+ stacklevel=2,
288
+ )
289
+ enabled = False
290
+ elif (
291
+ self.fast_dtype == torch.bfloat16
292
+ and not torch.cuda.is_bf16_supported()
293
+ ):
294
+ raise RuntimeError(
295
+ "Current CUDA Device does not support bfloat16. Please switch dtype to float16."
296
+ )
297
+ elif self.fast_dtype not in device_supported_dtypes:
298
+ error_message = (
299
+ f"In {device_name} autocast, but the target dtype is not supported. Disabling autocast.\n"
300
+ f"{device_name} Autocast only supports dtypes of "
301
+ + ", ".join(map(str, device_supported_dtypes))
302
+ + " currently."
303
+ )
304
+ warnings.warn(error_message, stacklevel=2)
305
+ enabled = False
306
+ # Special case for MPS bfloat16 support on macOS < 14
307
+ if (
308
+ self.device == "mps"
309
+ and self.fast_dtype == torch.bfloat16
310
+ and not torch.backends.mps.is_macos_or_newer(14, 0)
311
+ ):
312
+ error_message = (
313
+ "In MPS autocast, but the target dtype torch.bfloat16 is not supported "
314
+ "on macOS versions below 14. Disabling autocast."
315
+ )
316
+ warnings.warn(error_message, stacklevel=2)
317
+ enabled = False
318
+ self._enabled = enabled
319
+
320
+ def __enter__(self):
321
+ if torch._jit_internal.is_scripting():
322
+ if self.fast_dtype is None:
323
+ raise AssertionError("fast_dtype must not be None in scripting mode")
324
+ return self
325
+
326
+ self.prev_cache_enabled = torch.is_autocast_cache_enabled()
327
+ self.prev = torch.is_autocast_enabled(self.device)
328
+ self.prev_fastdtype = torch.get_autocast_dtype(self.device)
329
+ torch.set_autocast_enabled(self.device, self._enabled)
330
+ torch.set_autocast_dtype(self.device, self.fast_dtype) # type: ignore[arg-type]
331
+ torch.autocast_increment_nesting()
332
+ torch.set_autocast_cache_enabled(self._cache_enabled)
333
+
334
+ # only dispatch to PreDispatchTorchFunctionMode to avoid exposing this
335
+ # API to other functional modes. We only expose to PreDispatchTorchFunctionMode
336
+ # for preserving autocast in torch.export.export.
337
+ if torch._C._is_torch_function_mode_enabled():
338
+ stacks = torch.overrides._get_current_function_mode_stack()
339
+ for mode in stacks:
340
+ if isinstance(
341
+ mode,
342
+ torch.fx.experimental.proxy_tensor.PreDispatchTorchFunctionMode,
343
+ ):
344
+ args = (
345
+ self.device,
346
+ self.fast_dtype,
347
+ self._enabled,
348
+ self._cache_enabled,
349
+ )
350
+ mode.__torch_function__(torch.amp._enter_autocast, (), args)
351
+ return self
352
+
353
+ return self
354
+
355
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any): # type: ignore[override]
356
+ if torch._jit_internal.is_scripting():
357
+ return
358
+
359
+ # Drop the cache when we exit to a nesting level that's outside any instance of autocast.
360
+ if torch.autocast_decrement_nesting() == 0:
361
+ torch.clear_autocast_cache()
362
+ torch.set_autocast_enabled(self.device, self.prev)
363
+ torch.set_autocast_dtype(self.device, self.prev_fastdtype)
364
+ torch.set_autocast_cache_enabled(self.prev_cache_enabled)
365
+
366
+ # only dispatch to PreDispatchTorchFunctionMode to avoid exposing this
367
+ # API to other functional modes. We only expose to PreDispatchTorchFunctionMode
368
+ # for preserving autocast in torch.export.export.
369
+ if torch._C._is_torch_function_mode_enabled():
370
+ stacks = torch.overrides._get_current_function_mode_stack()
371
+ for mode in stacks:
372
+ if isinstance(
373
+ mode,
374
+ torch.fx.experimental.proxy_tensor.PreDispatchTorchFunctionMode,
375
+ ):
376
+ mode.__torch_function__(torch.amp._exit_autocast, (), ())
377
+ # This is very important because the above line actually doesn't
378
+ # run exit code so it end up swallowing exceptions.
379
+ return False
380
+ return False
381
+
382
+ def __call__(self, func):
383
+ if torch._jit_internal.is_scripting():
384
+ return func
385
+ return autocast_decorator(self, func)
386
+
387
+
388
+ # These functions aren't meant for public usage.
389
+ # They are what we trace into a graph during pre_dispatch tracing
390
+ # when we encounter an autocast context manager.
391
+ def _enter_autocast(*vals):
392
+ # For pre-dispatch tracing, if a TorchFunction mode is active, we'll want to trace this into a graph.
393
+ if torch._C._is_torch_function_mode_enabled():
394
+ return torch.overrides.handle_torch_function(
395
+ torch.amp._enter_autocast, [], *vals
396
+ )
397
+ mode = torch.amp.autocast(*vals)
398
+ mode.__enter__()
399
+ return mode
400
+
401
+
402
+ def _exit_autocast(mode):
403
+ if torch._C._is_torch_function_mode_enabled():
404
+ return torch.overrides.handle_torch_function(torch.amp._exit_autocast, [], mode)
405
+ mode.__exit__(None, None, None)
406
+
407
+
408
+ # Casts Tensors and containers of Tensors. Special-cases passthroughs for strings and np.ndarrays, which
409
+ # may be falsely detected as "Iterables."
410
+ def _cast(value, device_type: str, dtype: _dtype):
411
+ if isinstance(value, torch.Tensor):
412
+ is_eligible = (
413
+ value.is_floating_point()
414
+ and value.device.type == device_type
415
+ and (value.dtype is not torch.float64)
416
+ )
417
+ return value.to(dtype) if is_eligible else value
418
+ elif isinstance(value, (str, bytes)):
419
+ return value
420
+ elif HAS_NUMPY and isinstance(
421
+ value,
422
+ # pyrefly: ignore [missing-attribute]
423
+ np.ndarray,
424
+ ):
425
+ return value
426
+ elif isinstance(value, collections.abc.Mapping):
427
+ return {
428
+ _cast(k, device_type, dtype): _cast(v, device_type, dtype)
429
+ for k, v in value.items()
430
+ }
431
+ elif isinstance(value, collections.abc.Iterable):
432
+ iterable = (_cast(v, device_type, dtype) for v in value)
433
+ if isinstance(value, (list, tuple)):
434
+ return type(value)(iterable)
435
+ else:
436
+ return iterable
437
+ else:
438
+ return value
439
+
440
+
441
+ def custom_fwd(
442
+ fwd=None,
443
+ *,
444
+ device_type: str,
445
+ cast_inputs: Optional[_dtype] = None,
446
+ ):
447
+ """
448
+ Create a helper decorator for ``forward`` methods of custom autograd functions.
449
+
450
+ Autograd functions are subclasses of :class:`torch.autograd.Function`.
451
+ See the :ref:`example page<amp-custom-examples>` for more detail.
452
+
453
+ Args:
454
+ device_type(str): Device type to use. 'cuda', 'cpu', 'mtia', 'maia', 'xpu' and so on.
455
+ The type is the same as the `type` attribute of a :class:`torch.device`.
456
+ Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
457
+ cast_inputs (:class:`torch.dtype` or None, optional, default=None): If not ``None``,
458
+ when ``forward`` runs in an autocast-enabled region, casts incoming
459
+ floating-point Tensors to the target dtype (non-floating-point Tensors are not affected),
460
+ then executes ``forward`` with autocast disabled.
461
+ If ``None``, ``forward``'s internal ops execute with the current autocast state.
462
+
463
+ .. note::
464
+ If the decorated ``forward`` is called outside an autocast-enabled region,
465
+ :func:`custom_fwd<custom_fwd>` is a no-op and ``cast_inputs`` has no effect.
466
+ """
467
+ if not isinstance(device_type, str):
468
+ raise ValueError(
469
+ f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
470
+ )
471
+ if fwd is None:
472
+ return functools.partial(
473
+ custom_fwd, device_type=device_type, cast_inputs=cast_inputs
474
+ )
475
+
476
+ @functools.wraps(fwd)
477
+ def decorate_fwd(*args, **kwargs):
478
+ args[0]._dtype = torch.get_autocast_dtype(device_type)
479
+ if cast_inputs is None:
480
+ args[0]._fwd_used_autocast = torch.is_autocast_enabled(device_type)
481
+ return fwd(*args, **kwargs) # pyrefly: ignore [not-callable]
482
+ else:
483
+ autocast_context = torch.is_autocast_enabled(device_type)
484
+ args[0]._fwd_used_autocast = False
485
+ if autocast_context:
486
+ with autocast(device_type=device_type, enabled=False):
487
+ return fwd( # pyrefly: ignore # not-callable
488
+ *_cast(args, device_type, cast_inputs),
489
+ **_cast(kwargs, device_type, cast_inputs),
490
+ )
491
+ else:
492
+ return fwd(*args, **kwargs) # pyrefly: ignore [not-callable]
493
+
494
+ return decorate_fwd
495
+
496
+
497
+ # Autograd ensures incoming gradients are the same type as forward outputs. Allowing a separate
498
+ # cast_inputs argument on custom_bwd is unnecessary and could cause errors if it doesn't match
499
+ # cast_inputs supplied to custom_fwd.
500
+ def custom_bwd(bwd=None, *, device_type: str):
501
+ """Create a helper decorator for backward methods of custom autograd functions.
502
+
503
+ Autograd functions are subclasses of :class:`torch.autograd.Function`.
504
+ Ensures that ``backward`` executes with the same autocast state as ``forward``.
505
+ See the :ref:`example page<amp-custom-examples>` for more detail.
506
+
507
+ Args:
508
+ device_type(str): Device type to use. 'cuda', 'cpu', 'mtia', 'maia', 'xpu' and so on.
509
+ The type is the same as the `type` attribute of a :class:`torch.device`.
510
+ Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
511
+ """
512
+
513
+ if not isinstance(device_type, str):
514
+ raise ValueError(
515
+ f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
516
+ )
517
+ if bwd is None:
518
+ return functools.partial(custom_bwd, device_type=device_type)
519
+
520
+ @functools.wraps(bwd)
521
+ def decorate_bwd(*args, **kwargs):
522
+ with autocast(
523
+ device_type=device_type,
524
+ enabled=args[0]._fwd_used_autocast,
525
+ dtype=args[0]._dtype,
526
+ ):
527
+ return bwd(*args, **kwargs) # pyrefly: ignore [not-callable]
528
+
529
+ return decorate_bwd
.venv/lib/python3.10/site-packages/torch/amp/grad_scaler.py ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import inspect
5
+ import warnings
6
+ from collections import abc, defaultdict
7
+ from enum import Enum
8
+ from typing import Any, cast, Optional, overload, TYPE_CHECKING, Union
9
+
10
+ import torch
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Iterable
15
+
16
+
17
+ __all__ = ["OptState", "GradScaler"]
18
+
19
+
20
+ class _MultiDeviceReplicator:
21
+ """Lazily serves copies of a tensor to requested devices.
22
+
23
+ Copies are cached per-device.
24
+ """
25
+
26
+ def __init__(self, master_tensor: torch.Tensor) -> None:
27
+ self.master = master_tensor
28
+ self._per_device_tensors: dict[torch.device, torch.Tensor] = {}
29
+
30
+ def get(self, device: torch.device) -> torch.Tensor:
31
+ retval = self._per_device_tensors.get(device, None)
32
+ if retval is None:
33
+ retval = self.master.to(device=device, non_blocking=True, copy=True)
34
+ self._per_device_tensors[device] = retval
35
+ return retval
36
+
37
+
38
+ # Defines default_factory for GradScaler's _per_optimizer_states defaultdict,
39
+ # as well as associated "enum" values. Prefers defining these at top level because
40
+ # - Lambdas can't be pickled, so we don't want to supply a lambda as the factory.
41
+ # - Defining READY, UNSCALED, STEPPED and _refresh_per_optimizer_state within GradScaler
42
+ # causes a circular reference, which we'd rather avoid.
43
+ class OptState(Enum):
44
+ READY = 0
45
+ UNSCALED = 1
46
+ STEPPED = 2
47
+
48
+
49
+ def _refresh_per_optimizer_state() -> dict[str, Any]:
50
+ return {"stage": OptState.READY, "found_inf_per_device": {}}
51
+
52
+
53
+ class GradScaler:
54
+ """An instance ``scaler`` of :class:`GradScaler`.
55
+
56
+ Helps perform the steps of gradient scaling
57
+ conveniently.
58
+
59
+ * ``scaler.scale(loss)`` multiplies a given loss by ``scaler``'s current scale factor.
60
+ * ``scaler.step(optimizer)`` safely unscales gradients and calls ``optimizer.step()``.
61
+ * ``scaler.update()`` updates ``scaler``'s scale factor.
62
+
63
+ Example::
64
+
65
+ # Creates a GradScaler once at the beginning of training.
66
+ scaler = GradScaler()
67
+
68
+ for epoch in epochs:
69
+ for input, target in data:
70
+ optimizer.zero_grad()
71
+ output = model(input)
72
+ loss = loss_fn(output, target)
73
+
74
+ # Scales loss. Calls backward() on scaled loss to create scaled gradients.
75
+ scaler.scale(loss).backward()
76
+
77
+ # scaler.step() first unscales gradients of the optimizer's params.
78
+ # If gradients don't contain infs/NaNs, optimizer.step() is then called,
79
+ # otherwise, optimizer.step() is skipped.
80
+ scaler.step(optimizer)
81
+
82
+ # Updates the scale for next iteration.
83
+ scaler.update()
84
+
85
+ See the :ref:`Automatic Mixed Precision examples<amp-examples>` for usage
86
+ (along with autocasting) in more complex cases like gradient clipping, gradient accumulation, gradient penalty,
87
+ and multiple losses/optimizers.
88
+
89
+ ``scaler`` dynamically estimates the scale factor each iteration. To minimize gradient underflow,
90
+ a large scale factor should be used. However, ``float16`` values can "overflow" (become inf or NaN) if
91
+ the scale factor is too large. Therefore, the optimal scale factor is the largest factor that can be used
92
+ without incurring inf or NaN gradient values.
93
+ ``scaler`` approximates the optimal scale factor over time by checking the gradients for infs and NaNs during every
94
+ ``scaler.step(optimizer)`` (or optional separate ``scaler.unscale_(optimizer)``, see :meth:`unscale_`).
95
+
96
+ * If infs/NaNs are found, ``scaler.step(optimizer)`` skips the underlying ``optimizer.step()`` (so the params
97
+ themselves remain uncorrupted) and ``update()`` multiplies the scale by ``backoff_factor``.
98
+
99
+ * If no infs/NaNs are found, ``scaler.step(optimizer)`` runs the underlying ``optimizer.step()`` as usual.
100
+ If ``growth_interval`` unskipped iterations occur consecutively, ``update()`` multiplies the scale by
101
+ ``growth_factor``.
102
+
103
+ The scale factor often causes infs/NaNs to appear in gradients for the first few iterations as its
104
+ value calibrates. ``scaler.step`` will skip the underlying ``optimizer.step()`` for these
105
+ iterations. After that, step skipping should occur rarely (once every few hundred or thousand iterations).
106
+
107
+ Args:
108
+ device (str, optional, default="cuda"): Device type to use. Possible values are: 'cuda' and 'cpu'.
109
+ The type is the same as the `type` attribute of a :class:`torch.device`.
110
+ Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
111
+ init_scale (float, optional, default=2.**16): Initial scale factor.
112
+ growth_factor (float, optional, default=2.0): Factor by which the scale is multiplied during
113
+ :meth:`update` if no inf/NaN gradients occur for ``growth_interval`` consecutive iterations.
114
+ backoff_factor (float, optional, default=0.5): Factor by which the scale is multiplied during
115
+ :meth:`update` if inf/NaN gradients occur in an iteration.
116
+ growth_interval (int, optional, default=2000): Number of consecutive iterations without inf/NaN gradients
117
+ that must occur for the scale to be multiplied by ``growth_factor``.
118
+ enabled (bool, optional): If ``False``, disables gradient scaling. :meth:`step` simply
119
+ invokes the underlying ``optimizer.step()``, and other methods become no-ops.
120
+ Default: ``True``
121
+ """
122
+
123
+ def __init__(
124
+ self,
125
+ device: str = "cuda",
126
+ init_scale: float = 2.0**16,
127
+ growth_factor: float = 2.0,
128
+ backoff_factor: float = 0.5,
129
+ growth_interval: int = 2000,
130
+ enabled: bool = True,
131
+ ) -> None:
132
+ self._device = device
133
+ self._enabled = enabled
134
+ if self._device == "cuda":
135
+ if enabled and torch.cuda.amp.common.amp_definitely_not_available():
136
+ warnings.warn(
137
+ "torch.cuda.amp.GradScaler is enabled, but CUDA is not available. Disabling.",
138
+ stacklevel=2,
139
+ )
140
+ self._enabled = False
141
+
142
+ if self._enabled:
143
+ if growth_factor <= 1.0:
144
+ raise AssertionError("The growth factor must be > 1.0.")
145
+ if backoff_factor >= 1.0:
146
+ raise AssertionError("The backoff factor must be < 1.0.")
147
+
148
+ self._init_scale = init_scale
149
+ # self._scale will be lazily initialized during the first call to scale()
150
+ self._scale: Optional[torch.Tensor] = None
151
+ self._growth_factor = growth_factor
152
+ self._backoff_factor = backoff_factor
153
+ self._growth_interval = growth_interval
154
+ self._init_growth_tracker = 0
155
+ # self._growth_tracker will be lazily initialized during the first call to scale()
156
+ self._growth_tracker: Optional[torch.Tensor] = None
157
+ self._per_optimizer_states: dict[int, dict[str, Any]] = defaultdict(
158
+ _refresh_per_optimizer_state
159
+ )
160
+
161
+ def _check_scale_growth_tracker(
162
+ self, funcname: str
163
+ ) -> tuple[torch.Tensor, torch.Tensor]:
164
+ fix = "This may indicate your script did not use scaler.scale(loss or outputs) earlier in the iteration."
165
+ if self._scale is None:
166
+ raise AssertionError(f"Attempted {funcname} but _scale is None. " + fix)
167
+ if self._growth_tracker is None:
168
+ raise AssertionError(
169
+ f"Attempted {funcname} but _growth_tracker is None. " + fix
170
+ )
171
+ return (self._scale, self._growth_tracker)
172
+
173
+ def _lazy_init_scale_growth_tracker(self, dev: torch.device) -> None:
174
+ if self._growth_tracker is not None:
175
+ raise AssertionError("_growth_tracker initialized before _scale")
176
+ self._scale = torch.full((), self._init_scale, dtype=torch.float32, device=dev)
177
+ self._growth_tracker = torch.full(
178
+ (), self._init_growth_tracker, dtype=torch.int32, device=dev
179
+ )
180
+
181
+ @overload
182
+ def scale(self, outputs: torch.Tensor) -> torch.Tensor: ...
183
+
184
+ @overload
185
+ def scale(self, outputs: list[torch.Tensor]) -> list[torch.Tensor]: ...
186
+
187
+ @overload
188
+ def scale(self, outputs: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]: ...
189
+
190
+ @overload
191
+ def scale(self, outputs: Iterable[torch.Tensor]) -> Iterable[torch.Tensor]: ...
192
+
193
+ def scale(
194
+ self,
195
+ outputs: Union[torch.Tensor, Iterable[torch.Tensor]],
196
+ ) -> Union[torch.Tensor, Iterable[torch.Tensor]]:
197
+ """
198
+ Multiplies ('scales') a tensor or list of tensors by the scale factor.
199
+
200
+ Returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, outputs are returned
201
+ unmodified.
202
+
203
+ Args:
204
+ outputs (Tensor or iterable of Tensors): Outputs to scale.
205
+ """
206
+ if not self._enabled:
207
+ return outputs
208
+
209
+ # Short-circuit for the common case.
210
+ if isinstance(outputs, torch.Tensor):
211
+ if self._scale is None:
212
+ self._lazy_init_scale_growth_tracker(outputs.device)
213
+ # _scale is now guaranteed to be set
214
+ scale = self._scale
215
+ if scale is None:
216
+ raise AssertionError("_scale should not be None after lazy init")
217
+ return outputs * scale.to(device=outputs.device, non_blocking=True)
218
+
219
+ # Invoke the more complex machinery only if we're treating multiple outputs.
220
+ stash: list[
221
+ _MultiDeviceReplicator
222
+ ] = [] # holds a reference that can be overwritten by apply_scale
223
+
224
+ def apply_scale(val: Union[torch.Tensor, Iterable[torch.Tensor]]):
225
+ if isinstance(val, torch.Tensor):
226
+ if len(stash) == 0:
227
+ if self._scale is None:
228
+ self._lazy_init_scale_growth_tracker(val.device)
229
+ # _scale is now guaranteed to be set
230
+ scale = self._scale
231
+ if scale is None:
232
+ raise AssertionError(
233
+ "_scale should not be None after lazy init"
234
+ )
235
+ stash.append(_MultiDeviceReplicator(scale))
236
+ return val * stash[0].get(val.device)
237
+ if isinstance(val, abc.Iterable):
238
+ iterable = map(apply_scale, val)
239
+ if isinstance(val, (list, tuple)):
240
+ return type(val)(iterable)
241
+ return iterable
242
+ raise ValueError("outputs must be a Tensor or an iterable of Tensors")
243
+
244
+ return apply_scale(outputs)
245
+
246
+ def _unscale_grads_(
247
+ self,
248
+ optimizer: torch.optim.Optimizer,
249
+ inv_scale: torch.Tensor,
250
+ found_inf: torch.Tensor,
251
+ allow_fp16: bool,
252
+ ) -> dict[torch.device, torch.Tensor]:
253
+ per_device_inv_scale = _MultiDeviceReplicator(inv_scale)
254
+ per_device_found_inf = _MultiDeviceReplicator(found_inf)
255
+
256
+ # To set up _amp_foreach_non_finite_check_and_unscale_, split grads by device and dtype.
257
+ # There could be hundreds of grads, so we'd like to iterate through them just once.
258
+ # However, we don't know their devices or dtypes in advance.
259
+
260
+ # https://stackoverflow.com/questions/5029934/defaultdict-of-defaultdict
261
+ # Google says mypy struggles with defaultdicts type annotations.
262
+ per_device_and_dtype_grads: dict[
263
+ torch.device, dict[torch.dtype, list[torch.Tensor]]
264
+ ] = defaultdict(lambda: defaultdict(list))
265
+ with torch.no_grad():
266
+ for group in optimizer.param_groups:
267
+ for param in group["params"]:
268
+ if not isinstance(param, torch.Tensor):
269
+ raise AssertionError(
270
+ f"expected param to be torch.Tensor, got {type(param).__name__}"
271
+ )
272
+ if param.grad is None:
273
+ continue
274
+ if (not allow_fp16) and param.grad.dtype == torch.float16:
275
+ raise ValueError("Attempting to unscale FP16 gradients.")
276
+ if param.grad.is_sparse:
277
+ # is_coalesced() == False means the sparse grad has values with duplicate indices.
278
+ # coalesce() deduplicates indices and adds all values that have the same index.
279
+ # For scaled fp16 values, there's a good chance coalescing will cause overflow,
280
+ # so we should check the coalesced _values().
281
+ if param.grad.dtype is torch.float16:
282
+ param.grad = param.grad.coalesce()
283
+ to_unscale = param.grad._values()
284
+ else:
285
+ to_unscale = param.grad
286
+
287
+ # TODO: is there a way to split by device and dtype without appending in the inner loop?
288
+ per_device_and_dtype_grads[to_unscale.device][
289
+ to_unscale.dtype
290
+ ].append(to_unscale)
291
+
292
+ for device, per_dtype_grads in per_device_and_dtype_grads.items():
293
+ for grads in per_dtype_grads.values():
294
+ torch._amp_foreach_non_finite_check_and_unscale_(
295
+ grads,
296
+ per_device_found_inf.get(device),
297
+ per_device_inv_scale.get(device),
298
+ )
299
+
300
+ return per_device_found_inf._per_device_tensors
301
+
302
+ def unscale_(self, optimizer: torch.optim.Optimizer) -> None:
303
+ """
304
+ Divides ("unscales") the optimizer's gradient tensors by the scale factor.
305
+
306
+ :meth:`unscale_` is optional, serving cases where you need to
307
+ :ref:`modify or inspect gradients<working-with-unscaled-gradients>`
308
+ between the backward pass(es) and :meth:`step`.
309
+ If :meth:`unscale_` is not called explicitly, gradients will be unscaled automatically during :meth:`step`.
310
+
311
+ Simple example, using :meth:`unscale_` to enable clipping of unscaled gradients::
312
+
313
+ ...
314
+ scaler.scale(loss).backward()
315
+ scaler.unscale_(optimizer)
316
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
317
+ scaler.step(optimizer)
318
+ scaler.update()
319
+
320
+ Args:
321
+ optimizer (torch.optim.Optimizer): Optimizer that owns the gradients to be unscaled.
322
+
323
+ .. note::
324
+ :meth:`unscale_` does not incur a CPU-GPU sync.
325
+
326
+ .. warning::
327
+ :meth:`unscale_` should only be called once per optimizer per :meth:`step` call,
328
+ and only after all gradients for that optimizer's assigned parameters have been accumulated.
329
+ Calling :meth:`unscale_` twice for a given optimizer between each :meth:`step` triggers a RuntimeError.
330
+
331
+ .. warning::
332
+ :meth:`unscale_` may unscale sparse gradients out of place, replacing the ``.grad`` attribute.
333
+ """
334
+ if not self._enabled:
335
+ return
336
+
337
+ self._check_scale_growth_tracker("unscale_")
338
+
339
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
340
+
341
+ if optimizer_state["stage"] is OptState.UNSCALED:
342
+ raise RuntimeError(
343
+ "unscale_() has already been called on this optimizer since the last update()."
344
+ )
345
+ elif optimizer_state["stage"] is OptState.STEPPED:
346
+ raise RuntimeError("unscale_() is being called after step().")
347
+
348
+ # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
349
+ if self._scale is None:
350
+ raise AssertionError("_scale is None in unscale_")
351
+ inv_scale = (
352
+ self._scale.double().reciprocal().float()
353
+ if self._scale.device != torch.device("mps:0")
354
+ else self._scale.reciprocal()
355
+ )
356
+ found_inf = torch.full((), 0.0, dtype=torch.float32, device=self._scale.device)
357
+
358
+ optimizer_state["found_inf_per_device"] = self._unscale_grads_(
359
+ optimizer, inv_scale, found_inf, False
360
+ )
361
+ optimizer_state["stage"] = OptState.UNSCALED
362
+
363
+ def _maybe_opt_step(
364
+ self,
365
+ optimizer: torch.optim.Optimizer,
366
+ optimizer_state: dict[str, Any],
367
+ *args: Any,
368
+ **kwargs: Any,
369
+ ) -> Optional[float]:
370
+ retval: Optional[float] = None
371
+ if not sum(v.item() for v in optimizer_state["found_inf_per_device"].values()):
372
+ retval = optimizer.step(*args, **kwargs)
373
+ return retval
374
+
375
+ def step(
376
+ self, optimizer: torch.optim.Optimizer, *args: Any, **kwargs: Any
377
+ ) -> Optional[float]:
378
+ """Invoke ``unscale_(optimizer)`` followed by parameter update, if gradients are not infs/NaN.
379
+
380
+ :meth:`step` carries out the following two operations:
381
+
382
+ 1. Internally invokes ``unscale_(optimizer)`` (unless :meth:`unscale_` was explicitly called for ``optimizer``
383
+ earlier in the iteration). As part of the :meth:`unscale_`, gradients are checked for infs/NaNs.
384
+ 2. If no inf/NaN gradients are found, invokes ``optimizer.step()`` using the unscaled
385
+ gradients. Otherwise, ``optimizer.step()`` is skipped to avoid corrupting the params.
386
+
387
+ ``*args`` and ``**kwargs`` are forwarded to ``optimizer.step()``.
388
+
389
+ Returns the return value of ``optimizer.step(*args, **kwargs)``.
390
+
391
+ Args:
392
+ optimizer (torch.optim.Optimizer): Optimizer that applies the gradients.
393
+ args: Any arguments.
394
+ kwargs: Any keyword arguments.
395
+
396
+ .. warning::
397
+ Closure use is not currently supported.
398
+ """
399
+ if not self._enabled:
400
+ return optimizer.step(*args, **kwargs)
401
+
402
+ if "closure" in kwargs:
403
+ raise RuntimeError(
404
+ "Closure use is not currently supported if GradScaler is enabled."
405
+ )
406
+
407
+ self._check_scale_growth_tracker("step")
408
+
409
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
410
+
411
+ if optimizer_state["stage"] is OptState.STEPPED:
412
+ raise RuntimeError(
413
+ "step() has already been called since the last update()."
414
+ )
415
+
416
+ retval: Optional[float] = None
417
+
418
+ if getattr(optimizer, "_step_supports_amp_scaling", False):
419
+ # This optimizer has customized scale-handling logic, so we can call optimizer.step() directly.
420
+ # The contract with custom optimizers is that their step() should accept an additional,
421
+ # optional grad_scaler kwarg. We append self to the kwargs so the custom optimizer has full information:
422
+ # it can query its own state, invoke unscale_ on itself, etc
423
+ # The contract above is being deprecated to avoid introducing `grad_scaler: GradScaler` argument
424
+ # to `Optimizer.step`. The new behavior is going to add two Tensor attributes of `grad_scale`
425
+ # and `found_inf` to the passed optimizer so that the optimizer can utilize those
426
+ # to skip the parameter updates or unscale gradients before updating parameters in
427
+ # the fused kernel, e.g. `FusedAdamMathFunctor`.
428
+ # In this behavior, `GradScaler._check_inf_per_device` is called if `OptState.READY`,
429
+ # while the method is expected to be called by users side, i.e. their optimizers.
430
+ kwargs_ = kwargs
431
+ has_grad_scaler_kwarg = (
432
+ "grad_scaler" in inspect.signature(optimizer.step).parameters
433
+ )
434
+ if has_grad_scaler_kwarg:
435
+ warnings.warn(
436
+ "GradScaler is going to stop passing itself as a keyword argument to the passed "
437
+ "optimizer. In the near future GradScaler registers `grad_scale: Tensor` and "
438
+ "`found_inf: Tensor` to the passed optimizer and let the optimizer use them directly.",
439
+ FutureWarning,
440
+ stacklevel=2,
441
+ )
442
+ kwargs_.update({"grad_scaler": self})
443
+ else:
444
+ if optimizer_state["stage"] is OptState.READY:
445
+ self._check_inf_per_device(optimizer)
446
+ scaler = self._get_scale_async()
447
+ if scaler is None:
448
+ raise AssertionError("_get_scale_async returned None")
449
+ found_inf = cast(
450
+ torch.Tensor,
451
+ sum(
452
+ [ # noqa: C419
453
+ t.to(scaler.device, non_blocking=True)
454
+ for t in optimizer_state["found_inf_per_device"].values()
455
+ ]
456
+ ),
457
+ )
458
+ # Take the product of the scales, if the user has already set `optimizer.grad_scale`.
459
+ optimizer.grad_scale = ( # type: ignore[attr-defined]
460
+ getattr(optimizer, "grad_scale", None)
461
+ if optimizer_state["stage"] == OptState.UNSCALED
462
+ else scaler * getattr(optimizer, "grad_scale", 1)
463
+ )
464
+ optimizer.found_inf = found_inf # type: ignore[attr-defined]
465
+ retval = optimizer.step(*args, **kwargs_)
466
+ optimizer_state["stage"] = OptState.STEPPED
467
+ if not has_grad_scaler_kwarg:
468
+ del optimizer.grad_scale # type: ignore[attr-defined]
469
+ del optimizer.found_inf # type: ignore[attr-defined]
470
+ return retval
471
+
472
+ if optimizer_state["stage"] is OptState.READY:
473
+ self.unscale_(optimizer)
474
+
475
+ if len(optimizer_state["found_inf_per_device"]) == 0:
476
+ raise AssertionError("No inf checks were recorded for this optimizer.")
477
+
478
+ retval = self._maybe_opt_step(optimizer, optimizer_state, *args, **kwargs)
479
+
480
+ optimizer_state["stage"] = OptState.STEPPED
481
+
482
+ return retval
483
+
484
+ def update(self, new_scale: Optional[Union[float, torch.Tensor]] = None) -> None:
485
+ """Update the scale factor.
486
+
487
+ If any optimizer steps were skipped the scale is multiplied by ``backoff_factor``
488
+ to reduce it. If ``growth_interval`` unskipped iterations occurred consecutively,
489
+ the scale is multiplied by ``growth_factor`` to increase it.
490
+
491
+ Passing ``new_scale`` sets the new scale value manually. (``new_scale`` is not
492
+ used directly, it's used to fill GradScaler's internal scale tensor. So if
493
+ ``new_scale`` was a tensor, later in-place changes to that tensor will not further
494
+ affect the scale GradScaler uses internally.)
495
+
496
+ Args:
497
+ new_scale (float or :class:`torch.Tensor`, optional, default=None): New scale factor.
498
+
499
+ .. warning::
500
+ :meth:`update` should only be called at the end of the iteration, after ``scaler.step(optimizer)`` has
501
+ been invoked for all optimizers used this iteration.
502
+
503
+ .. warning::
504
+ For performance reasons, we do not check the scale factor value to avoid synchronizations,
505
+ so the scale factor is not guaranteed to be above 1. If the scale falls below 1 and/or
506
+ you are seeing NaNs in your gradients or loss, something is likely wrong. For example,
507
+ bf16-pretrained models are often incompatible with AMP/fp16 due to differing dynamic ranges.
508
+ """
509
+ if not self._enabled:
510
+ return
511
+
512
+ _scale, _growth_tracker = self._check_scale_growth_tracker("update")
513
+
514
+ if new_scale is not None:
515
+ if self._scale is None:
516
+ raise AssertionError("_scale is None in update")
517
+ # Accept a new user-defined scale.
518
+ if isinstance(new_scale, float):
519
+ self._scale.fill_(new_scale)
520
+ else:
521
+ reason = (
522
+ "new_scale should be a float or a 1-element torch.cuda.FloatTensor or "
523
+ "torch.FloatTensor with requires_grad=False."
524
+ )
525
+ if new_scale.device.type != self._device:
526
+ raise AssertionError(reason)
527
+ if new_scale.numel() != 1:
528
+ raise AssertionError(reason)
529
+ if new_scale.requires_grad is True:
530
+ raise AssertionError(reason)
531
+ self._scale.copy_(new_scale)
532
+ else:
533
+ # Consume shared inf/nan data collected from optimizers to update the scale.
534
+ # If all found_inf tensors are on the same device as self._scale, this operation is asynchronous.
535
+ found_infs = [
536
+ found_inf.to(device=_scale.device, non_blocking=True)
537
+ for state in self._per_optimizer_states.values()
538
+ for found_inf in state["found_inf_per_device"].values()
539
+ ]
540
+
541
+ if len(found_infs) == 0:
542
+ raise AssertionError("No inf checks were recorded prior to update.")
543
+
544
+ found_inf_combined = found_infs[0]
545
+ if len(found_infs) > 1:
546
+ for i in range(1, len(found_infs)):
547
+ found_inf_combined += found_infs[i]
548
+
549
+ torch._amp_update_scale_(
550
+ _scale,
551
+ _growth_tracker,
552
+ found_inf_combined,
553
+ self._growth_factor,
554
+ self._backoff_factor,
555
+ self._growth_interval,
556
+ )
557
+
558
+ # To prepare for next iteration, clear the data collected from optimizers this iteration.
559
+ self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
560
+
561
+ def _get_scale_async(self) -> Optional[torch.Tensor]:
562
+ return self._scale
563
+
564
+ def get_scale(self) -> float:
565
+ """Return a Python float containing the current scale, or 1.0 if scaling is disabled.
566
+
567
+ .. warning::
568
+ :meth:`get_scale` incurs a CPU-GPU sync.
569
+ """
570
+ if self._enabled:
571
+ return (
572
+ self._init_scale
573
+ if (scale := self._get_scale_async()) is None
574
+ else cast(float, scale.item())
575
+ )
576
+ return 1.0
577
+
578
+ def get_growth_factor(self) -> float:
579
+ r"""Return a Python float containing the scale growth factor."""
580
+ return self._growth_factor
581
+
582
+ def set_growth_factor(self, new_factor: float) -> None:
583
+ r"""Set a new scale growth factor.
584
+
585
+ Args:
586
+ new_scale (float): Value to use as the new scale growth factor.
587
+ """
588
+ self._growth_factor = new_factor
589
+
590
+ def get_backoff_factor(self) -> float:
591
+ r"""Return a Python float containing the scale backoff factor."""
592
+ return self._backoff_factor
593
+
594
+ def set_backoff_factor(self, new_factor: float) -> None:
595
+ r"""Set a new scale backoff factor.
596
+
597
+ Args:
598
+ new_scale (float): Value to use as the new scale backoff factor.
599
+ """
600
+ self._backoff_factor = new_factor
601
+
602
+ def get_growth_interval(self) -> int:
603
+ r"""Return a Python int containing the growth interval."""
604
+ return self._growth_interval
605
+
606
+ def set_growth_interval(self, new_interval: int) -> None:
607
+ r"""Set a new growth interval.
608
+
609
+ Args:
610
+ new_interval (int): Value to use as the new growth interval.
611
+ """
612
+ self._growth_interval = new_interval
613
+
614
+ def _get_growth_tracker(self) -> int:
615
+ if self._enabled:
616
+ return (
617
+ self._init_growth_tracker
618
+ if self._growth_tracker is None
619
+ else cast(int, self._growth_tracker.item())
620
+ )
621
+ return 0
622
+
623
+ def is_enabled(self) -> bool:
624
+ r"""Return a bool indicating whether this instance is enabled."""
625
+ return self._enabled
626
+
627
+ def state_dict(self) -> dict[str, Any]:
628
+ r"""Return the state of the scaler as a :class:`dict`.
629
+
630
+ It contains five entries:
631
+
632
+ * ``"scale"`` - a Python float containing the current scale
633
+ * ``"growth_factor"`` - a Python float containing the current growth factor
634
+ * ``"backoff_factor"`` - a Python float containing the current backoff factor
635
+ * ``"growth_interval"`` - a Python int containing the current growth interval
636
+ * ``"_growth_tracker"`` - a Python int containing the number of recent consecutive unskipped steps.
637
+
638
+ If this instance is not enabled, returns an empty dict.
639
+
640
+ .. note::
641
+ If you wish to checkpoint the scaler's state after a particular iteration, :meth:`state_dict`
642
+ should be called after :meth:`update`.
643
+ """
644
+ if self._enabled:
645
+ return {
646
+ "scale": self.get_scale(),
647
+ "growth_factor": self._growth_factor,
648
+ "backoff_factor": self._backoff_factor,
649
+ "growth_interval": self._growth_interval,
650
+ "_growth_tracker": self._get_growth_tracker(),
651
+ }
652
+ return {}
653
+
654
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
655
+ r"""Load the scaler state.
656
+
657
+ If this instance is disabled, :meth:`load_state_dict` is a no-op.
658
+
659
+ Args:
660
+ state_dict(dict): scaler state. Should be an object returned from a call to :meth:`state_dict`.
661
+ """
662
+ if not self._enabled:
663
+ return
664
+
665
+ if len(state_dict) == 0:
666
+ raise RuntimeError(
667
+ "The source state dict is empty, possibly because it was saved "
668
+ "from a disabled instance of GradScaler."
669
+ )
670
+
671
+ self._init_scale = cast(float, state_dict["scale"])
672
+ if self._scale is not None:
673
+ self._scale.fill_(state_dict["scale"])
674
+ self._growth_factor = cast(float, state_dict["growth_factor"])
675
+ self._backoff_factor = cast(float, state_dict["backoff_factor"])
676
+ self._growth_interval = cast(int, state_dict["growth_interval"])
677
+ self._init_growth_tracker = cast(int, state_dict["_growth_tracker"])
678
+ if self._growth_tracker is not None:
679
+ self._growth_tracker.fill_(state_dict["_growth_tracker"])
680
+
681
+ def __getstate__(self) -> dict[str, Any]:
682
+ state = self.__dict__.copy()
683
+ if self._enabled:
684
+ if len(self._per_optimizer_states) != 0:
685
+ raise AssertionError(
686
+ "A GradScaler instance may only be pickled at the beginning "
687
+ "of an iteration, or at the end after scaler.update()."
688
+ )
689
+ # Pickling _scale and _growth_tracker Tensors directly triggers
690
+ # "warnings.warn("pickle support for Storage will be removed in 1.5..."
691
+ # so instead, we set the unpickled instance up to reinitialize them lazily.
692
+ state["_init_scale"] = self.get_scale()
693
+ state["_init_growth_tracker"] = self._get_growth_tracker()
694
+ state["_scale"] = None
695
+ state["_growth_tracker"] = None
696
+ return state
697
+
698
+ def __setstate__(self, state: dict[str, Any]) -> None:
699
+ self.__dict__.update(state)
700
+
701
+ def _check_inf_per_device(self, optimizer: torch.optim.Optimizer) -> dict[str, Any]:
702
+ _scale, _ = self._check_scale_growth_tracker("_check_inf_per_device")
703
+
704
+ dummy_inv_scale = torch.full((), 1.0, dtype=torch.float32, device=_scale.device)
705
+ found_inf = torch.full((), 0.0, dtype=torch.float32, device=_scale.device)
706
+
707
+ self._per_optimizer_states[id(optimizer)]["found_inf_per_device"] = (
708
+ self._unscale_grads_(optimizer, dummy_inv_scale, found_inf, True)
709
+ )
710
+
711
+ return self._per_optimizer_states[id(optimizer)]["found_inf_per_device"]
712
+
713
+ def _found_inf_per_device(self, optimizer: torch.optim.Optimizer) -> dict[str, Any]:
714
+ return self._per_optimizer_states[id(optimizer)]["found_inf_per_device"]
.venv/lib/python3.10/site-packages/torch/ao/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # torch.ao is a package with a lot of interdependencies.
2
+ # We will use lazy import to avoid cyclic dependencies here.
3
+
4
+ from typing import TYPE_CHECKING as _TYPE_CHECKING
5
+
6
+
7
+ if _TYPE_CHECKING:
8
+ from types import ModuleType
9
+
10
+ from torch.ao import ( # noqa: TC004
11
+ nn as nn,
12
+ ns as ns,
13
+ pruning as pruning,
14
+ quantization as quantization,
15
+ )
16
+
17
+
18
+ __all__ = [
19
+ "nn",
20
+ "ns",
21
+ "pruning",
22
+ "quantization",
23
+ ]
24
+
25
+
26
+ def __getattr__(name: str) -> "ModuleType":
27
+ if name in __all__:
28
+ import importlib
29
+
30
+ return importlib.import_module("." + name, __name__)
31
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
.venv/lib/python3.10/site-packages/torch/ao/nn/__init__.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # We are exposing all subpackages to the end-user.
2
+ # Because of possible inter-dependency, we want to avoid
3
+ # the cyclic imports, thus implementing lazy version
4
+ # as per https://peps.python.org/pep-0562/
5
+
6
+ from typing import TYPE_CHECKING as _TYPE_CHECKING
7
+
8
+
9
+ if _TYPE_CHECKING:
10
+ from types import ModuleType
11
+
12
+ from torch.ao.nn import ( # noqa: TC004
13
+ intrinsic as intrinsic,
14
+ qat as qat,
15
+ quantizable as quantizable,
16
+ quantized as quantized,
17
+ sparse as sparse,
18
+ )
19
+
20
+
21
+ __all__ = [
22
+ "intrinsic",
23
+ "qat",
24
+ "quantizable",
25
+ "quantized",
26
+ "sparse",
27
+ ]
28
+
29
+
30
+ def __getattr__(name: str) -> "ModuleType":
31
+ if name in __all__:
32
+ import importlib
33
+
34
+ return importlib.import_module("." + name, __name__)
35
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/__init__.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import types
2
+
3
+ from .modules import * # noqa: F403
4
+ from .modules.fused import _FusedModule # noqa: F403
5
+
6
+
7
+ # # Subpackages
8
+ # from . import qat # noqa: F403
9
+ # from . import quantized # noqa: F403
10
+
11
+ __all__ = [
12
+ "ConvBn1d",
13
+ "ConvBn2d",
14
+ "ConvBn3d",
15
+ "ConvBnReLU1d",
16
+ "ConvBnReLU2d",
17
+ "ConvBnReLU3d",
18
+ "ConvReLU1d",
19
+ "ConvReLU2d",
20
+ "ConvReLU3d",
21
+ "LinearReLU",
22
+ "BNReLU2d",
23
+ "BNReLU3d",
24
+ "LinearBn1d",
25
+ "LinearLeakyReLU",
26
+ "LinearTanh",
27
+ "ConvAdd2d",
28
+ "ConvAddReLU2d",
29
+ ]
30
+
31
+
32
+ # We are exposing all subpackages to the end-user.
33
+ # Because of possible inter-dependency, we want to avoid
34
+ # the cyclic imports, thus implementing lazy version
35
+ # as per https://peps.python.org/pep-0562/
36
+ def __getattr__(name: str) -> types.ModuleType:
37
+ if name in __all__:
38
+ import importlib
39
+
40
+ return importlib.import_module("." + name, __name__)
41
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/modules/__init__.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .fused import ( # noqa: F401
2
+ _FusedModule,
3
+ BNReLU2d,
4
+ BNReLU3d,
5
+ ConvAdd2d,
6
+ ConvAddReLU2d,
7
+ ConvBn1d,
8
+ ConvBn2d,
9
+ ConvBn3d,
10
+ ConvBnReLU1d,
11
+ ConvBnReLU2d,
12
+ ConvBnReLU3d,
13
+ ConvReLU1d,
14
+ ConvReLU2d,
15
+ ConvReLU3d,
16
+ LinearBn1d,
17
+ LinearLeakyReLU,
18
+ LinearReLU,
19
+ LinearTanh,
20
+ )
21
+
22
+
23
+ __all__ = [
24
+ "ConvBn1d",
25
+ "ConvBn2d",
26
+ "ConvBn3d",
27
+ "ConvBnReLU1d",
28
+ "ConvBnReLU2d",
29
+ "ConvBnReLU3d",
30
+ "ConvReLU1d",
31
+ "ConvReLU2d",
32
+ "ConvReLU3d",
33
+ "LinearReLU",
34
+ "BNReLU2d",
35
+ "BNReLU3d",
36
+ "LinearBn1d",
37
+ "LinearLeakyReLU",
38
+ "LinearTanh",
39
+ "ConvAdd2d",
40
+ "ConvAddReLU2d",
41
+ ]
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/modules/fused.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ from torch.nn import (
4
+ BatchNorm1d,
5
+ BatchNorm2d,
6
+ BatchNorm3d,
7
+ Conv1d,
8
+ Conv2d,
9
+ Conv3d,
10
+ Linear,
11
+ ReLU,
12
+ )
13
+ from torch.nn.utils.parametrize import type_before_parametrizations
14
+
15
+
16
+ __all__ = [
17
+ "ConvReLU1d",
18
+ "ConvReLU2d",
19
+ "ConvReLU3d",
20
+ "LinearReLU",
21
+ "ConvBn1d",
22
+ "ConvBn2d",
23
+ "ConvBnReLU1d",
24
+ "ConvBnReLU2d",
25
+ "ConvBn3d",
26
+ "ConvBnReLU3d",
27
+ "BNReLU2d",
28
+ "BNReLU3d",
29
+ "LinearBn1d",
30
+ "LinearLeakyReLU",
31
+ "LinearTanh",
32
+ "ConvAdd2d",
33
+ "ConvAddReLU2d",
34
+ ]
35
+
36
+
37
+ # Used for identifying intrinsic modules used in quantization
38
+ class _FusedModule(torch.nn.Sequential):
39
+ pass
40
+
41
+
42
+ class ConvReLU1d(_FusedModule):
43
+ r"""This is a sequential container which calls the Conv1d and ReLU modules.
44
+ During quantization this will be replaced with the corresponding fused module."""
45
+
46
+ def __init__(self, conv, relu):
47
+ if not (
48
+ type_before_parametrizations(conv) == Conv1d
49
+ and type_before_parametrizations(relu) == ReLU
50
+ ):
51
+ raise AssertionError(
52
+ f"Incorrect types for input modules: "
53
+ f"{type_before_parametrizations(conv).__name__} and "
54
+ f"{type_before_parametrizations(relu).__name__}"
55
+ )
56
+ super().__init__(conv, relu)
57
+
58
+
59
+ class ConvReLU2d(_FusedModule):
60
+ r"""This is a sequential container which calls the Conv2d and ReLU modules.
61
+ During quantization this will be replaced with the corresponding fused module."""
62
+
63
+ def __init__(self, conv, relu):
64
+ if not (
65
+ type_before_parametrizations(conv) == Conv2d
66
+ and type_before_parametrizations(relu) == ReLU
67
+ ):
68
+ raise AssertionError(
69
+ f"Incorrect types for input modules: "
70
+ f"{type_before_parametrizations(conv).__name__} and "
71
+ f"{type_before_parametrizations(relu).__name__}"
72
+ )
73
+ super().__init__(conv, relu)
74
+
75
+
76
+ class ConvReLU3d(_FusedModule):
77
+ r"""This is a sequential container which calls the Conv3d and ReLU modules.
78
+ During quantization this will be replaced with the corresponding fused module."""
79
+
80
+ def __init__(self, conv, relu):
81
+ if not (
82
+ type_before_parametrizations(conv) == Conv3d
83
+ and type_before_parametrizations(relu) == ReLU
84
+ ):
85
+ raise AssertionError(
86
+ f"Incorrect types for input modules: "
87
+ f"{type_before_parametrizations(conv).__name__} and "
88
+ f"{type_before_parametrizations(relu).__name__}"
89
+ )
90
+ super().__init__(conv, relu)
91
+
92
+
93
+ class LinearReLU(_FusedModule):
94
+ r"""This is a sequential container which calls the Linear and ReLU modules.
95
+ During quantization this will be replaced with the corresponding fused module."""
96
+
97
+ def __init__(self, linear, relu):
98
+ if not (
99
+ type_before_parametrizations(linear) == Linear
100
+ and type_before_parametrizations(relu) == ReLU
101
+ ):
102
+ raise AssertionError(
103
+ f"Incorrect types for input modules: "
104
+ f"{type_before_parametrizations(linear).__name__} and "
105
+ f"{type_before_parametrizations(relu).__name__}"
106
+ )
107
+ super().__init__(linear, relu)
108
+
109
+
110
+ class ConvBn1d(_FusedModule):
111
+ r"""This is a sequential container which calls the Conv 1d and Batch Norm 1d modules.
112
+ During quantization this will be replaced with the corresponding fused module."""
113
+
114
+ def __init__(self, conv, bn):
115
+ if not (
116
+ type_before_parametrizations(conv) == Conv1d
117
+ and type_before_parametrizations(bn) == BatchNorm1d
118
+ ):
119
+ raise AssertionError(
120
+ f"Incorrect types for input modules: "
121
+ f"{type_before_parametrizations(conv).__name__} and "
122
+ f"{type_before_parametrizations(bn).__name__}"
123
+ )
124
+ super().__init__(conv, bn)
125
+
126
+
127
+ class ConvBn2d(_FusedModule):
128
+ r"""This is a sequential container which calls the Conv 2d and Batch Norm 2d modules.
129
+ During quantization this will be replaced with the corresponding fused module."""
130
+
131
+ def __init__(self, conv, bn):
132
+ if not (
133
+ type_before_parametrizations(conv) == Conv2d
134
+ and type_before_parametrizations(bn) == BatchNorm2d
135
+ ):
136
+ raise AssertionError(
137
+ f"Incorrect types for input modules: "
138
+ f"{type_before_parametrizations(conv).__name__} and "
139
+ f"{type_before_parametrizations(bn).__name__}"
140
+ )
141
+ super().__init__(conv, bn)
142
+
143
+
144
+ class ConvBnReLU1d(_FusedModule):
145
+ r"""This is a sequential container which calls the Conv 1d, Batch Norm 1d, and ReLU modules.
146
+ During quantization this will be replaced with the corresponding fused module."""
147
+
148
+ def __init__(self, conv, bn, relu):
149
+ if not (
150
+ type_before_parametrizations(conv) == Conv1d
151
+ and type_before_parametrizations(bn) == BatchNorm1d
152
+ and type_before_parametrizations(relu) == ReLU
153
+ ):
154
+ raise AssertionError(
155
+ f"Incorrect types for input modules: "
156
+ f"{type_before_parametrizations(conv).__name__}, "
157
+ f"{type_before_parametrizations(bn).__name__}, and "
158
+ f"{type_before_parametrizations(relu).__name__}"
159
+ )
160
+ super().__init__(conv, bn, relu)
161
+
162
+
163
+ class ConvBnReLU2d(_FusedModule):
164
+ r"""This is a sequential container which calls the Conv 2d, Batch Norm 2d, and ReLU modules.
165
+ During quantization this will be replaced with the corresponding fused module."""
166
+
167
+ def __init__(self, conv, bn, relu):
168
+ if not (
169
+ type_before_parametrizations(conv) == Conv2d
170
+ and type_before_parametrizations(bn) == BatchNorm2d
171
+ and type_before_parametrizations(relu) == ReLU
172
+ ):
173
+ raise AssertionError(
174
+ f"Incorrect types for input modules: "
175
+ f"{type_before_parametrizations(conv).__name__}, "
176
+ f"{type_before_parametrizations(bn).__name__}, and "
177
+ f"{type_before_parametrizations(relu).__name__}"
178
+ )
179
+ super().__init__(conv, bn, relu)
180
+
181
+
182
+ class ConvBn3d(_FusedModule):
183
+ r"""This is a sequential container which calls the Conv 3d and Batch Norm 3d modules.
184
+ During quantization this will be replaced with the corresponding fused module."""
185
+
186
+ def __init__(self, conv, bn):
187
+ if not (
188
+ type_before_parametrizations(conv) == Conv3d
189
+ and type_before_parametrizations(bn) == BatchNorm3d
190
+ ):
191
+ raise AssertionError(
192
+ f"Incorrect types for input modules: "
193
+ f"{type_before_parametrizations(conv).__name__} and "
194
+ f"{type_before_parametrizations(bn).__name__}"
195
+ )
196
+ super().__init__(conv, bn)
197
+
198
+
199
+ class ConvBnReLU3d(_FusedModule):
200
+ r"""This is a sequential container which calls the Conv 3d, Batch Norm 3d, and ReLU modules.
201
+ During quantization this will be replaced with the corresponding fused module."""
202
+
203
+ def __init__(self, conv, bn, relu):
204
+ if not (
205
+ type_before_parametrizations(conv) == Conv3d
206
+ and type_before_parametrizations(bn) == BatchNorm3d
207
+ and type_before_parametrizations(relu) == ReLU
208
+ ):
209
+ raise AssertionError(
210
+ f"Incorrect types for input modules: "
211
+ f"{type_before_parametrizations(conv).__name__}, "
212
+ f"{type_before_parametrizations(bn).__name__}, and "
213
+ f"{type_before_parametrizations(relu).__name__}"
214
+ )
215
+ super().__init__(conv, bn, relu)
216
+
217
+
218
+ class BNReLU2d(_FusedModule):
219
+ r"""This is a sequential container which calls the BatchNorm 2d and ReLU modules.
220
+ During quantization this will be replaced with the corresponding fused module."""
221
+
222
+ def __init__(self, batch_norm, relu):
223
+ if not (
224
+ type_before_parametrizations(batch_norm) == BatchNorm2d
225
+ and type_before_parametrizations(relu) == ReLU
226
+ ):
227
+ raise AssertionError(
228
+ f"Incorrect types for input modules: "
229
+ f"{type_before_parametrizations(batch_norm).__name__} and "
230
+ f"{type_before_parametrizations(relu).__name__}"
231
+ )
232
+ super().__init__(batch_norm, relu)
233
+
234
+
235
+ class BNReLU3d(_FusedModule):
236
+ r"""This is a sequential container which calls the BatchNorm 3d and ReLU modules.
237
+ During quantization this will be replaced with the corresponding fused module."""
238
+
239
+ def __init__(self, batch_norm, relu):
240
+ if not (
241
+ type_before_parametrizations(batch_norm) == BatchNorm3d
242
+ and type_before_parametrizations(relu) == ReLU
243
+ ):
244
+ raise AssertionError(
245
+ f"Incorrect types for input modules: "
246
+ f"{type_before_parametrizations(batch_norm).__name__} and "
247
+ f"{type_before_parametrizations(relu).__name__}"
248
+ )
249
+ super().__init__(batch_norm, relu)
250
+
251
+
252
+ class LinearBn1d(_FusedModule):
253
+ r"""This is a sequential container which calls the Linear and BatchNorm1d modules.
254
+ During quantization this will be replaced with the corresponding fused module."""
255
+
256
+ def __init__(self, linear, bn):
257
+ if not (
258
+ type_before_parametrizations(linear) == Linear
259
+ and type_before_parametrizations(bn) == BatchNorm1d
260
+ ):
261
+ raise AssertionError(
262
+ f"Incorrect types for input modules: "
263
+ f"{type_before_parametrizations(linear).__name__} and "
264
+ f"{type_before_parametrizations(bn).__name__}"
265
+ )
266
+ super().__init__(linear, bn)
267
+
268
+
269
+ class LinearLeakyReLU(_FusedModule):
270
+ r"""This is a sequential container which calls the Linear and LeakyReLU modules.
271
+ During quantization this will be replaced with the corresponding fused module."""
272
+
273
+ def __init__(self, linear, leaky_relu):
274
+ if not (type(linear) is Linear and type(leaky_relu) is torch.nn.LeakyReLU):
275
+ raise AssertionError(
276
+ f"Incorrect types for input modules: "
277
+ f"{type(linear).__name__} and {type(leaky_relu).__name__}"
278
+ )
279
+ super().__init__(linear, leaky_relu)
280
+
281
+
282
+ class LinearTanh(_FusedModule):
283
+ r"""This is a sequential container which calls the Linear and Tanh modules.
284
+ During quantization this will be replaced with the corresponding fused module."""
285
+
286
+ def __init__(self, linear, tanh):
287
+ if not (type(linear) is Linear and type(tanh) is torch.nn.Tanh):
288
+ raise AssertionError(
289
+ f"Incorrect types for input modules: "
290
+ f"{type(linear).__name__} and {type(tanh).__name__}"
291
+ )
292
+ super().__init__(linear, tanh)
293
+
294
+
295
+ class ConvAdd2d(_FusedModule):
296
+ r"""This is a sequential container which calls the Conv2d modules with extra Add.
297
+ During quantization this will be replaced with the corresponding fused module."""
298
+
299
+ def __init__(self, conv, add):
300
+ super().__init__(conv)
301
+ self.add = add
302
+
303
+ def forward(self, x1, x2): # type: ignore[override]
304
+ r"""Applies convolution to x1 and adds the result to x2."""
305
+ return self.add(self[0](x1), x2)
306
+
307
+
308
+ class ConvAddReLU2d(_FusedModule):
309
+ r"""This is a sequential container which calls the Conv2d, add, Relu.
310
+ During quantization this will be replaced with the corresponding fused module."""
311
+
312
+ def __init__(self, conv, add, relu):
313
+ super().__init__(conv)
314
+ self.add = add
315
+ self.relu = relu
316
+
317
+ def forward(self, x1, x2): # type: ignore[override]
318
+ r"""Applies convolution to x1, adds the result to x2, and applies ReLU."""
319
+ return self.relu(self.add(self[0](x1), x2))
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modules import * # noqa: F403
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .conv_fused import (
2
+ ConvBn1d,
3
+ ConvBn2d,
4
+ ConvBn3d,
5
+ ConvBnReLU1d,
6
+ ConvBnReLU2d,
7
+ ConvBnReLU3d,
8
+ ConvReLU1d,
9
+ ConvReLU2d,
10
+ ConvReLU3d,
11
+ freeze_bn_stats,
12
+ update_bn_stats,
13
+ )
14
+ from .linear_fused import LinearBn1d
15
+ from .linear_relu import LinearReLU
16
+
17
+
18
+ __all__ = [
19
+ "LinearReLU",
20
+ "LinearBn1d",
21
+ "ConvReLU1d",
22
+ "ConvReLU2d",
23
+ "ConvReLU3d",
24
+ "ConvBn1d",
25
+ "ConvBn2d",
26
+ "ConvBn3d",
27
+ "ConvBnReLU1d",
28
+ "ConvBnReLU2d",
29
+ "ConvBnReLU3d",
30
+ "update_bn_stats",
31
+ "freeze_bn_stats",
32
+ ]
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/conv_fused.py ADDED
@@ -0,0 +1,971 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ from typing import ClassVar
4
+
5
+ import torch
6
+ import torch.ao.nn.intrinsic as nni
7
+ import torch.ao.nn.qat as nnqat
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from torch.nn import init
11
+ from torch.nn.modules.utils import _pair, _single, _triple
12
+ from torch.nn.parameter import Parameter
13
+ from torch.nn.utils import fuse_conv_bn_weights
14
+
15
+
16
+ __all__ = [
17
+ "ConvBn1d",
18
+ "ConvBnReLU1d",
19
+ "ConvReLU1d",
20
+ "ConvBn2d",
21
+ "ConvBnReLU2d",
22
+ "ConvReLU2d",
23
+ "ConvBn3d",
24
+ "ConvBnReLU3d",
25
+ "ConvReLU3d",
26
+ "update_bn_stats",
27
+ "freeze_bn_stats",
28
+ ]
29
+ _BN_CLASS_MAP = {
30
+ 1: nn.BatchNorm1d,
31
+ 2: nn.BatchNorm2d,
32
+ 3: nn.BatchNorm3d,
33
+ }
34
+
35
+
36
+ class _ConvBnNd(nn.modules.conv._ConvNd, nni._FusedModule):
37
+ _version = 2
38
+ _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]]
39
+
40
+ def __init__(
41
+ self,
42
+ # ConvNd args
43
+ in_channels,
44
+ out_channels,
45
+ kernel_size,
46
+ stride,
47
+ padding,
48
+ dilation,
49
+ transposed,
50
+ output_padding,
51
+ groups,
52
+ bias,
53
+ padding_mode,
54
+ # BatchNormNd args
55
+ # num_features: out_channels
56
+ eps=1e-05,
57
+ momentum=0.1,
58
+ # affine: True
59
+ # track_running_stats: True
60
+ # Args for this module
61
+ freeze_bn=False,
62
+ qconfig=None,
63
+ dim=2,
64
+ ):
65
+ nn.modules.conv._ConvNd.__init__(
66
+ self,
67
+ in_channels,
68
+ out_channels,
69
+ kernel_size,
70
+ stride,
71
+ padding,
72
+ dilation,
73
+ transposed,
74
+ output_padding,
75
+ groups,
76
+ False,
77
+ padding_mode,
78
+ )
79
+ if not qconfig:
80
+ raise AssertionError("qconfig must be provided for QAT module")
81
+ self.qconfig = qconfig
82
+ self.freeze_bn = freeze_bn if self.training else True
83
+ self.bn = _BN_CLASS_MAP[dim](out_channels, eps, momentum, True, True)
84
+ self.weight_fake_quant = self.qconfig.weight()
85
+ if bias:
86
+ self.bias = Parameter(torch.empty(out_channels))
87
+ else:
88
+ self.register_parameter("bias", None)
89
+ self.reset_bn_parameters()
90
+
91
+ # this needs to be called after reset_bn_parameters,
92
+ # as they modify the same state
93
+ if self.training:
94
+ if freeze_bn:
95
+ self.freeze_bn_stats()
96
+ else:
97
+ self.update_bn_stats()
98
+ else:
99
+ self.freeze_bn_stats()
100
+
101
+ self._enable_slow_path_for_better_numerical_stability = False
102
+
103
+ def reset_running_stats(self):
104
+ self.bn.reset_running_stats()
105
+
106
+ def reset_bn_parameters(self):
107
+ self.bn.reset_running_stats()
108
+ init.uniform_(self.bn.weight)
109
+ init.zeros_(self.bn.bias)
110
+ # note: below is actually for conv, not BN
111
+ if self.bias is not None:
112
+ fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
113
+ bound = 1 / math.sqrt(fan_in)
114
+ init.uniform_(self.bias, -bound, bound)
115
+
116
+ def update_bn_stats(self):
117
+ self.freeze_bn = False
118
+ self.bn.training = True
119
+ return self
120
+
121
+ def freeze_bn_stats(self):
122
+ self.freeze_bn = True
123
+ self.bn.training = False
124
+ return self
125
+
126
+ def _forward(self, input):
127
+ if self._enable_slow_path_for_better_numerical_stability:
128
+ return self._forward_slow(input)
129
+ return self._forward_approximate(input)
130
+
131
+ def _forward_approximate(self, input):
132
+ """Approximated method to fuse conv and bn. It requires only one forward pass.
133
+ conv_orig = conv / scale_factor where scale_factor = bn.weight / running_std
134
+ """
135
+ if self.bn.running_var is None:
136
+ raise AssertionError("self.bn.running_var must not be None")
137
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
138
+ scale_factor = self.bn.weight / running_std
139
+ weight_shape = [1] * len(self.weight.shape)
140
+ weight_shape[0] = -1
141
+ bias_shape = [1] * len(self.weight.shape)
142
+ bias_shape[1] = -1
143
+ scaled_weight = self.weight_fake_quant(
144
+ self.weight * scale_factor.reshape(weight_shape)
145
+ )
146
+ # using zero bias here since the bias for original conv
147
+ # will be added later
148
+ if self.bias is not None:
149
+ zero_bias = torch.zeros_like(self.bias, dtype=input.dtype)
150
+ else:
151
+ zero_bias = torch.zeros(
152
+ self.out_channels, device=scaled_weight.device, dtype=input.dtype
153
+ )
154
+ conv = self._conv_forward(input, scaled_weight, zero_bias)
155
+ conv_orig = conv / scale_factor.reshape(bias_shape)
156
+ if self.bias is not None:
157
+ conv_orig = conv_orig + self.bias.reshape(bias_shape)
158
+ conv = self.bn(conv_orig)
159
+ return conv
160
+
161
+ def _forward_slow(self, input):
162
+ """
163
+ A more accurate but slow method to compute conv bn fusion, following https://arxiv.org/pdf/1806.08342.pdf
164
+ It requires two forward passes but handles the case bn.weight == 0
165
+
166
+ Conv: Y = WX + B_c
167
+ Conv without bias: Y0 = WX = Y - B_c, Y = Y0 + B_c
168
+
169
+ Batch statistics:
170
+ mean_Y = Y.mean()
171
+ = Y0.mean() + B_c
172
+ var_Y = (Y - mean_Y)^2.mean()
173
+ = (Y0 - Y0.mean())^2.mean()
174
+ BN (r: bn.weight, beta: bn.bias):
175
+ Z = r * (Y - mean_Y) / sqrt(var_Y + eps) + beta
176
+ = r * (Y0 - Y0.mean()) / sqrt(var_Y + eps) + beta
177
+
178
+ Fused Conv BN training (std_Y = sqrt(var_Y + eps)):
179
+ Z = (r * W / std_Y) * X + r * (B_c - mean_Y) / std_Y + beta
180
+ = (r * W / std_Y) * X - r * Y0.mean() / std_Y + beta
181
+
182
+ Fused Conv BN inference (running_std = sqrt(running_var + eps)):
183
+ Z = (r * W / running_std) * X - r * (running_mean - B_c) / running_std + beta
184
+
185
+ QAT with fused conv bn:
186
+ Z_train = fake_quant(r * W / running_std) * X * (running_std / std_Y) - r * Y0.mean() / std_Y + beta
187
+ = conv(X, fake_quant(r * W / running_std)) * (running_std / std_Y) - r * Y0.mean() / std_Y + beta
188
+ Z_inference = conv(X, fake_quant(r * W / running_std)) - r * (running_mean - B_c) / running_std + beta
189
+ """
190
+
191
+ if self.bn.running_var is None:
192
+ raise AssertionError("self.bn.running_var must not be None")
193
+ if self.bn.running_mean is None:
194
+ raise AssertionError("self.bn.running_mean must not be None")
195
+
196
+ # using zero bias here since the bias for original conv
197
+ # will be added later
198
+ zero_bias = torch.zeros(
199
+ self.out_channels, device=self.weight.device, dtype=input.dtype
200
+ )
201
+
202
+ weight_shape = [1] * len(self.weight.shape)
203
+ weight_shape[0] = -1
204
+ bias_shape = [1] * len(self.weight.shape)
205
+ bias_shape[1] = -1
206
+
207
+ if self.bn.training:
208
+ # needed to compute batch mean/std
209
+ conv_out = self._conv_forward(input, self.weight, zero_bias)
210
+ # update bn statistics
211
+ with torch.no_grad():
212
+ conv_out_bias = (
213
+ conv_out
214
+ if self.bias is None
215
+ else conv_out + self.bias.reshape(bias_shape)
216
+ )
217
+ self.bn(conv_out_bias)
218
+
219
+ # fused conv + bn without bias using bn running statistics
220
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
221
+ scale_factor = self.bn.weight / running_std
222
+ scaled_weight = self.weight_fake_quant(
223
+ self.weight * scale_factor.reshape(weight_shape)
224
+ )
225
+ # fused conv without bias for inference: (r * W / running_std) * X
226
+ conv_bn = self._conv_forward(input, scaled_weight, zero_bias)
227
+
228
+ avg_dims = [0] + list(range(2, len(self.weight.shape)))
229
+ batch_mean = conv_out.mean(avg_dims)
230
+ batch_var = torch.square(conv_out - batch_mean.reshape(bias_shape)).mean(
231
+ avg_dims
232
+ )
233
+ batch_std = torch.sqrt(batch_var + self.bn.eps)
234
+
235
+ # scale to use batch std in training mode
236
+ # conv(X, r * W / std_Y) = conv(X, r * W / running_std) * (running_std / std_Y)
237
+ unscale_factor = running_std / batch_std
238
+ conv_bn *= unscale_factor.reshape(bias_shape)
239
+
240
+ fused_mean = batch_mean
241
+ fused_std = batch_std
242
+ else:
243
+ # fused conv + bn without bias using bn running statistics
244
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
245
+ scale_factor = self.bn.weight / running_std
246
+ scaled_weight = self.weight_fake_quant(
247
+ self.weight * scale_factor.reshape(weight_shape)
248
+ )
249
+ # fused conv without bias for inference: (r * W / running_std) * X
250
+ conv_bn = self._conv_forward(input, scaled_weight, zero_bias)
251
+
252
+ fused_mean = self.bn.running_mean - (
253
+ self.bias if self.bias is not None else 0
254
+ )
255
+ fused_std = running_std
256
+
257
+ # fused bias = beta - r * mean / std
258
+ fused_bias = self.bn.bias - self.bn.weight * fused_mean / fused_std
259
+ conv_bn += fused_bias.reshape(bias_shape)
260
+
261
+ # HACK to let conv bias participate in loss to avoid DDP error (parameters
262
+ # were not used in producing loss)
263
+ if self.bias is not None:
264
+ conv_bn += (self.bias - self.bias).reshape(bias_shape)
265
+
266
+ return conv_bn
267
+
268
+ def forward(self, input):
269
+ return self._forward(input)
270
+
271
+ def train(self, mode=True):
272
+ """
273
+ Batchnorm's training behavior is using the self.training flag. Prevent
274
+ changing it if BN is frozen. This makes sure that calling `model.train()`
275
+ on a model with a frozen BN will behave properly.
276
+ """
277
+ self.training = mode
278
+ if not self.freeze_bn:
279
+ for module in self.children():
280
+ module.train(mode)
281
+ return self
282
+
283
+ # ===== Serialization version history =====
284
+ #
285
+ # Version 1/None
286
+ # self
287
+ # |--- weight : Tensor
288
+ # |--- bias : Tensor
289
+ # |--- gamma : Tensor
290
+ # |--- beta : Tensor
291
+ # |--- running_mean : Tensor
292
+ # |--- running_var : Tensor
293
+ # |--- num_batches_tracked : Tensor
294
+ #
295
+ # Version 2
296
+ # self
297
+ # |--- weight : Tensor
298
+ # |--- bias : Tensor
299
+ # |--- bn : Module
300
+ # |--- weight : Tensor (moved from v1.self.gamma)
301
+ # |--- bias : Tensor (moved from v1.self.beta)
302
+ # |--- running_mean : Tensor (moved from v1.self.running_mean)
303
+ # |--- running_var : Tensor (moved from v1.self.running_var)
304
+ # |--- num_batches_tracked : Tensor (moved from v1.self.num_batches_tracked)
305
+ def _load_from_state_dict(
306
+ self,
307
+ state_dict,
308
+ prefix,
309
+ local_metadata,
310
+ strict,
311
+ missing_keys,
312
+ unexpected_keys,
313
+ error_msgs,
314
+ ):
315
+ version = local_metadata.get("version", None)
316
+ if version is None or version == 1:
317
+ # BN related parameters and buffers were moved into the BN module for v2
318
+ v2_to_v1_names = {
319
+ "bn.weight": "gamma",
320
+ "bn.bias": "beta",
321
+ "bn.running_mean": "running_mean",
322
+ "bn.running_var": "running_var",
323
+ "bn.num_batches_tracked": "num_batches_tracked",
324
+ }
325
+ for v2_name, v1_name in v2_to_v1_names.items():
326
+ if prefix + v1_name in state_dict:
327
+ state_dict[prefix + v2_name] = state_dict[prefix + v1_name]
328
+ state_dict.pop(prefix + v1_name)
329
+ elif prefix + v2_name in state_dict:
330
+ # there was a brief period where forward compatibility
331
+ # for this module was broken (between
332
+ # https://github.com/pytorch/pytorch/pull/38478
333
+ # and https://github.com/pytorch/pytorch/pull/38820)
334
+ # and modules emitted the v2 state_dict format while
335
+ # specifying that version == 1. This patches the forward
336
+ # compatibility issue by allowing the v2 style entries to
337
+ # be used.
338
+ pass
339
+ elif strict:
340
+ missing_keys.append(prefix + v2_name)
341
+
342
+ super()._load_from_state_dict(
343
+ state_dict,
344
+ prefix,
345
+ local_metadata,
346
+ strict,
347
+ missing_keys,
348
+ unexpected_keys,
349
+ error_msgs,
350
+ )
351
+
352
+ @classmethod
353
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
354
+ r"""Create a qat module from a float module or qparams_dict
355
+
356
+ Args: `mod` a float module, either produced by torch.ao.quantization utilities
357
+ or directly from user
358
+ """
359
+ # The ignore is because _FLOAT_MODULE is a TypeVar here where the bound
360
+ # has no __name__ (code is fine though)
361
+ if type(mod) is not cls._FLOAT_MODULE:
362
+ raise AssertionError(
363
+ "qat."
364
+ + cls.__name__
365
+ + ".from_float only works for "
366
+ + cls._FLOAT_MODULE.__name__
367
+ )
368
+ if not hasattr(mod, "qconfig"):
369
+ raise AssertionError("Input float module must have qconfig defined")
370
+ if not mod.qconfig:
371
+ raise AssertionError("Input float module must have a valid qconfig")
372
+ qconfig = mod.qconfig
373
+ conv, bn = mod[0], mod[1] # type: ignore[index]
374
+ qat_convbn = cls(
375
+ conv.in_channels,
376
+ conv.out_channels,
377
+ conv.kernel_size,
378
+ conv.stride,
379
+ conv.padding,
380
+ conv.dilation,
381
+ conv.groups,
382
+ conv.bias is not None,
383
+ conv.padding_mode,
384
+ bn.eps,
385
+ bn.momentum,
386
+ False,
387
+ qconfig,
388
+ )
389
+ qat_convbn.weight = conv.weight
390
+ qat_convbn.bias = conv.bias
391
+ qat_convbn.bn.weight = bn.weight
392
+ qat_convbn.bn.bias = bn.bias
393
+ qat_convbn.bn.running_mean = bn.running_mean
394
+ qat_convbn.bn.running_var = bn.running_var
395
+ # mypy error: Cannot determine type of 'num_batches_tracked'
396
+ qat_convbn.bn.num_batches_tracked = bn.num_batches_tracked
397
+ return qat_convbn
398
+
399
+ def to_float(self):
400
+ cls = type(self)
401
+ conv = cls._FLOAT_CONV_MODULE( # type: ignore[attr-defined]
402
+ self.in_channels,
403
+ self.out_channels,
404
+ self.kernel_size,
405
+ self.stride,
406
+ self.padding,
407
+ self.dilation,
408
+ self.groups,
409
+ self.bias is not None,
410
+ self.padding_mode,
411
+ )
412
+ conv.weight = torch.nn.Parameter(self.weight.detach())
413
+ if self.bias is not None:
414
+ conv.bias = torch.nn.Parameter(self.bias.detach())
415
+
416
+ if cls._FLOAT_BN_MODULE: # type: ignore[attr-defined]
417
+ # fuse bn into conv
418
+ if self.bn.running_var is None or self.bn.running_mean is None:
419
+ raise AssertionError(
420
+ "self.bn.running_var and self.bn.running_mean must not be None"
421
+ )
422
+ conv.weight, conv.bias = fuse_conv_bn_weights(
423
+ conv.weight,
424
+ conv.bias,
425
+ self.bn.running_mean,
426
+ self.bn.running_var,
427
+ self.bn.eps,
428
+ self.bn.weight,
429
+ self.bn.bias,
430
+ )
431
+
432
+ if cls._FLOAT_RELU_MODULE: # type: ignore[attr-defined]
433
+ modules = []
434
+ modules.append(conv)
435
+ relu = cls._FLOAT_RELU_MODULE() # type: ignore[attr-defined]
436
+ modules.append(relu)
437
+ conv_relu = cls._FUSED_FLOAT_MODULE(*modules) # type: ignore[attr-defined]
438
+ conv_relu.train(self.training)
439
+ return conv_relu
440
+ else:
441
+ conv.train(self.training)
442
+ return conv
443
+
444
+
445
+ class ConvBn1d(_ConvBnNd, nn.Conv1d):
446
+ r"""
447
+ A ConvBn1d module is a module fused from Conv1d and BatchNorm1d,
448
+ attached with FakeQuantize modules for weight,
449
+ used in quantization aware training.
450
+
451
+ We combined the interface of :class:`torch.nn.Conv1d` and
452
+ :class:`torch.nn.BatchNorm1d`.
453
+
454
+ Similar to :class:`torch.nn.Conv1d`, with FakeQuantize modules initialized
455
+ to default.
456
+
457
+ Attributes:
458
+ freeze_bn:
459
+ weight_fake_quant: fake quant module for weight
460
+
461
+ """
462
+
463
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm1d]] = nn.BatchNorm1d
464
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
465
+ _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvBn1d # type: ignore[assignment]
466
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
467
+
468
+ def __init__(
469
+ self,
470
+ # Conv1d args
471
+ in_channels,
472
+ out_channels,
473
+ kernel_size,
474
+ stride=1,
475
+ padding=0,
476
+ dilation=1,
477
+ groups=1,
478
+ bias=None,
479
+ padding_mode="zeros",
480
+ # BatchNorm1d args
481
+ # num_features: out_channels
482
+ eps=1e-05,
483
+ momentum=0.1,
484
+ # affine: True
485
+ # track_running_stats: True
486
+ # Args for this module
487
+ freeze_bn=False,
488
+ qconfig=None,
489
+ ):
490
+ kernel_size = _single(kernel_size)
491
+ stride = _single(stride)
492
+ padding = _single(padding)
493
+ dilation = _single(dilation)
494
+ _ConvBnNd.__init__(
495
+ self,
496
+ in_channels,
497
+ out_channels,
498
+ kernel_size,
499
+ stride,
500
+ padding,
501
+ dilation,
502
+ False,
503
+ _single(0),
504
+ groups,
505
+ bias,
506
+ padding_mode,
507
+ eps,
508
+ momentum,
509
+ freeze_bn,
510
+ qconfig,
511
+ dim=1,
512
+ )
513
+
514
+
515
+ class ConvBnReLU1d(ConvBn1d):
516
+ r"""
517
+ A ConvBnReLU1d module is a module fused from Conv1d, BatchNorm1d and ReLU,
518
+ attached with FakeQuantize modules for weight,
519
+ used in quantization aware training.
520
+
521
+ We combined the interface of :class:`torch.nn.Conv1d` and
522
+ :class:`torch.nn.BatchNorm1d` and :class:`torch.nn.ReLU`.
523
+
524
+ Similar to `torch.nn.Conv1d`, with FakeQuantize modules initialized to
525
+ default.
526
+
527
+ Attributes:
528
+ weight_fake_quant: fake quant module for weight
529
+
530
+ """
531
+
532
+ # base class defines _FLOAT_MODULE as "ConvBn1d"
533
+ _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvBnReLU1d
534
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
535
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm1d]] = nn.BatchNorm1d
536
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
537
+ # module class after fusing bn into conv
538
+ _FUSED_FLOAT_MODULE: ClassVar[type[nn.Module] | None] = nni.ConvReLU1d
539
+
540
+ def forward(self, input):
541
+ r"""Performs forward pass through fused Conv1d, BatchNorm1d, and ReLU."""
542
+ return F.relu(self._forward(input))
543
+
544
+ @classmethod
545
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
546
+ r"""Creates a QAT module from a floating point module."""
547
+ return super().from_float(mod, use_precomputed_fake_quant)
548
+
549
+
550
+ class ConvReLU1d(nnqat.Conv1d, nni._FusedModule):
551
+ r"""A ConvReLU1d module is a fused module of Conv1d and ReLU, attached with
552
+ FakeQuantize modules for weight for
553
+ quantization aware training.
554
+
555
+ We combined the interface of :class:`~torch.nn.Conv1d` and
556
+ :class:`~torch.nn.BatchNorm1d`.
557
+
558
+ Attributes:
559
+ weight_fake_quant: fake quant module for weight
560
+
561
+ """
562
+
563
+ _FLOAT_MODULE: ClassVar[type[nni.ConvReLU1d]] = nni.ConvReLU1d # type: ignore[assignment]
564
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
565
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
566
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
567
+
568
+ def __init__(
569
+ self,
570
+ in_channels,
571
+ out_channels,
572
+ kernel_size,
573
+ stride=1,
574
+ padding=0,
575
+ dilation=1,
576
+ groups=1,
577
+ bias=True,
578
+ padding_mode="zeros",
579
+ qconfig=None,
580
+ ):
581
+ super().__init__(
582
+ in_channels,
583
+ out_channels,
584
+ kernel_size,
585
+ stride=stride,
586
+ padding=padding,
587
+ dilation=dilation,
588
+ groups=groups,
589
+ bias=bias,
590
+ # pyrefly: ignore [bad-argument-type]
591
+ padding_mode=padding_mode,
592
+ qconfig=qconfig,
593
+ )
594
+ if not qconfig:
595
+ raise AssertionError("qconfig must be provided for QAT module")
596
+ self.qconfig = qconfig
597
+ self.weight_fake_quant = self.qconfig.weight()
598
+
599
+ def forward(self, input):
600
+ r"""Performs forward pass through fused Conv1d and ReLU."""
601
+ return F.relu(
602
+ self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
603
+ )
604
+
605
+ @classmethod
606
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
607
+ r"""Creates a QAT module from a floating point module."""
608
+ return super().from_float(
609
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
610
+ )
611
+
612
+
613
+ class ConvBn2d(_ConvBnNd, nn.Conv2d):
614
+ r"""
615
+ A ConvBn2d module is a module fused from Conv2d and BatchNorm2d,
616
+ attached with FakeQuantize modules for weight,
617
+ used in quantization aware training.
618
+
619
+ We combined the interface of :class:`torch.nn.Conv2d` and
620
+ :class:`torch.nn.BatchNorm2d`.
621
+
622
+ Similar to :class:`torch.nn.Conv2d`, with FakeQuantize modules initialized
623
+ to default.
624
+
625
+ Attributes:
626
+ freeze_bn:
627
+ weight_fake_quant: fake quant module for weight
628
+
629
+ """
630
+
631
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBn2d]] = nni.ConvBn2d # type: ignore[assignment]
632
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
633
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = nn.BatchNorm2d
634
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
635
+
636
+ def __init__(
637
+ self,
638
+ # ConvNd args
639
+ in_channels,
640
+ out_channels,
641
+ kernel_size,
642
+ stride=1,
643
+ padding=0,
644
+ dilation=1,
645
+ groups=1,
646
+ bias=None,
647
+ padding_mode="zeros",
648
+ # BatchNorm2d args
649
+ # num_features: out_channels
650
+ eps=1e-05,
651
+ momentum=0.1,
652
+ # affine: True
653
+ # track_running_stats: True
654
+ # Args for this module
655
+ freeze_bn=False,
656
+ qconfig=None,
657
+ ):
658
+ kernel_size = _pair(kernel_size)
659
+ stride = _pair(stride)
660
+ padding = _pair(padding)
661
+ dilation = _pair(dilation)
662
+ _ConvBnNd.__init__(
663
+ self,
664
+ in_channels,
665
+ out_channels,
666
+ kernel_size,
667
+ stride,
668
+ padding,
669
+ dilation,
670
+ False,
671
+ _pair(0),
672
+ groups,
673
+ bias,
674
+ padding_mode,
675
+ eps,
676
+ momentum,
677
+ freeze_bn,
678
+ qconfig,
679
+ dim=2,
680
+ )
681
+
682
+
683
+ class ConvBnReLU2d(ConvBn2d):
684
+ r"""
685
+ A ConvBnReLU2d module is a module fused from Conv2d, BatchNorm2d and ReLU,
686
+ attached with FakeQuantize modules for weight,
687
+ used in quantization aware training.
688
+
689
+ We combined the interface of :class:`torch.nn.Conv2d` and
690
+ :class:`torch.nn.BatchNorm2d` and :class:`torch.nn.ReLU`.
691
+
692
+ Similar to `torch.nn.Conv2d`, with FakeQuantize modules initialized to
693
+ default.
694
+
695
+ Attributes:
696
+ weight_fake_quant: fake quant module for weight
697
+
698
+ """
699
+
700
+ # base class defines _FLOAT_MODULE as "ConvBn2d"
701
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBnReLU2d]] = nni.ConvBnReLU2d # type: ignore[assignment]
702
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
703
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm2d]] = nn.BatchNorm2d
704
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
705
+ # module class after fusing bn into conv
706
+ _FUSED_FLOAT_MODULE: ClassVar[type[nni.ConvReLU2d] | None] = nni.ConvReLU2d
707
+
708
+ def forward(self, input):
709
+ r"""Performs forward pass through fused Conv2d, BatchNorm2d, and ReLU."""
710
+ return F.relu(self._forward(input))
711
+
712
+ @classmethod
713
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
714
+ r"""Creates a QAT module from a floating point module."""
715
+ return super().from_float(mod, use_precomputed_fake_quant)
716
+
717
+
718
+ class ConvReLU2d(nnqat.Conv2d, nni._FusedModule):
719
+ r"""A ConvReLU2d module is a fused module of Conv2d and ReLU, attached with
720
+ FakeQuantize modules for weight for
721
+ quantization aware training.
722
+
723
+ We combined the interface of :class:`~torch.nn.Conv2d` and
724
+ :class:`~torch.nn.BatchNorm2d`.
725
+
726
+ Attributes:
727
+ weight_fake_quant: fake quant module for weight
728
+
729
+ """
730
+
731
+ _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvReLU2d # type: ignore[assignment]
732
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
733
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
734
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
735
+
736
+ def __init__(
737
+ self,
738
+ in_channels,
739
+ out_channels,
740
+ kernel_size,
741
+ stride=1,
742
+ padding=0,
743
+ dilation=1,
744
+ groups=1,
745
+ bias=True,
746
+ padding_mode="zeros",
747
+ qconfig=None,
748
+ ):
749
+ super().__init__(
750
+ in_channels,
751
+ out_channels,
752
+ kernel_size,
753
+ stride=stride,
754
+ padding=padding,
755
+ dilation=dilation,
756
+ groups=groups,
757
+ bias=bias,
758
+ # pyrefly: ignore [bad-argument-type]
759
+ padding_mode=padding_mode,
760
+ qconfig=qconfig,
761
+ )
762
+ if not qconfig:
763
+ raise AssertionError("qconfig must be provided for QAT module")
764
+ self.qconfig = qconfig
765
+ self.weight_fake_quant = self.qconfig.weight()
766
+
767
+ def forward(self, input):
768
+ r"""Performs forward pass through fused Conv2d and ReLU."""
769
+ return F.relu(
770
+ self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
771
+ )
772
+
773
+ @classmethod
774
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
775
+ r"""Creates a QAT module from a floating point module."""
776
+ return super().from_float(
777
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
778
+ )
779
+
780
+
781
+ class ConvBn3d(_ConvBnNd, nn.Conv3d):
782
+ r"""
783
+ A ConvBn3d module is a module fused from Conv3d and BatchNorm3d,
784
+ attached with FakeQuantize modules for weight,
785
+ used in quantization aware training.
786
+
787
+ We combined the interface of :class:`torch.nn.Conv3d` and
788
+ :class:`torch.nn.BatchNorm3d`.
789
+
790
+ Similar to :class:`torch.nn.Conv3d`, with FakeQuantize modules initialized
791
+ to default.
792
+
793
+ Attributes:
794
+ freeze_bn:
795
+ weight_fake_quant: fake quant module for weight
796
+
797
+ """
798
+
799
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBn3d]] = nni.ConvBn3d # type: ignore[assignment]
800
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
801
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = nn.BatchNorm3d
802
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
803
+
804
+ def __init__(
805
+ self,
806
+ # ConvNd args
807
+ in_channels,
808
+ out_channels,
809
+ kernel_size,
810
+ stride=1,
811
+ padding=0,
812
+ dilation=1,
813
+ groups=1,
814
+ bias=None,
815
+ padding_mode="zeros",
816
+ # BatchNorm3d args
817
+ # num_features: out_channels
818
+ eps=1e-05,
819
+ momentum=0.1,
820
+ # affine: True
821
+ # track_running_stats: True
822
+ # Args for this module
823
+ freeze_bn=False,
824
+ qconfig=None,
825
+ ):
826
+ kernel_size = _triple(kernel_size)
827
+ stride = _triple(stride)
828
+ padding = _triple(padding)
829
+ dilation = _triple(dilation)
830
+ _ConvBnNd.__init__(
831
+ self,
832
+ in_channels,
833
+ out_channels,
834
+ kernel_size,
835
+ stride,
836
+ padding,
837
+ dilation,
838
+ False,
839
+ _triple(0),
840
+ groups,
841
+ bias,
842
+ padding_mode,
843
+ eps,
844
+ momentum,
845
+ freeze_bn,
846
+ qconfig,
847
+ dim=3,
848
+ )
849
+
850
+
851
+ class ConvBnReLU3d(ConvBn3d):
852
+ r"""
853
+ A ConvBnReLU3d module is a module fused from Conv3d, BatchNorm3d and ReLU,
854
+ attached with FakeQuantize modules for weight,
855
+ used in quantization aware training.
856
+
857
+ We combined the interface of :class:`torch.nn.Conv3d` and
858
+ :class:`torch.nn.BatchNorm3d` and :class:`torch.nn.ReLU`.
859
+
860
+ Similar to `torch.nn.Conv3d`, with FakeQuantize modules initialized to
861
+ default.
862
+
863
+ Attributes:
864
+ weight_fake_quant: fake quant module for weight
865
+
866
+ """
867
+
868
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBnReLU3d]] = nni.ConvBnReLU3d # type: ignore[assignment]
869
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
870
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm3d]] = nn.BatchNorm3d
871
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.ReLU] | None] = nn.ReLU
872
+ # module class after fusing bn into conv
873
+ _FUSED_FLOAT_MODULE: ClassVar[type[nni.ConvReLU3d] | None] = nni.ConvReLU3d
874
+
875
+ def forward(self, input):
876
+ r"""Performs forward pass through fused Conv3d, BatchNorm3d, and ReLU."""
877
+ return F.relu(ConvBn3d._forward(self, input))
878
+
879
+ @classmethod
880
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
881
+ r"""Creates a QAT module from a floating point module."""
882
+ return super().from_float(
883
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
884
+ )
885
+
886
+
887
+ class ConvReLU3d(nnqat.Conv3d, nni._FusedModule):
888
+ r"""A ConvReLU3d module is a fused module of Conv3d and ReLU, attached with
889
+ FakeQuantize modules for weight for
890
+ quantization aware training.
891
+
892
+ We combined the interface of :class:`~torch.nn.Conv3d` and
893
+ :class:`~torch.nn.BatchNorm3d`.
894
+
895
+ Attributes:
896
+ weight_fake_quant: fake quant module for weight
897
+
898
+ """
899
+
900
+ _FLOAT_MODULE: ClassVar[type[nni.ConvReLU3d]] = nni.ConvReLU3d # type: ignore[assignment]
901
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
902
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
903
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
904
+
905
+ def __init__(
906
+ self,
907
+ in_channels,
908
+ out_channels,
909
+ kernel_size,
910
+ stride=1,
911
+ padding=0,
912
+ dilation=1,
913
+ groups=1,
914
+ bias=True,
915
+ padding_mode="zeros",
916
+ qconfig=None,
917
+ ):
918
+ super().__init__(
919
+ in_channels,
920
+ out_channels,
921
+ kernel_size,
922
+ stride=stride,
923
+ padding=padding,
924
+ dilation=dilation,
925
+ groups=groups,
926
+ bias=bias,
927
+ # pyrefly: ignore [bad-argument-type]
928
+ padding_mode=padding_mode,
929
+ qconfig=qconfig,
930
+ )
931
+ if not qconfig:
932
+ raise AssertionError("qconfig must be provided for QAT module")
933
+ self.qconfig = qconfig
934
+ self.weight_fake_quant = self.qconfig.weight()
935
+
936
+ def forward(self, input):
937
+ r"""Performs forward pass through fused Conv3d and ReLU."""
938
+ return F.relu(
939
+ self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
940
+ )
941
+
942
+ @classmethod
943
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
944
+ r"""Creates a QAT module from a floating point module."""
945
+ return super().from_float(
946
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
947
+ )
948
+
949
+
950
+ def update_bn_stats(mod):
951
+ if type(mod) in {
952
+ ConvBnReLU1d,
953
+ ConvBnReLU2d,
954
+ ConvBnReLU3d,
955
+ ConvBn1d,
956
+ ConvBn2d,
957
+ ConvBn3d,
958
+ }:
959
+ mod.update_bn_stats()
960
+
961
+
962
+ def freeze_bn_stats(mod):
963
+ if type(mod) in {
964
+ ConvBnReLU1d,
965
+ ConvBnReLU2d,
966
+ ConvBnReLU3d,
967
+ ConvBn1d,
968
+ ConvBn2d,
969
+ ConvBn3d,
970
+ }:
971
+ mod.freeze_bn_stats()
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_fused.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.ao.nn.intrinsic as nni
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from torch.nn import init
7
+ from torch.nn.parameter import Parameter
8
+ from torch.nn.utils.fusion import fuse_linear_bn_weights
9
+
10
+
11
+ __all__ = [
12
+ "LinearBn1d",
13
+ ]
14
+
15
+
16
+ class LinearBn1d(nn.modules.linear.Linear, nni._FusedModule):
17
+ r"""
18
+ A LinearBn1d module is a module fused from Linear and BatchNorm1d, attached
19
+ with FakeQuantize modules for weight, used in quantization aware training.
20
+
21
+ We combined the interface of :class:`torch.nn.Linear` and
22
+ :class:torch.nn.BatchNorm1d`.
23
+
24
+ Similar to :class:`torch.nn.Linear`, with FakeQuantize modules initialized
25
+ to default.
26
+
27
+ Attributes:
28
+ freeze_bn:
29
+ weight_fake_quant: fake quant module for weight
30
+
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ # Linear args
36
+ in_features,
37
+ out_features,
38
+ bias=True,
39
+ # BatchNorm1d args
40
+ # num_features: out_features
41
+ eps=1e-05,
42
+ momentum=0.1,
43
+ # affine: True
44
+ # track_running_stats: True
45
+ # Args for this module
46
+ freeze_bn=False,
47
+ qconfig=None,
48
+ ):
49
+ nn.modules.linear.Linear.__init__(self, in_features, out_features, bias)
50
+ if not qconfig:
51
+ raise AssertionError("qconfig must be provided for QAT module")
52
+ self.qconfig = qconfig
53
+ self.freeze_bn = freeze_bn if self.training else True
54
+ self.bn = nn.BatchNorm1d(out_features, eps, momentum, True, True)
55
+ self.weight_fake_quant = self.qconfig.weight()
56
+ if bias:
57
+ self.bias = Parameter(torch.empty(out_features))
58
+ else:
59
+ self.register_parameter("bias", None)
60
+ self.reset_bn_parameters()
61
+
62
+ # this needs to be called after reset_bn_parameters,
63
+ # as they modify the same state
64
+ if self.training:
65
+ if freeze_bn:
66
+ self.freeze_bn_stats()
67
+ else:
68
+ self.update_bn_stats()
69
+ else:
70
+ self.freeze_bn_stats()
71
+
72
+ def reset_running_stats(self):
73
+ self.bn.reset_running_stats()
74
+
75
+ def reset_bn_parameters(self):
76
+ self.bn.reset_running_stats()
77
+ init.uniform_(self.bn.weight)
78
+ init.zeros_(self.bn.bias)
79
+
80
+ def update_bn_stats(self):
81
+ self.freeze_bn = False
82
+ self.bn.training = True
83
+ return self
84
+
85
+ def freeze_bn_stats(self):
86
+ self.freeze_bn = True
87
+ self.bn.training = False
88
+ return self
89
+
90
+ def forward(self, input):
91
+ if self.bn.running_var is None:
92
+ raise AssertionError("self.bn.running_var must not be None")
93
+
94
+ # Scale the linear weights by BN's running statistics to reduce
95
+ # weight jitter, see https://arxiv.org/pdf/1806.08342.pdf, page 18
96
+ # for motivation.
97
+ #
98
+ # Instead of
99
+ #
100
+ # x1 = F.linear(x0, fq(w), b)
101
+ # x2 = self.bn(x1)
102
+ #
103
+ # We have
104
+ #
105
+ # # scale the weight by previous batch's running statistics
106
+ # scale_factor = bn.w / bn.running_std_from_prev_batch
107
+ # # do the linear transformation without bias
108
+ # x1_scaled = F.linear(x0, fq(w * scale_factor), 0)
109
+ # # reverse the scaling and add original bias
110
+ # x1_orig = x1_scaled / scale_factor + b
111
+ # x2 = self.bn(x1_orig)
112
+
113
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
114
+ scale_factor = self.bn.weight / running_std
115
+ weight_shape = [1] * len(self.weight.shape)
116
+ weight_shape[0] = -1
117
+ bias_shape = [1] * len(self.weight.shape)
118
+ bias_shape[1] = -1
119
+ scaled_weight = self.weight_fake_quant(
120
+ self.weight * scale_factor.reshape(weight_shape)
121
+ )
122
+ if self.bias is not None:
123
+ zero_bias = torch.zeros_like(self.bias)
124
+ else:
125
+ zero_bias = torch.zeros(self.out_features, device=scaled_weight.device)
126
+ linear_out = F.linear(input, scaled_weight, zero_bias)
127
+ linear_out_orig = linear_out / scale_factor.reshape(bias_shape)
128
+ if self.bias is not None:
129
+ linear_out_orig = linear_out_orig + self.bias.reshape(bias_shape)
130
+ bn_out = self.bn(linear_out_orig)
131
+ return bn_out
132
+
133
+ def train(self, mode=True):
134
+ """
135
+ Batchnorm's training behavior is using the self.training flag. Prevent
136
+ changing it if BN is frozen. This makes sure that calling `model.train()`
137
+ on a model with a frozen BN will behave properly.
138
+ """
139
+ self.training = mode
140
+ if not self.freeze_bn:
141
+ for module in self.children():
142
+ module.train(mode)
143
+ return self
144
+
145
+ @classmethod
146
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
147
+ r"""Create a qat module from a float module or qparams_dict
148
+
149
+ Args:
150
+ mod: A float module, either produced by torch.ao.quantization
151
+ utilities or directly from the user.
152
+ """
153
+ if type(mod) is not nni.LinearBn1d:
154
+ raise AssertionError(
155
+ "qat."
156
+ + cls.__name__
157
+ + ".from_float only works for "
158
+ + nni.LinearBn1d.__name__
159
+ )
160
+ if not hasattr(mod, "qconfig"):
161
+ raise AssertionError("Input float module must have qconfig defined")
162
+ if not mod.qconfig:
163
+ raise AssertionError("Input float module must have a valid config")
164
+ qconfig = mod.qconfig
165
+ linear, bn = mod[0], mod[1]
166
+ qat_linearbn = cls(
167
+ linear.in_features,
168
+ linear.out_features,
169
+ linear.bias is not None,
170
+ bn.eps,
171
+ bn.momentum,
172
+ False,
173
+ qconfig,
174
+ )
175
+ qat_linearbn.weight = linear.weight # type: ignore[assignment]
176
+ qat_linearbn.bias = linear.bias # type: ignore[assignment]
177
+ qat_linearbn.bn.weight = bn.weight # type: ignore[assignment]
178
+ qat_linearbn.bn.bias = bn.bias # type: ignore[assignment]
179
+ qat_linearbn.bn.running_mean = bn.running_mean # type: ignore[assignment]
180
+ qat_linearbn.bn.running_var = bn.running_var # type: ignore[assignment]
181
+ qat_linearbn.bn.num_batches_tracked = bn.num_batches_tracked # type: ignore[assignment]
182
+ return qat_linearbn
183
+
184
+ def to_float(self):
185
+ linear = torch.nn.Linear(self.in_features, self.out_features)
186
+ if self.bn.running_var is None or self.bn.running_mean is None:
187
+ raise AssertionError(
188
+ "self.bn.running_var and self.bn.running_mean must not be None"
189
+ )
190
+ linear.weight, linear.bias = fuse_linear_bn_weights(
191
+ self.weight,
192
+ self.bias,
193
+ self.bn.running_mean,
194
+ self.bn.running_var,
195
+ self.bn.eps,
196
+ self.bn.weight,
197
+ self.bn.bias,
198
+ )
199
+ return linear
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_relu.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import torch
6
+ import torch.ao.nn.intrinsic as nni
7
+ import torch.ao.nn.qat as nnqat
8
+ import torch.nn.functional as F
9
+ from torch.ao.nn.intrinsic.modules.fused import _FusedModule
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from torch.ao.quantization.qconfig import QConfigAny
14
+
15
+
16
+ __all__ = ["LinearReLU"]
17
+
18
+
19
+ class LinearReLU(nnqat.Linear, _FusedModule):
20
+ r"""
21
+ A LinearReLU module fused from Linear and ReLU modules, attached with
22
+ FakeQuantize modules for weight, used in
23
+ quantization aware training.
24
+
25
+ We adopt the same interface as :class:`torch.nn.Linear`.
26
+
27
+ Similar to `torch.ao.nn.intrinsic.LinearReLU`, with FakeQuantize modules initialized to
28
+ default.
29
+
30
+ Attributes:
31
+ weight: fake quant module for weight
32
+
33
+ Examples::
34
+
35
+ >>> # xdoctest: +SKIP
36
+ >>> m = nn.qat.LinearReLU(20, 30)
37
+ >>> input = torch.randn(128, 20)
38
+ >>> output = m(input)
39
+ >>> print(output.size())
40
+ torch.Size([128, 30])
41
+ """
42
+
43
+ # pyrefly: ignore [bad-override]
44
+ _FLOAT_MODULE = nni.LinearReLU
45
+
46
+ def __init__(
47
+ self,
48
+ in_features: int,
49
+ out_features: int,
50
+ bias: bool = True,
51
+ qconfig: QConfigAny = None,
52
+ ) -> None:
53
+ super().__init__(in_features, out_features, bias, qconfig)
54
+
55
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
56
+ return F.relu(F.linear(input, self.weight_fake_quant(self.weight), self.bias))
57
+
58
+ @classmethod
59
+ def from_float(
60
+ cls,
61
+ mod: torch.nn.Module,
62
+ use_precomputed_fake_quant: bool = False,
63
+ ) -> LinearReLU:
64
+ return super().from_float(mod, use_precomputed_fake_quant) # type: ignore[no-untyped-call,no-any-return]
65
+
66
+ def to_float(self) -> nni.LinearReLU:
67
+ linear = torch.nn.Linear(
68
+ self.in_features, self.out_features, self.bias is not None
69
+ )
70
+ linear.weight = torch.nn.Parameter(self.weight.detach())
71
+ if self.bias is not None:
72
+ linear.bias = torch.nn.Parameter(self.bias.detach())
73
+ relu = torch.nn.ReLU()
74
+ return torch.ao.nn.intrinsic.LinearReLU(linear, relu) # type: ignore[no-untyped-call]
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .modules import * # noqa: F403
2
+
3
+
4
+ __all__ = [
5
+ "BNReLU2d",
6
+ "BNReLU3d",
7
+ "ConvReLU1d",
8
+ "ConvReLU2d",
9
+ "ConvReLU3d",
10
+ "LinearReLU",
11
+ "LinearLeakyReLU",
12
+ "LinearTanh",
13
+ "ConvAdd2d",
14
+ "ConvAddReLU2d",
15
+ ]
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modules import * # noqa: F403
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .linear_relu import LinearReLU
2
+
3
+
4
+ __all__ = [
5
+ "LinearReLU",
6
+ ]
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ from typing_extensions import Self
3
+
4
+ import torch
5
+ import torch.ao.nn.intrinsic as nni
6
+ import torch.ao.nn.quantized.dynamic as nnqd
7
+
8
+
9
+ __all__ = ["LinearReLU"]
10
+
11
+
12
+ class LinearReLU(nnqd.Linear):
13
+ r"""
14
+ A LinearReLU module fused from Linear and ReLU modules that can be used
15
+ for dynamic quantization.
16
+ Supports both, FP16 and INT8 quantization.
17
+
18
+ We adopt the same interface as :class:`torch.ao.nn.quantized.dynamic.Linear`.
19
+
20
+ Attributes:
21
+ Same as torch.ao.nn.quantized.dynamic.Linear
22
+
23
+ Examples::
24
+
25
+ >>> # xdoctest: +SKIP
26
+ >>> m = nn.intrinsic.quantized.dynamic.LinearReLU(20, 30)
27
+ >>> input = torch.randn(128, 20)
28
+ >>> output = m(input)
29
+ >>> print(output.size())
30
+ torch.Size([128, 30])
31
+ """
32
+
33
+ # pyrefly: ignore [bad-override]
34
+ _FLOAT_MODULE = nni.LinearReLU
35
+
36
+ def __init__(
37
+ self,
38
+ in_features: int,
39
+ out_features: int,
40
+ bias: bool = True,
41
+ dtype: torch.dtype = torch.qint8,
42
+ ) -> None:
43
+ super().__init__(in_features, out_features, bias, dtype)
44
+
45
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
46
+ if self._packed_params.dtype == torch.qint8:
47
+ # TODO check if we should set reduce_rage = True by default here
48
+ Y = torch.ops.quantized.linear_relu_dynamic(
49
+ x, self._packed_params._packed_params, reduce_range=True
50
+ )
51
+ elif self._packed_params.dtype == torch.float16:
52
+ Y = torch.ops.quantized.linear_relu_dynamic_fp16(
53
+ x, self._packed_params._packed_params
54
+ )
55
+ else:
56
+ raise RuntimeError("Unsupported dtype on dynamic quantized linear relu!")
57
+ return Y.to(x.dtype)
58
+
59
+ def _get_name(self) -> str:
60
+ return "DynamicQuantizedLinearReLU"
61
+
62
+ @classmethod
63
+ def from_float(
64
+ cls, mod: torch.nn.Module, use_precomputed_fake_quant: bool = False
65
+ ) -> Self:
66
+ return super().from_float(
67
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
68
+ )
69
+
70
+ @classmethod
71
+ def from_reference(cls, ref_qlinear_relu: Any) -> Self: # type: ignore[override]
72
+ return super().from_reference(ref_qlinear_relu[0])
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .bn_relu import BNReLU2d, BNReLU3d
2
+ from .conv_add import ConvAdd2d, ConvAddReLU2d
3
+ from .conv_relu import ConvReLU1d, ConvReLU2d, ConvReLU3d
4
+ from .linear_relu import LinearLeakyReLU, LinearReLU, LinearTanh
5
+
6
+
7
+ __all__ = [
8
+ "LinearReLU",
9
+ "ConvReLU1d",
10
+ "ConvReLU2d",
11
+ "ConvReLU3d",
12
+ "BNReLU2d",
13
+ "BNReLU3d",
14
+ "LinearLeakyReLU",
15
+ "LinearTanh",
16
+ "ConvAdd2d",
17
+ "ConvAddReLU2d",
18
+ ]
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.ao.nn.intrinsic
5
+ import torch.ao.nn.intrinsic.qat
6
+ import torch.ao.nn.quantized as nnq
7
+
8
+
9
+ __all__ = ["BNReLU2d", "BNReLU3d"]
10
+
11
+
12
+ class BNReLU2d(nnq.BatchNorm2d):
13
+ r"""
14
+ A BNReLU2d module is a fused module of BatchNorm2d and ReLU
15
+
16
+ We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm2d`.
17
+
18
+ Attributes:
19
+ Same as torch.ao.nn.quantized.BatchNorm2d
20
+
21
+ """
22
+
23
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU2d
24
+
25
+ def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
26
+ super().__init__(
27
+ num_features, eps=eps, momentum=momentum, device=device, dtype=dtype
28
+ )
29
+
30
+ def forward(self, input):
31
+ r"""Applies fused BatchNorm2d and ReLU."""
32
+ # Temporarily using len(shape) instead of ndim due to JIT issue
33
+ # https://github.com/pytorch/pytorch/issues/23890
34
+ if len(input.shape) != 4:
35
+ raise ValueError("Input shape must be `(N, C, H, W)`!")
36
+ return torch.ops.quantized.batch_norm2d_relu(
37
+ input,
38
+ self.weight,
39
+ self.bias,
40
+ self.running_mean,
41
+ self.running_var,
42
+ self.eps,
43
+ self.scale,
44
+ self.zero_point,
45
+ )
46
+
47
+ def _get_name(self):
48
+ return "QuantizedBNReLU2d"
49
+
50
+ @classmethod
51
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
52
+ r"""Creates a quantized module from a float module."""
53
+ # TODO: Add qat support for BNReLU2d
54
+ return super().from_float(
55
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
56
+ )
57
+
58
+ @classmethod
59
+ def from_reference(cls, bn_relu, output_scale, output_zero_point):
60
+ r"""Creates a quantized module from a reference module."""
61
+ return super().from_reference(bn_relu[0], output_scale, output_zero_point)
62
+
63
+
64
+ class BNReLU3d(nnq.BatchNorm3d):
65
+ r"""
66
+ A BNReLU3d module is a fused module of BatchNorm3d and ReLU
67
+
68
+ We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm3d`.
69
+
70
+ Attributes:
71
+ Same as torch.ao.nn.quantized.BatchNorm3d
72
+
73
+ """
74
+
75
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU3d
76
+
77
+ def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
78
+ super().__init__(
79
+ num_features, eps=eps, momentum=momentum, device=device, dtype=dtype
80
+ )
81
+
82
+ def forward(self, input):
83
+ r"""Applies fused BatchNorm3d and ReLU."""
84
+ # Temporarily using len(shape) instead of ndim due to JIT issue
85
+ # https://github.com/pytorch/pytorch/issues/23890
86
+ if len(input.shape) != 5:
87
+ raise ValueError("Input shape must be `(N, C, D, H, W)`!")
88
+ return torch.ops.quantized.batch_norm3d_relu(
89
+ input,
90
+ self.weight,
91
+ self.bias,
92
+ self.running_mean,
93
+ self.running_var,
94
+ self.eps,
95
+ self.scale,
96
+ self.zero_point,
97
+ )
98
+
99
+ def _get_name(self):
100
+ return "QuantizedBNReLU3d"
101
+
102
+ @classmethod
103
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
104
+ r"""Creates a quantized module from a float module."""
105
+ # TODO: Add qat support for BNReLU3d
106
+ return super().from_float(
107
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
108
+ )
109
+
110
+ @classmethod
111
+ def from_reference(cls, bn_relu, output_scale, output_zero_point):
112
+ r"""Creates a quantized module from a reference module."""
113
+ return super().from_reference(bn_relu[0], output_scale, output_zero_point)
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.ao.nn.intrinsic
4
+ import torch.ao.nn.intrinsic.qat
5
+ import torch.ao.nn.quantized as nnq
6
+ import torch.nn.functional as F
7
+
8
+
9
+ _reverse_repeat_padding = nnq.modules.conv._reverse_repeat_padding
10
+
11
+
12
+ class ConvAdd2d(nnq.Conv2d):
13
+ r"""
14
+ A ConvAdd2d module is a fused module of Conv2d and Add
15
+
16
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
17
+
18
+ Attributes:
19
+ Same as torch.ao.nn.quantized.Conv2d
20
+
21
+ """
22
+
23
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvAdd2d # type: ignore[assignment]
24
+
25
+ def __init__(
26
+ self,
27
+ in_channels,
28
+ out_channels,
29
+ kernel_size,
30
+ stride=1,
31
+ padding=0,
32
+ dilation=1,
33
+ groups=1,
34
+ bias=True,
35
+ padding_mode="zeros",
36
+ device=None,
37
+ dtype=None,
38
+ ):
39
+ super().__init__(
40
+ in_channels,
41
+ out_channels,
42
+ kernel_size,
43
+ stride=stride,
44
+ padding=padding,
45
+ dilation=dilation,
46
+ groups=groups,
47
+ bias=bias,
48
+ padding_mode=padding_mode,
49
+ device=device,
50
+ dtype=dtype,
51
+ )
52
+
53
+ def forward(self, input, extra_input): # type: ignore[override]
54
+ r"""Applies fused quantized Conv2d and addition."""
55
+ # Temporarily using len(shape) instead of ndim due to JIT issue
56
+ # https://github.com/pytorch/pytorch/issues/23890
57
+ if len(input.shape) != 4:
58
+ raise ValueError("Input shape must be `(N, C, H, W)`!")
59
+ if self.padding_mode != "zeros":
60
+ _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
61
+ input = F.pad(
62
+ input, _reversed_padding_repeated_twice, mode=self.padding_mode
63
+ )
64
+ return torch.ops.quantized.conv2d_add(
65
+ input, extra_input, self._packed_params, self.scale, self.zero_point
66
+ )
67
+
68
+ def _get_name(self):
69
+ return "QuantizedConvAdd2d"
70
+
71
+ @classmethod
72
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
73
+ r"""Creates a quantized module from a float module."""
74
+ return super().from_float(
75
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
76
+ )
77
+
78
+ @classmethod
79
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
80
+ r"""Creates a quantized module from a reference module."""
81
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
82
+
83
+
84
+ class ConvAddReLU2d(nnq.Conv2d):
85
+ r"""
86
+ A ConvAddReLU2d module is a fused module of Conv2d, Add and Relu
87
+
88
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
89
+
90
+ Attributes:
91
+ Same as torch.ao.nn.quantized.Conv2d
92
+
93
+ """
94
+
95
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvAddReLU2d # type: ignore[assignment]
96
+
97
+ def __init__(
98
+ self,
99
+ in_channels,
100
+ out_channels,
101
+ kernel_size,
102
+ stride=1,
103
+ padding=0,
104
+ dilation=1,
105
+ groups=1,
106
+ bias=True,
107
+ padding_mode="zeros",
108
+ device=None,
109
+ dtype=None,
110
+ ):
111
+ super().__init__(
112
+ in_channels,
113
+ out_channels,
114
+ kernel_size,
115
+ stride=stride,
116
+ padding=padding,
117
+ dilation=dilation,
118
+ groups=groups,
119
+ bias=bias,
120
+ padding_mode=padding_mode,
121
+ device=device,
122
+ dtype=dtype,
123
+ )
124
+
125
+ def forward(self, input, extra_input): # type: ignore[override]
126
+ r"""Applies fused quantized Conv2d, addition, and ReLU."""
127
+ # Temporarily using len(shape) instead of ndim due to JIT issue
128
+ # https://github.com/pytorch/pytorch/issues/23890
129
+ if len(input.shape) != 4:
130
+ raise ValueError("Input shape must be `(N, C, H, W)`!")
131
+ if self.padding_mode != "zeros":
132
+ _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
133
+ input = F.pad(
134
+ input, _reversed_padding_repeated_twice, mode=self.padding_mode
135
+ )
136
+ return torch.ops.quantized.conv2d_add_relu(
137
+ input, extra_input, self._packed_params, self.scale, self.zero_point
138
+ )
139
+
140
+ def _get_name(self):
141
+ return "QuantizedConvAddReLU2d"
142
+
143
+ @classmethod
144
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
145
+ r"""Creates a quantized module from a float module."""
146
+ return super().from_float(
147
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
148
+ )
149
+
150
+ @classmethod
151
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
152
+ r"""Creates a quantized module from a reference module."""
153
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.ao.nn.intrinsic
5
+ import torch.ao.nn.intrinsic.qat
6
+ import torch.ao.nn.quantized as nnq
7
+ import torch.nn.functional as F
8
+ from torch.nn.utils import fuse_conv_bn_weights
9
+
10
+
11
+ __all__ = [
12
+ "ConvReLU1d",
13
+ "ConvReLU2d",
14
+ "ConvReLU3d",
15
+ ]
16
+
17
+ _reverse_repeat_padding = nnq.modules.conv._reverse_repeat_padding
18
+
19
+
20
+ # TODO: factor out the common parts to ConvNd
21
+ class ConvReLU1d(nnq.Conv1d):
22
+ r"""
23
+ A ConvReLU1d module is a fused module of Conv1d and ReLU
24
+
25
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Conv1d`.
26
+
27
+ Attributes:
28
+ Same as torch.ao.nn.quantized.Conv1d
29
+
30
+ """
31
+
32
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU1d # type: ignore[assignment]
33
+
34
+ def __init__(
35
+ self,
36
+ in_channels,
37
+ out_channels,
38
+ kernel_size,
39
+ stride=1,
40
+ padding=0,
41
+ dilation=1,
42
+ groups=1,
43
+ bias=True,
44
+ padding_mode="zeros",
45
+ device=None,
46
+ dtype=None,
47
+ ):
48
+ super().__init__(
49
+ in_channels,
50
+ out_channels,
51
+ kernel_size,
52
+ stride=stride,
53
+ padding=padding,
54
+ dilation=dilation,
55
+ groups=groups,
56
+ bias=bias,
57
+ # pyrefly: ignore [bad-argument-type]
58
+ padding_mode=padding_mode,
59
+ device=device,
60
+ dtype=dtype,
61
+ )
62
+
63
+ def forward(self, input):
64
+ r"""Applies fused quantized Conv1d and ReLU."""
65
+ # Temporarily using len(shape) instead of ndim due to JIT issue
66
+ # https://github.com/pytorch/pytorch/issues/23890
67
+ if len(input.shape) != 3:
68
+ raise ValueError("Input shape must be `(N, C, L)`!")
69
+ if self.padding_mode != "zeros":
70
+ # Padding in Conv1d is stored as (p, p), need to get (p,)
71
+ _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1])
72
+ input = F.pad(
73
+ input, _reversed_padding_repeated_twice, mode=self.padding_mode
74
+ )
75
+ return torch.ops.quantized.conv1d_relu(
76
+ input, self._packed_params, self.scale, self.zero_point
77
+ )
78
+
79
+ def _get_name(self):
80
+ return "QuantizedConvReLU1d"
81
+
82
+ @classmethod
83
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
84
+ r"""Creates a quantized module from a float module."""
85
+ if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU1d:
86
+ if mod.bn.running_var is None or mod.bn.running_mean is None:
87
+ raise AssertionError(
88
+ "mod.bn.running_var and mod.bn.running_mean must not be None"
89
+ )
90
+ mod.weight, mod.bias = fuse_conv_bn_weights(
91
+ mod.weight,
92
+ mod.bias,
93
+ mod.bn.running_mean,
94
+ mod.bn.running_var,
95
+ mod.bn.eps,
96
+ mod.bn.weight,
97
+ mod.bn.bias,
98
+ )
99
+ return super().from_float(mod, use_precomputed_fake_quant)
100
+
101
+ @classmethod
102
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
103
+ r"""Creates a quantized module from a reference module."""
104
+ if type(ref_qconv) is torch.ao.nn.intrinsic.ConvBnReLU1d:
105
+ raise AssertionError(
106
+ "BatchNorm1d should be fused into Conv1d before converting to reference module"
107
+ )
108
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
109
+
110
+
111
+ class ConvReLU2d(nnq.Conv2d):
112
+ r"""
113
+ A ConvReLU2d module is a fused module of Conv2d and ReLU
114
+
115
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
116
+
117
+ Attributes:
118
+ Same as torch.ao.nn.quantized.Conv2d
119
+
120
+ """
121
+
122
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU2d # type: ignore[assignment]
123
+
124
+ def __init__(
125
+ self,
126
+ in_channels,
127
+ out_channels,
128
+ kernel_size,
129
+ stride=1,
130
+ padding=0,
131
+ dilation=1,
132
+ groups=1,
133
+ bias=True,
134
+ padding_mode="zeros",
135
+ device=None,
136
+ dtype=None,
137
+ ):
138
+ super().__init__(
139
+ in_channels,
140
+ out_channels,
141
+ kernel_size,
142
+ stride=stride,
143
+ padding=padding,
144
+ dilation=dilation,
145
+ groups=groups,
146
+ bias=bias,
147
+ padding_mode=padding_mode,
148
+ device=device,
149
+ dtype=dtype,
150
+ )
151
+
152
+ def forward(self, input):
153
+ r"""Applies fused quantized Conv2d and ReLU."""
154
+ # Temporarily using len(shape) instead of ndim due to JIT issue
155
+ # https://github.com/pytorch/pytorch/issues/23890
156
+ if len(input.shape) != 4:
157
+ raise ValueError("Input shape must be `(N, C, H, W)`!")
158
+ if self.padding_mode != "zeros":
159
+ _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
160
+ input = F.pad(
161
+ input, _reversed_padding_repeated_twice, mode=self.padding_mode
162
+ )
163
+ return torch.ops.quantized.conv2d_relu(
164
+ input, self._packed_params, self.scale, self.zero_point
165
+ )
166
+
167
+ def _get_name(self):
168
+ return "QuantizedConvReLU2d"
169
+
170
+ @classmethod
171
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
172
+ r"""Creates a quantized module from a float module."""
173
+ if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU2d:
174
+ if mod.bn.running_var is None or mod.bn.running_mean is None:
175
+ raise AssertionError(
176
+ "mod.bn.running_var and mod.bn.running_mean must not be None"
177
+ )
178
+ mod.weight, mod.bias = fuse_conv_bn_weights(
179
+ mod.weight,
180
+ mod.bias,
181
+ mod.bn.running_mean,
182
+ mod.bn.running_var,
183
+ mod.bn.eps,
184
+ mod.bn.weight,
185
+ mod.bn.bias,
186
+ )
187
+ return super().from_float(
188
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
189
+ )
190
+
191
+ @classmethod
192
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
193
+ r"""Creates a quantized module from a reference module."""
194
+ if type(ref_qconv) is torch.ao.nn.intrinsic.ConvBnReLU2d:
195
+ raise AssertionError(
196
+ "BatchNorm2d should be fused into Conv2d before converting to reference module"
197
+ )
198
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
199
+
200
+
201
+ class ConvReLU3d(nnq.Conv3d):
202
+ r"""
203
+ A ConvReLU3d module is a fused module of Conv3d and ReLU
204
+
205
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Conv3d`.
206
+
207
+ Attributes: Same as torch.ao.nn.quantized.Conv3d
208
+
209
+ """
210
+
211
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU3d # type: ignore[assignment]
212
+
213
+ def __init__(
214
+ self,
215
+ in_channels,
216
+ out_channels,
217
+ kernel_size,
218
+ stride=1,
219
+ padding=0,
220
+ dilation=1,
221
+ groups=1,
222
+ bias=True,
223
+ padding_mode="zeros",
224
+ device=None,
225
+ dtype=None,
226
+ ):
227
+ if padding_mode == "reflect":
228
+ raise AssertionError("Conv3d does not support reflection padding")
229
+ super().__init__(
230
+ in_channels,
231
+ out_channels,
232
+ kernel_size,
233
+ stride=stride,
234
+ padding=padding,
235
+ dilation=dilation,
236
+ groups=groups,
237
+ bias=bias,
238
+ padding_mode=padding_mode,
239
+ device=device,
240
+ dtype=dtype,
241
+ )
242
+
243
+ def forward(self, input):
244
+ r"""Applies fused quantized Conv3d and ReLU."""
245
+ # Temporarily using len(shape) instead of ndim due to JIT issue
246
+ # https://github.com/pytorch/pytorch/issues/23890
247
+ if len(input.shape) != 5:
248
+ raise ValueError("Input shape must be `(N, C, D, H, W)`!")
249
+ if self.padding_mode != "zeros":
250
+ _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
251
+ input = F.pad(
252
+ input, _reversed_padding_repeated_twice, mode=self.padding_mode
253
+ )
254
+ return torch.ops.quantized.conv3d_relu(
255
+ input, self._packed_params, self.scale, self.zero_point
256
+ )
257
+
258
+ def _get_name(self):
259
+ return "QuantizedConvReLU3d"
260
+
261
+ @classmethod
262
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
263
+ r"""Creates a quantized module from a float module."""
264
+ if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU3d:
265
+ if mod.bn.running_var is None or mod.bn.running_mean is None:
266
+ raise AssertionError(
267
+ "mod.bn.running_var and mod.bn.running_mean must not be None"
268
+ )
269
+ mod.weight, mod.bias = fuse_conv_bn_weights(
270
+ mod.weight,
271
+ mod.bias,
272
+ mod.bn.running_mean,
273
+ mod.bn.running_var,
274
+ mod.bn.eps,
275
+ mod.bn.weight,
276
+ mod.bn.bias,
277
+ )
278
+ return super().from_float(
279
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
280
+ )
281
+
282
+ @classmethod
283
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
284
+ r"""Creates a quantized module from a reference module."""
285
+ if type(ref_qconv) is torch.ao.nn.intrinsic.ConvBnReLU3d:
286
+ raise AssertionError(
287
+ "BatchNorm3d should be fused into Conv3d before converting to reference module"
288
+ )
289
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
.venv/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/linear_relu.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.ao.nn.intrinsic as nni
4
+ import torch.ao.nn.quantized as nnq
5
+ from torch.ao.nn.quantized.modules.utils import _quantize_weight
6
+
7
+
8
+ __all__ = [
9
+ "LinearReLU",
10
+ "LinearLeakyReLU",
11
+ "LinearTanh",
12
+ ]
13
+
14
+
15
+ class LinearReLU(nnq.Linear):
16
+ r"""
17
+ A LinearReLU module fused from Linear and ReLU modules
18
+
19
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
20
+
21
+ Attributes:
22
+ Same as torch.ao.nn.quantized.Linear
23
+
24
+ Examples::
25
+
26
+ >>> # xdoctest: +SKIP
27
+ >>> m = nn.intrinsic.LinearReLU(20, 30)
28
+ >>> input = torch.randn(128, 20)
29
+ >>> output = m(input)
30
+ >>> print(output.size())
31
+ torch.Size([128, 30])
32
+ """
33
+
34
+ _FLOAT_MODULE = nni.LinearReLU # type: ignore[assignment]
35
+
36
+ def __init__(self, in_features, out_features, bias=True, dtype=torch.qint8):
37
+ super().__init__(in_features, out_features, bias, dtype)
38
+
39
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
40
+ return torch.ops.quantized.linear_relu(
41
+ x, self._packed_params._packed_params, self.scale, self.zero_point
42
+ )
43
+
44
+ def _get_name(self):
45
+ return "QuantizedLinearReLU"
46
+
47
+ @classmethod
48
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
49
+ return super().from_float(mod, use_precomputed_fake_quant)
50
+
51
+ @classmethod
52
+ def from_reference(cls, ref_linear_relu, output_scale, output_zero_point):
53
+ return super().from_reference(
54
+ ref_linear_relu[0], output_scale, output_zero_point
55
+ )
56
+
57
+
58
+ class LinearLeakyReLU(nnq.Linear):
59
+ r"""
60
+ For onednn backend only
61
+ A LinearLeakyReLU module fused from Linear and LeakyReLU modules
62
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
63
+ Attributes:
64
+ Same as torch.ao.nn.quantized.Linear
65
+ + negative_slope
66
+ Examples::
67
+ >>> # xdoctest: +SKIP
68
+ >>> m = nn.intrinsic.LinearLeakyReLU(20, 30, 0.01)
69
+ >>> input = torch.randn(128, 20)
70
+ >>> output = m(input)
71
+ >>> print(output.size())
72
+ torch.Size([128, 30])
73
+ """
74
+
75
+ _FLOAT_MODULE = nni.LinearLeakyReLU # type: ignore[assignment]
76
+
77
+ def __init__(
78
+ self, in_features, out_features, negative_slope, bias=True, dtype=torch.qint8
79
+ ):
80
+ super().__init__(in_features, out_features, bias, dtype)
81
+ self.negative_slope = negative_slope
82
+
83
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
84
+ return torch.ops.quantized.linear_leaky_relu(
85
+ x,
86
+ self._packed_params._packed_params,
87
+ self.scale,
88
+ self.zero_point,
89
+ self.negative_slope,
90
+ )
91
+
92
+ def _get_name(self):
93
+ return "QuantizedLinearLeakyReLU"
94
+
95
+ @classmethod
96
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
97
+ if type(mod) is not nni.LinearLeakyReLU:
98
+ raise AssertionError("Input float module should be LinearLeakyReLU")
99
+ if not hasattr(mod, "qconfig"):
100
+ raise AssertionError("Input float module must have qconfig defined")
101
+ activation_post_process = mod.activation_post_process
102
+ leaky_relu = mod[1]
103
+ mod = mod[0]
104
+ weight_post_process = mod.qconfig.weight() # type: ignore[union-attr, operator]
105
+ weight_post_process(mod.weight)
106
+ dtype = weight_post_process.dtype
107
+ act_scale, act_zp = activation_post_process.calculate_qparams() # type: ignore[union-attr,operator]
108
+ if dtype != torch.qint8:
109
+ raise AssertionError(
110
+ f"Weight observer must have dtype torch.qint8, got {dtype}"
111
+ )
112
+ qweight = _quantize_weight(mod.weight.float(), weight_post_process)
113
+ qlinear_leaky_relu = cls(
114
+ mod.in_features, mod.out_features, leaky_relu.negative_slope, dtype=dtype
115
+ )
116
+ qlinear_leaky_relu.set_weight_bias(qweight, mod.bias) # type: ignore[arg-type]
117
+ qlinear_leaky_relu.scale = float(act_scale)
118
+ qlinear_leaky_relu.zero_point = int(act_zp)
119
+ return qlinear_leaky_relu
120
+
121
+ @classmethod
122
+ def from_reference(cls, ref_mod, output_scale, output_zero_point):
123
+ linear = ref_mod[0]
124
+ leaky_relu = ref_mod[1]
125
+ qlinear_leaky_relu = cls(
126
+ linear.in_features, linear.out_features, leaky_relu.negative_slope
127
+ )
128
+ qweight = linear.get_quantized_weight()
129
+ qlinear_leaky_relu.set_weight_bias(qweight, linear.bias)
130
+ qlinear_leaky_relu.scale = float(output_scale)
131
+ qlinear_leaky_relu.zero_point = int(output_zero_point)
132
+ return qlinear_leaky_relu
133
+
134
+
135
+ class LinearTanh(nnq.Linear):
136
+ r"""
137
+ A LinearTanh module fused from Linear and Tanh modules
138
+
139
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
140
+
141
+ Attributes:
142
+ Same as torch.ao.nn.quantized.Linear
143
+
144
+ Examples::
145
+
146
+ >>> # xdoctest: +SKIP
147
+ >>> m = nn.intrinsic.LinearTanh(20, 30)
148
+ >>> input = torch.randn(128, 20)
149
+ >>> output = m(input)
150
+ >>> print(output.size())
151
+ torch.Size([128, 30])
152
+ """
153
+
154
+ _FLOAT_MODULE = nni.LinearTanh # type: ignore[assignment]
155
+
156
+ def __init__(self, in_features, out_features, bias=True, dtype=torch.qint8):
157
+ super().__init__(in_features, out_features, bias, dtype)
158
+
159
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
160
+ return torch.ops.quantized.linear_tanh(
161
+ x, self._packed_params._packed_params, self.scale, self.zero_point
162
+ )
163
+
164
+ def _get_name(self):
165
+ return "QuantizedLinearTanh"
166
+
167
+ @classmethod
168
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
169
+ if type(mod) is not nni.LinearTanh:
170
+ raise AssertionError("Input float module should be LinearTanh")
171
+ if not hasattr(mod, "qconfig"):
172
+ raise AssertionError("Input float module must have qconfig defined")
173
+ activation_post_process = mod.activation_post_process
174
+ mod = mod[0]
175
+ weight_post_process = mod.qconfig.weight() # type: ignore[union-attr,operator]
176
+ weight_post_process(mod.weight)
177
+ dtype = weight_post_process.dtype
178
+ act_scale, act_zp = activation_post_process.calculate_qparams() # type: ignore[union-attr,operator]
179
+ if dtype != torch.qint8:
180
+ raise AssertionError(
181
+ f"Weight observer must have dtype torch.qint8, got {dtype}"
182
+ )
183
+ qweight = _quantize_weight(mod.weight.float(), weight_post_process)
184
+ qlinear_tanh = cls(mod.in_features, mod.out_features, dtype=dtype)
185
+ qlinear_tanh.set_weight_bias(qweight, mod.bias) # type: ignore[arg-type]
186
+ qlinear_tanh.scale = float(act_scale)
187
+ qlinear_tanh.zero_point = int(act_zp)
188
+ return qlinear_tanh
189
+
190
+ @classmethod
191
+ def from_reference(cls, ref_mod, output_scale, output_zero_point):
192
+ linear = ref_mod[0]
193
+ qlinear_tanh = cls(linear.in_features, linear.out_features)
194
+ qweight = linear.get_quantized_weight()
195
+ qlinear_tanh.set_weight_bias(qweight, linear.bias)
196
+ qlinear_tanh.scale = float(output_scale)
197
+ qlinear_tanh.zero_point = int(output_zero_point)
198
+ return qlinear_tanh
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modules import * # noqa: F403
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modules import * # noqa: F403
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/modules/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .linear import Linear
2
+
3
+
4
+ __all__ = ["Linear"]
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/modules/linear.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, TYPE_CHECKING
2
+
3
+ import torch
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from torch.ao.quantization.qconfig import QConfig
8
+
9
+
10
+ __all__ = ["Linear"]
11
+
12
+
13
+ class Linear(torch.ao.nn.qat.Linear):
14
+ r"""
15
+ A linear module attached with FakeQuantize modules for weight,
16
+ used for dynamic quantization aware training.
17
+
18
+ We adopt the same interface as `torch.nn.Linear`, please see
19
+ https://pytorch.org/docs/stable/nn.html#torch.nn.Linear
20
+ for documentation.
21
+
22
+ Similar to `torch.nn.Linear`, with FakeQuantize modules initialized to
23
+ default.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ in_features: int,
29
+ out_features: int,
30
+ bias: bool = True,
31
+ qconfig: Optional["QConfig"] = None,
32
+ device: int | str | torch.device | None = None,
33
+ dtype: str | None = None,
34
+ ) -> None:
35
+ super().__init__(in_features, out_features, bias, qconfig, device, dtype)
36
+ if not torch.ao.quantization.qconfig._activation_is_memoryless(qconfig): # type: ignore[arg-type]
37
+ raise ValueError(
38
+ "Dynamic QAT requires a memoryless observer."
39
+ + "This means a MovingAverage observer with averaging constant equal to 1"
40
+ )
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .conv import Conv1d, Conv2d, Conv3d
2
+ from .embedding_ops import Embedding, EmbeddingBag
3
+ from .linear import Linear
4
+
5
+
6
+ __all__ = [
7
+ "Linear",
8
+ "Conv1d",
9
+ "Conv2d",
10
+ "Conv3d",
11
+ "Embedding",
12
+ "EmbeddingBag",
13
+ ]
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/conv.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import ClassVar, Literal
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from torch.ao.nn.intrinsic import _FusedModule
7
+ from torch.nn.common_types import _size_1_t, _size_2_t, _size_3_t
8
+ from torch.nn.modules.utils import _pair, _single, _triple
9
+
10
+
11
+ __all__ = ["Conv1d", "Conv2d", "Conv3d"]
12
+
13
+
14
+ class _ConvNd(nn.modules.conv._ConvNd):
15
+ _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]]
16
+
17
+ def __init__(
18
+ self,
19
+ in_channels: int,
20
+ out_channels: int,
21
+ kernel_size: tuple[int, ...],
22
+ stride: tuple[int, ...],
23
+ padding: str | tuple[int, ...],
24
+ dilation: tuple[int, ...],
25
+ transposed: bool,
26
+ output_padding: tuple[int, ...],
27
+ groups: int,
28
+ bias: bool,
29
+ padding_mode: Literal["zeros", "reflect", "replicate", "circular"],
30
+ qconfig=None,
31
+ device=None,
32
+ dtype=None,
33
+ ) -> None:
34
+ factory_kwargs = {"device": device, "dtype": dtype}
35
+ nn.modules.conv._ConvNd.__init__(
36
+ self,
37
+ in_channels,
38
+ out_channels,
39
+ kernel_size,
40
+ stride,
41
+ padding,
42
+ dilation,
43
+ transposed,
44
+ output_padding,
45
+ groups,
46
+ bias,
47
+ padding_mode,
48
+ **factory_kwargs,
49
+ )
50
+ if not qconfig:
51
+ raise AssertionError("qconfig must be provided for QAT module")
52
+ self.qconfig = qconfig
53
+ self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
54
+
55
+ def forward(self, input):
56
+ return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
57
+
58
+ @staticmethod
59
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
60
+ r"""Create a qat module from a float module
61
+
62
+ Args:
63
+ `mod`: a float module, either produced by torch.ao.quantization utilities
64
+ or directly from user
65
+ """
66
+ if type(mod) is not cls._FLOAT_MODULE:
67
+ raise AssertionError(
68
+ f"qat.{cls.__name__}.from_float only works for "
69
+ f"{cls._FLOAT_MODULE.__name__}, got {type(mod).__name__}"
70
+ )
71
+ if not hasattr(mod, "qconfig"):
72
+ raise AssertionError("Input float module must have qconfig defined")
73
+ if not mod.qconfig:
74
+ raise AssertionError("Input float module must have a valid qconfig")
75
+ if issubclass(type(mod), _FusedModule):
76
+ mod = mod[0]
77
+ qconfig = mod.qconfig
78
+ qat_conv = cls(
79
+ mod.in_channels,
80
+ mod.out_channels,
81
+ mod.kernel_size,
82
+ stride=mod.stride,
83
+ padding=mod.padding,
84
+ dilation=mod.dilation,
85
+ groups=mod.groups,
86
+ bias=mod.bias is not None,
87
+ padding_mode=mod.padding_mode,
88
+ qconfig=qconfig,
89
+ )
90
+ qat_conv.weight = mod.weight
91
+ qat_conv.bias = mod.bias
92
+ return qat_conv
93
+
94
+ def to_float(self):
95
+ """This works for both single qat conv, and the qat conv - relu modules
96
+ to convert the qat module to a floating point module
97
+ """
98
+ cls = type(self)
99
+ conv = cls._FLOAT_CONV_MODULE( # type: ignore[attr-defined]
100
+ self.in_channels,
101
+ self.out_channels,
102
+ self.kernel_size,
103
+ self.stride,
104
+ self.padding,
105
+ self.dilation,
106
+ self.groups,
107
+ self.bias is not None,
108
+ self.padding_mode,
109
+ )
110
+ conv.weight = torch.nn.Parameter(self.weight.detach())
111
+ if self.bias is not None:
112
+ conv.bias = torch.nn.Parameter(self.bias.detach())
113
+ # conv relu
114
+ if issubclass(cls, _FusedModule):
115
+ modules = [conv]
116
+ if not hasattr(cls, "_FLOAT_RELU_MODULE"):
117
+ raise AssertionError(
118
+ f"{cls.__name__} must have _FLOAT_RELU_MODULE attribute"
119
+ )
120
+ relu = cls._FLOAT_RELU_MODULE()
121
+ modules.append(relu)
122
+
123
+ # pyrefly: ignore [missing-attribute]
124
+ fused = cls._FLOAT_MODULE(*modules)
125
+ fused.train(self.training)
126
+ return fused
127
+ else:
128
+ return conv
129
+
130
+
131
+ class Conv1d(_ConvNd, nn.Conv1d):
132
+ r"""
133
+ A Conv1d module attached with FakeQuantize modules for weight,
134
+ used for quantization aware training.
135
+
136
+ We adopt the same interface as :class:`~torch.nn.Conv1d`
137
+
138
+ Similar to :class:`~torch.nn.Conv2d`, with FakeQuantize modules initialized to
139
+ default.
140
+
141
+ Attributes:
142
+ weight_fake_quant: fake quant module for weight
143
+ """
144
+
145
+ _FLOAT_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
146
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
147
+
148
+ def __init__(
149
+ self,
150
+ in_channels: int,
151
+ out_channels: int,
152
+ kernel_size: _size_1_t,
153
+ stride: _size_1_t = 1,
154
+ padding: str | _size_1_t = 0,
155
+ dilation: _size_1_t = 1,
156
+ groups: int = 1,
157
+ bias: bool = True,
158
+ padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
159
+ qconfig=None,
160
+ device=None,
161
+ dtype=None,
162
+ ) -> None:
163
+ kernel_size_ = _single(kernel_size)
164
+ stride_ = _single(stride)
165
+ padding_ = padding if isinstance(padding, str) else _single(padding)
166
+ dilation_ = _single(dilation)
167
+ super().__init__(
168
+ in_channels,
169
+ out_channels,
170
+ kernel_size_,
171
+ stride=stride_,
172
+ padding=padding_,
173
+ dilation=dilation_,
174
+ transposed=False,
175
+ output_padding=_single(0),
176
+ groups=groups,
177
+ bias=bias,
178
+ padding_mode=padding_mode,
179
+ qconfig=qconfig,
180
+ device=device,
181
+ dtype=dtype,
182
+ )
183
+
184
+ @classmethod
185
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
186
+ return super().from_float(
187
+ cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
188
+ )
189
+
190
+
191
+ class Conv2d(_ConvNd, nn.Conv2d):
192
+ r"""
193
+ A Conv2d module attached with FakeQuantize modules for weight,
194
+ used for quantization aware training.
195
+
196
+ We adopt the same interface as `torch.nn.Conv2d`, please see
197
+ https://pytorch.org/docs/stable/nn.html?highlight=conv2d#torch.nn.Conv2d
198
+ for documentation.
199
+
200
+ Similar to `torch.nn.Conv2d`, with FakeQuantize modules initialized to
201
+ default.
202
+
203
+ Attributes:
204
+ weight_fake_quant: fake quant module for weight
205
+ """
206
+
207
+ _FLOAT_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
208
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
209
+
210
+ def __init__(
211
+ self,
212
+ in_channels: int,
213
+ out_channels: int,
214
+ kernel_size: _size_2_t,
215
+ stride: _size_2_t = 1,
216
+ padding: str | _size_2_t = 0,
217
+ dilation: _size_2_t = 1,
218
+ groups: int = 1,
219
+ bias: bool = True,
220
+ padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
221
+ qconfig=None,
222
+ device=None,
223
+ dtype=None,
224
+ ) -> None:
225
+ kernel_size_ = _pair(kernel_size)
226
+ stride_ = _pair(stride)
227
+ padding_ = padding if isinstance(padding, str) else _pair(padding)
228
+ dilation_ = _pair(dilation)
229
+ super().__init__(
230
+ in_channels,
231
+ out_channels,
232
+ kernel_size_,
233
+ stride=stride_,
234
+ padding=padding_,
235
+ dilation=dilation_,
236
+ transposed=False,
237
+ output_padding=_pair(0),
238
+ groups=groups,
239
+ bias=bias,
240
+ padding_mode=padding_mode,
241
+ qconfig=qconfig,
242
+ device=device,
243
+ dtype=dtype,
244
+ )
245
+
246
+ def forward(self, input):
247
+ return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
248
+
249
+ @classmethod
250
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
251
+ return super().from_float(
252
+ cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
253
+ )
254
+
255
+
256
+ class Conv3d(_ConvNd, nn.Conv3d):
257
+ r"""
258
+ A Conv3d module attached with FakeQuantize modules for weight,
259
+ used for quantization aware training.
260
+
261
+ We adopt the same interface as `torch.nn.Conv3d`, please see
262
+ https://pytorch.org/docs/stable/nn.html?highlight=conv3d#torch.nn.Conv3d
263
+ for documentation.
264
+
265
+ Similar to `torch.nn.Conv3d`, with FakeQuantize modules initialized to
266
+ default.
267
+
268
+ Attributes:
269
+ weight_fake_quant: fake quant module for weight
270
+ """
271
+
272
+ _FLOAT_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
273
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
274
+
275
+ def __init__(
276
+ self,
277
+ in_channels: int,
278
+ out_channels: int,
279
+ kernel_size: _size_3_t,
280
+ stride: _size_3_t = 1,
281
+ padding: str | _size_3_t = 0,
282
+ dilation: _size_3_t = 1,
283
+ groups: int = 1,
284
+ bias: bool = True,
285
+ padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
286
+ qconfig=None,
287
+ device=None,
288
+ dtype=None,
289
+ ) -> None:
290
+ kernel_size_ = _triple(kernel_size)
291
+ stride_ = _triple(stride)
292
+ padding_ = padding if isinstance(padding, str) else _triple(padding)
293
+ dilation_ = _triple(dilation)
294
+ super().__init__(
295
+ in_channels,
296
+ out_channels,
297
+ kernel_size_,
298
+ stride=stride_,
299
+ padding=padding_,
300
+ dilation=dilation_,
301
+ transposed=False,
302
+ output_padding=_triple(0),
303
+ groups=groups,
304
+ bias=bias,
305
+ padding_mode=padding_mode,
306
+ qconfig=qconfig,
307
+ device=device,
308
+ dtype=dtype,
309
+ )
310
+
311
+ def forward(self, input):
312
+ return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
313
+
314
+ @classmethod
315
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
316
+ return super().from_float(
317
+ cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
318
+ )
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/embedding_ops.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torch import Tensor
6
+
7
+
8
+ __all__ = ["Embedding", "EmbeddingBag"]
9
+
10
+
11
+ class Embedding(nn.Embedding):
12
+ r"""
13
+ An embedding bag module attached with FakeQuantize modules for weight,
14
+ used for quantization aware training.
15
+
16
+ We adopt the same interface as `torch.nn.Embedding`, please see
17
+ https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding
18
+ for documentation.
19
+
20
+ Similar to `torch.nn.Embedding`, with FakeQuantize modules initialized to
21
+ default.
22
+
23
+ Attributes:
24
+ weight: fake quant module for weight
25
+ """
26
+
27
+ _FLOAT_MODULE = nn.Embedding
28
+
29
+ def __init__(
30
+ self,
31
+ num_embeddings,
32
+ embedding_dim,
33
+ padding_idx=None,
34
+ max_norm=None,
35
+ norm_type=2.0,
36
+ scale_grad_by_freq=False,
37
+ sparse=False,
38
+ _weight=None,
39
+ device=None,
40
+ dtype=None,
41
+ qconfig=None,
42
+ ) -> None:
43
+ factory_kwargs = {"device": device, "dtype": dtype}
44
+ super().__init__(
45
+ num_embeddings,
46
+ embedding_dim,
47
+ padding_idx,
48
+ max_norm,
49
+ norm_type,
50
+ scale_grad_by_freq,
51
+ sparse,
52
+ _weight,
53
+ # pyrefly: ignore [bad-argument-type]
54
+ **factory_kwargs,
55
+ )
56
+ if not qconfig:
57
+ raise AssertionError("qconfig must be provided for QAT module")
58
+ weight_qscheme = qconfig.weight().qscheme
59
+ if weight_qscheme != torch.per_channel_affine_float_qparams:
60
+ raise AssertionError(
61
+ "Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
62
+ + str(weight_qscheme)
63
+ )
64
+ self.qconfig = qconfig
65
+ self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
66
+
67
+ def forward(self, input) -> Tensor:
68
+ return F.embedding(
69
+ input,
70
+ self.weight_fake_quant(self.weight),
71
+ self.padding_idx,
72
+ self.max_norm,
73
+ self.norm_type,
74
+ self.scale_grad_by_freq,
75
+ self.sparse,
76
+ )
77
+
78
+ @classmethod
79
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
80
+ r"""Create a qat module from a float module
81
+
82
+ Args: `mod` a float module, either produced by torch.ao.quantization utilities
83
+ or directly from user
84
+ """
85
+ if type(mod) is not cls._FLOAT_MODULE:
86
+ raise AssertionError(
87
+ " qat."
88
+ + cls.__name__
89
+ + ".from_float only works for "
90
+ + cls._FLOAT_MODULE.__name__
91
+ )
92
+ if not hasattr(mod, "qconfig"):
93
+ raise AssertionError("Input float module must have qconfig defined")
94
+ if not mod.qconfig:
95
+ raise AssertionError("Input float module must have a valid qconfig")
96
+ weight_qscheme = mod.qconfig.weight().qscheme # type: ignore[union-attr, operator]
97
+ if weight_qscheme != torch.per_channel_affine_float_qparams:
98
+ raise AssertionError(
99
+ "Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
100
+ + str(weight_qscheme)
101
+ )
102
+
103
+ qconfig = mod.qconfig
104
+ qat_embedding_bag = cls(
105
+ mod.num_embeddings,
106
+ mod.embedding_dim,
107
+ mod.padding_idx,
108
+ mod.max_norm,
109
+ mod.norm_type,
110
+ mod.scale_grad_by_freq,
111
+ mod.sparse,
112
+ mod.weight,
113
+ qconfig=qconfig,
114
+ )
115
+
116
+ return qat_embedding_bag
117
+
118
+ def to_float(self):
119
+ embedding_bag = torch.nn.Embedding(
120
+ self.num_embeddings,
121
+ self.embedding_dim,
122
+ self.padding_idx,
123
+ self.max_norm,
124
+ self.norm_type,
125
+ self.scale_grad_by_freq,
126
+ self.sparse,
127
+ None,
128
+ )
129
+ embedding_bag.weight = torch.nn.Parameter(self.weight.detach())
130
+ embedding_bag.train(self.training)
131
+ return embedding_bag
132
+
133
+
134
+ class EmbeddingBag(nn.EmbeddingBag):
135
+ r"""
136
+ An embedding bag module attached with FakeQuantize modules for weight,
137
+ used for quantization aware training.
138
+
139
+ We adopt the same interface as `torch.nn.EmbeddingBag`, please see
140
+ https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html#torch.nn.EmbeddingBag
141
+ for documentation.
142
+
143
+ Similar to `torch.nn.EmbeddingBag`, with FakeQuantize modules initialized to
144
+ default.
145
+
146
+ Attributes:
147
+ weight: fake quant module for weight
148
+ """
149
+
150
+ _FLOAT_MODULE = nn.EmbeddingBag
151
+
152
+ def __init__(
153
+ self,
154
+ num_embeddings,
155
+ embedding_dim,
156
+ max_norm=None,
157
+ norm_type=2.0,
158
+ scale_grad_by_freq=False,
159
+ mode="mean",
160
+ sparse=False,
161
+ _weight=None,
162
+ include_last_offset=False,
163
+ padding_idx=None,
164
+ qconfig=None,
165
+ device=None,
166
+ dtype=None,
167
+ ) -> None:
168
+ factory_kwargs = {"device": device, "dtype": dtype}
169
+ super().__init__(
170
+ num_embeddings,
171
+ embedding_dim,
172
+ max_norm,
173
+ norm_type,
174
+ scale_grad_by_freq,
175
+ mode,
176
+ sparse,
177
+ _weight,
178
+ include_last_offset,
179
+ padding_idx,
180
+ **factory_kwargs,
181
+ )
182
+ if not qconfig:
183
+ raise AssertionError("qconfig must be provided for QAT module")
184
+ weight_qscheme = qconfig.weight().qscheme
185
+ if weight_qscheme != torch.per_channel_affine_float_qparams:
186
+ raise AssertionError(
187
+ "Embedding Bag weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
188
+ + str(weight_qscheme)
189
+ )
190
+ self.qconfig = qconfig
191
+ self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
192
+
193
+ def forward(self, input, offsets=None, per_sample_weights=None) -> Tensor:
194
+ return F.embedding_bag(
195
+ input,
196
+ self.weight_fake_quant(self.weight),
197
+ offsets,
198
+ self.max_norm,
199
+ self.norm_type,
200
+ self.scale_grad_by_freq,
201
+ self.mode,
202
+ self.sparse,
203
+ per_sample_weights,
204
+ self.include_last_offset,
205
+ self.padding_idx,
206
+ )
207
+
208
+ @classmethod
209
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
210
+ r"""Create a qat module from a float module
211
+
212
+ Args: `mod` a float module, either produced by torch.ao.quantization utilities
213
+ or directly from user
214
+ """
215
+ if type(mod) is not cls._FLOAT_MODULE:
216
+ raise AssertionError(
217
+ " qat."
218
+ + cls.__name__
219
+ + ".from_float only works for "
220
+ + cls._FLOAT_MODULE.__name__
221
+ )
222
+ if not hasattr(mod, "qconfig"):
223
+ raise AssertionError("Input float module must have qconfig defined")
224
+ if not mod.qconfig:
225
+ raise AssertionError("Input float module must have a valid qconfig")
226
+ weight_qscheme = mod.qconfig.weight().qscheme # type: ignore[union-attr, operator]
227
+ if weight_qscheme != torch.per_channel_affine_float_qparams:
228
+ raise AssertionError(
229
+ "Embedding Bag weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
230
+ + str(weight_qscheme)
231
+ )
232
+
233
+ qconfig = mod.qconfig
234
+ qat_embedding_bag = cls(
235
+ mod.num_embeddings,
236
+ mod.embedding_dim,
237
+ mod.max_norm,
238
+ mod.norm_type,
239
+ mod.scale_grad_by_freq,
240
+ mod.mode,
241
+ mod.sparse,
242
+ mod.weight,
243
+ mod.include_last_offset,
244
+ mod.padding_idx,
245
+ qconfig=qconfig,
246
+ )
247
+
248
+ return qat_embedding_bag
249
+
250
+ def to_float(self):
251
+ embedding_bag = torch.nn.EmbeddingBag(
252
+ self.num_embeddings,
253
+ self.embedding_dim,
254
+ self.max_norm,
255
+ self.norm_type,
256
+ self.scale_grad_by_freq,
257
+ self.mode,
258
+ self.sparse,
259
+ None,
260
+ self.include_last_offset,
261
+ self.padding_idx,
262
+ )
263
+ embedding_bag.weight = torch.nn.Parameter(self.weight.detach())
264
+ embedding_bag.train(self.training)
265
+ return embedding_bag
.venv/lib/python3.10/site-packages/torch/ao/nn/qat/modules/linear.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torch.ao.nn.intrinsic import LinearReLU
6
+ from torch.nn.utils.parametrize import (
7
+ is_parametrized,
8
+ transfer_parametrizations_and_params,
9
+ type_before_parametrizations,
10
+ )
11
+
12
+
13
+ __all__ = ["Linear"]
14
+
15
+
16
+ class Linear(nn.Linear):
17
+ r"""
18
+ A linear module attached with FakeQuantize modules for weight,
19
+ used for quantization aware training.
20
+
21
+ We adopt the same interface as `torch.nn.Linear`, please see
22
+ https://pytorch.org/docs/stable/nn.html#torch.nn.Linear
23
+ for documentation.
24
+
25
+ Similar to `torch.nn.Linear`, with FakeQuantize modules initialized to
26
+ default.
27
+
28
+ Attributes:
29
+ weight: fake quant module for weight
30
+ """
31
+
32
+ _FLOAT_MODULE = nn.Linear
33
+
34
+ def __init__(
35
+ self,
36
+ in_features,
37
+ out_features,
38
+ bias=True,
39
+ qconfig=None,
40
+ device=None,
41
+ dtype=None,
42
+ ) -> None:
43
+ factory_kwargs = {"device": device, "dtype": dtype}
44
+ super().__init__(in_features, out_features, bias, **factory_kwargs)
45
+ if not qconfig:
46
+ raise AssertionError("qconfig must be provided for QAT module")
47
+ self.qconfig = qconfig
48
+ self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
49
+
50
+ def forward(self, input):
51
+ return F.linear(input, self.weight_fake_quant(self.weight), self.bias)
52
+
53
+ @classmethod
54
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
55
+ r"""Create a qat module from a float module or qparams_dict
56
+ Args: `mod` a float module, either produced by torch.ao.quantization utilities
57
+ or directly from user
58
+ """
59
+ if type_before_parametrizations(mod) != cls._FLOAT_MODULE:
60
+ raise AssertionError(
61
+ f"qat.{cls.__name__}.from_float only works for "
62
+ f"{cls._FLOAT_MODULE.__name__}, got {type_before_parametrizations(mod).__name__}"
63
+ )
64
+ if not hasattr(mod, "qconfig"):
65
+ raise AssertionError("Input float module must have qconfig defined")
66
+ if not mod.qconfig:
67
+ raise AssertionError("Input float module must have a valid qconfig")
68
+ if type_before_parametrizations(mod) == LinearReLU:
69
+ mod = mod[0]
70
+
71
+ qconfig = mod.qconfig
72
+ qat_linear = cls(
73
+ mod.in_features,
74
+ mod.out_features,
75
+ bias=mod.bias is not None,
76
+ qconfig=qconfig,
77
+ )
78
+
79
+ if is_parametrized(mod, "weight"):
80
+ transfer_parametrizations_and_params(mod, qat_linear, "weight")
81
+ else:
82
+ qat_linear.weight = mod.weight
83
+
84
+ if is_parametrized(mod, "bias"):
85
+ transfer_parametrizations_and_params(mod, qat_linear, "bias")
86
+ else:
87
+ qat_linear.bias = mod.bias
88
+
89
+ return qat_linear
90
+
91
+ def to_float(self):
92
+ linear = torch.nn.Linear(
93
+ self.in_features, self.out_features, self.bias is not None
94
+ )
95
+ linear.weight = torch.nn.Parameter(self.weight.detach())
96
+ if self.bias is not None:
97
+ linear.bias = torch.nn.Parameter(self.bias.detach())
98
+ linear.train(self.training)
99
+ return linear
.venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modules import * # noqa: F403
.venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from .activation import MultiheadAttention
2
+ from .rnn import LSTM, LSTMCell
3
+
4
+
5
+ __all__ = [
6
+ "LSTM",
7
+ "LSTMCell",
8
+ "MultiheadAttention",
9
+ ]
.venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/activation.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+
4
+ import torch
5
+ import torch.jit # this is needed to avoid a circular import
6
+ import torch.nn.functional as F
7
+ from torch import nn, Tensor
8
+
9
+
10
+ __all__ = ["MultiheadAttention"]
11
+
12
+
13
+ class MultiheadAttention(nn.MultiheadAttention):
14
+ _FLOAT_MODULE = nn.MultiheadAttention
15
+
16
+ r"""Quantizable implementation of the MultiheadAttention.
17
+
18
+ Note::
19
+ Please, refer to :class:`~torch.nn.MultiheadAttention` for more
20
+ information
21
+
22
+ Allows the model to jointly attend to information from different
23
+ representation subspaces.
24
+ See reference: Attention Is All You Need
25
+
26
+ The original MHA module is not quantizable.
27
+ This reimplements it by explicitly instantiating the linear layers.
28
+
29
+ .. math::
30
+ \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
31
+ \text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)
32
+
33
+ Args:
34
+ embed_dim: total dimension of the model.
35
+ num_heads: parallel attention heads.
36
+ dropout: a Dropout layer on attn_output_weights. Default: 0.0.
37
+ bias: add bias as module parameter. Default: True.
38
+ add_bias_kv: add bias to the key and value sequences at dim=0.
39
+ add_zero_attn: add a new batch of zeros to the key and
40
+ value sequences at dim=1.
41
+ kdim: total number of features in key. Default: None.
42
+ vdim: total number of features in value. Default: None.
43
+ batch_first: If ``True``, then the input and output tensors are provided
44
+ as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
45
+
46
+ Note that if :attr:`kdim` and :attr:`vdim` are None, they will be set
47
+ to :attr:`embed_dim` such that query, key, and value have the same
48
+ number of features.
49
+
50
+ Examples::
51
+
52
+ >>> import torch.ao.nn.quantizable as nnqa
53
+ >>> multihead_attn = nnqa.MultiheadAttention(embed_dim, num_heads)
54
+ >>> attn_output, attn_output_weights = multihead_attn(query, key, value)
55
+
56
+ Note::
57
+ Please, follow the quantization flow to convert the quantizable MHA.
58
+ """
59
+ __constants__ = ["batch_first"]
60
+
61
+ def __init__(
62
+ self,
63
+ embed_dim: int,
64
+ num_heads: int,
65
+ dropout: float = 0.0,
66
+ bias: bool = True,
67
+ add_bias_kv: bool = False,
68
+ add_zero_attn: bool = False,
69
+ kdim: int | None = None,
70
+ vdim: int | None = None,
71
+ batch_first: bool = False,
72
+ device=None,
73
+ dtype=None,
74
+ ) -> None:
75
+ factory_kwargs = {"device": device, "dtype": dtype}
76
+ super().__init__(
77
+ embed_dim,
78
+ num_heads,
79
+ dropout,
80
+ bias,
81
+ add_bias_kv,
82
+ add_zero_attn,
83
+ kdim,
84
+ vdim,
85
+ batch_first,
86
+ **factory_kwargs,
87
+ )
88
+ self.linear_Q = nn.Linear(
89
+ self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs
90
+ )
91
+ self.linear_K = nn.Linear(
92
+ self.kdim, self.embed_dim, bias=bias, **factory_kwargs
93
+ )
94
+ self.linear_V = nn.Linear(
95
+ self.vdim, self.embed_dim, bias=bias, **factory_kwargs
96
+ )
97
+ # for the type: ignore, see https://github.com/pytorch/pytorch/issues/58969
98
+ # pyrefly: ignore [bad-assignment]
99
+ self.out_proj = nn.Linear(
100
+ self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs
101
+ ) # type: ignore[assignment]
102
+
103
+ # Functionals
104
+ self.q_scaling_product = torch.ao.nn.quantized.FloatFunctional()
105
+ # note: importing torch.ao.nn.quantized at top creates a circular import
106
+
107
+ # Quant/Dequant
108
+ self.quant_attn_output = torch.ao.quantization.QuantStub()
109
+ self.quant_attn_output_weights = torch.ao.quantization.QuantStub()
110
+ self.dequant_q = torch.ao.quantization.DeQuantStub()
111
+ self.dequant_k = torch.ao.quantization.DeQuantStub()
112
+ self.dequant_v = torch.ao.quantization.DeQuantStub()
113
+
114
+ def _get_name(self):
115
+ return "QuantizableMultiheadAttention"
116
+
117
+ @classmethod
118
+ def from_float(cls, other):
119
+ if type(other) is not cls._FLOAT_MODULE:
120
+ raise AssertionError(
121
+ f"Expected type {cls._FLOAT_MODULE}, got {type(other)}"
122
+ )
123
+ if not hasattr(other, "qconfig"):
124
+ raise AssertionError("The float module must have 'qconfig'")
125
+ # Setting the dropout to 0.0!
126
+ observed = cls(
127
+ other.embed_dim,
128
+ other.num_heads,
129
+ other.dropout,
130
+ (other.in_proj_bias is not None),
131
+ (other.bias_k is not None),
132
+ other.add_zero_attn,
133
+ other.kdim,
134
+ other.vdim,
135
+ other.batch_first,
136
+ )
137
+ observed.bias_k = other.bias_k
138
+ observed.bias_v = other.bias_v
139
+ observed.qconfig = other.qconfig
140
+
141
+ # Set the linear weights
142
+ # for the type: ignores, see https://github.com/pytorch/pytorch/issues/58969
143
+ observed.out_proj.weight = other.out_proj.weight
144
+ observed.out_proj.bias = other.out_proj.bias
145
+ if other._qkv_same_embed_dim:
146
+ # Use separate params
147
+ bias = other.in_proj_bias
148
+ _start = 0
149
+ _end = _start + other.embed_dim
150
+ weight = other.in_proj_weight[_start:_end, :]
151
+ if bias is not None:
152
+ bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
153
+ observed.linear_Q.weight = torch.nn.Parameter(weight, weight.requires_grad)
154
+ observed.linear_Q.bias = bias
155
+
156
+ bias = other.in_proj_bias
157
+ _start = _end
158
+ _end = _start + other.embed_dim
159
+ weight = other.in_proj_weight[_start:_end, :]
160
+ if bias is not None:
161
+ bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
162
+ observed.linear_K.weight = torch.nn.Parameter(weight, weight.requires_grad)
163
+ observed.linear_K.bias = bias
164
+
165
+ bias = other.in_proj_bias
166
+ _start = _end
167
+ weight = other.in_proj_weight[_start:, :]
168
+ if bias is not None:
169
+ bias = torch.nn.Parameter(bias[_start:], bias.requires_grad)
170
+ observed.linear_V.weight = torch.nn.Parameter(weight, weight.requires_grad)
171
+ observed.linear_V.bias = bias
172
+ else:
173
+ observed.linear_Q.weight = nn.Parameter(other.q_proj_weight)
174
+ observed.linear_K.weight = nn.Parameter(other.k_proj_weight)
175
+ observed.linear_V.weight = nn.Parameter(other.v_proj_weight)
176
+ if other.in_proj_bias is None:
177
+ # pyrefly: ignore [bad-assignment]
178
+ observed.linear_Q.bias = None
179
+ # pyrefly: ignore [bad-assignment]
180
+ observed.linear_K.bias = None
181
+ # pyrefly: ignore [bad-assignment]
182
+ observed.linear_V.bias = None
183
+ else:
184
+ observed.linear_Q.bias = nn.Parameter(
185
+ other.in_proj_bias[0 : other.embed_dim]
186
+ )
187
+ observed.linear_K.bias = nn.Parameter(
188
+ other.in_proj_bias[other.embed_dim : (other.embed_dim * 2)]
189
+ )
190
+ observed.linear_V.bias = nn.Parameter(
191
+ other.in_proj_bias[(other.embed_dim * 2) :]
192
+ )
193
+ observed.eval()
194
+ # Explicit prepare
195
+ observed = torch.ao.quantization.prepare(observed, inplace=True)
196
+ return observed
197
+
198
+ @torch.jit.unused
199
+ def dequantize(self):
200
+ r"""Utility to convert the quantized MHA back to float.
201
+
202
+ The motivation for this is that it is not trivial to convert the weights
203
+ from the format that is used in the quantized version back to the
204
+ float.
205
+ """
206
+ fp = self._FLOAT_MODULE(
207
+ self.embed_dim,
208
+ self.num_heads,
209
+ self.dropout,
210
+ (self.linear_Q._weight_bias()[1] is not None), # type: ignore[operator]
211
+ (self.bias_k is not None),
212
+ self.add_zero_attn,
213
+ self.kdim,
214
+ self.vdim,
215
+ self.batch_first,
216
+ )
217
+ if fp._qkv_same_embed_dim != self._qkv_same_embed_dim:
218
+ raise AssertionError(
219
+ f"_qkv_same_embed_dim mismatch: {fp._qkv_same_embed_dim} != {self._qkv_same_embed_dim}"
220
+ )
221
+ if self.bias_k is not None:
222
+ fp.bias_k = nn.Parameter(self.bias_k.dequantize())
223
+ if self.bias_v is not None:
224
+ fp.bias_v = nn.Parameter(self.bias_v.dequantize())
225
+
226
+ # Set the linear weights
227
+ # Note: Because the linear layers are quantized, mypy does not know how
228
+ # to deal with them -- might need to ignore the typing checks.
229
+ # for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
230
+ w, b = self.out_proj._weight_bias() # type: ignore[operator, has-type]
231
+ fp.out_proj.weight = nn.Parameter(w.dequantize())
232
+ if b is not None:
233
+ fp.out_proj.bias = nn.Parameter(b)
234
+
235
+ wQ, bQ = self.linear_Q._weight_bias() # type: ignore[operator]
236
+ wQ = wQ.dequantize()
237
+ wK, bK = self.linear_K._weight_bias() # type: ignore[operator]
238
+ wK = wK.dequantize()
239
+ wV, bV = self.linear_V._weight_bias() # type: ignore[operator]
240
+ wV = wV.dequantize()
241
+ if fp._qkv_same_embed_dim:
242
+ # Use separate params
243
+ _start = 0
244
+ _end = _start + fp.embed_dim
245
+ fp.in_proj_weight[_start:_end, :] = wQ
246
+ if fp.in_proj_bias is not None:
247
+ # pyrefly: ignore [bad-argument-type]
248
+ if not all(bQ == 0):
249
+ raise AssertionError("Expected all bQ elements to be 0")
250
+ fp.in_proj_bias[_start:_end] = bQ
251
+
252
+ _start = _end
253
+ _end = _start + fp.embed_dim
254
+ fp.in_proj_weight[_start:_end, :] = wK
255
+ if fp.in_proj_bias is not None:
256
+ # pyrefly: ignore [bad-argument-type]
257
+ if not all(bK == 0):
258
+ raise AssertionError("Expected all bK elements to be 0")
259
+ fp.in_proj_bias[_start:_end] = bK
260
+
261
+ _start = _end
262
+ fp.in_proj_weight[_start:, :] = wV
263
+ if fp.in_proj_bias is not None:
264
+ # pyrefly: ignore [bad-argument-type]
265
+ if not all(bV == 0):
266
+ raise AssertionError("Expected all bV elements to be 0")
267
+ fp.in_proj_bias[_start:] = bV
268
+ else:
269
+ fp.q_proj_weight = nn.Parameter(wQ)
270
+ fp.k_proj_weight = nn.Parameter(wK)
271
+ fp.v_proj_weight = nn.Parameter(wV)
272
+ if fp.in_proj_bias is None:
273
+ # pyrefly: ignore [bad-assignment]
274
+ self.linear_Q.bias = None
275
+ # pyrefly: ignore [bad-assignment]
276
+ self.linear_K.bias = None
277
+ # pyrefly: ignore [bad-assignment]
278
+ self.linear_V.bias = None
279
+ else:
280
+ fp.in_proj_bias[0 : fp.embed_dim] = bQ
281
+ fp.in_proj_bias[fp.embed_dim : (fp.embed_dim * 2)] = bK
282
+ fp.in_proj_bias[(fp.embed_dim * 2) :] = bV
283
+
284
+ return fp
285
+
286
+ @classmethod
287
+ def from_observed(cls, other):
288
+ # The whole flow is float -> observed -> quantized
289
+ # This class does float -> observed only
290
+ # See nn.quantized.MultiheadAttention
291
+ raise NotImplementedError(
292
+ "It looks like you are trying to prepare an "
293
+ "MHA module. Please, see "
294
+ "the examples on quantizable MHAs."
295
+ )
296
+
297
+ def forward(
298
+ self,
299
+ query: Tensor,
300
+ key: Tensor,
301
+ value: Tensor,
302
+ key_padding_mask: Tensor | None = None,
303
+ need_weights: bool = True,
304
+ attn_mask: Tensor | None = None,
305
+ average_attn_weights: bool = True,
306
+ is_causal: bool = False,
307
+ ) -> tuple[Tensor, Tensor | None]:
308
+ r"""
309
+ Note::
310
+ Please, refer to :func:`~torch.nn.MultiheadAttention.forward` for more
311
+ information
312
+
313
+ Args:
314
+ query, key, value: map a query and a set of key-value pairs to an output.
315
+ See "Attention Is All You Need" for more details.
316
+ key_padding_mask: if provided, specified padding elements in the key will
317
+ be ignored by the attention. When given a binary mask and a value is True,
318
+ the corresponding value on the attention layer will be ignored.
319
+ need_weights: output attn_output_weights.
320
+ attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
321
+ the batches while a 3D mask allows to specify a different mask for the entries of each batch.
322
+
323
+ Shape:
324
+ - Inputs:
325
+ - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
326
+ the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
327
+ - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
328
+ the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
329
+ - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
330
+ the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
331
+ - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
332
+ If a BoolTensor is provided, the positions with the
333
+ value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
334
+ - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
335
+ 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
336
+ S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked
337
+ positions. If a BoolTensor is provided, positions with ``True``
338
+ is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
339
+ is provided, it will be added to the attention weight.
340
+ - is_causal: If specified, applies a causal mask as attention mask. Mutually exclusive with providing attn_mask.
341
+ Default: ``False``.
342
+ - average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
343
+ heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
344
+ effect when ``need_weights=True.``. Default: True (i.e. average weights across heads)
345
+
346
+ - Outputs:
347
+ - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
348
+ E is the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
349
+ - attn_output_weights: If ``average_attn_weights=True``, returns attention weights averaged
350
+ across heads of shape :math:`(N, L, S)`, where N is the batch size, L is the target sequence length,
351
+ S is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
352
+ head of shape :math:`(N, num_heads, L, S)`.
353
+ """
354
+ return self._forward_impl(
355
+ query,
356
+ key,
357
+ value,
358
+ key_padding_mask,
359
+ need_weights,
360
+ attn_mask,
361
+ average_attn_weights,
362
+ is_causal,
363
+ )
364
+
365
+ def _forward_impl(
366
+ self,
367
+ query: Tensor,
368
+ key: Tensor,
369
+ value: Tensor,
370
+ key_padding_mask: Tensor | None = None,
371
+ need_weights: bool = True,
372
+ attn_mask: Tensor | None = None,
373
+ average_attn_weights: bool = True,
374
+ is_causal: bool = False,
375
+ ) -> tuple[Tensor, Tensor | None]:
376
+ # This version will not deal with the static key/value pairs.
377
+ # Keeping it here for future changes.
378
+ #
379
+ # TODO: This method has some duplicate lines with the
380
+ # `torch.nn.functional.multi_head_attention`. Will need to refactor.
381
+ static_k = None
382
+ static_v = None
383
+
384
+ if attn_mask is not None and is_causal:
385
+ raise AssertionError("Only allow causal mask or attn_mask")
386
+
387
+ if is_causal:
388
+ raise AssertionError("causal mask not supported by AO MHA module")
389
+
390
+ if self.batch_first:
391
+ query, key, value = (x.transpose(0, 1) for x in (query, key, value))
392
+
393
+ tgt_len, bsz, embed_dim_to_check = query.size()
394
+ if self.embed_dim != embed_dim_to_check:
395
+ raise AssertionError(
396
+ f"embed_dim mismatch: {self.embed_dim} != {embed_dim_to_check}"
397
+ )
398
+ # allow MHA to have different sizes for the feature dimension
399
+ if key.size(0) != value.size(0) or key.size(1) != value.size(1):
400
+ raise AssertionError(
401
+ f"key and value size mismatch: key.size()={key.size()}, value.size()={value.size()}"
402
+ )
403
+
404
+ head_dim = self.embed_dim // self.num_heads
405
+ if head_dim * self.num_heads != self.embed_dim:
406
+ raise AssertionError("embed_dim must be divisible by num_heads")
407
+ scaling = float(head_dim) ** -0.5
408
+
409
+ q = self.linear_Q(query)
410
+ k = self.linear_K(key)
411
+ v = self.linear_V(value)
412
+
413
+ q = self.q_scaling_product.mul_scalar(q, scaling)
414
+
415
+ if attn_mask is not None:
416
+ if attn_mask.dtype == torch.uint8:
417
+ warnings.warn(
418
+ "Byte tensor for `attn_mask` in `nn.MultiheadAttention` is deprecated. "
419
+ "Use bool tensor instead.",
420
+ stacklevel=3,
421
+ )
422
+ attn_mask = attn_mask.to(torch.bool)
423
+ if not attn_mask.is_floating_point() and attn_mask.dtype != torch.bool:
424
+ raise AssertionError(
425
+ f"Only float and bool types are supported for attn_mask, not {attn_mask.dtype}"
426
+ )
427
+
428
+ if attn_mask.dim() == 2:
429
+ attn_mask = attn_mask.unsqueeze(0)
430
+ if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
431
+ raise RuntimeError("The size of the 2D attn_mask is not correct.")
432
+ elif attn_mask.dim() == 3:
433
+ if list(attn_mask.size()) != [
434
+ bsz * self.num_heads,
435
+ query.size(0),
436
+ key.size(0),
437
+ ]:
438
+ raise RuntimeError("The size of the 3D attn_mask is not correct.")
439
+ else:
440
+ raise RuntimeError(
441
+ f"attn_mask's dimension {attn_mask.dim()} is not supported"
442
+ )
443
+ # attn_mask's dim is 3 now.
444
+
445
+ # convert ByteTensor key_padding_mask to bool
446
+ if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
447
+ warnings.warn(
448
+ "Byte tensor for `key_padding_mask` in `nn.MultiheadAttention` is deprecated. "
449
+ "Use bool tensor instead.",
450
+ stacklevel=3,
451
+ )
452
+ key_padding_mask = key_padding_mask.to(torch.bool)
453
+ if self.bias_k is not None and self.bias_v is not None:
454
+ if static_k is None and static_v is None:
455
+ # Explicitly check that bias_k and bias_v are not None
456
+ # in a way that TorchScript can understand.
457
+ bias_k = self.bias_k
458
+ if bias_k is None:
459
+ raise AssertionError("bias_k must not be None")
460
+ bias_v = self.bias_v
461
+ if bias_v is None:
462
+ raise AssertionError("bias_v must not be None")
463
+
464
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
465
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
466
+ if attn_mask is not None:
467
+ attn_mask = F.pad(attn_mask, (0, 1))
468
+ if key_padding_mask is not None:
469
+ key_padding_mask = F.pad(key_padding_mask, (0, 1))
470
+ else:
471
+ if static_k is not None:
472
+ raise AssertionError("bias cannot be added to static key.")
473
+ if static_v is not None:
474
+ raise AssertionError("bias cannot be added to static value.")
475
+ else:
476
+ if self.bias_k is not None:
477
+ raise AssertionError(
478
+ "self.bias_k must be None when self.bias_v is None"
479
+ )
480
+ if self.bias_v is not None:
481
+ raise AssertionError(
482
+ "self.bias_v must be None when self.bias_k is None"
483
+ )
484
+
485
+ q = q.contiguous().view(tgt_len, bsz * self.num_heads, head_dim).transpose(0, 1)
486
+ if k is not None:
487
+ k = k.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
488
+ if v is not None:
489
+ v = v.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
490
+
491
+ if static_k is not None:
492
+ if static_k.size(0) != bsz * self.num_heads:
493
+ raise AssertionError(
494
+ f"static_k.size(0) must be {bsz * self.num_heads}, got {static_k.size(0)}"
495
+ )
496
+ if static_k.size(2) != head_dim:
497
+ raise AssertionError(
498
+ f"static_k.size(2) must be {head_dim}, got {static_k.size(2)}"
499
+ )
500
+ k = static_k
501
+
502
+ if static_v is not None:
503
+ if static_v.size(0) != bsz * self.num_heads:
504
+ raise AssertionError(
505
+ f"static_v.size(0) must be {bsz * self.num_heads}, got {static_v.size(0)}"
506
+ )
507
+ if static_v.size(2) != head_dim:
508
+ raise AssertionError(
509
+ f"static_v.size(2) must be {head_dim}, got {static_v.size(2)}"
510
+ )
511
+ v = static_v
512
+
513
+ src_len = k.size(1)
514
+
515
+ if key_padding_mask is not None:
516
+ if key_padding_mask.size(0) != bsz:
517
+ raise AssertionError(
518
+ f"key_padding_mask.size(0) must be {bsz}, got {key_padding_mask.size(0)}"
519
+ )
520
+ if key_padding_mask.size(1) != src_len:
521
+ raise AssertionError(
522
+ f"key_padding_mask.size(1) must be {src_len}, got {key_padding_mask.size(1)}"
523
+ )
524
+
525
+ if self.add_zero_attn:
526
+ src_len += 1
527
+
528
+ k_zeros = torch.zeros((k.size(0), 1) + k.size()[2:])
529
+
530
+ if k.is_quantized:
531
+ k_zeros = torch.quantize_per_tensor(
532
+ k_zeros,
533
+ k.q_scale(),
534
+ k.q_zero_point(),
535
+ k.dtype,
536
+ )
537
+
538
+ k = torch.cat([k, k_zeros], dim=1)
539
+
540
+ v_zeros = torch.zeros((v.size(0), 1) + k.size()[2:])
541
+
542
+ if v.is_quantized:
543
+ v_zeros = torch.quantize_per_tensor(
544
+ v_zeros,
545
+ v.q_scale(),
546
+ v.q_zero_point(),
547
+ v.dtype,
548
+ )
549
+
550
+ v = torch.cat([v, v_zeros], dim=1)
551
+
552
+ if attn_mask is not None:
553
+ attn_mask = F.pad(attn_mask, (0, 1))
554
+ if key_padding_mask is not None:
555
+ key_padding_mask = F.pad(key_padding_mask, (0, 1))
556
+
557
+ # Leaving the quantized zone here
558
+ q = self.dequant_q(q)
559
+ k = self.dequant_k(k)
560
+ v = self.dequant_v(v)
561
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2))
562
+ expected_size = [bsz * self.num_heads, tgt_len, src_len]
563
+ if list(attn_output_weights.size()) != expected_size:
564
+ raise AssertionError(
565
+ f"attn_output_weights size mismatch: expected {expected_size}, "
566
+ f"got {list(attn_output_weights.size())}"
567
+ )
568
+
569
+ if attn_mask is not None:
570
+ if attn_mask.dtype == torch.bool:
571
+ attn_output_weights.masked_fill_(attn_mask, float("-inf"))
572
+ else:
573
+ attn_output_weights += attn_mask
574
+
575
+ if key_padding_mask is not None:
576
+ attn_output_weights = attn_output_weights.view(
577
+ bsz, self.num_heads, tgt_len, src_len
578
+ )
579
+ attn_output_weights = attn_output_weights.masked_fill(
580
+ key_padding_mask.unsqueeze(1).unsqueeze(2),
581
+ float("-inf"),
582
+ )
583
+ attn_output_weights = attn_output_weights.view(
584
+ bsz * self.num_heads, tgt_len, src_len
585
+ )
586
+
587
+ attn_output_weights = F.softmax(attn_output_weights, dim=-1)
588
+ attn_output_weights = F.dropout(
589
+ attn_output_weights, p=self.dropout, training=self.training
590
+ )
591
+
592
+ attn_output = torch.bmm(attn_output_weights, v)
593
+ expected_output_size = [bsz * self.num_heads, tgt_len, head_dim]
594
+ if list(attn_output.size()) != expected_output_size:
595
+ raise AssertionError(
596
+ f"attn_output size mismatch: expected {expected_output_size}, "
597
+ f"got {list(attn_output.size())}"
598
+ )
599
+ if self.batch_first:
600
+ attn_output = attn_output.view(bsz, tgt_len, self.embed_dim)
601
+ else:
602
+ attn_output = (
603
+ attn_output.transpose(0, 1)
604
+ .contiguous()
605
+ .view(tgt_len, bsz, self.embed_dim)
606
+ )
607
+
608
+ # Reentering the quantized zone
609
+ attn_output = self.quant_attn_output(attn_output)
610
+ # for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
611
+ attn_output = self.out_proj(attn_output) # type: ignore[has-type]
612
+ attn_output_weights = self.quant_attn_output_weights(attn_output_weights)
613
+
614
+ if need_weights:
615
+ # average attention weights over heads
616
+ attn_output_weights = attn_output_weights.view(
617
+ bsz, self.num_heads, tgt_len, src_len
618
+ )
619
+ if average_attn_weights:
620
+ attn_output_weights = attn_output_weights.mean(dim=1)
621
+ return attn_output, attn_output_weights
622
+ else:
623
+ return attn_output, None
.venv/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/rnn.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ We will recreate all the RNN modules as we require the modules to be decomposed
3
+ into its building blocks to be able to observe.
4
+ """
5
+
6
+ # mypy: allow-untyped-defs
7
+
8
+ import numbers
9
+ import warnings
10
+
11
+ import torch
12
+ from torch import Tensor
13
+
14
+
15
+ __all__ = ["LSTMCell", "LSTM"]
16
+
17
+
18
+ class LSTMCell(torch.nn.Module):
19
+ r"""A quantizable long short-term memory (LSTM) cell.
20
+
21
+ For the description and the argument types, please, refer to :class:`~torch.nn.LSTMCell`
22
+
23
+ `split_gates`: specify True to compute the input/forget/cell/output gates separately
24
+ to avoid an intermediate tensor which is subsequently chunk'd. This optimization can
25
+ be beneficial for on-device inference latency. This flag is cascaded down from the
26
+ parent classes.
27
+
28
+ Examples::
29
+
30
+ >>> import torch.ao.nn.quantizable as nnqa
31
+ >>> rnn = nnqa.LSTMCell(10, 20)
32
+ >>> input = torch.randn(6, 10)
33
+ >>> hx = torch.randn(3, 20)
34
+ >>> cx = torch.randn(3, 20)
35
+ >>> output = []
36
+ >>> for i in range(6):
37
+ ... hx, cx = rnn(input[i], (hx, cx))
38
+ ... output.append(hx)
39
+ """
40
+
41
+ _FLOAT_MODULE = torch.nn.LSTMCell
42
+ __constants__ = ["split_gates"] # for jit.script
43
+
44
+ def __init__(
45
+ self,
46
+ input_dim: int,
47
+ hidden_dim: int,
48
+ bias: bool = True,
49
+ device=None,
50
+ dtype=None,
51
+ *,
52
+ split_gates=False,
53
+ ) -> None:
54
+ factory_kwargs = {"device": device, "dtype": dtype}
55
+ super().__init__()
56
+ self.input_size = input_dim
57
+ self.hidden_size = hidden_dim
58
+ self.bias = bias
59
+ self.split_gates = split_gates
60
+
61
+ if not split_gates:
62
+ self.igates: torch.nn.Module = torch.nn.Linear(
63
+ input_dim, 4 * hidden_dim, bias=bias, **factory_kwargs
64
+ )
65
+ self.hgates: torch.nn.Module = torch.nn.Linear(
66
+ hidden_dim, 4 * hidden_dim, bias=bias, **factory_kwargs
67
+ )
68
+ self.gates: torch.nn.Module = torch.ao.nn.quantized.FloatFunctional()
69
+ else:
70
+ # keep separate Linear layers for each gate
71
+ self.igates = torch.nn.ModuleDict()
72
+ self.hgates = torch.nn.ModuleDict()
73
+ self.gates = torch.nn.ModuleDict()
74
+ for g in ["input", "forget", "cell", "output"]:
75
+ # pyre-fixme[29]: `Union[torch._tensor.Tensor, torch.nn.modules.module.Module]`
76
+ self.igates[g] = torch.nn.Linear(
77
+ input_dim, hidden_dim, bias=bias, **factory_kwargs
78
+ )
79
+ # pyre-fixme[29]: `Union[torch._tensor.Tensor, torch.nn.modules.module.Module]`
80
+ self.hgates[g] = torch.nn.Linear(
81
+ hidden_dim, hidden_dim, bias=bias, **factory_kwargs
82
+ )
83
+ # pyre-fixme[29]: `Union[torch._tensor.Tensor, torch.nn.modules.module.Module]`
84
+ self.gates[g] = torch.ao.nn.quantized.FloatFunctional()
85
+
86
+ self.input_gate = torch.nn.Sigmoid()
87
+ self.forget_gate = torch.nn.Sigmoid()
88
+ self.cell_gate = torch.nn.Tanh()
89
+ self.output_gate = torch.nn.Sigmoid()
90
+
91
+ self.fgate_cx = torch.ao.nn.quantized.FloatFunctional()
92
+ self.igate_cgate = torch.ao.nn.quantized.FloatFunctional()
93
+ self.fgate_cx_igate_cgate = torch.ao.nn.quantized.FloatFunctional()
94
+
95
+ self.ogate_cy = torch.ao.nn.quantized.FloatFunctional()
96
+
97
+ self.initial_hidden_state_qparams: tuple[float, int] = (1.0, 0)
98
+ self.initial_cell_state_qparams: tuple[float, int] = (1.0, 0)
99
+ self.hidden_state_dtype: torch.dtype = torch.quint8
100
+ self.cell_state_dtype: torch.dtype = torch.quint8
101
+
102
+ def forward(
103
+ self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None
104
+ ) -> tuple[Tensor, Tensor]:
105
+ if hidden is None or hidden[0] is None or hidden[1] is None:
106
+ hidden = self.initialize_hidden(x.shape[0], x.is_quantized)
107
+ hx, cx = hidden
108
+
109
+ if not self.split_gates:
110
+ igates = self.igates(x)
111
+ hgates = self.hgates(hx)
112
+ gates = self.gates.add(igates, hgates) # type: ignore[operator]
113
+
114
+ input_gate, forget_gate, cell_gate, out_gate = gates.chunk(4, 1)
115
+
116
+ input_gate = self.input_gate(input_gate)
117
+ forget_gate = self.forget_gate(forget_gate)
118
+ cell_gate = self.cell_gate(cell_gate)
119
+ out_gate = self.output_gate(out_gate)
120
+ else:
121
+ # apply each input + hidden projection and add together
122
+ gate = {}
123
+ for (key, gates), igates, hgates in zip(
124
+ self.gates.items(), # type: ignore[operator]
125
+ self.igates.values(), # type: ignore[operator]
126
+ self.hgates.values(), # type: ignore[operator]
127
+ ):
128
+ gate[key] = gates.add(igates(x), hgates(hx))
129
+
130
+ input_gate = self.input_gate(gate["input"])
131
+ forget_gate = self.forget_gate(gate["forget"])
132
+ cell_gate = self.cell_gate(gate["cell"])
133
+ out_gate = self.output_gate(gate["output"])
134
+
135
+ fgate_cx = self.fgate_cx.mul(forget_gate, cx)
136
+ igate_cgate = self.igate_cgate.mul(input_gate, cell_gate)
137
+ fgate_cx_igate_cgate = self.fgate_cx_igate_cgate.add(fgate_cx, igate_cgate)
138
+ cy = fgate_cx_igate_cgate
139
+
140
+ # TODO: make this tanh a member of the module so its qparams can be configured
141
+ tanh_cy = torch.tanh(cy)
142
+ hy = self.ogate_cy.mul(out_gate, tanh_cy)
143
+ return hy, cy
144
+
145
+ def initialize_hidden(
146
+ self, batch_size: int, is_quantized: bool = False
147
+ ) -> tuple[Tensor, Tensor]:
148
+ h, c = (
149
+ torch.zeros((batch_size, self.hidden_size)),
150
+ torch.zeros((batch_size, self.hidden_size)),
151
+ )
152
+ if is_quantized:
153
+ (h_scale, h_zp) = self.initial_hidden_state_qparams
154
+ (c_scale, c_zp) = self.initial_cell_state_qparams
155
+ h = torch.quantize_per_tensor(
156
+ h, scale=h_scale, zero_point=h_zp, dtype=self.hidden_state_dtype
157
+ )
158
+ c = torch.quantize_per_tensor(
159
+ c, scale=c_scale, zero_point=c_zp, dtype=self.cell_state_dtype
160
+ )
161
+ return h, c
162
+
163
+ def _get_name(self):
164
+ return "QuantizableLSTMCell"
165
+
166
+ @classmethod
167
+ def from_params(cls, wi, wh, bi=None, bh=None, split_gates=False):
168
+ """Uses the weights and biases to create a new LSTM cell.
169
+
170
+ Args:
171
+ wi, wh: Weights for the input and hidden layers
172
+ bi, bh: Biases for the input and hidden layers
173
+ """
174
+ if (bi is None) != (bh is None):
175
+ raise AssertionError("bi and bh must both be None or both have values")
176
+ input_size = wi.shape[1]
177
+ hidden_size = wh.shape[1]
178
+ cell = cls(
179
+ input_dim=input_size,
180
+ hidden_dim=hidden_size,
181
+ bias=(bi is not None),
182
+ split_gates=split_gates,
183
+ )
184
+
185
+ if not split_gates:
186
+ cell.igates.weight = torch.nn.Parameter(wi)
187
+ if bi is not None:
188
+ cell.igates.bias = torch.nn.Parameter(bi)
189
+ cell.hgates.weight = torch.nn.Parameter(wh)
190
+ if bh is not None:
191
+ cell.hgates.bias = torch.nn.Parameter(bh)
192
+ else:
193
+ # split weight/bias
194
+ for w, b, gates in zip([wi, wh], [bi, bh], [cell.igates, cell.hgates]):
195
+ for w_chunk, gate in zip(w.chunk(4, dim=0), gates.values()): # type: ignore[operator]
196
+ gate.weight = torch.nn.Parameter(w_chunk)
197
+
198
+ if b is not None:
199
+ for b_chunk, gate in zip(b.chunk(4, dim=0), gates.values()): # type: ignore[operator]
200
+ gate.bias = torch.nn.Parameter(b_chunk)
201
+
202
+ return cell
203
+
204
+ @classmethod
205
+ def from_float(cls, other, use_precomputed_fake_quant=False, split_gates=False):
206
+ if type(other) is not cls._FLOAT_MODULE:
207
+ raise AssertionError(
208
+ f"Expected module type {cls._FLOAT_MODULE}, got {type(other)}"
209
+ )
210
+ if not hasattr(other, "qconfig"):
211
+ raise AssertionError("The float module must have 'qconfig'")
212
+ observed = cls.from_params(
213
+ other.weight_ih,
214
+ other.weight_hh,
215
+ other.bias_ih,
216
+ other.bias_hh,
217
+ split_gates=split_gates,
218
+ )
219
+ observed.qconfig = other.qconfig
220
+ observed.igates.qconfig = other.qconfig
221
+ observed.hgates.qconfig = other.qconfig
222
+ if split_gates:
223
+ # also apply qconfig directly to Linear modules
224
+ for g in observed.igates.values():
225
+ g.qconfig = other.qconfig
226
+ for g in observed.hgates.values():
227
+ g.qconfig = other.qconfig
228
+ return observed
229
+
230
+
231
+ class _LSTMSingleLayer(torch.nn.Module):
232
+ r"""A single one-directional LSTM layer.
233
+
234
+ The difference between a layer and a cell is that the layer can process a
235
+ sequence, while the cell only expects an instantaneous value.
236
+ """
237
+
238
+ def __init__(
239
+ self,
240
+ input_dim: int,
241
+ hidden_dim: int,
242
+ bias: bool = True,
243
+ device=None,
244
+ dtype=None,
245
+ *,
246
+ split_gates=False,
247
+ ) -> None:
248
+ factory_kwargs = {"device": device, "dtype": dtype}
249
+ super().__init__()
250
+ self.cell = LSTMCell(
251
+ input_dim, hidden_dim, bias=bias, split_gates=split_gates, **factory_kwargs
252
+ )
253
+
254
+ def forward(self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None):
255
+ result = []
256
+ seq_len = x.shape[0]
257
+ for i in range(seq_len):
258
+ hidden = self.cell(x[i], hidden)
259
+ result.append(hidden[0]) # type: ignore[index]
260
+ result_tensor = torch.stack(result, 0)
261
+ return result_tensor, hidden
262
+
263
+ @classmethod
264
+ def from_params(cls, *args, **kwargs):
265
+ cell = LSTMCell.from_params(*args, **kwargs)
266
+ layer = cls(
267
+ cell.input_size, cell.hidden_size, cell.bias, split_gates=cell.split_gates
268
+ )
269
+ layer.cell = cell
270
+ return layer
271
+
272
+
273
+ class _LSTMLayer(torch.nn.Module):
274
+ r"""A single bi-directional LSTM layer."""
275
+
276
+ def __init__(
277
+ self,
278
+ input_dim: int,
279
+ hidden_dim: int,
280
+ bias: bool = True,
281
+ batch_first: bool = False,
282
+ bidirectional: bool = False,
283
+ device=None,
284
+ dtype=None,
285
+ *,
286
+ split_gates=False,
287
+ ) -> None:
288
+ factory_kwargs = {"device": device, "dtype": dtype}
289
+ super().__init__()
290
+ self.batch_first = batch_first
291
+ self.bidirectional = bidirectional
292
+ self.layer_fw = _LSTMSingleLayer(
293
+ input_dim, hidden_dim, bias=bias, split_gates=split_gates, **factory_kwargs
294
+ )
295
+ if self.bidirectional:
296
+ self.layer_bw = _LSTMSingleLayer(
297
+ input_dim,
298
+ hidden_dim,
299
+ bias=bias,
300
+ split_gates=split_gates,
301
+ **factory_kwargs,
302
+ )
303
+
304
+ def forward(self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None):
305
+ if self.batch_first:
306
+ x = x.transpose(0, 1)
307
+ if hidden is None:
308
+ hx_fw, cx_fw = (None, None)
309
+ else:
310
+ hx_fw, cx_fw = hidden
311
+ hidden_bw: tuple[Tensor, Tensor] | None = None
312
+ if self.bidirectional:
313
+ if hx_fw is None:
314
+ hx_bw = None
315
+ else:
316
+ hx_bw = hx_fw[1]
317
+ hx_fw = hx_fw[0]
318
+ if cx_fw is None:
319
+ cx_bw = None
320
+ else:
321
+ cx_bw = cx_fw[1]
322
+ cx_fw = cx_fw[0]
323
+ if hx_bw is not None and cx_bw is not None:
324
+ hidden_bw = hx_bw, cx_bw
325
+ if hx_fw is None and cx_fw is None:
326
+ hidden_fw = None
327
+ else:
328
+ hidden_fw = (
329
+ torch.jit._unwrap_optional(hx_fw),
330
+ torch.jit._unwrap_optional(cx_fw),
331
+ )
332
+ result_fw, hidden_fw = self.layer_fw(x, hidden_fw)
333
+
334
+ if hasattr(self, "layer_bw") and self.bidirectional:
335
+ x_reversed = x.flip(0)
336
+ result_bw, hidden_bw = self.layer_bw(x_reversed, hidden_bw)
337
+ result_bw = result_bw.flip(0)
338
+
339
+ result = torch.cat([result_fw, result_bw], result_fw.dim() - 1)
340
+ if hidden_fw is None and hidden_bw is None:
341
+ h = None
342
+ c = None
343
+ elif hidden_fw is None:
344
+ (h, c) = torch.jit._unwrap_optional(hidden_bw)
345
+ elif hidden_bw is None:
346
+ (h, c) = torch.jit._unwrap_optional(hidden_fw)
347
+ else:
348
+ h = torch.stack([hidden_fw[0], hidden_bw[0]], 0) # type: ignore[list-item]
349
+ c = torch.stack([hidden_fw[1], hidden_bw[1]], 0) # type: ignore[list-item]
350
+ else:
351
+ result = result_fw
352
+ h, c = torch.jit._unwrap_optional(hidden_fw) # type: ignore[assignment]
353
+
354
+ if self.batch_first:
355
+ result.transpose_(0, 1)
356
+
357
+ return result, (h, c)
358
+
359
+ @classmethod
360
+ def from_float(cls, other, layer_idx=0, qconfig=None, **kwargs):
361
+ r"""
362
+ There is no FP equivalent of this class. This function is here just to
363
+ mimic the behavior of the `prepare` within the `torch.ao.quantization`
364
+ flow.
365
+ """
366
+ if not hasattr(other, "qconfig") and qconfig is None:
367
+ raise AssertionError("other must have qconfig or qconfig must be provided")
368
+
369
+ input_size = kwargs.get("input_size", other.input_size)
370
+ hidden_size = kwargs.get("hidden_size", other.hidden_size)
371
+ bias = kwargs.get("bias", other.bias)
372
+ batch_first = kwargs.get("batch_first", other.batch_first)
373
+ bidirectional = kwargs.get("bidirectional", other.bidirectional)
374
+ split_gates = kwargs.get("split_gates", False)
375
+
376
+ layer = cls(
377
+ # pyrefly: ignore [bad-argument-type]
378
+ input_size,
379
+ # pyrefly: ignore [bad-argument-type]
380
+ hidden_size,
381
+ # pyrefly: ignore [bad-argument-type]
382
+ bias,
383
+ # pyrefly: ignore [bad-argument-type]
384
+ batch_first,
385
+ # pyrefly: ignore [bad-argument-type]
386
+ bidirectional,
387
+ split_gates=split_gates,
388
+ )
389
+ # pyrefly: ignore [bad-argument-type]
390
+ layer.qconfig = getattr(other, "qconfig", qconfig)
391
+ wi = getattr(other, f"weight_ih_l{layer_idx}")
392
+ wh = getattr(other, f"weight_hh_l{layer_idx}")
393
+ bi = getattr(other, f"bias_ih_l{layer_idx}", None)
394
+ bh = getattr(other, f"bias_hh_l{layer_idx}", None)
395
+
396
+ layer.layer_fw = _LSTMSingleLayer.from_params(
397
+ wi, wh, bi, bh, split_gates=split_gates
398
+ )
399
+
400
+ if other.bidirectional:
401
+ wi = getattr(other, f"weight_ih_l{layer_idx}_reverse")
402
+ wh = getattr(other, f"weight_hh_l{layer_idx}_reverse")
403
+ bi = getattr(other, f"bias_ih_l{layer_idx}_reverse", None)
404
+ bh = getattr(other, f"bias_hh_l{layer_idx}_reverse", None)
405
+ layer.layer_bw = _LSTMSingleLayer.from_params(
406
+ wi, wh, bi, bh, split_gates=split_gates
407
+ )
408
+ return layer
409
+
410
+
411
+ class LSTM(torch.nn.Module):
412
+ r"""A quantizable long short-term memory (LSTM).
413
+
414
+ For the description and the argument types, please, refer to :class:`~torch.nn.LSTM`
415
+
416
+ Attributes:
417
+ layers : instances of the `_LSTMLayer`
418
+
419
+ .. note::
420
+ To access the weights and biases, you need to access them per layer.
421
+ See examples below.
422
+
423
+ Examples::
424
+
425
+ >>> import torch.ao.nn.quantizable as nnqa
426
+ >>> rnn = nnqa.LSTM(10, 20, 2)
427
+ >>> input = torch.randn(5, 3, 10)
428
+ >>> h0 = torch.randn(2, 3, 20)
429
+ >>> c0 = torch.randn(2, 3, 20)
430
+ >>> output, (hn, cn) = rnn(input, (h0, c0))
431
+ >>> # To get the weights:
432
+ >>> # xdoctest: +SKIP
433
+ >>> print(rnn.layers[0].weight_ih)
434
+ tensor([[...]])
435
+ >>> print(rnn.layers[0].weight_hh)
436
+ AssertionError: There is no reverse path in the non-bidirectional layer
437
+ """
438
+
439
+ _FLOAT_MODULE = torch.nn.LSTM
440
+
441
+ def __init__(
442
+ self,
443
+ input_size: int,
444
+ hidden_size: int,
445
+ num_layers: int = 1,
446
+ bias: bool = True,
447
+ batch_first: bool = False,
448
+ dropout: float = 0.0,
449
+ bidirectional: bool = False,
450
+ device=None,
451
+ dtype=None,
452
+ *,
453
+ split_gates: bool = False,
454
+ ) -> None:
455
+ factory_kwargs = {"device": device, "dtype": dtype}
456
+ super().__init__()
457
+ self.input_size = input_size
458
+ self.hidden_size = hidden_size
459
+ self.num_layers = num_layers
460
+ self.bias = bias
461
+ self.batch_first = batch_first
462
+ self.dropout = float(dropout)
463
+ self.bidirectional = bidirectional
464
+ self.training = False # Default to eval mode. If we want to train, we will explicitly set to training.
465
+
466
+ if (
467
+ not isinstance(dropout, numbers.Number)
468
+ or not 0 <= dropout <= 1
469
+ or isinstance(dropout, bool)
470
+ ):
471
+ raise ValueError(
472
+ "dropout should be a number in range [0, 1] "
473
+ "representing the probability of an element being "
474
+ "zeroed"
475
+ )
476
+
477
+ if dropout > 0:
478
+ warnings.warn(
479
+ "dropout option for quantizable LSTM is ignored. "
480
+ "If you are training, please, use nn.LSTM version "
481
+ "followed by `prepare` step.",
482
+ stacklevel=2,
483
+ )
484
+ if num_layers == 1:
485
+ warnings.warn(
486
+ "dropout option adds dropout after all but last "
487
+ "recurrent layer, so non-zero dropout expects "
488
+ f"num_layers greater than 1, but got dropout={dropout} "
489
+ f"and num_layers={num_layers}",
490
+ stacklevel=2,
491
+ )
492
+
493
+ layers = [
494
+ _LSTMLayer(
495
+ self.input_size,
496
+ self.hidden_size,
497
+ self.bias,
498
+ batch_first=False,
499
+ bidirectional=self.bidirectional,
500
+ split_gates=split_gates,
501
+ **factory_kwargs,
502
+ )
503
+ ]
504
+ layers.extend(
505
+ _LSTMLayer(
506
+ self.hidden_size,
507
+ self.hidden_size,
508
+ self.bias,
509
+ batch_first=False,
510
+ bidirectional=self.bidirectional,
511
+ split_gates=split_gates,
512
+ **factory_kwargs,
513
+ )
514
+ for _ in range(1, num_layers)
515
+ )
516
+ self.layers = torch.nn.ModuleList(layers)
517
+
518
+ def forward(self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None):
519
+ if self.batch_first:
520
+ x = x.transpose(0, 1)
521
+
522
+ max_batch_size = x.size(1)
523
+ num_directions = 2 if self.bidirectional else 1
524
+ if hidden is None:
525
+ zeros = torch.zeros(
526
+ num_directions,
527
+ max_batch_size,
528
+ self.hidden_size,
529
+ dtype=torch.float,
530
+ device=x.device,
531
+ )
532
+ zeros.squeeze_(0)
533
+ if x.is_quantized:
534
+ zeros = torch.quantize_per_tensor(
535
+ zeros, scale=1.0, zero_point=0, dtype=x.dtype
536
+ )
537
+ hxcx = [(zeros, zeros) for _ in range(self.num_layers)]
538
+ else:
539
+ hidden_non_opt = torch.jit._unwrap_optional(hidden)
540
+ if isinstance(hidden_non_opt[0], Tensor):
541
+ hx = hidden_non_opt[0].reshape(
542
+ self.num_layers, num_directions, max_batch_size, self.hidden_size
543
+ )
544
+ cx = hidden_non_opt[1].reshape(
545
+ self.num_layers, num_directions, max_batch_size, self.hidden_size
546
+ )
547
+ hxcx = [
548
+ (hx[idx].squeeze(0), cx[idx].squeeze(0))
549
+ for idx in range(self.num_layers)
550
+ ]
551
+ else:
552
+ hxcx = hidden_non_opt
553
+
554
+ hx_list = []
555
+ cx_list = []
556
+ for idx, layer in enumerate(self.layers):
557
+ x, (h, c) = layer(x, hxcx[idx])
558
+ hx_list.append(torch.jit._unwrap_optional(h))
559
+ cx_list.append(torch.jit._unwrap_optional(c))
560
+ hx_tensor = torch.stack(hx_list)
561
+ cx_tensor = torch.stack(cx_list)
562
+
563
+ # We are creating another dimension for bidirectional case
564
+ # need to collapse it
565
+ hx_tensor = hx_tensor.reshape(-1, hx_tensor.shape[-2], hx_tensor.shape[-1])
566
+ cx_tensor = cx_tensor.reshape(-1, cx_tensor.shape[-2], cx_tensor.shape[-1])
567
+
568
+ if self.batch_first:
569
+ x = x.transpose(0, 1)
570
+
571
+ return x, (hx_tensor, cx_tensor)
572
+
573
+ def _get_name(self):
574
+ return "QuantizableLSTM"
575
+
576
+ @classmethod
577
+ def from_float(cls, other, qconfig=None, split_gates=False):
578
+ if not isinstance(other, cls._FLOAT_MODULE):
579
+ raise AssertionError(
580
+ f"Expected module type {cls._FLOAT_MODULE}, got {type(other)}"
581
+ )
582
+ if not hasattr(other, "qconfig") and not qconfig:
583
+ raise AssertionError("other must have qconfig or qconfig must be provided")
584
+ observed = cls(
585
+ other.input_size,
586
+ other.hidden_size,
587
+ other.num_layers,
588
+ other.bias,
589
+ other.batch_first,
590
+ other.dropout,
591
+ other.bidirectional,
592
+ split_gates=split_gates,
593
+ )
594
+ # pyrefly: ignore [bad-argument-type]
595
+ observed.qconfig = getattr(other, "qconfig", qconfig)
596
+ for idx in range(other.num_layers):
597
+ observed.layers[idx] = _LSTMLayer.from_float(
598
+ other, idx, qconfig, batch_first=False, split_gates=split_gates
599
+ )
600
+
601
+ # Prepare the model
602
+ if other.training:
603
+ observed.train()
604
+ observed = torch.ao.quantization.prepare_qat(observed, inplace=True)
605
+ else:
606
+ observed.eval()
607
+ observed = torch.ao.quantization.prepare(observed, inplace=True)
608
+ return observed
609
+
610
+ @classmethod
611
+ def from_observed(cls, other):
612
+ # The whole flow is float -> observed -> quantized
613
+ # This class does float -> observed only
614
+ raise NotImplementedError(
615
+ "It looks like you are trying to convert a "
616
+ "non-quantizable LSTM module. Please, see "
617
+ "the examples on quantizable LSTMs."
618
+ )
.venv/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import functional
2
+ from .modules import * # noqa: F403
3
+ from .modules import MaxPool2d
4
+
5
+
6
+ __all__ = [
7
+ "BatchNorm2d",
8
+ "BatchNorm3d",
9
+ "Conv1d",
10
+ "Conv2d",
11
+ "Conv3d",
12
+ "ConvTranspose1d",
13
+ "ConvTranspose2d",
14
+ "ConvTranspose3d",
15
+ "DeQuantize",
16
+ "ELU",
17
+ "Embedding",
18
+ "EmbeddingBag",
19
+ "GroupNorm",
20
+ "Hardswish",
21
+ "InstanceNorm1d",
22
+ "InstanceNorm2d",
23
+ "InstanceNorm3d",
24
+ "LayerNorm",
25
+ "LeakyReLU",
26
+ "Linear",
27
+ "LSTM",
28
+ "MultiheadAttention",
29
+ "Quantize",
30
+ "ReLU6",
31
+ "Sigmoid",
32
+ "Softmax",
33
+ "Dropout",
34
+ "PReLU",
35
+ # Wrapper modules
36
+ "FloatFunctional",
37
+ "FXFloatFunctional",
38
+ "QFunctional",
39
+ ]