jasonfan commited on
Commit
e1e2f25
·
verified ·
1 Parent(s): 62c2cbd

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. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/fft.py +593 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py +435 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/nn/__init__.py +1 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py +1293 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/special/__init__.py +238 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_strobelight/__init__.py +0 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_strobelight/cli_function_profiler.py +322 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_strobelight/compile_time_profiler.py +224 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/__init__.py +17 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/_fake_tensor_utils.py +263 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/__init__.py +9 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_core.py +151 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/__init__.py +5 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/aten.py +934 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/common.py +317 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/prims.py +34 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/fake_impls.py +1465 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py +0 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/fake_utils.py +305 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/functional_tensor.py +837 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/meta_utils.py +1972 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/schema_check_mode.py +230 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vendor/__init__.py +0 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vendor/packaging/__init__.py +15 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vendor/packaging/_structures.py +61 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vendor/packaging/version.py +563 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/accelerator/__init__.py +299 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/accelerator/_utils.py +26 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/accelerator/memory.py +236 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/amp/__init__.py +9 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/amp/autocast_mode.py +525 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/amp/grad_scaler.py +693 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/__init__.py +31 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/__init__.py +35 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/__init__.py +41 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/modules/__init__.py +41 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/modules/fused.py +289 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/__init__.py +1 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/__init__.py +32 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/conv_fused.py +958 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_fused.py +191 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_relu.py +74 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/__init__.py +15 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py +1 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py +6 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py +72 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py +18 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py +113 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py +153 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py +276 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/fft.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert len(dims) == len(sizes)
99
+ must_copy = False
100
+ x_sizes = x.shape
101
+ pad_amount = [0] * len(x_sizes) * 2
102
+ for i in range(len(dims)):
103
+ if sizes[i] == -1:
104
+ continue
105
+
106
+ if x_sizes[dims[i]] < sizes[i]:
107
+ must_copy = True
108
+ pad_idx = len(pad_amount) - 2 * dims[i] - 1
109
+
110
+ pad_amount[pad_idx] = sizes[i] - x_sizes[dims[i]]
111
+
112
+ if x_sizes[dims[i]] > sizes[i]:
113
+ x = x.narrow(dims[i], 0, sizes[i])
114
+
115
+ return torch.constant_pad_nd(x, pad_amount) if must_copy else x
116
+
117
+
118
+ def _fft_c2r(
119
+ func_name: str,
120
+ input: TensorLikeType,
121
+ n: Optional[int],
122
+ dim: int,
123
+ norm: NormType,
124
+ forward: bool,
125
+ ) -> TensorLikeType:
126
+ """Common code for performing any complex to real FFT (irfft or hfft)"""
127
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
128
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
129
+ last_dim_size = n if n is not None else 2 * (input.shape[dim] - 1)
130
+ torch._check(
131
+ last_dim_size >= 1,
132
+ lambda: f"Invalid number of data points ({last_dim_size}) specified",
133
+ )
134
+
135
+ if n is not None:
136
+ input = _resize_fft_input(input, dims=dims, sizes=(last_dim_size // 2 + 1,))
137
+
138
+ if forward:
139
+ input = torch.conj(input)
140
+
141
+ output = prims.fft_c2r(input, dim=dims, last_dim_size=last_dim_size)
142
+ return _apply_norm(output, norm=norm, signal_numel=last_dim_size, forward=forward)
143
+
144
+
145
+ def _fft_r2c(
146
+ func_name: str,
147
+ input: TensorLikeType,
148
+ n: Optional[int],
149
+ dim: int,
150
+ norm: NormType,
151
+ forward: bool,
152
+ onesided: bool,
153
+ ) -> TensorLikeType:
154
+ """Common code for performing any real to complex FFT (rfft or ihfft)"""
155
+ torch._check(
156
+ not input.dtype.is_complex,
157
+ lambda: f"{func_name} expects a floating point input tensor, but got {input.dtype}",
158
+ )
159
+ input = _maybe_promote_tensor_fft(input)
160
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
161
+ dim_size = n if n is not None else input.shape[dim]
162
+ torch._check(
163
+ dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified"
164
+ )
165
+
166
+ if n is not None:
167
+ input = _resize_fft_input(input, dims, (n,))
168
+
169
+ ret = prims.fft_r2c(input, dim=dims, onesided=onesided)
170
+ ret = _apply_norm(ret, norm, dim_size, forward)
171
+ return ret if forward else torch.conj(ret)
172
+
173
+
174
+ def _fft_c2c(
175
+ func_name: str,
176
+ input: TensorLikeType,
177
+ n: Optional[int],
178
+ dim: int,
179
+ norm: NormType,
180
+ forward: bool,
181
+ ) -> TensorLikeType:
182
+ """Common code for performing any complex to complex FFT (fft or ifft)"""
183
+ torch._check(
184
+ input.dtype.is_complex,
185
+ lambda: f"{func_name} expects a complex input tensor, but got {input.dtype}",
186
+ )
187
+ dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),)
188
+ dim_size = n if n is not None else input.shape[dim]
189
+ torch._check(
190
+ dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified"
191
+ )
192
+
193
+ if n is not None:
194
+ input = _resize_fft_input(input, dims, (n,))
195
+
196
+ ret = prims.fft_c2c(input, dim=dims, forward=forward)
197
+ return _apply_norm(ret, norm, dim_size, forward)
198
+
199
+
200
+ @register_decomposition(aten.fft_fft)
201
+ @out_wrapper()
202
+ def fft(
203
+ input: TensorLikeType,
204
+ n: Optional[int] = None,
205
+ dim: int = -1,
206
+ norm: NormType = None,
207
+ ) -> TensorLikeType:
208
+ if input.dtype.is_complex:
209
+ return _fft_c2c("fft", input, n, dim, norm, forward=True)
210
+ else:
211
+ return _fft_r2c("fft", input, n, dim, norm, forward=True, onesided=False)
212
+
213
+
214
+ @register_decomposition(aten.fft_ifft)
215
+ @out_wrapper()
216
+ def ifft(
217
+ input: TensorLikeType,
218
+ n: Optional[int] = None,
219
+ dim: int = -1,
220
+ norm: NormType = None,
221
+ ) -> TensorLikeType:
222
+ if input.dtype.is_complex:
223
+ return _fft_c2c("ifft", input, n, dim, norm, forward=False)
224
+ else:
225
+ return _fft_r2c("ifft", input, n, dim, norm, forward=False, onesided=False)
226
+
227
+
228
+ @register_decomposition(aten.fft_rfft)
229
+ @out_wrapper()
230
+ def rfft(
231
+ input: TensorLikeType,
232
+ n: Optional[int] = None,
233
+ dim: int = -1,
234
+ norm: NormType = None,
235
+ ) -> TensorLikeType:
236
+ return _fft_r2c("rfft", input, n, dim, norm, forward=True, onesided=True)
237
+
238
+
239
+ @register_decomposition(aten.fft_irfft)
240
+ @out_wrapper()
241
+ def irfft(
242
+ input: TensorLikeType,
243
+ n: Optional[int] = None,
244
+ dim: int = -1,
245
+ norm: NormType = None,
246
+ ) -> TensorLikeType:
247
+ return _fft_c2r("irfft", input, n, dim, norm, forward=False)
248
+
249
+
250
+ @register_decomposition(aten.fft_hfft)
251
+ @out_wrapper()
252
+ def hfft(
253
+ input: TensorLikeType,
254
+ n: Optional[int] = None,
255
+ dim: int = -1,
256
+ norm: NormType = None,
257
+ ) -> TensorLikeType:
258
+ return _fft_c2r("hfft", input, n, dim, norm, forward=True)
259
+
260
+
261
+ @register_decomposition(aten.fft_ihfft)
262
+ @out_wrapper()
263
+ def ihfft(
264
+ input: TensorLikeType,
265
+ n: Optional[int] = None,
266
+ dim: int = -1,
267
+ norm: NormType = None,
268
+ ) -> TensorLikeType:
269
+ return _fft_r2c("ihfft", input, n, dim, norm, forward=False, onesided=True)
270
+
271
+
272
+ class _ShapeAndDims(NamedTuple):
273
+ shape: tuple[int, ...]
274
+ dims: tuple[int, ...]
275
+
276
+
277
+ def _canonicalize_fft_shape_and_dim_args(
278
+ input: TensorLikeType, shape: Optional[ShapeType], dim: Optional[DimsType]
279
+ ) -> _ShapeAndDims:
280
+ """Convert the shape and dim arguments into a canonical form where neither are optional"""
281
+ input_dim = input.ndim
282
+ input_sizes = input.shape
283
+
284
+ if dim is not None:
285
+ if not isinstance(dim, Sequence):
286
+ dim = (dim,)
287
+ ret_dims = utils.canonicalize_dims(input_dim, dim, wrap_scalar=False)
288
+
289
+ # Check dims are unique
290
+ torch._check(
291
+ len(set(ret_dims)) == len(ret_dims), lambda: "FFT dims must be unique"
292
+ )
293
+
294
+ if shape is not None:
295
+ if not isinstance(shape, Sequence):
296
+ shape = (shape,)
297
+
298
+ # Has shape, might have dim
299
+ torch._check(
300
+ dim is None or len(dim) == len(shape),
301
+ lambda: "When given, dim and shape arguments must have the same length",
302
+ )
303
+ transform_ndim = len(shape)
304
+
305
+ torch._check(
306
+ transform_ndim <= input_dim,
307
+ lambda: f"Got shape with {transform_ndim} values but input tensor "
308
+ f"only has {input_dim} dimensions.",
309
+ )
310
+
311
+ # If shape is given, dims defaults to the last len(shape) dimensions
312
+ if dim is None:
313
+ ret_dims = tuple(range(input_dim - transform_ndim, input_dim))
314
+
315
+ # Translate any -1 values in shape to the default length
316
+ ret_shape = tuple(
317
+ s if s != -1 else input_sizes[d]
318
+ for (s, d) in zip(shape, ret_dims) # type: ignore[possibly-undefined]
319
+ )
320
+ elif dim is None:
321
+ # No shape, no dim
322
+ ret_dims = tuple(range(input_dim))
323
+ ret_shape = tuple(input_sizes)
324
+ else:
325
+ # No shape, has dim
326
+ ret_shape = tuple(input_sizes[d] for d in ret_dims) # type: ignore[possibly-undefined]
327
+
328
+ for n in ret_shape:
329
+ torch._check(n > 0, lambda: f"Invalid number of data points ({n}) specified")
330
+
331
+ return _ShapeAndDims(shape=ret_shape, dims=ret_dims) # type: ignore[possibly-undefined]
332
+
333
+
334
+ def _prod(xs: Iterable[int]) -> int:
335
+ """Compute product of a list"""
336
+ prod = 1
337
+ for x in xs:
338
+ prod *= x
339
+ return prod
340
+
341
+
342
+ def _fftn_c2c(
343
+ function_name: str,
344
+ input: TensorLikeType,
345
+ shape: tuple[int, ...],
346
+ dim: tuple[int, ...],
347
+ norm: NormType,
348
+ forward: bool,
349
+ ) -> TensorLikeType:
350
+ """Common code for n-dimensional complex to complex FFTs (fftn or ifftn)"""
351
+ torch._check(
352
+ input.dtype.is_complex,
353
+ lambda: f"{function_name} expects a complex input tensor, "
354
+ f"but got {input.dtype}",
355
+ )
356
+ x = _resize_fft_input(input, dim, shape)
357
+ output = prims.fft_c2c(x, dim=dim, forward=forward)
358
+ return _apply_norm(output, norm=norm, signal_numel=_prod(shape), forward=forward)
359
+
360
+
361
+ @register_decomposition(aten.fft_fftn)
362
+ @out_wrapper()
363
+ def fftn(
364
+ input: TensorLikeType,
365
+ s: Optional[ShapeType] = None,
366
+ dim: Optional[DimsType] = None,
367
+ norm: NormType = None,
368
+ ) -> TensorLikeType:
369
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
370
+ x = _maybe_promote_tensor_fft(input, require_complex=True)
371
+ return _fftn_c2c("fftn", x, shape, dim, norm, forward=True)
372
+
373
+
374
+ @register_decomposition(aten.fft_ifftn)
375
+ @out_wrapper()
376
+ def ifftn(
377
+ input: TensorLikeType,
378
+ s: Optional[ShapeType] = None,
379
+ dim: Optional[DimsType] = None,
380
+ norm: NormType = None,
381
+ ) -> TensorLikeType:
382
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
383
+ x = _maybe_promote_tensor_fft(input, require_complex=True)
384
+ return _fftn_c2c("ifftn", x, shape, dim, norm, forward=False)
385
+
386
+
387
+ @register_decomposition(aten.fft_rfftn)
388
+ @out_wrapper()
389
+ def rfftn(
390
+ input: TensorLikeType,
391
+ s: Optional[ShapeType] = None,
392
+ dim: Optional[DimsType] = None,
393
+ norm: NormType = None,
394
+ ) -> TensorLikeType:
395
+ torch._check(
396
+ not input.dtype.is_complex,
397
+ lambda: f"rfftn expects a real-valued input tensor, but got {input.dtype}",
398
+ )
399
+ shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim)
400
+ input = _maybe_promote_tensor_fft(input, require_complex=False)
401
+ input = _resize_fft_input(input, dim, shape)
402
+ out = prims.fft_r2c(input, dim=dim, onesided=True)
403
+ return _apply_norm(out, norm=norm, signal_numel=_prod(shape), forward=True)
404
+
405
+
406
+ @register_decomposition(aten.fft_ihfftn)
407
+ @out_wrapper()
408
+ def ihfftn(
409
+ input: TensorLikeType,
410
+ s: Optional[ShapeType] = None,
411
+ dim: Optional[DimsType] = None,
412
+ norm: NormType = None,
413
+ ) -> TensorLikeType:
414
+ torch._check(
415
+ not input.dtype.is_complex,
416
+ lambda: f"ihfftn expects a real-valued input tensor, but got {input.dtype}",
417
+ )
418
+ shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim)
419
+ torch._check(len(shape) > 0, lambda: "ihfftn must transform at least one axis")
420
+ input = _maybe_promote_tensor_fft(input, require_complex=False)
421
+ input = _resize_fft_input(input, dim, shape)
422
+
423
+ tmp = prims.fft_r2c(input, dim=dim[-1:], onesided=True)
424
+
425
+ if len(dim) == 1:
426
+ tmp = _apply_norm(tmp, norm=norm, signal_numel=shape[0], forward=False)
427
+ return prims.conj(tmp)
428
+
429
+ tmp = prims.conj_physical(tmp)
430
+ tmp = prims.fft_c2c(tmp, dim=dim[:-1], forward=False)
431
+ return _apply_norm(tmp, norm=norm, signal_numel=_prod(shape), forward=False)
432
+
433
+
434
+ class _CanonicalizeC2rReturn(NamedTuple):
435
+ shape: tuple[int, ...]
436
+ dim: tuple[int, ...]
437
+ last_dim_size: int
438
+
439
+
440
+ def _canonicalize_fft_c2r_shape_and_dim_args(
441
+ fname: str,
442
+ input: TensorLikeType,
443
+ s: Optional[ShapeType],
444
+ dim: Optional[DimsType],
445
+ ) -> _CanonicalizeC2rReturn:
446
+ """Canonicalize shape and dim arguments for n-dimensional c2r transforms,
447
+ as well as calculating the last_dim_size which is shape[dim[-1]] for the output"""
448
+ (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim)
449
+ torch._check(len(shape) > 0, lambda: f"{fname} must transform at least one axis")
450
+
451
+ if s is None or s[-1] == -1:
452
+ last_dim_size = 2 * (input.shape[dim[-1]] - 1)
453
+ else:
454
+ last_dim_size = shape[-1]
455
+
456
+ torch._check(
457
+ last_dim_size >= 1,
458
+ lambda: f"Invalid number of data points ({last_dim_size}) specified",
459
+ )
460
+
461
+ shape_list = list(shape)
462
+ shape_list[-1] = last_dim_size // 2 + 1
463
+ return _CanonicalizeC2rReturn(
464
+ shape=tuple(shape_list), dim=dim, last_dim_size=last_dim_size
465
+ )
466
+
467
+
468
+ @register_decomposition(aten.fft_irfftn)
469
+ @out_wrapper()
470
+ def irfftn(
471
+ input: TensorLikeType,
472
+ s: Optional[ShapeType] = None,
473
+ dim: Optional[DimsType] = None,
474
+ norm: NormType = None,
475
+ ) -> TensorLikeType:
476
+ shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args(
477
+ "irfftn", input, s, dim
478
+ )
479
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
480
+ input = _resize_fft_input(input, dim, shape)
481
+ out = prims.fft_c2r(input, dim=dim, last_dim_size=last_dim_size)
482
+ return _apply_norm(out, norm, _prod(out.shape[d] for d in dim), forward=False)
483
+
484
+
485
+ @register_decomposition(aten.fft_hfftn)
486
+ @out_wrapper()
487
+ def hfftn(
488
+ input: TensorLikeType,
489
+ s: Optional[ShapeType] = None,
490
+ dim: Optional[DimsType] = None,
491
+ norm: NormType = None,
492
+ ) -> TensorLikeType:
493
+ shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args(
494
+ "hfftn", input, s, dim
495
+ )
496
+ input = _maybe_promote_tensor_fft(input, require_complex=True)
497
+ input = _resize_fft_input(input, dim, shape)
498
+
499
+ tmp = prims.fft_c2c(input, dim=dim[:-1], forward=True) if len(dim) > 1 else input
500
+ tmp = _apply_norm(tmp, norm, _prod(shape[:-1]), forward=True)
501
+ tmp = prims.conj_physical(tmp)
502
+ out = prims.fft_c2r(tmp, dim=dim[-1:], last_dim_size=last_dim_size)
503
+ return _apply_norm(out, norm, last_dim_size, forward=True)
504
+
505
+
506
+ @register_decomposition(aten.fft_fft2)
507
+ @out_wrapper()
508
+ def fft2(
509
+ input: TensorLikeType,
510
+ s: Optional[ShapeType] = None,
511
+ dim: Optional[DimsType] = (-2, -1),
512
+ norm: NormType = None,
513
+ ) -> TensorLikeType:
514
+ return torch.fft.fftn(input, s=s, dim=dim, norm=norm)
515
+
516
+
517
+ @register_decomposition(aten.fft_ifft2)
518
+ @out_wrapper()
519
+ def ifft2(
520
+ input: TensorLikeType,
521
+ s: Optional[ShapeType] = None,
522
+ dim: Optional[DimsType] = (-2, -1),
523
+ norm: NormType = None,
524
+ ) -> TensorLikeType:
525
+ return torch.fft.ifftn(input, s=s, dim=dim, norm=norm)
526
+
527
+
528
+ @register_decomposition(aten.fft_rfft2)
529
+ @out_wrapper()
530
+ def rfft2(
531
+ input: TensorLikeType,
532
+ s: Optional[ShapeType] = None,
533
+ dim: Optional[DimsType] = (-2, -1),
534
+ norm: NormType = None,
535
+ ) -> TensorLikeType:
536
+ return torch.fft.rfftn(input, s=s, dim=dim, norm=norm)
537
+
538
+
539
+ @register_decomposition(aten.fft_irfft2)
540
+ @out_wrapper()
541
+ def irfft2(
542
+ input: TensorLikeType,
543
+ s: Optional[ShapeType] = None,
544
+ dim: Optional[DimsType] = (-2, -1),
545
+ norm: NormType = None,
546
+ ) -> TensorLikeType:
547
+ return torch.fft.irfftn(input, s=s, dim=dim, norm=norm)
548
+
549
+
550
+ @register_decomposition(aten.fft_hfft2)
551
+ @out_wrapper()
552
+ def hfft2(
553
+ input: TensorLikeType,
554
+ s: Optional[ShapeType] = None,
555
+ dim: Optional[DimsType] = (-2, -1),
556
+ norm: NormType = None,
557
+ ) -> TensorLikeType:
558
+ return torch.fft.hfftn(input, s=s, dim=dim, norm=norm)
559
+
560
+
561
+ @register_decomposition(aten.fft_ihfft2)
562
+ @out_wrapper()
563
+ def ihfft2(
564
+ input: TensorLikeType,
565
+ s: Optional[ShapeType] = None,
566
+ dim: Optional[DimsType] = (-2, -1),
567
+ norm: NormType = None,
568
+ ) -> TensorLikeType:
569
+ return torch.fft.ihfftn(input, s=s, dim=dim, norm=norm)
570
+
571
+
572
+ def _default_alldims(dim: Optional[DimsType], x: TensorLikeType) -> list[int]:
573
+ """Convert Optional[DimsType] to a simple list, defaulting to all dimensions"""
574
+ if dim is None:
575
+ return list(range(x.ndim))
576
+ elif not isinstance(dim, Sequence):
577
+ return [dim]
578
+ else:
579
+ return list(dim)
580
+
581
+
582
+ @register_decomposition(aten.fft_fftshift)
583
+ def fftshift(input: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType:
584
+ dims = _default_alldims(dim, input)
585
+ shift = [input.shape[d] // 2 for d in dims]
586
+ return torch.roll(input, shift, dims)
587
+
588
+
589
+ @register_decomposition(aten.fft_ifftshift)
590
+ def ifftshift(input: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType:
591
+ dims = _default_alldims(dim, input)
592
+ shift = [(input.shape[d] + 1) // 2 for d in dims]
593
+ return torch.roll(input, shift, dims)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/linalg/__init__.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 [index-error]
229
+ dim[0] != dim[1],
230
+ # pyrefly: ignore [index-error]
231
+ lambda: f"linalg.matrix_norm: dims must be different. Got ({dim[0]}, {dim[1]})",
232
+ )
233
+ # dtype arg
234
+ _check_norm_dtype(dtype, A.dtype, "linalg.matrix_norm")
235
+
236
+ if isinstance(ord, str):
237
+ # ord
238
+ torch._check(
239
+ ord in ("fro", "nuc"),
240
+ lambda: f"linalg.matrix_norm: Order {ord} not supported.",
241
+ )
242
+ # dtype
243
+ check_fp_or_complex(
244
+ A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != "nuc"
245
+ )
246
+
247
+ if ord == "fro":
248
+ return vector_norm(A, 2, dim, keepdim, dtype=dtype)
249
+ else: # ord == "nuc"
250
+ if dtype is not None:
251
+ A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
252
+ # pyrefly: ignore [index-error]
253
+ perm = _backshift_permutation(dim[0], dim[1], A.ndim)
254
+ result = torch.sum(svdvals(prims.transpose(A, perm)), -1, keepdim)
255
+ if keepdim:
256
+ inv_perm = _inverse_permutation(perm)
257
+ result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
258
+ return result
259
+ else:
260
+ # ord
261
+ abs_ord = abs(ord)
262
+ torch._check(
263
+ abs_ord in (2, 1, float("inf")),
264
+ lambda: f"linalg.matrix_norm: Order {ord} not supported.",
265
+ )
266
+ # dtype
267
+ check_fp_or_complex(
268
+ A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != 2
269
+ )
270
+
271
+ max_min = partial(torch.amax if ord > 0.0 else torch.amin, keepdim=keepdim)
272
+
273
+ def _max_min_wrapper(A, dim):
274
+ # pyrefly: ignore [unsupported-operation]
275
+ if A.size(dim) == 0 and ord > 0.0:
276
+ new_size = list(A.size())
277
+ if keepdim:
278
+ new_size[dim] = 1
279
+ else:
280
+ del new_size[dim]
281
+ return torch.zeros(new_size, dtype=A.dtype, device=A.device)
282
+ else:
283
+ return max_min(A, dim)
284
+
285
+ if abs_ord == 2.0:
286
+ if dtype is not None:
287
+ A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment]
288
+ # pyrefly: ignore [index-error]
289
+ perm = _backshift_permutation(dim[0], dim[1], A.ndim)
290
+ result = _max_min_wrapper(svdvals(prims.transpose(A, perm)), dim=-1)
291
+ if keepdim:
292
+ inv_perm = _inverse_permutation(perm)
293
+ result = prims.transpose(torch.unsqueeze(result, -1), inv_perm)
294
+ return result
295
+ else: # 1, -1, inf, -inf
296
+ # pyrefly: ignore [bad-unpacking]
297
+ dim0, dim1 = dim
298
+ if abs_ord == float("inf"):
299
+ dim0, dim1 = dim1, dim0
300
+ if not keepdim and (dim0 < dim1):
301
+ dim1 -= 1
302
+ return _max_min_wrapper(
303
+ vector_norm(A, 1.0, dim=dim0, keepdim=keepdim, dtype=dtype), dim1
304
+ )
305
+
306
+
307
+ # CompositeImplicitAutograd
308
+ @out_wrapper(exact_dtype=True)
309
+ def norm(
310
+ A: TensorLikeType,
311
+ ord: Optional[Union[float, str]] = None,
312
+ dim: Optional[DimsType] = None,
313
+ keepdim: bool = False,
314
+ *,
315
+ dtype: Optional[torch.dtype] = None,
316
+ ) -> TensorLikeType:
317
+ if dim is not None:
318
+ if isinstance(dim, Dim):
319
+ dim = (dim,) # type: ignore[assignment]
320
+ torch._check(
321
+ len(dim) in (1, 2),
322
+ lambda: f"linalg.norm: If dim is specified, it must be of length 1 or 2. Got {dim}",
323
+ )
324
+ elif ord is not None:
325
+ torch._check(
326
+ A.ndim in (1, 2),
327
+ lambda: f"linalg.norm: If dim is not specified but ord is, the input must be 1D or 2D. Got {A.ndim}D",
328
+ )
329
+
330
+ if ord is not None and (
331
+ (dim is not None and len(dim) == 2) or (dim is None and A.ndim == 2)
332
+ ):
333
+ if dim is None:
334
+ dim = (0, 1)
335
+ return matrix_norm(A, ord, dim, keepdim, dtype=dtype)
336
+ else:
337
+ if ord is None:
338
+ ord = 2.0
339
+ return vector_norm(A, ord, dim, keepdim, dtype=dtype) # type: ignore[arg-type]
340
+
341
+
342
+ # CompositeImplicitAutograd
343
+ @out_wrapper("U", "S", "Vh", exact_dtype=True)
344
+ def svd(A: TensorLikeType, full_matrices: bool = True) -> tuple[Tensor, Tensor, Tensor]:
345
+ return prims.svd(A, full_matrices=full_matrices)
346
+
347
+
348
+ # CompositeImplicitAutograd
349
+ @out_wrapper(exact_dtype=True)
350
+ def svdvals(A: TensorLikeType) -> Tensor:
351
+ return svd(A, full_matrices=False)[1]
352
+
353
+
354
+ # CompositeImplicitAutograd
355
+ @out_wrapper()
356
+ @elementwise_type_promotion_wrapper(
357
+ type_promoting_args=("x", "y"),
358
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
359
+ )
360
+ def vecdot(x: Tensor, y: Tensor, dim: int = -1) -> Tensor:
361
+ check_fp_or_complex(x.dtype, "linalg.vecdot")
362
+ return (x.conj() * y).sum(dim=dim)
363
+
364
+
365
+ def _pivots_to_permutation(pivots, shape, *, inverse=False):
366
+ perm = torch.empty(shape, dtype=torch.int32, device=pivots.device)
367
+ perm[..., :] = torch.arange(shape[-1], dtype=torch.int32, device=pivots.device)
368
+ indices = range(shape[-1])
369
+ if inverse:
370
+ indices = reversed(indices)
371
+
372
+ if len(shape) > 1:
373
+ for i in indices:
374
+ j_s = pivots[..., i]
375
+ perm_i = perm[..., i].clone()
376
+ j_idx = torch.meshgrid(
377
+ *[torch.arange(s, device=perm.device) for s in j_s.shape], indexing="ij"
378
+ ) + (j_s,)
379
+ perm_j = perm[j_idx]
380
+ perm.index_put_(j_idx, perm_i)
381
+ perm[..., i].copy_(perm_j)
382
+
383
+ else:
384
+ for i in indices:
385
+ j = pivots[i]
386
+ perm_i = perm[i].clone()
387
+ perm_j = perm[j].clone()
388
+ perm[i].copy_(perm_j)
389
+ perm[j].copy_(perm_i)
390
+
391
+ return perm
392
+
393
+
394
+ def _apply_pivots(a, pivots, shape, *, inverse=False):
395
+ perm = _pivots_to_permutation(pivots - 1, shape, inverse=inverse)
396
+
397
+ if len(shape) == 1:
398
+ return a[perm, :]
399
+ else:
400
+ idx = torch.meshgrid(
401
+ *[torch.arange(s, device=a.device) for s in perm.shape], indexing="ij"
402
+ )[:-1] + (perm, slice(None))
403
+ return a[idx]
404
+
405
+
406
+ def linalg_lu_solve_out_mps(LU, pivots, B, *, left=True, adjoint=False, out):
407
+ if out.numel() == 0:
408
+ return
409
+
410
+ if not left:
411
+ adjoint = not adjoint
412
+ B = B.mH
413
+
414
+ if adjoint:
415
+ lu_ = LU.mH
416
+ x = torch.linalg.solve_triangular(lu_, B, left=True, upper=False)
417
+ x = torch.linalg.solve_triangular(
418
+ lu_, x, left=True, upper=True, unitriangular=True
419
+ )
420
+ x = _apply_pivots(x, pivots, LU.shape[:-1], inverse=True)
421
+ else:
422
+ x = _apply_pivots(B, pivots, LU.shape[:-1])
423
+ x = torch.linalg.solve_triangular(
424
+ LU, x, left=True, upper=False, unitriangular=True
425
+ )
426
+ x = torch.linalg.solve_triangular(LU, x, left=True, upper=True)
427
+
428
+ if not left:
429
+ x = x.mH
430
+
431
+ out.copy_(x)
432
+
433
+
434
+ mps_lib = torch.library.Library("aten", "IMPL", "MPS") # noqa: TOR901
435
+ mps_lib.impl("aten::linalg_lu_solve.out", linalg_lu_solve_out_mps)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/nn/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __all__: list[str] = []
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/nn/functional/__init__.py ADDED
@@ -0,0 +1,1293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, low=0.0, high=1.0, dtype=torch.float32, device=self.device
95
+ )
96
+ < val
97
+ )
98
+
99
+
100
+ @register_decomposition(aten.alpha_dropout)
101
+ def alpha_dropout(
102
+ self: TensorLikeType, p: float = 0.5, training: bool = False, inplace: bool = False
103
+ ) -> TensorLikeType:
104
+ if inplace:
105
+ raise NotImplementedError
106
+
107
+ if not training:
108
+ return self
109
+
110
+ torch._check(
111
+ p <= 1 and p >= 0,
112
+ lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
113
+ )
114
+
115
+ if p == 1:
116
+ return torch.zeros_like(self)
117
+
118
+ if p == 0:
119
+ return self
120
+
121
+ dropout_mask = _dropout_helper(self, 1 - p)
122
+
123
+ # From paper: Self-Normalizing Neural Networks (https://arxiv.org/pdf/1706.02515.pdf)
124
+ # alpha = - SELU.alpha * SELU.scale, here
125
+ # SELU.alpha = 1.6732632423543772848170429916717 and
126
+ # SELU.scale = 1.0507009873554804934193349852946
127
+ alpha = -1.7580993408473766
128
+
129
+ a = 1.0 / math.sqrt((alpha * alpha * p + 1) * (1 - p))
130
+ b = torch.logical_not(dropout_mask)
131
+ b = b * (alpha * a) + alpha * a * p
132
+ dropout_mask = a * dropout_mask
133
+
134
+ return self * dropout_mask + b
135
+
136
+
137
+ def _inplace_wrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]:
138
+ """
139
+ Given a nn.functional non-linearity, implements its `inplace: bool` argument
140
+ """
141
+
142
+ # nb. We use the name of the first argument used in the unary references
143
+ @wraps(fn)
144
+ def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T:
145
+ # pyrefly: ignore [unsupported-operation]
146
+ a = args[0]
147
+ if "inplace" not in kwargs:
148
+ kwargs["inplace"] = False
149
+ # pyrefly: ignore [unsupported-operation]
150
+ if kwargs["inplace"]:
151
+ torch._check(
152
+ "out" not in kwargs,
153
+ lambda: "Cannot set inplace=True and pass out= at the same time",
154
+ )
155
+ kwargs["inplace"] = False
156
+ kwargs["out"] = a
157
+ return fn(*args, **kwargs)
158
+ else:
159
+ return fn(*args, **kwargs)
160
+
161
+ return _fn
162
+
163
+
164
+ # celu is implemented specially because it has an alpha argument
165
+ # celu is very similar to elu
166
+ @register_decomposition(aten.celu)
167
+ @_inplace_wrapper
168
+ @out_wrapper()
169
+ @elementwise_type_promotion_wrapper(
170
+ type_promoting_args=("a",),
171
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
172
+ )
173
+ def celu(
174
+ a: TensorLikeType, alpha: Optional[NumberType] = None, inplace: bool = False
175
+ ) -> TensorLikeType:
176
+ """
177
+ Reference implementation of torch.nn.functional.celu
178
+ """
179
+
180
+ if inplace:
181
+ raise NotImplementedError
182
+
183
+ rhs: TensorLikeType
184
+ if alpha is not None:
185
+ python_type = utils.dtype_to_type(a.dtype)
186
+ if not utils.is_weakly_lesser_type(type(alpha), python_type):
187
+ msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!"
188
+ raise ValueError(msg)
189
+ rhs = alpha * torch.expm1(torch.true_divide(a, alpha)) # type: ignore[arg-type]
190
+ else:
191
+ rhs = torch.expm1(a)
192
+
193
+ return torch.where(a > 0, a, rhs)
194
+
195
+
196
+ @_inplace_wrapper
197
+ @out_wrapper()
198
+ def dropout(
199
+ a: TensorLikeType, p: float = 0.5, training: bool = True, inplace: bool = False
200
+ ) -> TensorLikeType:
201
+ if inplace:
202
+ raise NotImplementedError
203
+
204
+ if not training:
205
+ return a
206
+
207
+ torch._check(
208
+ p <= 1 and p >= 0,
209
+ lambda: f"dropout probability has to be between 0 and 1, but got, {p}",
210
+ )
211
+
212
+ if p == 1:
213
+ return torch.zeros_like(a)
214
+
215
+ if p == 0:
216
+ return a
217
+
218
+ scale = 1 / (1 - p)
219
+ dropout_mask = _dropout_helper(a, 1 - p)
220
+
221
+ return a * dropout_mask * scale
222
+
223
+
224
+ @register_decomposition(aten.elu)
225
+ @_inplace_wrapper
226
+ @out_wrapper()
227
+ @elementwise_type_promotion_wrapper(
228
+ type_promoting_args=("a",),
229
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
230
+ )
231
+ def elu(
232
+ a: TensorLikeType,
233
+ alpha: NumberType = 1.0,
234
+ scale: NumberType = 1.0,
235
+ input_scale: NumberType = 1.0,
236
+ inplace: bool = False,
237
+ ) -> TensorLikeType:
238
+ """
239
+ Reference implementation of torch.nn.functional.elu
240
+ """
241
+ if inplace:
242
+ raise NotImplementedError
243
+
244
+ # nb. This should be factored out into a can_cast aux function
245
+ python_type = utils.dtype_to_type(a.dtype)
246
+ torch._check(
247
+ utils.is_weakly_lesser_type(type(input_scale), python_type),
248
+ lambda: f"input_scale argument of type {type(input_scale)} cannot be safely cast to type {python_type}!",
249
+ )
250
+ torch._check(
251
+ utils.is_weakly_lesser_type(type(scale), python_type),
252
+ lambda: f"scale argument of type {type(scale)} cannot be safely cast to type {python_type}!",
253
+ )
254
+ torch._check(
255
+ utils.is_weakly_lesser_type(type(alpha), python_type),
256
+ lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!",
257
+ )
258
+
259
+ return torch.where(a > 0, scale * a, (alpha * scale) * torch.expm1(a * input_scale))
260
+
261
+
262
+ @register_decomposition(aten.relu)
263
+ @_inplace_wrapper
264
+ @out_wrapper()
265
+ @elementwise_type_promotion_wrapper(
266
+ type_promoting_args=("a",),
267
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
268
+ )
269
+ def relu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
270
+ """
271
+ Reference implementation of torch.nn.functional.relu
272
+ """
273
+
274
+ if inplace:
275
+ raise NotImplementedError
276
+
277
+ return torch.where(torch.le(a, 0), 0, a)
278
+
279
+
280
+ @register_decomposition(aten.channel_shuffle)
281
+ @out_wrapper()
282
+ def channel_shuffle(input: TensorLikeType, groups: int) -> TensorLikeType:
283
+ """
284
+ Reference implementation of :func:`torch.nn.functional.channel_shuffle`.
285
+ """
286
+ from torch._meta_registrations import device_hint
287
+
288
+ torch._check(
289
+ input.dim() > 2,
290
+ lambda: f"channel_shuffle expects input with > 2 dims, but got input with sizes {list(input.size())}",
291
+ )
292
+ c = input.shape[1]
293
+ torch._check(
294
+ groups > 0,
295
+ lambda: f"Number of groups to divide channels in must be positive. Value of groups:{groups}",
296
+ )
297
+ torch._check(
298
+ (c % groups) == 0,
299
+ lambda: f"Number of channels must be divisible by groups. Got {c} channels and {groups} groups.",
300
+ )
301
+ n = input.shape[0]
302
+ cg = c // groups
303
+ dhw = input.shape[2:]
304
+
305
+ if input.numel() == 0 or (
306
+ device_hint(input) == "cuda" and (groups == 1 or groups == c)
307
+ ):
308
+ return input.view(input.shape)
309
+
310
+ return (
311
+ input.reshape(n, groups, cg, *dhw)
312
+ .transpose(1, 2)
313
+ .reshape(input.shape)
314
+ .contiguous()
315
+ )
316
+
317
+
318
+ def group_norm(
319
+ input: Tensor,
320
+ num_groups: int,
321
+ weight: Optional[Tensor] = None,
322
+ bias: Optional[Tensor] = None,
323
+ eps: float = 1e-5,
324
+ ) -> Tensor:
325
+ """
326
+ Reference implementation of :func:`torch.nn.functional.group_norm`.
327
+ """
328
+ torch._check(
329
+ input.ndim >= 2,
330
+ lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}",
331
+ )
332
+
333
+ batch_size = input.shape[0]
334
+ num_channels = input.shape[1]
335
+ torch._check(
336
+ num_channels % num_groups == 0,
337
+ lambda: "Expected number of channels in input to be divisible by num_groups, "
338
+ + f"but got input of shape {input.shape} and num_groups = {num_groups}",
339
+ )
340
+
341
+ # input shape is (N, C, *), so we flatten all inner dimensions except (N, C)
342
+ flattened_inner_size = 1
343
+ for dim_length in input.shape[2:]:
344
+ flattened_inner_size *= dim_length
345
+
346
+ return torch.native_group_norm(
347
+ input,
348
+ weight,
349
+ bias,
350
+ batch_size,
351
+ num_channels,
352
+ flattened_inner_size,
353
+ num_groups,
354
+ eps,
355
+ )[0]
356
+
357
+
358
+ def layer_norm(
359
+ input: Tensor,
360
+ normalized_shape: ShapeType,
361
+ weight: Optional[Tensor] = None,
362
+ bias: Optional[Tensor] = None,
363
+ eps: float = 1e-5,
364
+ ) -> Tensor:
365
+ """
366
+ Reference implementation of :func:`torch.nn.functional.layer_norm`.
367
+ """
368
+ return torch.native_layer_norm(input, normalized_shape, weight, bias, eps)[0]
369
+
370
+
371
+ @register_decomposition(aten.leaky_relu)
372
+ @_inplace_wrapper
373
+ @out_wrapper()
374
+ @elementwise_type_promotion_wrapper(
375
+ type_promoting_args=("a",),
376
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
377
+ )
378
+ def leaky_relu(
379
+ a: TensorLikeType, negative_slope: float = 0.01, inplace: bool = False
380
+ ) -> TensorLikeType:
381
+ """
382
+ Reference implementation of torch.nn.functional.leaky_relu
383
+ """
384
+
385
+ if inplace:
386
+ raise NotImplementedError
387
+
388
+ python_type = utils.dtype_to_type(a.dtype)
389
+ if not utils.is_weakly_lesser_type(type(negative_slope), python_type):
390
+ msg = f"negative_slope argument of type {type(negative_slope)} cannot be safely cast to type {python_type}!"
391
+ raise ValueError(msg)
392
+ return torch.where(torch.gt(a, 0), a, torch.mul(a, negative_slope))
393
+
394
+
395
+ @register_decomposition(aten.mish)
396
+ @_inplace_wrapper
397
+ @out_wrapper()
398
+ @elementwise_type_promotion_wrapper(
399
+ type_promoting_args=("a",),
400
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
401
+ )
402
+ def mish(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
403
+ """
404
+ Reference implementation of torch.nn.functional.mish
405
+ """
406
+
407
+ if inplace:
408
+ raise NotImplementedError
409
+ return a * torch.tanh(torch.nn.functional.softplus(a))
410
+
411
+
412
+ @register_decomposition(aten.selu)
413
+ @_inplace_wrapper
414
+ @out_wrapper()
415
+ @elementwise_type_promotion_wrapper(
416
+ type_promoting_args=("a",),
417
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
418
+ )
419
+ def selu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
420
+ """
421
+ Reference implementation of torch.nn.functional.selu
422
+ """
423
+ if inplace:
424
+ raise NotImplementedError
425
+
426
+ alpha = 1.6732632423543772848170429916717
427
+ scale = 1.0507009873554804934193349852946
428
+
429
+ rhs = alpha * torch.expm1(a)
430
+
431
+ return scale * torch.where(a > 0, a, rhs)
432
+
433
+
434
+ # Forwarding alias: the functional variant doesn't support the out kwarg
435
+ # CompositeImplicitAutograd - don't register decomp
436
+ def softmax(
437
+ a: TensorLikeType,
438
+ dim: Optional[int] = None,
439
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
440
+ dtype: Optional[torch.dtype] = None,
441
+ ) -> TensorLikeType:
442
+ # The error is for compat with regular PyTorch, which has this behavior
443
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
444
+ # behavior because it requires explicit opt in. This error is to inform
445
+ # users how to update their calls.
446
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
447
+ return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
448
+
449
+
450
+ # CompositeImplicitAutograd - don't register decomp
451
+ def softmin(
452
+ a: TensorLikeType,
453
+ dim: Optional[int] = None,
454
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
455
+ dtype: Optional[torch.dtype] = None,
456
+ ) -> TensorLikeType:
457
+ # The error is for compat with regular PyTorch, which has this behavior
458
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
459
+ # behavior because it requires explicit opt in. This error is to inform
460
+ # users how to update their calls.
461
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
462
+ return torch.softmax(a=-a, dim=dim, dtype=dtype) # type: ignore[call-overload]
463
+
464
+
465
+ # softplus is implemented specially because it has beta and threshold arguments
466
+ @register_decomposition(aten.softplus)
467
+ @_inplace_wrapper
468
+ @out_wrapper()
469
+ @elementwise_type_promotion_wrapper(
470
+ type_promoting_args=("a",),
471
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
472
+ )
473
+ def softplus(
474
+ a: TensorLikeType,
475
+ beta: Optional[NumberType] = None,
476
+ threshold: NumberType = 20,
477
+ inplace: bool = False,
478
+ ) -> TensorLikeType:
479
+ """
480
+ Reference implementation of torch.nn.functional.softplus
481
+ """
482
+
483
+ if inplace:
484
+ raise NotImplementedError
485
+
486
+ rhs: TensorLikeType
487
+ if beta is not None:
488
+ python_type = utils.dtype_to_type(a.dtype)
489
+ if not utils.is_weakly_lesser_type(type(beta), python_type):
490
+ msg = f"beta argument of type {type(beta)} cannot be safely cast to type {python_type}!"
491
+ raise ValueError(msg)
492
+ scaled_input = a * beta
493
+ rhs = torch.true_divide(torch.log1p(torch.exp(scaled_input)), beta) # type: ignore[arg-type]
494
+
495
+ else:
496
+ scaled_input = a
497
+ rhs = torch.log1p(torch.exp(scaled_input))
498
+
499
+ return torch.where(scaled_input > threshold, a, rhs)
500
+
501
+
502
+ @aten.hardshrink.default.py_impl(DispatchKey.Autograd)
503
+ @register_decomposition(aten.hardshrink)
504
+ @out_wrapper()
505
+ def hardshrink(a: TensorLikeType, lambd: float = 0.5):
506
+ # Formula for reference,
507
+ # hardshrink(x) = x if x > lambd
508
+ # = x if x < -lambd
509
+ # = 0 otherwise
510
+ return torch.where(torch.abs(a) <= lambd, 0, a)
511
+
512
+
513
+ @aten.softshrink.default.py_impl(DispatchKey.Autograd)
514
+ @register_decomposition(aten.softshrink)
515
+ @out_wrapper()
516
+ def softshrink(a: TensorLikeType, lambd: float = 0.5):
517
+ # Formula for reference,
518
+ # softshrink(x) = x - lambd if x > lambd
519
+ # = x + lambd if x < -lambd
520
+ # = 0 otherwise
521
+ torch._check(
522
+ 0 <= lambd <= torch.finfo(a.dtype).max,
523
+ lambda: f"lambda must be in range [0, {torch.finfo(a.dtype).max}] for input dtype {a.dtype}, but found {lambd}",
524
+ )
525
+ # We implement this in one torch.where to generate better code in the backward
526
+ # see https://github.com/pytorch/pytorch/pull/107052#discussion_r1293748211
527
+ # We multiply by 0 for dealing with nans
528
+ return torch.where(torch.abs(a) > lambd, a - torch.sign(a) * lambd, a * 0)
529
+
530
+
531
+ # Losses
532
+ def _reduction_int_to_str(reduction: int) -> str:
533
+ from torch._decomp.decompositions import Reduction
534
+
535
+ if reduction == Reduction.NONE.value:
536
+ return "none"
537
+ elif reduction == Reduction.MEAN.value:
538
+ return "mean"
539
+ elif reduction == Reduction.SUM.value:
540
+ return "sum"
541
+ else:
542
+ raise ValueError(f"{reduction} is not a valid value for reduction")
543
+
544
+
545
+ def _apply_loss_reduction(loss: TensorLikeType, reduction: str) -> TensorLikeType:
546
+ if reduction == "sum":
547
+ return torch.sum(loss)
548
+ elif reduction == "mean":
549
+ return torch.mean(loss)
550
+ else: # reduction == "none"
551
+ return loss
552
+
553
+
554
+ def _check_reduction_value(reduction: str):
555
+ if reduction not in ("mean", "sum", "none"):
556
+ raise ValueError(f"{reduction} is not a valid value for reduction")
557
+
558
+
559
+ # This helper function maps depreciated arguments, "size_average" and "reduce"
560
+ # to their corresponding "reduction" string argument
561
+ def _get_string_reduction_arg(
562
+ *, size_average: Optional[bool], reduce: Optional[bool]
563
+ ) -> str:
564
+ if size_average is None:
565
+ size_average = True
566
+ if reduce is None:
567
+ reduce = True
568
+ if size_average and reduce:
569
+ ret = "mean"
570
+ elif reduce:
571
+ ret = "sum"
572
+ else:
573
+ ret = "none"
574
+ return ret
575
+
576
+
577
+ # CompositeImplicitAutograd - don't register decomp
578
+ @elementwise_type_promotion_wrapper(
579
+ type_promoting_args=("input", "target"),
580
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
581
+ )
582
+ def l1_loss(
583
+ input: TensorLikeType,
584
+ target: TensorLikeType,
585
+ size_average: Optional[bool] = None,
586
+ reduce: Optional[bool] = None,
587
+ reduction: str = "mean",
588
+ ) -> TensorLikeType:
589
+ """
590
+ Reference implementation of torch.nn.functional.l1_loss
591
+ """
592
+ if size_average is not None or reduce is not None:
593
+ # TODO: Raise exception instead of converting value. This is only for
594
+ # primTorch since it can drop support for deprecated arguments.
595
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
596
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
597
+ _check_reduction_value(reduction)
598
+ loss = torch.abs(input - target)
599
+ return _apply_loss_reduction(loss, reduction)
600
+
601
+
602
+ @elementwise_type_promotion_wrapper(
603
+ type_promoting_args=("input", "target"),
604
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
605
+ )
606
+ def smooth_l1_loss(
607
+ input: TensorLikeType,
608
+ target: TensorLikeType,
609
+ size_average: Optional[bool] = None,
610
+ reduce: Optional[bool] = None,
611
+ reduction: str = "mean",
612
+ beta: float = 1.0,
613
+ ) -> TensorLikeType:
614
+ """
615
+ Reference implementation of torch.nn.functional.smooth_l1_loss
616
+ """
617
+ if size_average is not None or reduce is not None:
618
+ # TODO: Raise exception instead of converting value. This is only for
619
+ # primTorch since it can drop support for deprecated arguments.
620
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
621
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
622
+ _check_reduction_value(reduction)
623
+
624
+ if beta == 0.0:
625
+ return torch.nn.functional.l1_loss(
626
+ input, target, size_average=size_average, reduce=reduce, reduction=reduction
627
+ )
628
+ else:
629
+ loss = torch.abs(input - target)
630
+ # pyrefly: ignore [unsupported-operation]
631
+ loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta)
632
+ return _apply_loss_reduction(loss, reduction)
633
+
634
+
635
+ # Forwarding alias: the functional variant doesn't support the out kwarg
636
+ # CompositeImplicitAutograd - don't register decomp
637
+ def log_softmax(
638
+ a: TensorLikeType,
639
+ dim: Optional[int] = None,
640
+ _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True)
641
+ dtype: Optional[torch.dtype] = None,
642
+ ) -> TensorLikeType:
643
+ # The error is for compat with regular PyTorch, which has this behavior
644
+ # deprecated. For PrimTorch, it's fine to drop support for deprecated
645
+ # behavior because it requires explicit opt in. This error is to inform
646
+ # users how to update their calls.
647
+ torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X")
648
+ return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
649
+
650
+
651
+ @register_decomposition(aten.margin_ranking_loss)
652
+ def margin_ranking_loss(
653
+ input1: TensorLikeType,
654
+ input2: TensorLikeType,
655
+ target: TensorLikeType,
656
+ margin: float = 0.0,
657
+ reduction: str = "mean",
658
+ ) -> TensorLikeType:
659
+ # loss_without_reduction = max(0, -target * (input1 - input2) + margin)
660
+ if input1.ndim != input2.ndim or input1.ndim != target.ndim:
661
+ raise RuntimeError(
662
+ "margin_ranking_loss : All input tensors should have same dimension but got sizes: "
663
+ f"input1: {input1.shape}, input2: {input2.shape}, target: {target.shape} "
664
+ )
665
+ _check_reduction_value(reduction)
666
+ loss = torch.clamp_min(-target * (input1 - input2) + margin, 0)
667
+ return _apply_loss_reduction(loss, reduction)
668
+
669
+
670
+ @elementwise_type_promotion_wrapper(
671
+ type_promoting_args=("input", "target"),
672
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
673
+ )
674
+ def mse_loss(
675
+ input: TensorLikeType,
676
+ target: TensorLikeType,
677
+ size_average: Optional[bool] = None,
678
+ reduce: Optional[bool] = None,
679
+ reduction: str = "mean",
680
+ ) -> TensorLikeType:
681
+ if size_average is not None or reduce is not None:
682
+ # TODO: Raise exception instead of converting value. This is only for
683
+ # primTorch since it can drop support for deprecated arguments.
684
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
685
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
686
+ _check_reduction_value(reduction)
687
+ loss = torch.pow(input - target, 2)
688
+ return _apply_loss_reduction(loss, reduction)
689
+
690
+
691
+ @register_decomposition(aten.hinge_embedding_loss)
692
+ def hinge_embedding_loss(
693
+ input: TensorLikeType,
694
+ target: TensorLikeType,
695
+ margin: float = 1.0,
696
+ reduction: str = "mean",
697
+ ) -> TensorLikeType:
698
+ # loss_without_reduction = input if y == 1
699
+ # = max(0, margin - input) if y == -1
700
+ _check_reduction_value(reduction)
701
+ margin_clamp = torch.clamp_min(margin - input, 0)
702
+ output_margin = torch.where(target != 1, margin_clamp, 0)
703
+ output_self = torch.where(target != -1, input, 0)
704
+ loss = output_margin + output_self
705
+ return _apply_loss_reduction(loss, reduction)
706
+
707
+
708
+ def _nll_loss_nd(
709
+ input: TensorLikeType,
710
+ target: TensorLikeType,
711
+ weight: Optional[TensorLikeType],
712
+ reduction: str,
713
+ ignore_index: int,
714
+ ) -> TensorLikeType:
715
+ torch._check(
716
+ input.ndim > 0 and input.ndim <= 3,
717
+ lambda: f"Expected input dimension to be either [1, 2, 3] but received {input.ndim}.",
718
+ )
719
+
720
+ torch._check(
721
+ (input.ndim == 1) or (input.shape[0] == target.shape[0]),
722
+ lambda: f"Expected input batch size {input.shape[0]} to match target batch size {target.shape[0]}.",
723
+ )
724
+
725
+ _check_reduction_value(reduction)
726
+
727
+ flat_target = torch.flatten(target)
728
+ ignore_classes_mask = torch.eq(flat_target, ignore_index)
729
+
730
+ # TODO: Enable data-dependent checks with debug mode
731
+ # TODO: This check does not work with FakeTensor inputs; See Issue #85834
732
+ # Explicit cast for class_check to bool; See Issue #78071
733
+ """
734
+ from torch._subclasses.fake_tensor import FakeTensor
735
+ num_classes = input.shape[1] if input.ndim > 1 else input.shape[0]
736
+ valid_classes_mask = torch.logical_and(
737
+ (flat_target >= 0), (flat_target < num_classes)
738
+ )
739
+ class_check = torch.all(torch.logical_or(ignore_classes_mask, valid_classes_mask))
740
+ torch._check(
741
+ isinstance(target, FakeTensor) or bool(class_check.item()),
742
+ lambda: "A target class is out-of-bounds and not the ignore index.",
743
+ )
744
+ """
745
+
746
+ ignore_class_weight = torch.scalar_tensor(0, dtype=input.dtype, device=input.device)
747
+ class_weight = (
748
+ torch.scalar_tensor(1, dtype=input.dtype, device=input.device)
749
+ if weight is None
750
+ else weight[flat_target]
751
+ )
752
+ current_weight = torch.where(
753
+ ignore_classes_mask,
754
+ ignore_class_weight,
755
+ class_weight,
756
+ )
757
+
758
+ if input.ndim == 1:
759
+ # implicit batch size = 1
760
+ # input (1 batch size, C classes)
761
+ loss = -input[target] * current_weight
762
+ elif input.ndim == 2:
763
+ # input (N batch size, C classes)
764
+ batch_size = input.shape[0]
765
+ loss = -input[torch.arange(batch_size), target] * current_weight
766
+ else:
767
+ # 3D case (N batch size, C classes, K dimensions)
768
+ # input (N batch size, C classes, K)
769
+ batch_size = input.shape[0]
770
+ extent = input.shape[2]
771
+ numel = batch_size * extent
772
+ indices = torch.arange(numel)
773
+ bdx = indices // extent
774
+ kdx = indices % extent
775
+ loss = -input[bdx, flat_target, kdx] * current_weight
776
+ loss = torch.reshape(loss, target.shape)
777
+
778
+ if reduction == "none":
779
+ return loss
780
+ elif reduction == "sum":
781
+ return torch.sum(loss)
782
+ else:
783
+ # calculate weighted mean of the loss function
784
+ return torch.sum(loss) / torch.sum(current_weight)
785
+
786
+
787
+ @register_decomposition(aten.nll_loss)
788
+ @out_wrapper()
789
+ @elementwise_type_promotion_wrapper(
790
+ type_promoting_args=("input",),
791
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
792
+ )
793
+ def nll_loss(
794
+ input: TensorLikeType,
795
+ target: TensorLikeType,
796
+ weight: Optional[TensorLikeType] = None,
797
+ size_average: Optional[bool] = None,
798
+ ignore_index: int = -100,
799
+ reduce: Optional[bool] = None,
800
+ reduction: str = "mean",
801
+ ) -> TensorLikeType:
802
+ """
803
+ Reference implementation of torch.nn.functional.nll_loss
804
+ """
805
+ torch._check(
806
+ input.ndim > 0,
807
+ lambda: f"Expected input tensor to have 1 or more dimensions (got {input.ndim})",
808
+ )
809
+
810
+ # TODO: raise exception instead of converting value
811
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
812
+ # Convert these options for consistency with the eager mode
813
+ if size_average is not None or reduce is not None:
814
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
815
+
816
+ # The expected behavior when the target and input have zero elements:
817
+ # reduction = 'none' --- tensor([])
818
+ # reduction = 'sum' --- tensor(0.)
819
+ # reduction = 'mean' --- tensor(nan)
820
+ # Mean reduction on empty tensors produces NaN. See the discussion in
821
+ # https://github.com/pytorch/pytorch/pull/64572#issuecomment-926504162
822
+ if input.numel() == 0 and target.numel() == 0:
823
+ if reduction == "none":
824
+ return torch.zeros_like(target)
825
+ elif reduction == "sum":
826
+ return torch.empty_like(target)
827
+ else:
828
+ return torch.full_like(target, float("nan"))
829
+
830
+ # The _nll_loss_nd helper function handles the most common cases.
831
+ # ndim == 1 (Single Example)
832
+ # => Batch Size: 1, Input: (C), Target: ()
833
+ # ndim == 2 (k = 1)
834
+ # => Batch Size: N, Input: (N, C), Target: (N)
835
+ # ndim == 3 (k > 1)
836
+ # => Batch Size: N, Input: (N, C, K), Target: (N, K)
837
+ if input.ndim <= 3:
838
+ return _nll_loss_nd(input, target, weight, reduction, ignore_index)
839
+
840
+ # For ndim > 3, we reshape the input and target to 3-D case.
841
+ # Input (N batch-size, C classes, k-dimensions)
842
+ # Target (N batch-size, k-dimensions)
843
+ torch._check(
844
+ input.ndim > 0 and target.ndim > 0 and target.shape[1:] == input.shape[2:],
845
+ lambda: (
846
+ "Expected input and target to both have ndim > 0 and "
847
+ "target.shape[1:] == input.shape[2:], but got "
848
+ f"target.shape {target.shape} and input.shape {input.shape}"
849
+ ),
850
+ )
851
+
852
+ batch_size = input.shape[0]
853
+ num_classes = input.shape[1]
854
+ out_size = [batch_size] + list(target.shape[1:])
855
+
856
+ input = torch.reshape(input, [batch_size, num_classes, -1])
857
+ target = torch.reshape(target, [batch_size, -1])
858
+ if reduction != "none":
859
+ return _nll_loss_nd(input, target, weight, reduction, ignore_index)
860
+ else:
861
+ result = _nll_loss_nd(input, target, weight, reduction, ignore_index)
862
+ # reshape flattened inner-dim to original k-dimensions
863
+ return torch.reshape(result, out_size)
864
+
865
+
866
+ # TODO: This ref supports int reduction and out kwarg to be compatible with ATen:
867
+ # https://github.com/pytorch/pytorch/issues/83931
868
+ # TODO: Could be rewritten to support complex:
869
+ # https://github.com/pytorch/pytorch/pull/85041
870
+ @register_decomposition(aten.huber_loss)
871
+ @out_wrapper()
872
+ @elementwise_type_promotion_wrapper(
873
+ type_promoting_args=("input", "target"),
874
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
875
+ )
876
+ def huber_loss(
877
+ input: TensorLikeType,
878
+ target: TensorLikeType,
879
+ reduction: Union[str, int] = "mean",
880
+ delta: float = 1.0,
881
+ ) -> TensorLikeType:
882
+ """
883
+ Reference implementation of torch.nn.functional.huber_loss
884
+ """
885
+ if type(reduction) is int:
886
+ reduction = _reduction_int_to_str(reduction)
887
+ _check_reduction_value(reduction) # type: ignore[arg-type]
888
+ torch._check(
889
+ delta > 0,
890
+ lambda: "huber_loss does not support non-positive values for delta.",
891
+ )
892
+ z = (input - target).abs()
893
+ loss = torch.where(z < delta, 0.5 * z * z, delta * (z - 0.5 * delta))
894
+ return _apply_loss_reduction(loss, reduction) # type: ignore[arg-type]
895
+
896
+
897
+ # tanhshrink does not use _make_elementwise_unary_reference because it does not support out
898
+ @elementwise_unary_scalar_wrapper
899
+ @elementwise_type_promotion_wrapper(
900
+ type_promoting_args=("a",),
901
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
902
+ )
903
+ def tanhshrink(a: TensorLikeType) -> TensorLikeType:
904
+ """
905
+ Reference implementation of torch.nn.functional.tanhshrink
906
+ """
907
+ if not isinstance(a, TensorLike):
908
+ raise RuntimeError(
909
+ "Expected a tensor input for an elementwise unary operation!"
910
+ )
911
+ return a - torch.tanh(a)
912
+
913
+
914
+ @register_decomposition(aten.threshold)
915
+ @_inplace_wrapper
916
+ @out_wrapper()
917
+ @elementwise_type_promotion_wrapper(
918
+ type_promoting_args=("a",),
919
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
920
+ )
921
+ def threshold(
922
+ a: TensorLikeType,
923
+ threshold: NumberType,
924
+ value: Union[bool, int, float],
925
+ inplace: bool = False,
926
+ ) -> TensorLikeType:
927
+ """
928
+ Reference implementation of torch.nn.functional.threshold
929
+ """
930
+
931
+ if inplace:
932
+ raise NotImplementedError
933
+
934
+ return torch.where(a <= threshold, value, a)
935
+
936
+
937
+ # CompositeImplicitAutograd - don't register decomp
938
+ # No elementwise type promotion - core op doesn't explicitly type promote
939
+ def triplet_margin_loss(
940
+ anchor: TensorLikeType,
941
+ positive: TensorLikeType,
942
+ negative: TensorLikeType,
943
+ margin: float = 1.0,
944
+ p: float = 2,
945
+ eps: float = 1e-6,
946
+ swap: bool = False,
947
+ size_average: Optional[bool] = None,
948
+ reduce: Optional[bool] = None,
949
+ reduction: str = "mean",
950
+ ) -> TensorLikeType:
951
+ if size_average is not None or reduce is not None:
952
+ # TODO: Raise exception instead of converting value. This is only for
953
+ # primTorch since it can drop support for deprecated arguments.
954
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
955
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
956
+
957
+ if margin <= 0:
958
+ raise ValueError(f"margin must be greater than 0, got {margin}")
959
+
960
+ # torch.nn.functional.triplet_margin_with_distance_loss has no ref defined
961
+ # since it's a pure Python implementation. Use this helper instead.
962
+ return _triplet_margin_with_distance_loss(
963
+ anchor=anchor,
964
+ positive=positive,
965
+ negative=negative,
966
+ distance_function=lambda x, y: torch.pairwise_distance(x, y, p, eps),
967
+ margin=margin,
968
+ swap=swap,
969
+ reduction=reduction,
970
+ )
971
+
972
+
973
+ # Pure Python impl - don't register decomp and don't add a ref. Defined as a
974
+ # helper here since triplet_margin_loss can be nicely implemented with it.
975
+ def _triplet_margin_with_distance_loss(
976
+ anchor: TensorLikeType,
977
+ positive: TensorLikeType,
978
+ negative: TensorLikeType,
979
+ *,
980
+ distance_function: Optional[
981
+ Callable[[TensorLikeType, TensorLikeType], TensorLikeType]
982
+ ] = None,
983
+ margin: float = 1.0,
984
+ swap: bool = False,
985
+ reduction: str = "mean",
986
+ ) -> TensorLikeType:
987
+ _check_reduction_value(reduction)
988
+
989
+ a_dim = anchor.ndim
990
+ p_dim = positive.ndim
991
+ n_dim = negative.ndim
992
+ torch._check(
993
+ a_dim == p_dim and p_dim == n_dim,
994
+ lambda: (
995
+ f"The anchor, positive, and negative tensors are expected to have "
996
+ f"the same number of dimensions, but got: anchor {a_dim}D, "
997
+ f"positive {p_dim}D, and negative {n_dim}D inputs"
998
+ ),
999
+ )
1000
+
1001
+ if distance_function is None:
1002
+ distance_function = torch.pairwise_distance
1003
+
1004
+ dist_pos = distance_function(anchor, positive)
1005
+ dist_neg = distance_function(anchor, negative)
1006
+ # The distance swap is described in the paper "Learning shallow
1007
+ # convolutional feature descriptors with triplet losses" by V. Balntas, E.
1008
+ # Riba et al. If True, and if the positive example is closer to the
1009
+ # negative example than the anchor is, swaps the positive example and the
1010
+ # anchor in the loss computation.
1011
+ if swap:
1012
+ dist_swap = distance_function(positive, negative)
1013
+ dist_neg = torch.minimum(dist_neg, dist_swap)
1014
+ loss = torch.clamp_min(margin + dist_pos - dist_neg, 0)
1015
+ return _apply_loss_reduction(loss, reduction)
1016
+
1017
+
1018
+ @register_decomposition(aten.hardtanh)
1019
+ @_inplace_wrapper
1020
+ @out_wrapper()
1021
+ @elementwise_unary_scalar_wrapper
1022
+ @elementwise_type_promotion_wrapper(
1023
+ type_promoting_args=("a"),
1024
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1025
+ )
1026
+ def hardtanh(
1027
+ a: TensorLikeType,
1028
+ min_val: NumberType = -1,
1029
+ max_val: NumberType = 1,
1030
+ inplace: bool = False,
1031
+ ) -> TensorLikeType:
1032
+ """
1033
+ Reference implementation of torch.nn.functional.hardtanh
1034
+ """
1035
+ if inplace:
1036
+ raise NotImplementedError
1037
+ if utils.is_boolean_dtype(a.dtype):
1038
+ raise RuntimeError("Bool inputs not supported for hardtanh")
1039
+
1040
+ # preserve legacy behavior of boundaries not causing type promotion
1041
+ if utils.is_integer_dtype(a.dtype):
1042
+ min_val = int(min_val) # type: ignore[arg-type]
1043
+ max_val = int(max_val) # type: ignore[arg-type]
1044
+ if not (a.dtype != torch.uint8 or (min_val >= 0 and max_val >= 0)):
1045
+ raise RuntimeError(
1046
+ "Cannot do hardtanh on an unsigned type with negative limits"
1047
+ )
1048
+
1049
+ if min_val > max_val: # type: ignore[operator]
1050
+ raise ValueError("min_val cannot be greater than max_val")
1051
+
1052
+ return torch.clamp(a, min_val, max_val) # type: ignore[arg-type]
1053
+
1054
+
1055
+ @register_decomposition(aten.gelu)
1056
+ @out_wrapper()
1057
+ @elementwise_unary_scalar_wrapper
1058
+ @elementwise_type_promotion_wrapper(
1059
+ type_promoting_args=("a",),
1060
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1061
+ )
1062
+ def gelu(a: TensorLikeType, approximate: str = "none") -> TensorLikeType:
1063
+ """
1064
+ Reference implementation of torch.nn.functional.gelu
1065
+ """
1066
+ if not isinstance(a, TensorLike):
1067
+ raise RuntimeError(
1068
+ "Expected a tensor input for an elementwise unary operation!"
1069
+ )
1070
+ M_SQRT2 = 1.41421356237309504880
1071
+ M_SQRT1_2 = 0.70710678118654752440
1072
+ M_2_SQRTPI = 1.12837916709551257390
1073
+ if approximate == "tanh":
1074
+ kBeta = M_SQRT2 * M_2_SQRTPI * 0.5
1075
+ kKappa = 0.044715
1076
+ a_cube = a * a * a
1077
+ inner = kBeta * (a + kKappa * a_cube)
1078
+ return 0.5 * a * (1 + torch.tanh(inner))
1079
+ elif approximate == "none":
1080
+ kAlpha = M_SQRT1_2
1081
+ return a * 0.5 * (1 + torch.erf(a * kAlpha))
1082
+ else:
1083
+ raise RuntimeError("approximate argument must be either none or tanh.")
1084
+
1085
+
1086
+ # CompositeImplicitAutograd - don't register decomp
1087
+ @elementwise_type_promotion_wrapper(
1088
+ type_promoting_args=("input", "target"),
1089
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
1090
+ )
1091
+ def poisson_nll_loss(
1092
+ input: TensorLikeType,
1093
+ target: TensorLikeType,
1094
+ log_input: bool = True,
1095
+ full: bool = False,
1096
+ size_average: Optional[bool] = None,
1097
+ eps: float = 1e-8,
1098
+ reduce: Optional[bool] = None,
1099
+ reduction: str = "mean",
1100
+ ) -> TensorLikeType:
1101
+ """
1102
+ Reference implementation of torch.nn.functional.poisson_nll_loss
1103
+ """
1104
+ if size_average is not None or reduce is not None:
1105
+ # TODO: Raise exception instead of converting value. This is only for
1106
+ # primTorch since it can drop support for deprecated arguments.
1107
+ # msg = "size_average and reduce args are deprecated, please use reduction argument."
1108
+ reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce)
1109
+ _check_reduction_value(reduction)
1110
+ if log_input:
1111
+ loss = torch.exp(input) - target * input
1112
+ else:
1113
+ loss = input - target * torch.log(input + eps)
1114
+
1115
+ if full:
1116
+ stirling_term = (
1117
+ target * torch.log(target) - target + 0.5 * torch.log(2 * torch.pi * target)
1118
+ )
1119
+ # avoid inplace add
1120
+ loss = loss + stirling_term.masked_fill(target <= 1, 0)
1121
+ return _apply_loss_reduction(loss, reduction)
1122
+
1123
+
1124
+ @register_decomposition(aten.prelu)
1125
+ @elementwise_type_promotion_wrapper(
1126
+ type_promoting_args=("a", "weight"),
1127
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1128
+ )
1129
+ def prelu(a: TensorLikeType, weight: TensorLikeType) -> TensorLikeType:
1130
+ """
1131
+ Reference implementation of torch.nn.functional.prelu
1132
+ """
1133
+ torch._check(
1134
+ isinstance(a, TensorLike),
1135
+ lambda: f"prelu: Expected `a` to be tensor, but got: {type(a)}",
1136
+ )
1137
+ torch._check(
1138
+ isinstance(weight, TensorLike),
1139
+ lambda: f"prelu: Expected `weight` to be tensor, but got: {type(weight)}",
1140
+ )
1141
+
1142
+ if weight.numel() != 1:
1143
+ torch._check(a.ndim > 0, lambda: "Not allow zero-dim input tensor.")
1144
+ channel_size = a.shape[1] if a.ndim >= 2 else 1
1145
+ torch._check(
1146
+ weight.numel() == channel_size,
1147
+ lambda: f"Mismatch of parameter numbers and input channel size. Found parameter numbers ="
1148
+ f" {weight.numel()} and channel size = {channel_size}.",
1149
+ )
1150
+
1151
+ torch._check(
1152
+ weight.ndim == 0 or weight.ndim == 1,
1153
+ lambda: f"prelu: Expected `weight` to be a scalar or 1D tensor, but got: "
1154
+ f"ndim = {weight.ndim}",
1155
+ )
1156
+ if a.ndim == 0:
1157
+ weight = weight[0] if weight.ndim == 1 else weight
1158
+ else:
1159
+ weight = prims.broadcast_in_dim(
1160
+ weight, a.shape, () if weight.ndim == 0 else (0 if a.ndim == 1 else 1,)
1161
+ )
1162
+
1163
+ return torch.where(a > 0, a, a * weight)
1164
+
1165
+
1166
+ @register_decomposition(aten.relu6)
1167
+ @_inplace_wrapper
1168
+ @out_wrapper()
1169
+ def relu6(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
1170
+ """
1171
+ Reference implementation of torch.nn.functional.relu6
1172
+ """
1173
+ if inplace:
1174
+ raise NotImplementedError
1175
+
1176
+ # See https://github.com/pytorch/pytorch/pull/81142#discussion_r918220126
1177
+ # It may be better to use clamp here, but we use hardtanh to replicate
1178
+ # the behavior of the existing implementation
1179
+ return torch.nn.functional.hardtanh(a, 0, 6)
1180
+
1181
+
1182
+ @register_decomposition(aten.glu)
1183
+ @out_wrapper()
1184
+ @elementwise_type_promotion_wrapper(
1185
+ type_promoting_args=("a",),
1186
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1187
+ )
1188
+ def glu(a: TensorLikeType, dim: int = -1) -> TensorLikeType:
1189
+ dim = utils.canonicalize_dims(a.ndim, dim)
1190
+ torch._check(
1191
+ a.shape[dim] % 2 == 0,
1192
+ lambda: f"Halving dimension must be even, but dimension {dim} is size {a.shape[dim]}",
1193
+ )
1194
+ b, c = torch.tensor_split(a, 2, dim)
1195
+
1196
+ return b * torch.sigmoid(c)
1197
+
1198
+
1199
+ @register_decomposition(aten.pairwise_distance)
1200
+ @out_wrapper()
1201
+ def pairwise_distance(
1202
+ x1: TensorLikeType,
1203
+ x2: TensorLikeType,
1204
+ p: NumberType = 2.0,
1205
+ eps: NumberType = 1e-6,
1206
+ keepdim=False,
1207
+ ) -> TensorLikeType:
1208
+ return torch.linalg.vector_norm(x1 - x2 + eps, ord=p, dim=-1, keepdim=keepdim)
1209
+
1210
+
1211
+ @register_decomposition(aten.pdist)
1212
+ @out_wrapper()
1213
+ @elementwise_type_promotion_wrapper(
1214
+ type_promoting_args=("a",),
1215
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
1216
+ )
1217
+ def pdist(a: TensorLikeType, p: float = 2) -> TensorLikeType:
1218
+ torch._check(a.ndim == 2, lambda: f"pdist only supports 2D tensors, got: {a.ndim}D")
1219
+ torch._check(p >= 0, lambda: "pdist only supports non-negative p values")
1220
+ # For p == 2 we can use an efficient implementation, but other values of p
1221
+ # require creating a much bigger tensor for an intermediate step
1222
+ if p == 2:
1223
+ aTa = torch.mm(a, a.T)
1224
+ aTa_diag = torch.diag(aTa)
1225
+ t = torch.sqrt(torch.clamp(aTa_diag + aTa_diag.unsqueeze(-1) - 2 * aTa, min=0))
1226
+ else:
1227
+ t = torch.linalg.vector_norm(a.unsqueeze(1) - a, ord=p, dim=2)
1228
+ i = torch.triu_indices(t.shape[0], t.shape[1], offset=1, device=a.device)
1229
+ return t.flatten().index_select(0, i[0] * t.shape[0] + i[1])
1230
+
1231
+
1232
+ @register_decomposition(aten.pixel_shuffle)
1233
+ @out_wrapper()
1234
+ def pixel_shuffle(self: Tensor, upscale_factor: int):
1235
+ torch._check(
1236
+ self.dim() >= 3,
1237
+ lambda: f"pixel_shuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
1238
+ )
1239
+ batch = self.shape[:-3]
1240
+ C_out = self.shape[-3] // upscale_factor**2
1241
+ HW_out = (self.shape[-2] * upscale_factor, self.shape[-1] * upscale_factor)
1242
+ n = len(batch)
1243
+ B_dims = range(n)
1244
+ C_dim, r1_dim, r2_dim, H_dim, W_dim = range(n, n + 5)
1245
+ return (
1246
+ self.view(
1247
+ *batch,
1248
+ C_out,
1249
+ upscale_factor,
1250
+ upscale_factor,
1251
+ self.shape[-2],
1252
+ self.shape[-1],
1253
+ )
1254
+ .permute(*B_dims, C_dim, H_dim, r1_dim, W_dim, r2_dim)
1255
+ .reshape(*batch, C_out, *HW_out)
1256
+ .clone(memory_format=utils.suggest_memory_format(self))
1257
+ )
1258
+
1259
+
1260
+ @register_decomposition(aten.pixel_unshuffle)
1261
+ @out_wrapper()
1262
+ def pixel_unshuffle(self: Tensor, downscale_factor: int):
1263
+ torch._check(
1264
+ self.dim() >= 3,
1265
+ lambda: f"pixel_unshuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)",
1266
+ )
1267
+ batch = self.shape[:-3]
1268
+ C_out = self.shape[-3] * downscale_factor**2
1269
+ HW_out = (self.shape[-2] // downscale_factor, self.shape[-1] // downscale_factor)
1270
+ n = len(batch)
1271
+ B_dims = range(n)
1272
+ C_dim, H_dim, r1_dim, W_dim, r2_dim = range(n, n + 5)
1273
+ return (
1274
+ self.view(
1275
+ *batch,
1276
+ self.shape[-3],
1277
+ HW_out[0],
1278
+ downscale_factor,
1279
+ HW_out[1],
1280
+ downscale_factor,
1281
+ )
1282
+ .permute(*B_dims, C_dim, r1_dim, r2_dim, H_dim, W_dim)
1283
+ .reshape(*batch, C_out, *HW_out)
1284
+ .clone(memory_format=utils.suggest_memory_format(self))
1285
+ )
1286
+
1287
+
1288
+ # Needed as aten.{celu_,elu_...} exist (even if they don't have the in-place kwarg)
1289
+ celu_ = _make_inplace(celu)
1290
+ elu_ = _make_inplace(elu)
1291
+ mish_ = _make_inplace(mish)
1292
+ selu_ = _make_inplace(selu)
1293
+ threshold_ = _make_inplace(threshold)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_refs/special/__init__.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert isinstance(a, TensorLike)
166
+ assert isinstance(b, TensorLike)
167
+ rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log1p(b)))
168
+ return torch.where(torch.isnan(b), float("nan"), rhs)
169
+
170
+
171
+ @register_decomposition(aten.mvlgamma)
172
+ @out_wrapper()
173
+ @elementwise_type_promotion_wrapper(
174
+ type_promoting_args=("a",),
175
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
176
+ )
177
+ def multigammaln(a: TensorLikeType, p: int) -> TensorLikeType:
178
+ c = 0.25 * p * (p - 1) * math.log(math.pi)
179
+ b = 0.5 * torch.arange(start=(1 - p), end=1, step=1, dtype=a.dtype, device=a.device)
180
+ return torch.sum(torch.lgamma(a.unsqueeze(-1) + b), dim=-1) + c
181
+
182
+
183
+ @register_decomposition(aten.special_ndtr)
184
+ @out_wrapper()
185
+ @elementwise_type_promotion_wrapper(
186
+ type_promoting_args=("a",),
187
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
188
+ )
189
+ def ndtr(a: TensorLikeType) -> TensorLikeType:
190
+ # Note: M_SQRT1_2 is the value of 1 / sqrt(2)
191
+ M_SQRT1_2 = 0.707106781186547524400844362104849039
192
+ a_sqrt_2 = a * M_SQRT1_2
193
+ return (1 + torch.erf(a_sqrt_2)) * 0.5
194
+
195
+
196
+ @register_decomposition(aten.special_ndtri)
197
+ @out_wrapper()
198
+ @elementwise_type_promotion_wrapper(
199
+ type_promoting_args=("a",),
200
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
201
+ )
202
+ def ndtri(a: TensorLikeType) -> TensorLikeType:
203
+ return prims.ndtri(a)
204
+
205
+
206
+ # Forwarding alias: the special variant doesn't support the out kwarg
207
+ # CompositeImplicitAutograd - don't register decomp
208
+ def log_softmax(
209
+ a: TensorLikeType,
210
+ dim: int,
211
+ dtype: Optional[torch.dtype] = None,
212
+ ) -> TensorLikeType:
213
+ return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
214
+
215
+
216
+ # Forwarding alias: the special variant doesn't support the out kwarg
217
+ # CompositeImplicitAutograd - don't register decomp
218
+ def softmax(
219
+ a: TensorLikeType,
220
+ dim: int,
221
+ dtype: Optional[torch.dtype] = None,
222
+ ) -> TensorLikeType:
223
+ return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload]
224
+
225
+
226
+ @_make_elementwise_unary_reference(
227
+ ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
228
+ )
229
+ def spherical_bessel_j0(a: TensorLikeType) -> TensorLikeType:
230
+ return prims.spherical_bessel_j0(a)
231
+
232
+
233
+ # TODO: add docstring
234
+ @_make_elementwise_binary_reference(
235
+ type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
236
+ )
237
+ def zeta(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
238
+ return prims.zeta(a, b)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_strobelight/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_strobelight/cli_function_profiler.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disallow-untyped-defs
2
+
3
+ import functools
4
+ import logging
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import time
9
+ from collections.abc import Callable, Sequence
10
+ from threading import Lock
11
+ from timeit import default_timer as timer
12
+ from typing import Any, Optional, TypeVar
13
+ from typing_extensions import ParamSpec
14
+
15
+
16
+ logger = logging.getLogger("strobelight_function_profiler")
17
+
18
+ console_handler = logging.StreamHandler()
19
+ formatter = logging.Formatter(
20
+ "%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s"
21
+ )
22
+ console_handler.setFormatter(formatter)
23
+
24
+ logger.addHandler(console_handler)
25
+ logger.setLevel(logging.INFO)
26
+ logger.propagate = False
27
+
28
+ _P = ParamSpec("_P")
29
+ _R = TypeVar("_R")
30
+
31
+
32
+ class StrobelightCLIProfilerError(Exception):
33
+ """
34
+ Raised when an error happens during strobelight profiling
35
+ """
36
+
37
+
38
+ def _pid_namespace_link(pid: Optional[int] = None) -> str:
39
+ """Returns the link to the process's namespace, example: pid:[4026531836]"""
40
+ PID_NAMESPACE_PATH = "/proc/{}/ns/pid"
41
+ pid = pid or os.getpid()
42
+ return os.readlink(PID_NAMESPACE_PATH.format(pid))
43
+
44
+
45
+ def _pid_namespace(pid: Optional[int] = None) -> int:
46
+ """Returns the process's namespace id"""
47
+ pid = pid or os.getpid()
48
+ link = _pid_namespace_link(pid)
49
+ return int(link[link.find("[") + 1 : -1])
50
+
51
+
52
+ def _command_to_string(command: Sequence[str]) -> str:
53
+ return " ".join(command)
54
+
55
+
56
+ class StrobelightCLIFunctionProfiler:
57
+ """
58
+ Note: this is a Meta only tool.
59
+
60
+ StrobelightCLIFunctionProfiler can be used to profile a python function and
61
+ generate a strobelight link with the results. It works on meta servers but
62
+ does not requires an fbcode target.
63
+ When stop_at_error is false(default), error during profiling does not prevent
64
+ the work function from running.
65
+
66
+ Check function_profiler_example.py for an example.
67
+ """
68
+
69
+ # This lock is used to make sure only one thread is running the profiler at any point.
70
+ _lock = Lock()
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ stop_at_error: bool = False,
76
+ max_profile_duration_sec: int = 60 * 10,
77
+ sample_each: float = 1e7, # sample each sample_each cycles.
78
+ run_user_name: str = "pytorch-strobelight-ondemand",
79
+ timeout_wait_for_running_sec: int = 60,
80
+ timeout_wait_for_finished_sec: int = 60,
81
+ recorded_env_variables: Optional[list[str]] = None,
82
+ sample_tags: Optional[list[str]] = None,
83
+ stack_max_len: int = 127,
84
+ async_stack_max_len: int = 127,
85
+ ):
86
+ self.stop_at_error = stop_at_error
87
+ self.max_profile_duration_sec = max_profile_duration_sec
88
+ self.sample_each = sample_each
89
+ self.run_user_name = run_user_name
90
+ self.timeout_wait_for_running_sec = timeout_wait_for_running_sec
91
+ self.timeout_wait_for_finished_sec = timeout_wait_for_finished_sec
92
+ # Results of the most recent run.
93
+ # Tracks the strobelight run id of the most recent run
94
+ self.current_run_id: Optional[int] = None
95
+ self.profile_result: Optional[list[str]] = None
96
+ self.sample_tags = sample_tags
97
+
98
+ def _run_async(self) -> None:
99
+ processId = os.getpid()
100
+ namespace = _pid_namespace(processId)
101
+ command = [
102
+ "strobeclient",
103
+ "run",
104
+ "--profiler",
105
+ "pyperf",
106
+ "--event",
107
+ "cycles",
108
+ "--async",
109
+ "--sample-interval",
110
+ f"{int(self.sample_each)}",
111
+ "--duration-ms",
112
+ f"{int(self.max_profile_duration_sec * 1000)}",
113
+ "--pid",
114
+ f"{namespace}:{processId}",
115
+ ]
116
+
117
+ if self.sample_tags:
118
+ command.append("--sample-tags")
119
+ command.append(",".join(self.sample_tags))
120
+
121
+ logger.debug("running command: %s", _command_to_string(command))
122
+ result = subprocess.run(command, capture_output=True)
123
+ output = result.stderr.decode("utf-8")
124
+ logger.debug("output:\n{%s}", output)
125
+
126
+ if result.returncode != 0:
127
+ raise StrobelightCLIProfilerError(
128
+ f"failed to start strobelight profiling, error in run_async:{output}"
129
+ )
130
+
131
+ if match := re.search(r"INFO Run Id: (-?\d+)", output):
132
+ self.current_run_id = int(match.group(1))
133
+ return
134
+
135
+ raise StrobelightCLIProfilerError(
136
+ f"failed to start strobelight profiling, unexpected result {output}"
137
+ )
138
+
139
+ def _wait_for_running(self, counter: int = 0) -> None:
140
+ if counter > 20:
141
+ raise StrobelightCLIProfilerError(
142
+ "wait_for_running called more than 20 times"
143
+ )
144
+
145
+ command = ["strobeclient", "getRunStatus", "--run-id", f"{self.current_run_id}"]
146
+ logger.debug("running command: %s", _command_to_string(command))
147
+ result = subprocess.run(command, capture_output=True)
148
+ output = result.stderr.decode("utf-8")
149
+ logger.debug("output:\n{%s}", output)
150
+
151
+ if result.returncode != 0:
152
+ raise StrobelightCLIProfilerError(
153
+ f"failed to start strobelight profiling, error in wait_for_running:{output}"
154
+ )
155
+
156
+ if match := re.search("Profile run status: (.*)", output):
157
+ current_status = match.group(1)
158
+ if current_status == "RUNNING":
159
+ return
160
+ elif current_status == "PREPARING":
161
+ time.sleep(10)
162
+ self._wait_for_running(counter + 1)
163
+ return
164
+ else:
165
+ raise StrobelightCLIProfilerError(f"unexpected {current_status} phase")
166
+
167
+ raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ")
168
+
169
+ def _stop_run(self) -> None:
170
+ command = ["strobeclient", "stopRun", "--run-id", str(self.current_run_id)]
171
+ logger.debug("running command: %s", _command_to_string(command))
172
+ result = subprocess.run(command, capture_output=True)
173
+ output = result.stderr.decode("utf-8")
174
+ logger.debug("output:\n{%s}", output)
175
+
176
+ if result.returncode != 0:
177
+ raise StrobelightCLIProfilerError(
178
+ f"failed to stop strobelight profiling, return code is not 0 :{output}"
179
+ )
180
+
181
+ if match := re.search("INFO ::1:(.*)", output):
182
+ current_status = match.group(1)
183
+ if current_status.__contains__("Success!"):
184
+ return
185
+ else:
186
+ raise StrobelightCLIProfilerError(
187
+ f"failed to stop strobelight profiling, got {current_status} result"
188
+ )
189
+
190
+ raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ")
191
+
192
+ def _get_results(self) -> None:
193
+ command = ["strobeclient", "getRunStatus", "--run-id", str(self.current_run_id)]
194
+ logger.debug("running command: %s", _command_to_string(command))
195
+ result = subprocess.run(command, capture_output=True)
196
+ output = result.stderr.decode("utf-8")
197
+ logger.debug("output:\n{%s}", output)
198
+
199
+ if result.returncode != 0:
200
+ raise StrobelightCLIProfilerError(
201
+ f"failed to extract profiling results, return code is not 0 : {output}"
202
+ )
203
+
204
+ if match := re.search("INFO ::1:(.*)", output):
205
+ current_status = match.group(1)
206
+ if current_status.__contains__("Profile run status: PROCESSING"):
207
+ time.sleep(10)
208
+ self._get_results()
209
+ return
210
+ elif not current_status.__contains__("Profile run finished with SUCCESS"):
211
+ raise StrobelightCLIProfilerError(
212
+ f"failed to extract profiling results, unexpected response {output}"
213
+ )
214
+
215
+ self.profile_result = []
216
+ for item in re.findall(
217
+ r"(Total samples(.*)|GraphProfiler(.*)|Icicle view \(python stack\)(.*))",
218
+ output,
219
+ ):
220
+ self.profile_result += item[0]
221
+ logger.info(item[0])
222
+
223
+ def _stop_strobelight_no_throw(
224
+ self,
225
+ collect_results: bool,
226
+ ) -> None:
227
+ try:
228
+ # call stop run
229
+ self._stop_run()
230
+ logger.info("strobelight profiling stopped")
231
+
232
+ logger.debug("collection stopped")
233
+
234
+ if not collect_results:
235
+ return
236
+
237
+ self._get_results()
238
+ except Exception:
239
+ logger.warning("error during stop_strobelight", exc_info=True)
240
+
241
+ # Return true if strobelight started and is running. Never throw.
242
+ def _start_strobelight(self) -> bool:
243
+ strobelight_started = False
244
+ try:
245
+ self._run_async()
246
+ strobelight_started = True
247
+ logger.info("strobelight run id is: %s", self.current_run_id)
248
+ self._wait_for_running()
249
+ logger.info("strobelight profiling running")
250
+ return True
251
+
252
+ except Exception:
253
+ logger.warning("error during start_strobelight:", exc_info=True)
254
+ if strobelight_started:
255
+ self._stop_strobelight_no_throw(collect_results=False)
256
+ return False
257
+
258
+ def profile(
259
+ self, work_function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs
260
+ ) -> Optional[_R]:
261
+ self.current_run_id = None
262
+ self.profile_result = None
263
+
264
+ if locked := StrobelightCLIFunctionProfiler._lock.acquire(False):
265
+ if not locked:
266
+ if self.stop_at_error:
267
+ raise StrobelightCLIProfilerError("concurrent runs not supported")
268
+
269
+ logger.warning("concurrent runs not supported")
270
+ return work_function(*args, **kwargs)
271
+
272
+ started = self._start_strobelight()
273
+ if not started:
274
+ if self.stop_at_error:
275
+ StrobelightCLIFunctionProfiler._lock.release()
276
+ raise StrobelightCLIProfilerError(
277
+ "failed to start strobelight profiling"
278
+ )
279
+ result = work_function(*args, **kwargs)
280
+ StrobelightCLIFunctionProfiler._lock.release()
281
+ return result
282
+
283
+ try:
284
+ logger.debug("collection started")
285
+ start = timer()
286
+ result = work_function(*args, **kwargs)
287
+ end = timer()
288
+ total_time = end - start # Time in seconds, e.g. 5.38091952400282
289
+ logger.info("work function took %s seconds", total_time)
290
+ self._stop_strobelight_no_throw(collect_results=True)
291
+ StrobelightCLIFunctionProfiler._lock.release()
292
+ return result
293
+ except Exception as error:
294
+ logger.warning("work function throw exception", exc_info=True)
295
+ self._stop_strobelight_no_throw(collect_results=False)
296
+ StrobelightCLIFunctionProfiler._lock.release()
297
+ raise error
298
+ return None
299
+
300
+
301
+ # A function decorator that wraps profile, if no profiler is provided one with
302
+ # default args is created. A function can be annotated as:
303
+ # @strobelight()
304
+ # @strobelight(profiler = StrobelightFunctionProfiler(stop_at_error=True,..))
305
+ # @strobelight(stop_at_error=True,...)
306
+ def strobelight(
307
+ profiler: Optional[StrobelightCLIFunctionProfiler] = None, **kwargs: Any
308
+ ) -> Callable[[Callable[_P, _R]], Callable[_P, Optional[_R]]]:
309
+ if not profiler:
310
+ profiler = StrobelightCLIFunctionProfiler(**kwargs)
311
+
312
+ def strobelight_inner(
313
+ work_function: Callable[_P, _R],
314
+ ) -> Callable[_P, Optional[_R]]:
315
+ @functools.wraps(work_function)
316
+ def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> Optional[_R]:
317
+ # pyrefly: ignore [bad-argument-type]
318
+ return profiler.profile(work_function, *args, **kwargs)
319
+
320
+ return wrapper_function
321
+
322
+ return strobelight_inner
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_strobelight/compile_time_profiler.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disallow-untyped-defs
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import re
7
+ import subprocess
8
+ from datetime import datetime
9
+ from socket import gethostname
10
+ from typing import Any, Optional
11
+
12
+ from torch._strobelight.cli_function_profiler import StrobelightCLIFunctionProfiler
13
+
14
+
15
+ logger = logging.getLogger("strobelight_compile_time_profiler")
16
+
17
+ console_handler = logging.StreamHandler()
18
+ formatter = logging.Formatter(
19
+ "%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s"
20
+ )
21
+ console_handler.setFormatter(formatter)
22
+
23
+ logger.addHandler(console_handler)
24
+ logger.setLevel(logging.INFO)
25
+ logger.propagate = False
26
+
27
+
28
+ def get_fburl(url: str) -> str:
29
+ short_url = url
30
+ # Attempt to shorten the URL
31
+ try:
32
+ result = subprocess.run(
33
+ ["fburl", url], capture_output=True, stdin=subprocess.DEVNULL
34
+ )
35
+ if result.returncode == 0:
36
+ short_url = result.stdout.decode("utf-8")
37
+ except Exception as e:
38
+ logger.warning("URL shortening failed: %s, using long URL", repr(e))
39
+ return short_url
40
+
41
+
42
+ def get_strobelight_url(identifier: str) -> str:
43
+ scuba_json = {
44
+ "aggregateList": [],
45
+ "aggregation_field": "async_stack_complete",
46
+ "b_constraints": [[]],
47
+ "c_constraints": [[]],
48
+ "cols": ["namespace_id", "namespace_process_id"],
49
+ "compare": "none",
50
+ "constraints": [
51
+ [{"column": "sample_tags", "op": "all", "value": [f'["{identifier}"]']}]
52
+ ],
53
+ "derivedCols": [],
54
+ "end": "now",
55
+ "enumCols": [],
56
+ "filterMode": "DEFAULT",
57
+ "hideEmptyColumns": "false",
58
+ "ignoreGroupByInComparison": "false",
59
+ "is_timeseries": "false",
60
+ "mappedCols": [],
61
+ "metric": "count",
62
+ "modifiers": [],
63
+ "order": "weight",
64
+ "order_desc": "true",
65
+ "param_dimensions": [
66
+ {"dim": "py_async_stack", "op": "edge", "param": "0", "anchor": "0"}
67
+ ],
68
+ "purposes": [],
69
+ "return_remainder": "false",
70
+ "samplingRatio": "1",
71
+ "should_pivot": "false",
72
+ "start": "-30 days",
73
+ "timezone": "America/Los_Angeles",
74
+ "top": 10000,
75
+ }
76
+ scuba_url_prefix = "https://www.internalfb.com/intern/scuba/query/?dataset=pyperf_experimental/on_demand&drillstate="
77
+ scuba_url_suff = "&view=GraphProfilerView&&normalized=1726332703&pool=uber"
78
+ long_url = scuba_url_prefix + json.dumps(scuba_json) + scuba_url_suff
79
+ return get_fburl(long_url)
80
+
81
+
82
+ class StrobelightCompileTimeProfiler:
83
+ success_profile_count: int = 0
84
+ failed_profile_count: int = 0
85
+ ignored_profile_runs: int = 0
86
+ inside_profile_compile_time: bool = False
87
+ enabled: bool = False
88
+
89
+ # A regex that can be used to filter out what frames to profile. ex: "1/.*"
90
+ frame_id_filter: Optional[str] = os.environ.get("COMPILE_STROBELIGHT_FRAME_FILTER")
91
+
92
+ # A unique identifier that is used as the run_user_name in the strobelight profile to
93
+ # associate all compile time profiles together.
94
+ identifier: Optional[str] = None
95
+
96
+ current_phase: Optional[str] = None
97
+
98
+ profiler: Optional[Any] = None
99
+
100
+ max_stack_length: int = int(
101
+ os.environ.get("COMPILE_STROBELIGHT_MAX_STACK_LENGTH", 500)
102
+ )
103
+ max_profile_time: int = int(
104
+ os.environ.get("COMPILE_STROBELIGHT_MAX_PROFILE_TIME", 60 * 30)
105
+ )
106
+ # Collect sample each x cycles.
107
+ sample_each: int = int(
108
+ float(os.environ.get("COMPILE_STROBELIGHT_SAMPLE_RATE", 1e7))
109
+ )
110
+
111
+ @classmethod
112
+ def get_frame(cls) -> str:
113
+ from torch._guards import CompileContext
114
+
115
+ return (str)(CompileContext.current_trace_id())
116
+
117
+ @classmethod
118
+ def enable(cls, profiler_class: Any = StrobelightCLIFunctionProfiler) -> None:
119
+ if cls.enabled:
120
+ logger.info("compile time strobelight profiling already enabled")
121
+ return
122
+
123
+ logger.info("compile time strobelight profiling enabled")
124
+
125
+ if profiler_class is StrobelightCLIFunctionProfiler:
126
+ import shutil
127
+
128
+ if not shutil.which("strobeclient"):
129
+ logger.info(
130
+ "strobeclient not found, can't enable compile time strobelight profiling, seems"
131
+ "like you are not on a FB machine."
132
+ )
133
+ return
134
+
135
+ cls.enabled = True
136
+ cls._cls_init()
137
+ # profiler_class should have public API similar to that of StrobelightCLIFunctionProfiler.
138
+ # we have pass different functionProfilerClass for meta-internal fbcode targets.
139
+ # NB: the actual implementation in Meta is at
140
+ # fbcode/caffe2/fb/strobelight/function_profiler.py
141
+ cls.profiler = profiler_class(
142
+ sample_each=cls.sample_each,
143
+ max_profile_duration_sec=cls.max_profile_time,
144
+ stack_max_len=cls.max_stack_length,
145
+ async_stack_max_len=cls.max_stack_length,
146
+ run_user_name="pt2-profiler/"
147
+ + os.environ.get("USER", os.environ.get("USERNAME", "")),
148
+ sample_tags={cls.identifier}, # pyrefly: ignore # bad-argument-type
149
+ )
150
+
151
+ @classmethod
152
+ def _cls_init(cls) -> None:
153
+ cls.identifier = "{date}{pid}{hostname}".format(
154
+ date=datetime.now().strftime("%Y-%m-%d-%H:%M:%S"),
155
+ pid=os.getpid(),
156
+ hostname=gethostname(),
157
+ )
158
+
159
+ logger.info("Unique sample tag for this run is: %s", cls.identifier)
160
+ logger.info(
161
+ "URL to access the strobelight profile at the end of the run: %s",
162
+ get_strobelight_url(cls.identifier),
163
+ )
164
+
165
+ @classmethod
166
+ def _log_stats(cls) -> None:
167
+ logger.info(
168
+ "%s strobelight success runs out of %s non-recursive compilation events.",
169
+ cls.success_profile_count,
170
+ cls.success_profile_count + cls.failed_profile_count,
171
+ )
172
+
173
+ # TODO use threadlevel meta data to tags to record phases.
174
+ @classmethod
175
+ def profile_compile_time(
176
+ cls, func: Any, phase_name: str, *args: Any, **kwargs: Any
177
+ ) -> Any:
178
+ def skip() -> Any:
179
+ return func(*args, **kwargs)
180
+
181
+ if not cls.enabled:
182
+ return skip()
183
+
184
+ if cls.profiler is None:
185
+ logger.error("profiler is not set")
186
+ return
187
+
188
+ frame_id = cls.get_frame()
189
+
190
+ if cls.inside_profile_compile_time:
191
+ cls.ignored_profile_runs += 1
192
+ logger.info(
193
+ "profile_compile_time is requested for phase: %s, frame %s, while already in running phase: %s,"
194
+ "frame %s, recursive call ignored",
195
+ phase_name,
196
+ frame_id,
197
+ cls.current_phase,
198
+ frame_id,
199
+ )
200
+ return skip()
201
+
202
+ if cls.frame_id_filter is not None:
203
+ should_run = re.match(cls.frame_id_filter, frame_id) is not None
204
+ if not should_run:
205
+ logger.info(
206
+ "profiling frame %s is skipped due to frame_id_filter %s",
207
+ frame_id,
208
+ cls.frame_id_filter,
209
+ )
210
+ return skip()
211
+
212
+ cls.inside_profile_compile_time = True
213
+ cls.current_phase = phase_name
214
+ logger.info("profiling frame %s", frame_id)
215
+ work_result = cls.profiler.profile(func, *args, **kwargs)
216
+
217
+ if cls.profiler.profile_result is not None:
218
+ cls.success_profile_count += 1
219
+ else:
220
+ cls.failed_profile_count += 1
221
+
222
+ cls._log_stats()
223
+ cls.inside_profile_compile_time = False
224
+ return work_result
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch._subclasses.fake_tensor import (
3
+ DynamicOutputShapeException,
4
+ FakeTensor,
5
+ FakeTensorMode,
6
+ UnsupportedFakeTensorException,
7
+ )
8
+ from torch._subclasses.fake_utils import CrossRefFakeMode
9
+
10
+
11
+ __all__ = [
12
+ "FakeTensor",
13
+ "FakeTensorMode",
14
+ "UnsupportedFakeTensorException",
15
+ "DynamicOutputShapeException",
16
+ "CrossRefFakeMode",
17
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/_fake_tensor_utils.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional, TYPE_CHECKING, Union
5
+
6
+ import torch
7
+ from torch import SymInt
8
+ from torch.fx.experimental.sym_node import SymNode
9
+ from torch.types import py_sym_types, PySymType
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ import sympy
14
+
15
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv
16
+
17
+ from .fake_tensor import _DispatchCacheKey, _MetadataIntLike
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class _DeconstructedSymNode:
22
+ """
23
+ Represents a SymNode without the associated ShapeEnv
24
+ """
25
+
26
+ # n.b. keep the same protocol as SymNode
27
+ _expr: sympy.Expr
28
+ pytype: type
29
+ _hint: Optional[Union[int, float, bool]]
30
+ constant: Optional[Union[int, float, bool]]
31
+ fx_node: torch.fx.Node
32
+
33
+ @staticmethod
34
+ def from_node(node: SymNode) -> _DeconstructedSymNode:
35
+ return _DeconstructedSymNode(
36
+ node._expr,
37
+ node.pytype,
38
+ node._hint,
39
+ node.constant,
40
+ # pyrefly: ignore [bad-argument-type]
41
+ node.fx_node,
42
+ )
43
+
44
+ def extract(self, shape_env: ShapeEnv) -> SymNode:
45
+ return SymNode(
46
+ self._expr, shape_env, self.pytype, self._hint, self.constant, self.fx_node
47
+ )
48
+
49
+ def __str__(self) -> str:
50
+ return str(self._expr)
51
+
52
+ def __repr__(self) -> str:
53
+ return f"_DeconstructedSymNode{{{self._expr!r}, {self.pytype!r}, {self._hint!r}, {self.constant!r}, {self.fx_node!r}}}"
54
+
55
+ def __eq__(self, other: object) -> bool:
56
+ raise NotImplementedError
57
+
58
+ def __hash__(self) -> int:
59
+ raise NotImplementedError
60
+
61
+ # _value_eq to match SymNode
62
+ def _value_eq(self, other: object) -> bool:
63
+ if isinstance(other, (SymNode, _DeconstructedSymNode)):
64
+ return (
65
+ self._expr == other._expr
66
+ and self.pytype == other.pytype
67
+ and self._hint == other._hint
68
+ and self.constant == other.constant
69
+ and self.fx_node == other.fx_node
70
+ )
71
+ else:
72
+ return False
73
+
74
+ # _value_hash to match SymNode
75
+ def _value_hash(self) -> int:
76
+ return hash((self._expr, self.pytype, self._hint, self.constant, self.fx_node))
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class _DeconstructedSymType:
81
+ """
82
+ Represents a SymInt, SymFloat, SymBool without the associated ShapeEnv
83
+ """
84
+
85
+ ty: type[PySymType]
86
+ node: _DeconstructedSymNode
87
+
88
+ @staticmethod
89
+ def from_sym_type(value: PySymType) -> _DeconstructedSymType:
90
+ return _DeconstructedSymType(type(value), value.node)
91
+
92
+ def extract(self, shape_env: ShapeEnv) -> PySymType:
93
+ return self.ty(self.node.extract(shape_env))
94
+
95
+ def __str__(self) -> str:
96
+ return f"{self.ty}({self.node})"
97
+
98
+ def __repr__(self) -> str:
99
+ return f"_DeconstructedSymType({self.ty}, {self.node!r})"
100
+
101
+ def __eq__(self, other: object) -> bool:
102
+ return NotImplemented
103
+
104
+ def __hash__(self) -> int:
105
+ return NotImplemented
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class _InputBackref:
110
+ value: int
111
+
112
+
113
+ @dataclass(slots=True)
114
+ class _PySymInputStub:
115
+ """
116
+ Represents a SymInt in the cached key. Needed because SymInt doesn't
117
+ support __eq__ or __hash__ directly.
118
+ """
119
+
120
+ # value can be:
121
+ # PySymType: This is the 'normal' SymInt value, wrapped so we can use
122
+ # hash/eq as value hash/eq (normally SymInt does object
123
+ # hash/eq).
124
+ # _DeconstructedSymType: This is used when storing the _PySymInputStub in
125
+ # the cache to avoid cyclic ShapeEnv references.
126
+ # _InputBackref: This is a back-reference to a previous _PySymInputStub in
127
+ # the key.
128
+ value: Union[PySymType, _DeconstructedSymType, _InputBackref]
129
+
130
+ def __init__(
131
+ self, value: Union[PySymType, _DeconstructedSymType, _InputBackref]
132
+ ) -> None:
133
+ # For inputs (values in the `key`) we need to keep the PySymType intact
134
+ # - this way if we need to reuse it as an output we can properly copy
135
+ # the original value.
136
+ self.value = value
137
+
138
+ def strip_shape_env(self) -> None:
139
+ if isinstance(self.value, py_sym_types):
140
+ self.value = _DeconstructedSymType.from_sym_type(self.value)
141
+
142
+ def extract(self, shape_env: ShapeEnv) -> PySymType:
143
+ if isinstance(self.value, _DeconstructedSymType):
144
+ return self.value.extract(shape_env)
145
+ else:
146
+ # We should never see an _InputBackref here - anyone extracting a
147
+ # value should be pulling from the original entry (the one this
148
+ # backref points at).
149
+ assert not isinstance(self.value, _InputBackref)
150
+ return self.value
151
+
152
+ def __str__(self) -> str:
153
+ return str(self.value)
154
+
155
+ def __repr__(self) -> str:
156
+ return f"_PySymInputStub({self.value!r})"
157
+
158
+ def __eq__(self, other: object) -> bool:
159
+ if not isinstance(other, _PySymInputStub):
160
+ return False
161
+ elif isinstance(self.value, _InputBackref) or isinstance(
162
+ other.value, _InputBackref
163
+ ):
164
+ return self.value == other.value
165
+ else:
166
+ return self.value.node._value_eq(other.value.node)
167
+
168
+ def __hash__(self) -> int:
169
+ if isinstance(self.value, _InputBackref):
170
+ return hash(self.value)
171
+ else:
172
+ return self.value.node._value_hash()
173
+
174
+
175
+ @dataclass(slots=True)
176
+ class _SymIntOutputStub:
177
+ """
178
+ Represents a SymInt in the cached output.
179
+ """
180
+
181
+ # This is either an `int` which represents the index in the key to copy the
182
+ # SymNode from or it's the deconstructed SymNode itself.
183
+ value: Union[int, _DeconstructedSymNode]
184
+
185
+ def __init__(self, value: SymInt, key_path: Optional[int]) -> None:
186
+ if key_path is None:
187
+ self.value = _DeconstructedSymNode.from_node(value.node)
188
+ else:
189
+ self.value = key_path
190
+
191
+ def extract(self, key: _DispatchCacheKey, shape_env: ShapeEnv) -> SymInt:
192
+ if isinstance(self.value, _DeconstructedSymNode):
193
+ return SymInt(self.value.extract(shape_env))
194
+ else:
195
+ src = key.key[self.value]
196
+ assert isinstance(src, _PySymInputStub) and isinstance(src.value, SymInt)
197
+ return src.value
198
+
199
+ def __repr__(self) -> str:
200
+ return f"_SymIntOutputStub({self.value!r})"
201
+
202
+ def __eq__(self, other: object) -> bool:
203
+ raise NotImplementedError
204
+
205
+ def __hash__(self) -> int:
206
+ raise NotImplementedError
207
+
208
+
209
+ @dataclass(slots=True)
210
+ class _CacheKeyState:
211
+ """
212
+ State used while building our cache key.
213
+ """
214
+
215
+ # We track the SymNodes so when we get the output we can see if it exactly
216
+ # matches one of the inputs so we can uncache it properly.
217
+ sym_node_lookup: dict[int, int] # id(SymNode) -> index
218
+
219
+ # This is a list of all seen input sympy.Symbols. We use it when building
220
+ # the cache entry to see if the output value has any symbols that we didn't
221
+ # see on input. See _has_unrepresented_symbols().
222
+ known_symbols: set[sympy.Symbol]
223
+
224
+ # There are cases where we're asked to perform an op when we have no
225
+ # ShapeEnv on the FakeTensorMode - but for SymNodes we MUST have a
226
+ # ShapeEnv. So as we scan if we see a SymNode (with a ShapeEnv) we record it
227
+ # here.
228
+ shape_env: Optional[ShapeEnv]
229
+
230
+ def __init__(self, shape_env: Optional[ShapeEnv] = None) -> None:
231
+ self.sym_node_lookup = {}
232
+ self.known_symbols = set()
233
+ self.shape_env = shape_env
234
+
235
+ def cache_on_shape_env(self) -> bool:
236
+ """
237
+ Returns true if the CacheKey needs to be cached on the ShapeEnv
238
+ rather than the global cache.
239
+
240
+ If our inputs contain a SymNode then we can't cache this operation on
241
+ the global cache because the cached output will implicitly depend on
242
+ guard values which might not be true on some other ShapeEnv. So unless
243
+ we're also going to cache the guards we need to cache this operation on
244
+ the ShapeEnv instead of globally.
245
+ """
246
+ return bool(self.sym_node_lookup)
247
+
248
+ def convert_sym_int(self, result: list[object], arg: SymInt) -> None:
249
+ node_id = id(arg.node)
250
+ if node_id in self.sym_node_lookup:
251
+ result.append(_InputBackref(self.sym_node_lookup[node_id]))
252
+ else:
253
+ self.sym_node_lookup[node_id] = len(result)
254
+ self.known_symbols.update(arg.node.expr.free_symbols)
255
+ if self.shape_env is None:
256
+ self.shape_env = arg.node.shape_env
257
+ result.append(_PySymInputStub(arg))
258
+
259
+ def convert_output(self, arg: _MetadataIntLike) -> _MetadataIntLike:
260
+ if isinstance(arg, SymInt):
261
+ return _SymIntOutputStub(arg, self.sym_node_lookup.get(id(arg.node), None))
262
+ else:
263
+ return arg
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from ._core import ComplexTensor
2
+ from ._ops import ComplexTensorMode, is_complex_tensor
3
+
4
+
5
+ __all__ = ["ComplexTensor", "ComplexTensorMode", "is_complex_tensor"]
6
+
7
+ ComplexTensor.__module__ = __name__
8
+ ComplexTensorMode.__module__ = __name__
9
+ is_complex_tensor.__module__ = __name__
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_core.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, TYPE_CHECKING
4
+ from typing_extensions import Self
5
+
6
+ import torch
7
+ from torch import Tensor
8
+ from torch.autograd import Function
9
+
10
+
11
+ if TYPE_CHECKING:
12
+ from torch._ops import OpOverload
13
+ from torch._prims_common import DeviceLikeType
14
+ from torch.autograd.function import FunctionCtx
15
+
16
+
17
+ class ComplexTensor(Tensor):
18
+ """A class that decomposes all ops on complex Tensors into their real and imaginary parts."""
19
+
20
+ _re: Tensor
21
+ _im: Tensor
22
+
23
+ def __new__(cls, real: Tensor, imag: Tensor) -> Self:
24
+ """Initialize a ComplexTensor from its real and imaginary parts."""
25
+ from ._ops.common import REAL_TO_COMPLEX
26
+
27
+ shape = real.shape
28
+ device = real.device
29
+
30
+ # TODO (hameerabbasi): `torch.compile` sometimes fails here without making these
31
+ # contiguous. Why?
32
+ real = real.contiguous()
33
+ imag = imag.contiguous()
34
+
35
+ # TODO (hameerabbasi):
36
+ # What should we do with dtype?
37
+ # We could convert to the complex type (float32 -> complex64), but we
38
+ # can't use that model for say `bfloat16` which does not have a
39
+ # corresponding complex dtype.
40
+ # If we want to support this complex rep using any float type (see
41
+ # https://github.com/pytorch/pytorch/issues/95100)
42
+ # We either need to:
43
+ # 1) add the complex types for say `complexbf32`, knowing they can't really be used anywhere
44
+ # else.
45
+ # 2) We use the real float dtype here, and it is up to the user to know
46
+ # that dtype=float<size> here really means complex<2xSize> with dtype
47
+ # matching that of re/im parts alone
48
+ # I'm going with 1 for now, so that I can make gradcheck and some complex
49
+ # ops work properly, but might want to discuss this in the RFP.
50
+ dtype = REAL_TO_COMPLEX.get(real.dtype)
51
+ if dtype is None:
52
+ raise TypeError(
53
+ "Unsupported dtype for constituent tensors. Supported dtypes are: "
54
+ f"{set(REAL_TO_COMPLEX.keys())!r}."
55
+ )
56
+ storage_offset = real.storage_offset()
57
+ strides = real.stride()
58
+ layout = real.layout
59
+ pin_memory = real.is_pinned()
60
+
61
+ assert shape == imag.shape, f"Expected imag shape {shape}, got {imag.shape}"
62
+ assert device == imag.device, (
63
+ f"Expected imag device {device}, got {imag.device}"
64
+ )
65
+ assert real.dtype == imag.dtype, (
66
+ f"Expected imag dtype {real.dtype}, got {imag.dtype}"
67
+ )
68
+ assert pin_memory == imag.is_pinned(), (
69
+ f"Expected imag pinning {pin_memory}, got {imag.is_pinned()}"
70
+ )
71
+
72
+ res = Tensor._make_wrapper_subclass( # type: ignore[attr-defined]
73
+ cls,
74
+ shape,
75
+ device=device,
76
+ dtype=dtype,
77
+ storage_offset=storage_offset,
78
+ strides=strides,
79
+ pin_memory=pin_memory,
80
+ layout=layout,
81
+ requires_grad=False,
82
+ )
83
+ res._re = real.clone().detach()
84
+ res._im = imag.clone().detach()
85
+
86
+ return res
87
+
88
+ @property
89
+ def re(self) -> Tensor:
90
+ return self._re
91
+
92
+ @property
93
+ def im(self) -> Tensor:
94
+ return self._im
95
+
96
+ @classmethod
97
+ def __torch_dispatch__(
98
+ cls,
99
+ func: OpOverload,
100
+ types: tuple[type, ...],
101
+ args: tuple = (),
102
+ kwargs: dict | None = None,
103
+ ):
104
+ from ._ops.common import lookup_complex
105
+
106
+ kwargs = {} if kwargs is None else kwargs
107
+
108
+ impl = lookup_complex(func, *args, **kwargs)
109
+ if impl is None:
110
+ return NotImplemented
111
+
112
+ return impl(*args, **kwargs)
113
+
114
+ @staticmethod
115
+ def from_interleaved(t: Tensor) -> ComplexTensor:
116
+ t_real = torch.real(t)
117
+ t_imag = torch.imag(t) if t.dtype.is_complex else torch.zeros_like(t_real)
118
+ return Complex.apply(t_real, t_imag)
119
+
120
+ def as_interleaved(self) -> Tensor:
121
+ return torch.complex(self.real, self.imag)
122
+
123
+ @staticmethod
124
+ def __tensor_unflatten__(
125
+ inner_tensors: dict[str, Tensor],
126
+ meta: Any,
127
+ outer_size: tuple[int, ...],
128
+ outer_stride: tuple[int, ...],
129
+ ) -> ComplexTensor:
130
+ assert meta is None
131
+ re, im = inner_tensors["re"], inner_tensors["im"]
132
+ return ComplexTensor(re, im)
133
+
134
+ def __tensor_flatten__(self) -> tuple[list[str], Any]:
135
+ return ["re", "im"], None
136
+
137
+ def __repr__(self, *, tensor_contents=None) -> str:
138
+ return f"ComplexTensor(real={self.re!r}, imag={self.im!r})"
139
+
140
+ def is_pinned(self, device: DeviceLikeType | None = None) -> bool:
141
+ return self.re.is_pinned(device)
142
+
143
+
144
+ class Complex(Function):
145
+ @staticmethod
146
+ def forward(ctx: FunctionCtx, real: Tensor, imag: Tensor) -> ComplexTensor: # type: ignore[bad-override]
147
+ return ComplexTensor(real, imag)
148
+
149
+ @staticmethod
150
+ def backward(ctx: FunctionCtx, grad_output: ComplexTensor) -> tuple[Tensor, Tensor]: # type: ignore[bad-override]
151
+ return grad_output.real, grad_output.imag
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from . import aten, prims
2
+ from .common import ComplexTensorMode, is_complex_tensor
3
+
4
+
5
+ __all__ = ["ComplexTensorMode", "is_complex_tensor", "aten", "prims"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/aten.py ADDED
@@ -0,0 +1,934 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+ from typing import TYPE_CHECKING
5
+
6
+ import torch
7
+
8
+ from .._core import ComplexTensor
9
+ from .common import (
10
+ _get_func_name,
11
+ COMPLEX_TO_REAL,
12
+ complex_to_real_dtype,
13
+ is_complex,
14
+ OpType,
15
+ promote_tensors,
16
+ register_binary_nonlinear,
17
+ register_complex,
18
+ register_error,
19
+ register_force_test,
20
+ register_simple,
21
+ split_complex_arg,
22
+ split_complex_tensor,
23
+ )
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Callable, Sequence
28
+ from typing import Any
29
+
30
+ aten = torch.ops.aten
31
+
32
+
33
+ def register_binary_linear(op: OpType):
34
+ def impl_with_alpha(
35
+ lhs: ComplexTensor, rhs: ComplexTensor, *args, alpha, **kwargs
36
+ ) -> ComplexTensor:
37
+ return op(lhs, aten.mul(rhs, alpha, *args, **kwargs), *args, **kwargs)
38
+
39
+ def impl(lhs: ComplexTensor, rhs: ComplexTensor, *args, **kwargs) -> ComplexTensor:
40
+ alpha = kwargs.pop("alpha", None)
41
+ if alpha is not None:
42
+ return impl_with_alpha(lhs, rhs, *args, alpha=alpha, **kwargs)
43
+ a_r, a_i = split_complex_arg(lhs)
44
+ b_r, b_i = split_complex_arg(rhs)
45
+ out_dt, (a_r, a_i, b_r, b_i) = promote_tensors(a_r, a_i, b_r, b_i)
46
+ u = op(a_r, b_r, *args, **kwargs)
47
+ v = op(a_i, b_i, *args, **kwargs)
48
+ return ComplexTensor(u.to(out_dt), v.to(out_dt))
49
+
50
+ return register_complex(op, impl)
51
+
52
+
53
+ @register_complex(aten.real)
54
+ def real_impl(self: ComplexTensor) -> torch.Tensor:
55
+ re, _ = split_complex_tensor(self)
56
+ return re
57
+
58
+
59
+ @register_complex(aten.imag)
60
+ def imag_impl(self: ComplexTensor) -> torch.Tensor:
61
+ _, im = split_complex_tensor(self)
62
+ return im
63
+
64
+
65
+ @register_complex(aten.is_pinned)
66
+ def is_pinned_impl(self: ComplexTensor, device: torch.device | None = None) -> bool:
67
+ return self.is_pinned(device)
68
+
69
+
70
+ SIMPLE_OPS_LIST = [
71
+ aten.slice,
72
+ aten.flatten,
73
+ aten.view,
74
+ aten.diagonal,
75
+ aten.expand,
76
+ aten.unsqueeze,
77
+ aten.unsqueeze_,
78
+ aten.mean,
79
+ aten.sum,
80
+ aten.clone,
81
+ aten.neg,
82
+ aten.flip,
83
+ aten.permute,
84
+ aten.repeat,
85
+ aten.index_select,
86
+ aten.split,
87
+ aten.split_with_sizes,
88
+ aten.cumsum,
89
+ aten.detach,
90
+ aten.select,
91
+ aten.squeeze,
92
+ aten.zero_,
93
+ aten.transpose,
94
+ aten.t,
95
+ aten.gather,
96
+ ]
97
+
98
+ for simple_op in SIMPLE_OPS_LIST:
99
+ globals()[_get_func_name(simple_op)] = register_simple(simple_op)
100
+
101
+ # TODO (hameerabbasi): Not being tested
102
+ SIMPLE_FORCE_TESTED_OPS = [
103
+ aten.copy,
104
+ aten.col2im,
105
+ aten.alias,
106
+ aten.lift_fresh,
107
+ aten._unsafe_view,
108
+ aten.index,
109
+ aten._neg_view,
110
+ aten.avg_pool2d,
111
+ aten.avg_pool3d,
112
+ aten.avg_pool2d_backward,
113
+ aten.avg_pool3d_backward,
114
+ aten.masked_scatter_backward,
115
+ aten.select_backward,
116
+ aten.slice_backward,
117
+ aten.embedding,
118
+ ]
119
+
120
+ for simple_op in SIMPLE_FORCE_TESTED_OPS:
121
+ globals()[_get_func_name(simple_op)] = register_force_test(
122
+ simple_op, register_simple(simple_op)
123
+ )
124
+
125
+ del simple_op
126
+
127
+ # some binary ops which we can stamp out
128
+ mul_impl = register_binary_nonlinear(aten.mul)
129
+ mul__impl = register_binary_nonlinear(aten.mul_)
130
+ mm_impl = register_binary_nonlinear(aten.mm)
131
+ dot_impl = register_binary_nonlinear(aten.dot)
132
+ bmm_impl = register_binary_nonlinear(aten.bmm)
133
+
134
+ # TODO (hameerabbasi): Not being tested
135
+ convolution_impl = register_force_test(
136
+ aten.convolution, register_binary_nonlinear(aten.convolution)
137
+ )
138
+
139
+ slice_scatter_impl = register_force_test(
140
+ aten.slice_scatter, register_binary_linear(aten.slice_scatter)
141
+ )
142
+ select_scatter_impl = register_force_test(
143
+ aten.select_scatter, register_binary_linear(aten.select_scatter)
144
+ )
145
+
146
+ add_impl = register_binary_linear(aten.add)
147
+ add__impl = register_binary_linear(aten.add_)
148
+ sub_impl = register_binary_linear(aten.sub)
149
+ sub__impl = register_binary_linear(aten.sub_)
150
+ diagonal_scatter_impl = register_binary_linear(aten.diagonal_scatter)
151
+ fill__impl = register_binary_linear(aten.fill_)
152
+
153
+
154
+ @register_complex(aten.rsub)
155
+ def rsub_impl(lhs: ComplexTensor, rhs: ComplexTensor, alpha=None) -> ComplexTensor:
156
+ if alpha is None:
157
+ return torch.sub(rhs, lhs) # type: ignore[bad-return]
158
+ return torch.sub(rhs, lhs, alpha=alpha) # type: ignore[bad-return]
159
+
160
+
161
+ @register_complex(aten.div)
162
+ @register_complex(aten.true_divide)
163
+ def div_impl(lhs: ComplexTensor, rhs: ComplexTensor, *, rounding_mode=None):
164
+ if rounding_mode is not None:
165
+ raise NotImplementedError(
166
+ "`rounding_mode` other than `None` not implemented for`ComplexTensor`."
167
+ )
168
+ a_r, a_i = split_complex_arg(lhs)
169
+ if not is_complex(rhs):
170
+ return ComplexTensor(a_r / rhs, a_i / rhs)
171
+ b_r, b_i = split_complex_arg(rhs)
172
+ out_dt, (a_r, a_i, b_r, b_i) = promote_tensors(a_r, a_i, b_r, b_i)
173
+ num_r = a_r * b_r + a_i * b_i
174
+ num_i = a_i * b_r - a_r * b_i
175
+ den = b_r * b_r + b_i * b_i
176
+ return ComplexTensor(
177
+ (num_r / den).to(out_dt),
178
+ (num_i / den).to(out_dt),
179
+ )
180
+
181
+
182
+ @register_complex(aten.reciprocal)
183
+ def reciprocal_impl(self: ComplexTensor):
184
+ self_r, self_i = split_complex_tensor(self)
185
+ out_dt, (self_r, self_i) = promote_tensors(self_r, self_i)
186
+ den = self_r * self_r + self_i * self_i
187
+ return ComplexTensor(
188
+ aten.div(self_r, den).to(out_dt),
189
+ aten.div(-self_i, den).to(out_dt),
190
+ )
191
+
192
+
193
+ # reductions
194
+ @register_complex(aten.prod)
195
+ def prod_impl(self: ComplexTensor, *args, **kwargs) -> ComplexTensor:
196
+ out_dt, (self,) = promote_tensors(self)
197
+ dtype = kwargs.pop("dtype", out_dt)
198
+ kwargs["dtype"] = complex_to_real_dtype(self.dtype)
199
+
200
+ prod_r = torch.prod(torch.abs(self), *args, **kwargs)
201
+ sum_phi = torch.sum(torch.angle(self), *args, **kwargs)
202
+ u = prod_r * torch.cos(sum_phi)
203
+ v = prod_r * torch.sin(sum_phi)
204
+ return ComplexTensor(u, v).to(dtype) # type: ignore[bad-return]
205
+
206
+
207
+ @register_complex(aten.pow)
208
+ def pow_impl(self: ComplexTensor, exponent: ComplexTensor) -> ComplexTensor:
209
+ out_dt, (self, exponent) = promote_tensors(self, exponent)
210
+ return torch.exp(exponent * torch.log(self)).to(out_dt) # type: ignore[bad-return]
211
+
212
+
213
+ @register_complex(aten.cumprod)
214
+ def cumprod_impl(self: ComplexTensor, *args, **kwargs) -> ComplexTensor:
215
+ dtype = kwargs.pop("dtype", self.dtype)
216
+ kwargs["dtype"] = complex_to_real_dtype(dtype)
217
+
218
+ prod_r = torch.cumprod(torch.abs(self), *args, **kwargs)
219
+ sum_phi = torch.cumsum(torch.angle(self), *args, **kwargs)
220
+ u = prod_r * torch.cos(sum_phi)
221
+ v = prod_r * torch.sin(sum_phi)
222
+ return ComplexTensor(u, v)
223
+
224
+
225
+ # unary funcs,
226
+ # most of these are simple or require some kind of identity
227
+ @register_complex(aten.abs)
228
+ def abs_impl(self: ComplexTensor) -> torch.Tensor:
229
+ x, y = split_complex_tensor(self)
230
+ out_dt, (x, y) = promote_tensors(x, y)
231
+ result = torch.hypot(x, y)
232
+ return result.to(out_dt)
233
+
234
+
235
+ @register_complex(aten.angle)
236
+ def angle_impl(self: ComplexTensor) -> torch.Tensor:
237
+ x, y = split_complex_tensor(self)
238
+ return torch.atan2(y, x)
239
+
240
+
241
+ @register_complex(aten.acos)
242
+ def acos_impl(self: ComplexTensor) -> ComplexTensor:
243
+ _, y = split_complex_tensor(self)
244
+ acosh_z = torch.acosh(self)
245
+ assert isinstance(acosh_z, ComplexTensor)
246
+ acosh_z_re, acosh_z_im = split_complex_tensor(acosh_z)
247
+ sign_im = 2 * torch.signbit(y) - 1
248
+ return ComplexTensor(torch.abs(acosh_z_im), sign_im * torch.abs(acosh_z_re))
249
+
250
+
251
+ @register_complex(aten.asin)
252
+ def asin_impl(self: ComplexTensor) -> ComplexTensor:
253
+ x, y = split_complex_tensor(self)
254
+ asinh_iz = torch.asinh(ComplexTensor(-y, x))
255
+ assert isinstance(asinh_iz, ComplexTensor)
256
+ asinh_iz_re, asinh_iz_im = split_complex_tensor(asinh_iz)
257
+ return ComplexTensor(asinh_iz_im, -asinh_iz_re)
258
+
259
+
260
+ @register_complex(aten.atan)
261
+ def atan_impl(self: ComplexTensor) -> ComplexTensor:
262
+ x, y = split_complex_tensor(self)
263
+ tanh_iz = torch.atanh(ComplexTensor(-y, x))
264
+ assert isinstance(tanh_iz, ComplexTensor)
265
+ tanh_iz_re, tanh_iz_im = split_complex_tensor(tanh_iz)
266
+ return ComplexTensor(tanh_iz_im, -tanh_iz_re)
267
+
268
+
269
+ @register_complex(aten.asinh)
270
+ def asinh_impl(self: ComplexTensor) -> ComplexTensor:
271
+ out_dt, (self,) = promote_tensors(self)
272
+ return torch.log(self + torch.sqrt(self * self + 1)).to(out_dt) # type: ignore[bad-return]
273
+
274
+
275
+ @register_complex(aten.acosh)
276
+ def acosh_impl(self: ComplexTensor) -> ComplexTensor:
277
+ out_dt, (self,) = promote_tensors(self)
278
+ return torch.log(self + torch.sqrt(self * self - 1)).to(out_dt) # type: ignore[bad-return]
279
+
280
+
281
+ @register_complex(aten.atanh)
282
+ def atanh_impl(self: ComplexTensor) -> ComplexTensor:
283
+ x, y = split_complex_tensor(self)
284
+ out_dt, (x, y) = promote_tensors(x, y)
285
+
286
+ ret = 0.5 * (
287
+ torch.log(ComplexTensor(1 + x, y)) - torch.log(ComplexTensor(1 - x, -y))
288
+ )
289
+ assert isinstance(ret, ComplexTensor)
290
+ ret_re, ret_im = split_complex_tensor(ret)
291
+
292
+ return ComplexTensor(ret_re.to(out_dt), ret_im.to(out_dt))
293
+
294
+
295
+ @register_complex(aten.cos)
296
+ def cos_impl(self: ComplexTensor) -> ComplexTensor:
297
+ x, y = split_complex_tensor(self)
298
+ return torch.cosh(ComplexTensor(-y, x)) # type: ignore[bad-return]
299
+
300
+
301
+ @register_complex(aten.cosh)
302
+ def cosh_impl(self: ComplexTensor) -> ComplexTensor:
303
+ x, y = split_complex_tensor(self)
304
+ out_dt, (x, y) = promote_tensors(x, y)
305
+ u = torch.cosh(x) * torch.cos(y)
306
+ v = torch.sinh(x) * torch.sin(y)
307
+ return ComplexTensor(u.to(out_dt), v.to(out_dt))
308
+
309
+
310
+ @register_complex(aten.sin)
311
+ def sin_impl(self: ComplexTensor) -> ComplexTensor:
312
+ x, y = split_complex_tensor(self)
313
+ sinh_iz = torch.sinh(ComplexTensor(-y, x))
314
+ assert isinstance(sinh_iz, ComplexTensor)
315
+ sinh_iz_re, sinh_iz_im = split_complex_tensor(sinh_iz)
316
+ return ComplexTensor(sinh_iz_im, -sinh_iz_re)
317
+
318
+
319
+ @register_complex(aten.sinh)
320
+ def sinh_impl(self: ComplexTensor) -> ComplexTensor:
321
+ x, y = split_complex_tensor(self)
322
+ out_dt, (x, y) = promote_tensors(x, y)
323
+ u = torch.sinh(x) * torch.cos(y)
324
+ v = torch.cosh(x) * torch.sin(y)
325
+ return ComplexTensor(u.to(out_dt), v.to(out_dt))
326
+
327
+
328
+ @register_complex(aten.tan)
329
+ def tan_impl(self: ComplexTensor) -> ComplexTensor:
330
+ x, y = split_complex_tensor(self)
331
+ tanh_iz = torch.tanh(ComplexTensor(-y, x))
332
+ assert isinstance(tanh_iz, ComplexTensor)
333
+ tanh_iz_re, tanh_iz_im = split_complex_tensor(tanh_iz)
334
+ return ComplexTensor(tanh_iz_im, -tanh_iz_re)
335
+
336
+
337
+ @register_complex(aten.tanh)
338
+ def tanh_impl(self: ComplexTensor) -> ComplexTensor:
339
+ x, y = split_complex_tensor(self)
340
+ out_dt, (x, y) = promote_tensors(x, y)
341
+
342
+ _2x = 2 * x
343
+ _2y = 2 * y
344
+ _d = torch.cosh(_2x) + torch.cos(_2y)
345
+ _2xsh = torch.sinh(_2x)
346
+
347
+ out_re = _2xsh / _d
348
+ out_im = torch.sin(_2y) / _d
349
+
350
+ return ComplexTensor(out_re.to(out_dt), out_im.to(out_dt))
351
+
352
+
353
+ @register_complex(aten.exp)
354
+ def exp_impl(self: ComplexTensor) -> ComplexTensor:
355
+ x, y = split_complex_tensor(self)
356
+ out_dt, (x, y) = promote_tensors(x, y)
357
+ ex = torch.exp(x)
358
+ u = ex * torch.cos(y)
359
+ v = ex * torch.sin(y)
360
+ return ComplexTensor(u.to(out_dt), v.to(out_dt))
361
+
362
+
363
+ @register_complex(aten.expm1)
364
+ def expm1_impl(self: ComplexTensor) -> ComplexTensor:
365
+ x, y = split_complex_tensor(self)
366
+ out_dt, (x, y) = promote_tensors(x, y)
367
+ # TODO (hameerabbasi): The two lines below may have numerical issues
368
+ ex = torch.exp(x)
369
+ u = ex * torch.cos(y) - 1
370
+ v = ex * torch.sin(y)
371
+ return ComplexTensor(u.to(out_dt), v.to(out_dt))
372
+
373
+
374
+ @register_complex(aten.log)
375
+ def log_impl(self: ComplexTensor) -> ComplexTensor:
376
+ out_dt, (self,) = promote_tensors(self)
377
+ re = torch.log(torch.abs(self))
378
+ im = torch.angle(self)
379
+ return ComplexTensor(re, im).to(out_dt) # type: ignore[bad-return]
380
+
381
+
382
+ @register_complex(aten.log1p)
383
+ def log1p_impl(self: ComplexTensor) -> ComplexTensor:
384
+ x, y = split_complex_tensor(self)
385
+ # TODO (hameerabbasi): The line below may have numerical issues
386
+ return torch.log(ComplexTensor(x + 1, y)) # type: ignore[bad-return]
387
+
388
+
389
+ @register_complex(aten.any)
390
+ def any_impl(self: ComplexTensor, *args, **kwargs) -> torch.Tensor:
391
+ x, y = split_complex_tensor(self)
392
+ return torch.any(x, *args, **kwargs) | torch.any(y, *args, **kwargs)
393
+
394
+
395
+ @register_complex(aten.all)
396
+ def all_impl(self: ComplexTensor, *args, **kwargs) -> torch.Tensor:
397
+ x, y = split_complex_tensor(self)
398
+ return torch.any(x, *args, **kwargs) & torch.any(y, *args, **kwargs)
399
+
400
+
401
+ @register_complex(aten.eq)
402
+ def eq_impl(self: ComplexTensor, rhs: ComplexTensor, *args, **kwargs) -> torch.Tensor:
403
+ a_r, a_i = split_complex_arg(self)
404
+ b_r, b_i = split_complex_arg(rhs)
405
+ return torch.eq(a_r, b_r, *args, **kwargs) & torch.eq(a_i, b_i, *args, **kwargs)
406
+
407
+
408
+ @register_complex(aten.ne)
409
+ def ne_impl(self: ComplexTensor, rhs: ComplexTensor, *args, **kwargs) -> torch.Tensor:
410
+ a_r, a_i = split_complex_tensor(self)
411
+ b_r, b_i = split_complex_arg(rhs)
412
+ return torch.ne(a_r, b_r, *args, **kwargs) | torch.ne(a_i, b_i, *args, **kwargs)
413
+
414
+
415
+ @register_complex(aten.isnan)
416
+ def isnan_impl(self: ComplexTensor) -> torch.Tensor:
417
+ re, im = split_complex_tensor(self)
418
+ return torch.isnan(re) | torch.isnan(im)
419
+
420
+
421
+ @register_complex(aten.isinf)
422
+ def isinf_impl(self: ComplexTensor) -> torch.Tensor:
423
+ re, im = split_complex_tensor(self)
424
+ return torch.isinf(re) | torch.isinf(im)
425
+
426
+
427
+ @register_complex(aten.isfinite)
428
+ def isfinite_impl(self: ComplexTensor) -> torch.Tensor:
429
+ re, im = split_complex_tensor(self)
430
+ return torch.isfinite(re) & torch.isfinite(im)
431
+
432
+
433
+ @register_complex(aten.isclose)
434
+ def isclose_impl(
435
+ self: ComplexTensor,
436
+ rhs: ComplexTensor,
437
+ rtol=1e-5,
438
+ atol=1e-8,
439
+ equal_nan: bool = False,
440
+ ) -> torch.Tensor:
441
+ abs_diff = torch.abs(self - rhs)
442
+ abs_other = torch.abs(rhs)
443
+ basic_condition = abs_diff <= (rtol * abs_other + atol)
444
+
445
+ # This is the nontrivial part
446
+ if equal_nan:
447
+ a_r, a_i = split_complex_tensor(self)
448
+ b_r, b_i = split_complex_arg(rhs)
449
+
450
+ a_r_nan = torch.isnan(a_r)
451
+ b_r_nan = torch.isnan(b_r)
452
+ a_i_nan = torch.isnan(a_i)
453
+ b_i_nan = torch.isnan(b_i)
454
+ a_nan = a_r_nan | a_i_nan
455
+
456
+ # This logical expression makes sure that the isnan of both the real and imaginary parts
457
+ # matches (so 1 + nan*i doesn't equal nan + 1*i)
458
+ equal_nan_condition = ((a_r_nan == b_r_nan) & (a_i_nan == b_i_nan)) & a_nan
459
+ return basic_condition | equal_nan_condition
460
+
461
+ return basic_condition
462
+
463
+
464
+ ERROR_OPS_LIST = [
465
+ aten.lt,
466
+ aten.le,
467
+ aten.gt,
468
+ aten.ge,
469
+ aten.amin,
470
+ aten.amax,
471
+ aten.clamp,
472
+ aten.ceil,
473
+ aten.floor,
474
+ aten.minimum,
475
+ aten.maximum,
476
+ aten.trunc,
477
+ aten.sign,
478
+ aten.argmax,
479
+ aten.argmin,
480
+ aten.sort,
481
+ aten.topk,
482
+ aten.round,
483
+ aten.fmod,
484
+ ]
485
+
486
+
487
+ ERROR_TYPES = {
488
+ aten.minimum: RuntimeError,
489
+ aten.maximum: RuntimeError,
490
+ aten.argmax: RuntimeError,
491
+ aten.argmin: RuntimeError,
492
+ aten.sort: RuntimeError,
493
+ aten.topk: RuntimeError,
494
+ }
495
+
496
+
497
+ for err_op in ERROR_OPS_LIST:
498
+ globals()[_get_func_name(err_op)] = register_error(
499
+ err_op, ERROR_TYPES.get(err_op, NotImplementedError)
500
+ )
501
+
502
+ del err_op
503
+
504
+
505
+ @register_complex(aten.masked_scatter)
506
+ def masked_scatter_impl(
507
+ self: ComplexTensor, mask: torch.Tensor, source: ComplexTensor
508
+ ) -> ComplexTensor:
509
+ self_r, self_i = split_complex_tensor(self)
510
+ source_r, source_i = split_complex_arg(source)
511
+ ret_r = torch.masked_scatter(self_r, mask, source_r)
512
+ ret_i = torch.masked_scatter(self_i, mask, source_i)
513
+
514
+ return ComplexTensor(ret_r, ret_i)
515
+
516
+
517
+ @register_complex(aten.where)
518
+ def where_impl(mask: torch.Tensor, x: ComplexTensor, y: ComplexTensor) -> ComplexTensor:
519
+ x_r, x_i = split_complex_arg(x)
520
+ y_r, y_i = split_complex_arg(y)
521
+
522
+ ret_r = torch.where(mask, x_r, y_r)
523
+ ret_i = torch.where(mask, x_i, y_i)
524
+
525
+ return ComplexTensor(ret_r, ret_i)
526
+
527
+
528
+ @register_complex(aten.full_like)
529
+ def full_like_impl(
530
+ input: ComplexTensor,
531
+ fill_value: complex,
532
+ *args,
533
+ dtype: torch.dtype | None = None,
534
+ **kwargs,
535
+ ) -> torch.Tensor | ComplexTensor:
536
+ # Note: Cannot be merged with the cases below due to the `fill_value` argument
537
+ input_r, input_i = split_complex_tensor(input)
538
+ if dtype is not None and dtype not in COMPLEX_TO_REAL:
539
+ return torch.full_like(input_r, fill_value, *args, dtype=dtype, **kwargs)
540
+
541
+ if dtype is not None:
542
+ kwargs["dtype"] = COMPLEX_TO_REAL[dtype]
543
+
544
+ fv_r, fv_i = split_complex_arg(fill_value)
545
+ ret_r = torch.full_like(input_r, fv_r, *args, **kwargs)
546
+ ret_i = torch.full_like(input_i, fv_i, *args, **kwargs)
547
+
548
+ return ComplexTensor(ret_r, ret_i)
549
+
550
+
551
+ def register_like(op: OpType) -> Callable[..., torch.Tensor | ComplexTensor]:
552
+ def impl(
553
+ self: ComplexTensor, *args, dtype: torch.dtype | None = None, **kwargs
554
+ ) -> torch.Tensor | ComplexTensor:
555
+ self_re, self_im = split_complex_tensor(self)
556
+
557
+ if dtype is not None and dtype not in COMPLEX_TO_REAL:
558
+ return op(self_re, *args, dtype=dtype, **kwargs)
559
+
560
+ if dtype is not None:
561
+ kwargs["dtype"] = COMPLEX_TO_REAL[dtype]
562
+
563
+ ret_re = op(self_re, *args, **kwargs)
564
+ ret_im = op(self_im, *args, **kwargs)
565
+
566
+ return ComplexTensor(ret_re, ret_im)
567
+
568
+ func_name = _get_func_name(op)
569
+ impl.__name__ = func_name
570
+ impl.__qualname__ = func_name
571
+
572
+ return register_complex(op, impl)
573
+
574
+
575
+ LIKE_OPS_LIST = [
576
+ aten.empty_like,
577
+ aten.zeros_like,
578
+ aten.randn_like,
579
+ aten.new_zeros,
580
+ ]
581
+
582
+ for like_op in LIKE_OPS_LIST:
583
+ globals()[_get_func_name(like_op)] = register_like(like_op)
584
+
585
+ del like_op
586
+
587
+
588
+ @register_complex(aten.cat)
589
+ def cat_impl(tensors: Sequence[ComplexTensor], dim: int = 0) -> ComplexTensor:
590
+ tensors_r = []
591
+ tensors_i = []
592
+
593
+ for t in tensors:
594
+ t_r, t_i = split_complex_arg(t)
595
+ tensors_r.append(t_r)
596
+ tensors_i.append(t_i)
597
+
598
+ ret_r = torch.cat(tensors_r, dim=dim)
599
+ ret_i = torch.cat(tensors_i, dim=dim)
600
+
601
+ return ComplexTensor(ret_r, ret_i)
602
+
603
+
604
+ @register_complex(aten.sgn)
605
+ def sgn_impl(self: ComplexTensor) -> ComplexTensor:
606
+ self_r, self_i = split_complex_tensor(self)
607
+ out_dt, (self_r, self_i) = promote_tensors(self_r, self_i)
608
+ abs_self = torch.abs(ComplexTensor(self_r, self_i))
609
+ mask = (self_r != 0) | (self_i != 0)
610
+ masked_sgn = ComplexTensor(
611
+ (self_r / abs_self).to(out_dt), (self_i / abs_self).to(out_dt)
612
+ )
613
+ return torch.where(mask, masked_sgn, 0) # type: ignore[bad-return]
614
+
615
+
616
+ @register_complex(aten.sqrt)
617
+ def sqrt_impl(self: ComplexTensor) -> ComplexTensor:
618
+ self_r, self_i = split_complex_tensor(self)
619
+ out_dt, (self_r, self_i) = promote_tensors(self_r, self_i)
620
+ self = ComplexTensor(self_r, self_i)
621
+ self_abs_sqrt = torch.sqrt(torch.abs(self))
622
+ self_half_angle = 0.5 * torch.angle(self)
623
+
624
+ ret_r = self_abs_sqrt * torch.cos(self_half_angle)
625
+ ret_i = self_abs_sqrt * torch.sin(self_half_angle)
626
+
627
+ return ComplexTensor(ret_r.to(out_dt), ret_i.to(out_dt))
628
+
629
+
630
+ @register_complex(aten.rsqrt)
631
+ def rsqrt_impl(self: ComplexTensor) -> ComplexTensor:
632
+ self_r, self_i = split_complex_tensor(self)
633
+ out_dt, (self_r, self_i) = promote_tensors(self_r, self_i)
634
+ self = ComplexTensor(self_r, self_i)
635
+ self_abs_rsqrt = torch.rsqrt(torch.abs(self))
636
+ self_neg_half_angle = -0.5 * torch.angle(self)
637
+
638
+ ret_r = self_abs_rsqrt * torch.cos(self_neg_half_angle)
639
+ ret_i = self_abs_rsqrt * torch.sin(self_neg_half_angle)
640
+
641
+ return ComplexTensor(ret_r.to(out_dt), ret_i.to(out_dt))
642
+
643
+
644
+ @register_complex(aten.addmm)
645
+ def addmm_impl(
646
+ input: ComplexTensor,
647
+ mat1: ComplexTensor,
648
+ mat2: ComplexTensor,
649
+ out_dtype: torch.dtype | None = None,
650
+ beta: complex = 1,
651
+ alpha: complex = 1,
652
+ ) -> ComplexTensor:
653
+ ret = beta * input + alpha * torch.mm(mat1, mat2)
654
+ assert isinstance(ret, ComplexTensor)
655
+ ret_r, ret_i = split_complex_tensor(ret)
656
+ if out_dtype is not None:
657
+ out_dtype = COMPLEX_TO_REAL[out_dtype]
658
+ ret_r, ret_i = ret_r.to(out_dtype), ret_i.to(out_dtype)
659
+ return ComplexTensor(ret_r, ret_i)
660
+
661
+
662
+ def elemwise_nonzero(self: ComplexTensor) -> torch.Tensor:
663
+ re, im = split_complex_tensor(self)
664
+ return (re != 0) | (im != 0)
665
+
666
+
667
+ def register_nonzero_impl(op: OpType):
668
+ def nonzero_impl(
669
+ self: ComplexTensor, other: ComplexTensor, *args, **kwargs
670
+ ) -> torch.Tensor:
671
+ return op(elemwise_nonzero(self), elemwise_nonzero(other), *args, **kwargs)
672
+
673
+ func_name = _get_func_name(op)
674
+ nonzero_impl.__name__ = func_name
675
+ nonzero_impl.__qualname__ = func_name
676
+
677
+ return register_complex(op, nonzero_impl)
678
+
679
+
680
+ logical_and_impl = register_nonzero_impl(aten.logical_and)
681
+ logical_or_impl = register_nonzero_impl(aten.logical_or)
682
+ logical_xor_impl = register_nonzero_impl(aten.logical_xor)
683
+
684
+
685
+ @register_complex(aten.logical_not)
686
+ def logical_not_impl(self: ComplexTensor, *args, **kwargs) -> torch.Tensor:
687
+ return torch.logical_not(elemwise_nonzero(self), *args, **kwargs)
688
+
689
+
690
+ @register_complex(aten.view_as_real)
691
+ def view_as_real_impl(self: ComplexTensor) -> torch.Tensor:
692
+ re, im = split_complex_tensor(self)
693
+ return torch.stack([re, im], dim=-1)
694
+
695
+
696
+ @register_complex(aten.linalg_vector_norm)
697
+ def linalg_vector_norm_impl(self: ComplexTensor, *args, **kwargs) -> torch.Tensor:
698
+ return torch.linalg.vector_norm(torch.abs(self), *args, **kwargs)
699
+
700
+
701
+ @register_force_test(aten.copy_)
702
+ def copy__impl(
703
+ self: ComplexTensor | torch.Tensor,
704
+ src: ComplexTensor | torch.Tensor,
705
+ *args,
706
+ **kwargs,
707
+ ) -> ComplexTensor | torch.Tensor:
708
+ if not self.dtype.is_complex:
709
+ warnings.warn(
710
+ "Casting complex values to real discards the imaginary part", UserWarning
711
+ )
712
+ src_re, src_im = split_complex_arg(src)
713
+ return self.copy_(src_re)
714
+
715
+ self_re, self_im = split_complex_arg(self)
716
+ src_re, src_im = split_complex_arg(src)
717
+
718
+ ret_re = self_re.copy_(src_re, *args, **kwargs)
719
+ ret_im = self_im.copy_(src_im, *args, **kwargs)
720
+
721
+ return ComplexTensor(ret_re, ret_im)
722
+
723
+
724
+ @register_complex(aten._local_scalar_dense)
725
+ def _local_scalar_dense_impl(self: ComplexTensor, *args, **kwargs) -> complex:
726
+ x, y = split_complex_tensor(self)
727
+ u = aten._local_scalar_dense(x, *args, **kwargs)
728
+ v = aten._local_scalar_dense(y, *args, **kwargs)
729
+ return complex(u, v)
730
+
731
+
732
+ @register_complex(aten.allclose)
733
+ def allclose_impl(
734
+ input: torch.Tensor,
735
+ other: torch.Tensor,
736
+ rtol: float = 1e-05,
737
+ atol: float = 1e-08,
738
+ equal_nan: bool = False,
739
+ ) -> bool:
740
+ return torch.all(
741
+ torch.isclose(input, other, rtol=rtol, atol=atol, equal_nan=equal_nan)
742
+ ).item() # type: ignore[bad-return]
743
+
744
+
745
+ @register_complex(aten.stack)
746
+ def stack_impl(self: list[ComplexTensor], *args, **kwargs) -> ComplexTensor:
747
+ re_im_tuples = [split_complex_arg(self_i) for self_i in self]
748
+ u = torch.stack([c[0] for c in re_im_tuples], *args, **kwargs)
749
+ v = torch.stack([c[1] for c in re_im_tuples], *args, **kwargs)
750
+ return ComplexTensor(u, v)
751
+
752
+
753
+ # TODO (hameerabbasi): Not being tested
754
+ @register_complex(aten._conj_physical)
755
+ @register_complex(aten.conj_physical)
756
+ def conj_physical_impl(self: ComplexTensor) -> ComplexTensor:
757
+ re, im = split_complex_tensor(self)
758
+ return ComplexTensor(re, -im)
759
+
760
+
761
+ # TODO (hameerabbasi): Not being tested
762
+ @register_complex(aten._conj)
763
+ def _conj_impl(self: ComplexTensor) -> ComplexTensor:
764
+ re, im = split_complex_tensor(self)
765
+ return ComplexTensor(re, torch._neg_view(im))
766
+
767
+
768
+ @register_complex(aten.index_add)
769
+ def index_add_impl(
770
+ self: ComplexTensor, dim: int, index: torch.Tensor, source: ComplexTensor, **kwargs
771
+ ) -> ComplexTensor:
772
+ alpha = kwargs.pop("alpha", None)
773
+ if alpha is not None:
774
+ source = source * alpha
775
+ self_re, self_im = split_complex_arg(self)
776
+ source_re, source_im = split_complex_arg(source)
777
+
778
+ ret_re = self_re.index_add(dim, index, source_re)
779
+ ret_im = self_im.index_add(dim, index, source_im)
780
+
781
+ return ComplexTensor(ret_re, ret_im)
782
+
783
+
784
+ # TODO (hameerabbasi): Not being tested
785
+ @register_complex(aten.index_add_)
786
+ def index_add__impl(
787
+ self: ComplexTensor, dim: int, index: torch.Tensor, source: ComplexTensor, **kwargs
788
+ ) -> ComplexTensor:
789
+ alpha = kwargs.pop("alpha", None)
790
+ if alpha is not None:
791
+ source = source * alpha
792
+
793
+ self_re, self_im = split_complex_arg(self)
794
+ source_re, source_im = split_complex_arg(source)
795
+
796
+ ret_re = self_re.index_add_(dim, index, source_re)
797
+ ret_im = self_im.index_add_(dim, index, source_im)
798
+
799
+ return ComplexTensor(ret_re, ret_im)
800
+
801
+
802
+ @register_complex(aten.masked_fill)
803
+ def masked_fill_impl(
804
+ self: ComplexTensor, mask: torch.Tensor, value: complex
805
+ ) -> ComplexTensor:
806
+ self_re, self_im = split_complex_arg(self)
807
+ value_re, value_im = split_complex_arg(value)
808
+
809
+ ret_re = self_re.masked_fill(mask, value_re)
810
+ ret_im = self_im.masked_fill(mask, value_im)
811
+
812
+ return ComplexTensor(ret_re, ret_im)
813
+
814
+
815
+ # TODO (hameerabbasi): Not being tested
816
+ @register_complex(aten.masked_fill_)
817
+ def masked_fill__impl(
818
+ self: ComplexTensor, mask: torch.Tensor, value: complex
819
+ ) -> ComplexTensor:
820
+ self_re, self_im = split_complex_arg(self)
821
+ value_re, value_im = split_complex_arg(value)
822
+
823
+ ret_re = self_re.masked_fill_(mask, value_re)
824
+ ret_im = self_im.masked_fill_(mask, value_im)
825
+
826
+ return ComplexTensor(ret_re, ret_im)
827
+
828
+
829
+ @register_complex(aten.constant_pad_nd)
830
+ def constant_pad_nd_impl(
831
+ self: ComplexTensor, pad, value: complex | None = None
832
+ ) -> ComplexTensor:
833
+ self_re, self_im = split_complex_tensor(self)
834
+ if value is None:
835
+ ret_re = aten.constant_pad_nd(self_re, pad)
836
+ ret_im = aten.constant_pad_nd(self_im, pad)
837
+ else:
838
+ value_re, value_im = split_complex_arg(value)
839
+ ret_re = aten.constant_pad_nd(self_re, pad, value_re)
840
+ ret_im = aten.constant_pad_nd(self_im, pad, value_im)
841
+
842
+ return ComplexTensor(ret_re, ret_im)
843
+
844
+
845
+ @register_complex(aten.var)
846
+ def var_impl(self: ComplexTensor, *args, **kwargs) -> torch.Tensor:
847
+ self_re, self_im = split_complex_tensor(self)
848
+ return torch.var(self_re, *args, **kwargs) + torch.var(self_im, *args, **kwargs)
849
+
850
+
851
+ @register_complex(aten.scatter_add)
852
+ def scatter_add_impl(
853
+ self: ComplexTensor, dim, index, src: ComplexTensor
854
+ ) -> ComplexTensor:
855
+ self_re, self_im = split_complex_arg(self)
856
+ src_re, src_im = split_complex_arg(src)
857
+
858
+ ret_re = torch.scatter_add(self_re, dim, index, src_re)
859
+ ret_im = torch.scatter_add(self_im, dim, index, src_im)
860
+
861
+ return ComplexTensor(ret_re, ret_im)
862
+
863
+
864
+ @register_complex(aten.scatter_add_)
865
+ def scatter_add__impl(
866
+ self: ComplexTensor, dim, index, src: ComplexTensor
867
+ ) -> ComplexTensor:
868
+ self_re, self_im = split_complex_arg(self)
869
+ src_re, src_im = split_complex_arg(src)
870
+
871
+ out_re = self_re.scatter_add_(dim, index, src_re)
872
+ out_im = self_im.scatter_add_(dim, index, src_im)
873
+
874
+ return ComplexTensor(out_re, out_im)
875
+
876
+
877
+ @register_complex(aten.index_put_)
878
+ def index_put__impl(
879
+ self: ComplexTensor,
880
+ indices: tuple[torch.Tensor, ...],
881
+ values: ComplexTensor,
882
+ accumulate: bool = False,
883
+ ) -> ComplexTensor:
884
+ self_re, self_im = split_complex_arg(self)
885
+ values_re, values_im = split_complex_arg(values)
886
+
887
+ out_re = self_re.index_put_(indices, values_re, accumulate=accumulate)
888
+ out_im = self_im.index_put_(indices, values_im, accumulate=accumulate)
889
+
890
+ return ComplexTensor(out_re, out_im)
891
+
892
+
893
+ @register_complex(aten.tanh_backward)
894
+ def tanh_backward(out_grad: torch.Tensor, y: torch.Tensor):
895
+ return out_grad * (1.0 - y * y).conj_physical()
896
+
897
+
898
+ @register_complex(aten.diagonal_backward)
899
+ def diagonal_backward(
900
+ grad_output: torch.Tensor, input_sizes: list[int], offset: int, dim1: int, dim2: int
901
+ ):
902
+ grad_input = grad_output.new_zeros(input_sizes)
903
+ return torch.diagonal_scatter(grad_input, grad_output, offset, dim1, dim2)
904
+
905
+
906
+ def _dt_to_real(dt: torch.dtype | Any) -> torch.dtype | Any:
907
+ if not isinstance(dt, torch.dtype):
908
+ return dt
909
+
910
+ return COMPLEX_TO_REAL[dt]
911
+
912
+
913
+ def register_to_impl(op: OpType):
914
+ """Register an op similar to `aten.to`, but may have different signatures."""
915
+
916
+ def impl(self: ComplexTensor, *args, **kwargs) -> torch.Tensor | ComplexTensor:
917
+ x, y = split_complex_tensor(self)
918
+ try:
919
+ args = tuple(_dt_to_real(a) for a in args)
920
+ kwargs = {k: _dt_to_real(v) for k, v in kwargs.items()}
921
+ except KeyError:
922
+ return op(x, *args, **kwargs)
923
+
924
+ return ComplexTensor(op(x, *args, **kwargs), op(y, *args, **kwargs))
925
+
926
+ func_name = _get_func_name(op)
927
+ impl.__name__ = func_name
928
+ impl.__qualname__ = func_name
929
+
930
+ return register_complex(op, impl)
931
+
932
+
933
+ to_impl = register_to_impl(aten.to)
934
+ _to_copy_impl = register_to_impl(aten._to_copy)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/common.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any, overload, TypeAlias
3
+ from typing_extensions import TypeIs
4
+
5
+ import torch
6
+ from torch import Tensor
7
+ from torch._decomp import get_decompositions
8
+ from torch._ops import OpOverload, OpOverloadPacket
9
+ from torch._refs import is_complex as _is_complex
10
+ from torch.types import Number
11
+ from torch.utils._python_dispatch import TorchDispatchMode
12
+ from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten
13
+
14
+ from .._core import ComplexTensor
15
+
16
+
17
+ OpType: TypeAlias = OpOverloadPacket | OpOverload
18
+
19
+ TableType: TypeAlias = dict[OpType, Callable]
20
+
21
+ # Mapping from ops to implementations
22
+ COMPLEX_OPS_TABLE: TableType = {}
23
+
24
+ COMPLEX_TO_REAL = {
25
+ torch.complex128: torch.float64,
26
+ torch.complex64: torch.float32,
27
+ torch.complex32: torch.float16,
28
+ }
29
+
30
+ REAL_TO_COMPLEX = {v: k for k, v in COMPLEX_TO_REAL.items()}
31
+
32
+ # Used to promote dtypes in `promote_real_cpu_tensors`
33
+ PROMOTE_TYPES = {
34
+ torch.float16: torch.float32,
35
+ torch.bfloat16: torch.float32,
36
+ torch.complex32: torch.complex64,
37
+ }
38
+
39
+
40
+ def is_complex_tensor(obj: Any, /) -> TypeIs[ComplexTensor]:
41
+ r"""Returns True if the input is a ComplexTensor, else False
42
+
43
+ Args:
44
+ a: any input
45
+
46
+ Examples:
47
+
48
+ >>> # xdoctest: +SKIP
49
+ >>> from torch.complex import ComplexTensor
50
+ >>> data = torch.zeros((3, 2), dtype=torch.complex64)
51
+ >>> ct = ComplexTensor.from_interleaved(data)
52
+ >>> is_complex_tensor(ct)
53
+ True
54
+ """
55
+ return isinstance(obj, ComplexTensor)
56
+
57
+
58
+ @overload
59
+ def promote_tensors(
60
+ *tensors: ComplexTensor,
61
+ ) -> tuple[torch.dtype, tuple[ComplexTensor, ...]]: ...
62
+
63
+
64
+ @overload
65
+ def promote_tensors(
66
+ *tensors: Tensor,
67
+ ) -> tuple[torch.dtype, tuple[Tensor, ...]]: ...
68
+
69
+
70
+ def promote_tensors(
71
+ *tensors: Tensor | ComplexTensor,
72
+ ) -> tuple[torch.dtype, tuple[Tensor | ComplexTensor, ...]]:
73
+ """
74
+ Promotes all tensors to a common dtype.
75
+ Additionally promotes CPU tensors to at least `float32`.
76
+ """
77
+ tensor = next(t for t in tensors if isinstance(t, Tensor))
78
+ out_dt = tensor.dtype
79
+ for t in tensors:
80
+ if isinstance(t, Tensor):
81
+ out_dt = torch.promote_types(out_dt, t.dtype)
82
+
83
+ prom_dt = PROMOTE_TYPES.get(out_dt, out_dt)
84
+ return out_dt, tuple(
85
+ t.to(prom_dt) if isinstance(t, Tensor) else torch.asarray(t, dtype=prom_dt)
86
+ for t in tensors
87
+ )
88
+
89
+
90
+ def register_complex(
91
+ op: OpType,
92
+ func_impl: Callable | None = None,
93
+ ):
94
+ """Decorator to register an implementation for some ops in some dispatch tables"""
95
+
96
+ def inner(func):
97
+ if COMPLEX_OPS_TABLE.get(op, func) is not func:
98
+ raise RuntimeError(f"Attempted to register multiple functions for {op}")
99
+ COMPLEX_OPS_TABLE[op] = func
100
+ return func
101
+
102
+ if func_impl is None:
103
+ return inner
104
+
105
+ return inner(func_impl)
106
+
107
+
108
+ FORCE_TEST_LIST: list[OpType] = []
109
+
110
+
111
+ def register_force_test(op: OpType, *args, **kwargs):
112
+ """Will attempt to test these ops even if they err on "normal" inputs"""
113
+ FORCE_TEST_LIST.append(op)
114
+ return register_complex(op, *args, **kwargs)
115
+
116
+
117
+ DECOMPOSITIONS = get_decompositions(list(torch.ops.aten)) # type: ignore[no-matching-overload]
118
+
119
+
120
+ def lookup_complex(func: OpOverload, *args, **kwargs) -> Callable | None:
121
+ """
122
+ Lookup an impl from the table.
123
+
124
+ Try the particular overload first, then the overload packet.
125
+
126
+ If nothing is found, try the decompositions with both.
127
+ """
128
+ return COMPLEX_OPS_TABLE.get(
129
+ func,
130
+ COMPLEX_OPS_TABLE.get(
131
+ func.overloadpacket,
132
+ DECOMPOSITIONS.get(func, DECOMPOSITIONS.get(func.overloadpacket)),
133
+ ),
134
+ )
135
+
136
+
137
+ def is_complex(x: Any, /) -> bool:
138
+ """Utility to detect if a given object is (known) to be complex."""
139
+ return (isinstance(x, Tensor) and _is_complex(x)) or isinstance(x, complex)
140
+
141
+
142
+ @overload
143
+ def split_complex_arg(
144
+ arg: Tensor | ComplexTensor,
145
+ ) -> tuple[Tensor, Tensor]: ...
146
+
147
+
148
+ @overload
149
+ def split_complex_arg(
150
+ arg: complex | Number,
151
+ ) -> tuple[Number, Number]: ...
152
+
153
+
154
+ def split_complex_arg(
155
+ arg: Tensor | ComplexTensor | complex | Number,
156
+ ) -> tuple[Tensor, Tensor] | tuple[Number, Number]:
157
+ """
158
+ Split a complex argument into a real/imaginary component.
159
+
160
+ If real, use zero for the imaginary part.
161
+ """
162
+ if isinstance(arg, ComplexTensor):
163
+ return split_complex_tensor(arg)
164
+ if isinstance(arg, Tensor):
165
+ if is_complex(arg):
166
+ return arg.real, arg.imag
167
+ return arg, torch.zeros_like(arg)
168
+ # TODO (hameerabbasi): Should there be a `torch.SymComplex`?
169
+ if isinstance(arg, complex):
170
+ return arg.real, arg.imag
171
+ if isinstance(arg, float | torch.SymFloat):
172
+ return arg, 0.0
173
+ if isinstance(arg, int | torch.SymInt):
174
+ return arg, 0
175
+ if isinstance(arg, bool | torch.SymBool):
176
+ return arg, False
177
+ raise TypeError(f"Expected tensor or number got, {type(arg)}")
178
+
179
+
180
+ def split_complex_tensor(complex_tensor: ComplexTensor) -> tuple[Tensor, Tensor]:
181
+ """Split a ComplexTensor into its real and imaginary parts."""
182
+ return complex_tensor.re, complex_tensor.im
183
+
184
+
185
+ def complex_to_real_dtype(dtype: torch.dtype) -> torch.dtype:
186
+ """Convert a complex dtype to the dtype of its real part. Return other dtypes as-is."""
187
+ return COMPLEX_TO_REAL.get(dtype, dtype)
188
+
189
+
190
+ def _get_op_name(op: OpType) -> str:
191
+ """Get the op name from the op."""
192
+ if isinstance(op, OpOverload):
193
+ op = op.overloadpacket
194
+ return str(op).split(".", 1)[1]
195
+
196
+
197
+ def _get_func_name(op: OpType) -> str:
198
+ """Get the name of the implementation function from the op."""
199
+ return f"{_get_op_name(op)}_impl"
200
+
201
+
202
+ def register_error(op: OpType, exc_type: type[Exception] = NotImplementedError):
203
+ msg = f"`aten.{_get_op_name(op)}` not implemented for `{ComplexTensor.__name__}`."
204
+
205
+ def ordered_impl(*args, **kwargs):
206
+ raise exc_type(msg)
207
+
208
+ func_name = _get_func_name(op)
209
+ ordered_impl.__name__ = func_name
210
+ ordered_impl.__qualname__ = func_name
211
+
212
+ return register_force_test(op, ordered_impl)
213
+
214
+
215
+ def register_binary_nonlinear(op: OpType) -> Callable:
216
+ """Register a "multiplication-style" op, e.g. aten.mul, aten.mm, ..."""
217
+
218
+ def impl(lhs: ComplexTensor, rhs: ComplexTensor, *args, **kwargs) -> ComplexTensor:
219
+ a_r, a_i = split_complex_arg(lhs)
220
+ b_r, b_i = split_complex_arg(rhs)
221
+ out_dt, (a_r, a_i, b_r, b_i) = promote_tensors(a_r, a_i, b_r, b_i)
222
+ real = op(a_r, b_r, *args, **kwargs) - op(a_i, b_i, *args, **kwargs)
223
+ imag = op(a_r, b_i, *args, **kwargs) + op(a_i, b_r, *args, **kwargs)
224
+ return ComplexTensor(real.to(out_dt), imag.to(out_dt))
225
+
226
+ func_name = _get_func_name(op)
227
+ impl.__name__ = func_name
228
+ impl.__qualname__ = func_name
229
+
230
+ return register_complex(op, impl)
231
+
232
+
233
+ def register_simple(op: OpType):
234
+ """Register an op which can be applied independently to the real and complex parts to get the result."""
235
+
236
+ def impl(
237
+ self: ComplexTensor, *args, dtype: torch.dtype | None = None, **kwargs
238
+ ) -> ComplexTensor:
239
+ x, y = split_complex_tensor(self)
240
+ if dtype is not None and dtype not in COMPLEX_TO_REAL:
241
+ raise RuntimeError(
242
+ "Non-complex `dtype` specified, please write custom impl."
243
+ )
244
+
245
+ if dtype in COMPLEX_TO_REAL:
246
+ assert dtype is not None
247
+ kwargs["dtype"] = COMPLEX_TO_REAL[dtype]
248
+
249
+ u = op(x, *args, **kwargs)
250
+ v = op(y, *args, **kwargs)
251
+
252
+ u_flat, u_spec = tree_flatten(u)
253
+ v_flat, v_spec = tree_flatten(v)
254
+ assert u_spec == v_spec
255
+ out_flat = [
256
+ ComplexTensor(ui, vi) for ui, vi in zip(u_flat, v_flat, strict=False)
257
+ ]
258
+ return tree_unflatten(out_flat, u_spec)
259
+
260
+ func_name = _get_func_name(op)
261
+ impl.__name__ = func_name
262
+ impl.__qualname__ = func_name
263
+
264
+ return register_complex(op, impl)
265
+
266
+
267
+ def _as_complex_tensor(arg: Tensor | Any) -> Tensor | ComplexTensor | Any:
268
+ """Convert a Tensor with complex dtypes to a ComplexTensor. Pass along other args as-is."""
269
+ if (
270
+ not isinstance(arg, ComplexTensor)
271
+ and isinstance(arg, Tensor)
272
+ and arg.dtype in COMPLEX_TO_REAL
273
+ ):
274
+ return ComplexTensor.from_interleaved(arg)
275
+ return arg
276
+
277
+
278
+ def _as_interleaved(arg: ComplexTensor | Any) -> Tensor | Any:
279
+ """Convert a ComplexTensor to a Tensor with a complex dtype. Pass other arguments as-is."""
280
+ if isinstance(arg, ComplexTensor):
281
+ return arg.as_interleaved()
282
+ return arg
283
+
284
+
285
+ class ComplexTensorMode(TorchDispatchMode):
286
+ _compile: bool
287
+
288
+ """ A TorchDispatchMode to replace any Tensor that has a complex dtype with a ComplexTensor for the computation. """
289
+
290
+ def __init__(self, _dispatch_key=None, *, _compile: bool = False):
291
+ """Initialize a ComplexTensorMode.
292
+
293
+ Args:
294
+ _dispatch_key: passed on to TorchDispatchMode
295
+ _compile: Compile the op before the computation
296
+ """
297
+ super().__init__(_dispatch_key)
298
+ self._compile = _compile
299
+
300
+ def __torch_dispatch__(
301
+ self,
302
+ func: OpOverload,
303
+ types: tuple[type],
304
+ args: tuple = (),
305
+ kwargs: dict[str, Any] | None = None,
306
+ ):
307
+ if kwargs is None:
308
+ kwargs = {}
309
+
310
+ # TODO (hameerabbasi): Test perf with `_compile` set to `True`
311
+ if self._compile:
312
+ func = torch.compile(func) # type: ignore[bad-assignment]
313
+
314
+ args = tree_map(_as_complex_tensor, args)
315
+ kwargs = tree_map(_as_complex_tensor, kwargs)
316
+
317
+ return tree_map(_as_interleaved, func(*args, **kwargs))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/complex_tensor/_ops/prims.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .._core import ComplexTensor
4
+ from .common import (
5
+ complex_to_real_dtype,
6
+ register_complex,
7
+ register_force_test,
8
+ split_complex_tensor,
9
+ )
10
+
11
+
12
+ prims = torch.ops.prims
13
+ aten = torch.ops.aten
14
+
15
+
16
+ # TODO (hameerabbasi): Not being tested
17
+ @register_force_test(prims.convert_element_type)
18
+ def convert_element_type_impl(x: ComplexTensor, dtype: torch.dtype) -> ComplexTensor:
19
+ dtype = complex_to_real_dtype(dtype)
20
+ u, v = split_complex_tensor(x)
21
+ u_out = prims.convert_element_type(u, dtype)
22
+ v_out = prims.convert_element_type(v, dtype)
23
+
24
+ return ComplexTensor(u_out, v_out)
25
+
26
+
27
+ @register_complex(prims.conj_physical)
28
+ def conj_physical_impl(self: ComplexTensor) -> ComplexTensor:
29
+ return aten._conj_physical(self)
30
+
31
+
32
+ @register_complex(prims.conj)
33
+ def conj_impl(self: ComplexTensor) -> ComplexTensor:
34
+ return aten._conj(self)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/fake_impls.py ADDED
@@ -0,0 +1,1465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import functools
4
+ import itertools
5
+ import math
6
+ import operator
7
+ import sys
8
+ from collections.abc import Callable
9
+ from functools import reduce
10
+ from typing import Optional, Union
11
+
12
+ import torch
13
+ import torch._custom_op
14
+ import torch._logging
15
+ import torch._prims_common as utils
16
+ from torch._dispatch.python import no_python_dispatcher
17
+ from torch._ops import OpOverload
18
+ from torch._prims_common import (
19
+ canonicalize_dim,
20
+ elementwise_dtypes,
21
+ ELEMENTWISE_TYPE_PROMOTION_KIND,
22
+ is_boolean_dtype,
23
+ is_contiguous,
24
+ is_contiguous_for_memory_format_or_false,
25
+ is_contiguous_or_false,
26
+ is_float_dtype,
27
+ is_integer_dtype,
28
+ make_contiguous_strides_for,
29
+ )
30
+ from torch._subclasses.fake_tensor import (
31
+ DataDependentOutputException,
32
+ DynamicOutputShapeException,
33
+ FakeTensor,
34
+ in_kernel_invocation_manager,
35
+ run_fallback_kernel,
36
+ UnsupportedOperatorException,
37
+ )
38
+ from torch.fx.operator_schemas import normalize_function
39
+ from torch.utils._stats import count_label
40
+
41
+
42
+ pytree = torch.utils._pytree
43
+
44
+ __all__ = [
45
+ "op_implementations_checks",
46
+ "get_fast_op_impls",
47
+ "stride_incorrect_op",
48
+ "has_meta",
49
+ ]
50
+
51
+ op_implementations_dict = {}
52
+ op_implementations_checks = []
53
+
54
+
55
+ aten = torch._ops.ops.aten
56
+
57
+
58
+ def ordered_set(*items):
59
+ return dict.fromkeys(items, True)
60
+
61
+
62
+ # This function indicates if the backend device
63
+ # supports non-contiguous tensors
64
+ def is_noncontiguous_supported(device):
65
+ return device.type != "hpu"
66
+
67
+
68
+ _like_tensor_constructors = ordered_set(
69
+ aten.empty_like.default,
70
+ aten.empty_like.out,
71
+ aten.full_like.default,
72
+ aten.full_like.out,
73
+ aten.ones_like.default,
74
+ aten.ones_like.out,
75
+ aten.rand_like.default,
76
+ aten.rand_like.generator,
77
+ aten.rand_like.out,
78
+ aten.rand_like.generator_out,
79
+ aten.randn_like.default,
80
+ aten.randn_like.generator,
81
+ aten.randn_like.out,
82
+ aten.randn_like.generator_out,
83
+ aten.randint_like.default,
84
+ aten.randint_like.generator,
85
+ aten.randint_like.Tensor,
86
+ aten.randint_like.Tensor_generator,
87
+ aten.randint_like.Tensor_out,
88
+ aten.randint_like.Tensor_generator_out,
89
+ aten.randint_like.out,
90
+ aten.randint_like.generator_out,
91
+ aten.randint_like.low_dtype,
92
+ aten.randint_like.low_generator_dtype,
93
+ aten.randint_like.low_dtype_out,
94
+ aten.randint_like.low_generator_dtype_out,
95
+ aten.zeros_like.default,
96
+ aten.zeros_like.out,
97
+ aten.new_empty.default,
98
+ aten.new_empty.out,
99
+ aten.new_empty_strided.default,
100
+ aten.new_empty_strided.out,
101
+ aten.new_full.default,
102
+ aten.new_full.out,
103
+ aten.new_zeros.default,
104
+ aten.new_zeros.out,
105
+ aten.new_ones.default,
106
+ aten.new_ones.out,
107
+ )
108
+
109
+
110
+ _device_not_kwarg_ops = ordered_set(
111
+ aten._resize_output_.default,
112
+ aten._nested_tensor_from_tensor_list.default,
113
+ aten._nested_tensor_from_tensor_list.out,
114
+ aten.pin_memory.default,
115
+ aten.to.device,
116
+ aten.to.prim_Device,
117
+ aten.is_pinned.default,
118
+ aten._pin_memory.default,
119
+ aten._pin_memory.out,
120
+ aten._resize_output.default,
121
+ aten._resize_output.out,
122
+ )
123
+
124
+ # this op is never actually used
125
+ _non_kwarg_device_constructors = (aten._list_to_tensor,)
126
+
127
+
128
+ def contains_tensor_types(type):
129
+ tensor_type = torch._C.TensorType.get()
130
+ return type.isSubtypeOf(tensor_type) or any(
131
+ contains_tensor_types(e) for e in type.containedTypes()
132
+ )
133
+
134
+
135
+ @functools.cache
136
+ def _is_tensor_constructor(func: OpOverload):
137
+ assert isinstance(func, OpOverload)
138
+ schema = func._schema
139
+ if any(contains_tensor_types(arg.type) for arg in schema.arguments):
140
+ return False
141
+ # TODO: no real reason to restrict multiple outputs
142
+ return (
143
+ len(schema.returns) == 1 and schema.returns[0].type is torch._C.TensorType.get()
144
+ )
145
+
146
+
147
+ def register_op_impl(run_impl_check: Union[Callable[[OpOverload], bool], OpOverload]):
148
+ def impl_decorator(op_impl):
149
+ if isinstance(run_impl_check, OpOverload):
150
+ assert run_impl_check not in op_implementations_dict, (
151
+ f"duplicate registration: {run_impl_check}"
152
+ )
153
+ op_implementations_dict[run_impl_check] = op_impl
154
+ elif isinstance(run_impl_check, (list, tuple)):
155
+ for op in run_impl_check:
156
+ register_op_impl(op)(op_impl)
157
+ else:
158
+ assert callable(run_impl_check)
159
+ op_implementations_checks.append((run_impl_check, op_impl))
160
+
161
+ return op_impl
162
+
163
+ return impl_decorator
164
+
165
+
166
+ def _is_op_registered_to_fake_rule(op):
167
+ return op in op_implementations_dict
168
+
169
+
170
+ def _deregister_op_impl(op):
171
+ op_implementations_dict.pop(op, None)
172
+ for check, impl in op_implementations_checks:
173
+ if check is op:
174
+ op_implementations_checks.remove((check, impl))
175
+ break
176
+
177
+
178
+ @register_op_impl(op_implementations_dict.__contains__)
179
+ def dispatch_to_op_implementations_dict(fake_mode, func, *args, **kwargs):
180
+ return op_implementations_dict[func](fake_mode, func, *args, **kwargs)
181
+
182
+
183
+ @register_op_impl(_is_tensor_constructor)
184
+ @register_op_impl([*_like_tensor_constructors])
185
+ def constructors(fake_mode, func, *args, **kwargs):
186
+ assert func not in _non_kwarg_device_constructors
187
+ _, new_kwargs = normalize_function(
188
+ func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True
189
+ )
190
+ if "names" in kwargs:
191
+ raise UnsupportedOperatorException(
192
+ "torch.compile doesn't support named tensors"
193
+ )
194
+
195
+ if func in _like_tensor_constructors:
196
+ default_device = new_kwargs["input"].device
197
+ # TODO: file issue
198
+ args = (new_kwargs.pop("input"),)
199
+ else:
200
+ # cpu is default device if none is specified
201
+ default_device = torch.device("cpu")
202
+ args = ()
203
+ out_device = new_kwargs.pop("device", None)
204
+ out_device = out_device if out_device is not None else default_device
205
+ new_kwargs["device"] = torch.device("meta")
206
+ # _like constructors have fake tensor inputs (maybe this causes the non-like
207
+ # to fail? hmmm)
208
+ with in_kernel_invocation_manager(fake_mode):
209
+ r = func(*args, **new_kwargs)
210
+ return FakeTensor(fake_mode, r, out_device)
211
+
212
+
213
+ @register_op_impl(aten.is_pinned.default)
214
+ def non_kwarg_is_pinned(fake_mode, func, *args, **kwargs):
215
+ _, new_kwargs = normalize_function(
216
+ func, args, kwargs, normalize_to_only_use_kwargs=True
217
+ )
218
+ inp = new_kwargs.pop("input")
219
+ # we'll ignore device argument because it is deprecated and not
220
+ # actually used by is_pinned.
221
+ with in_kernel_invocation_manager(fake_mode):
222
+ r = func(inp)
223
+ return r
224
+
225
+
226
+ @register_op_impl(aten.to.prim_Device)
227
+ @register_op_impl(aten.to.device)
228
+ def non_kwarg_to(fake_mode, func, *args, **kwargs):
229
+ _, new_kwargs = normalize_function(
230
+ func, args, kwargs, normalize_to_only_use_kwargs=True
231
+ )
232
+ input_device = new_kwargs["device"]
233
+ out_device = input_device if input_device else new_kwargs["input"].device
234
+ new_kwargs["device"] = torch.device("meta")
235
+ inp = new_kwargs.pop("input")
236
+ with in_kernel_invocation_manager(fake_mode):
237
+ r = func(inp, **new_kwargs)
238
+ # TODO: I think this does the wrong thing if r is inp
239
+ return fake_mode.fake_tensor_converter.from_meta_and_device(
240
+ fake_mode, r, out_device
241
+ )
242
+
243
+
244
+ def stride_incorrect_op(op):
245
+ return False
246
+
247
+
248
+ # These operators have meta implementations with incorrect strides
249
+ @register_op_impl(stride_incorrect_op)
250
+ def wordaround_stride_incorrect_op(fake_mode, func, *args, **kwargs):
251
+ # This is a workaround for meta implementations with incorrect strides
252
+
253
+ def is_symbolic(x):
254
+ if isinstance(x, FakeTensor):
255
+ return x._has_symbolic_sizes_strides
256
+ if isinstance(x, (torch.SymInt, torch.SymFloat, torch.SymBool)):
257
+ return True
258
+ return False
259
+
260
+ # For static shapes, we can fall back to eager for the real strides
261
+ if fake_mode.allow_fallback_kernels:
262
+ require_dynamic = any(
263
+ is_symbolic(x) for x in itertools.chain(args, kwargs.values())
264
+ )
265
+ if not require_dynamic:
266
+ flat_args, args_spec = pytree.tree_flatten((args, kwargs))
267
+ return run_fallback_kernel(fake_mode, func, flat_args, args_spec, None)
268
+
269
+ raise UnsupportedOperatorException(func)
270
+
271
+
272
+ # Dont default to default device handling,
273
+ # since the device of `the_template` is ignored
274
+ @register_op_impl(aten.resize_as_.default)
275
+ def resize_as_(fake_mode, func, *args, **kwargs):
276
+ with in_kernel_invocation_manager(fake_mode):
277
+ return func(*args, **kwargs)
278
+
279
+
280
+ @register_op_impl(aten._sparse_coo_tensor_with_dims_and_tensors.default)
281
+ def _sparse_coo_tensor_with_dims_and_tensors(fake_mode, func, *args, **kwargs):
282
+ # TODO: remove me
283
+ return constructors(fake_mode, func, *args, **kwargs)
284
+
285
+
286
+ # index.Tensor data-dependent in only some conditions
287
+ @register_op_impl(
288
+ lambda func: torch.Tag.dynamic_output_shape in func.tags
289
+ and func
290
+ not in [aten.index.Tensor, aten.nonzero.default, aten.repeat_interleave.Tensor]
291
+ )
292
+ def dyn_shape(fake_mode, func, *args, **kwargs):
293
+ raise DynamicOutputShapeException(func)
294
+
295
+
296
+ def _unique(
297
+ fake_mode,
298
+ func,
299
+ arg,
300
+ dim,
301
+ sorted=True,
302
+ return_inverse=False,
303
+ return_counts=False,
304
+ *,
305
+ unique_consecutive=False,
306
+ ):
307
+ if (
308
+ fake_mode.shape_env is None
309
+ or not fake_mode.shape_env.allow_dynamic_output_shape_ops
310
+ ):
311
+ # Without symints/symfloats, cannot handle this
312
+ raise DynamicOutputShapeException(func)
313
+
314
+ nnz = arg.unique_consecutive_memo if unique_consecutive else arg.unique_memo
315
+
316
+ # Do not use a memo for unique_dim
317
+ if dim is not None or nnz is None:
318
+ # Avoid importing sympy at a module level
319
+ from torch.fx.experimental.symbolic_shapes import (
320
+ _constrain_range_for_size,
321
+ has_free_symbols,
322
+ )
323
+
324
+ if not has_free_symbols(arg.numel()) and arg.numel() == 0:
325
+ # If numel is zero, then the output size must be zero.
326
+ # In this case, we must not allocate an unbacked SymInt,
327
+ # because if we do, it will immediately get refined to
328
+ # zero, but this will be inconsistent with size oblivious
329
+ # tests (which will continue to claim that the unbacked
330
+ # symint cannot equal zero). We could also unconditionally
331
+ # allocate an unbacked SymInt and not refine its range,
332
+ # but this seems more precise.
333
+ nnz = 0
334
+ else:
335
+ nnz = fake_mode.shape_env.create_unbacked_symint()
336
+
337
+ maxval = sys.maxsize - 1
338
+
339
+ numel = arg.numel() if dim is None else arg.size(dim)
340
+ if not has_free_symbols(numel):
341
+ maxval = int(numel)
342
+
343
+ _constrain_range_for_size(nnz, max=maxval)
344
+
345
+ if dim is None:
346
+ if unique_consecutive:
347
+ arg.unique_consecutive_memo = nnz
348
+ else:
349
+ arg.unique_memo = nnz
350
+
351
+ if dim is None:
352
+ ret = [arg.new_empty((nnz,))]
353
+ else:
354
+ ret = [arg.new_empty(*arg.shape[:dim], nnz, *arg.shape[dim + 1 :])]
355
+
356
+ return_if_dim_and_cpu = dim is not None and arg.fake_device == torch.device("cpu")
357
+ if return_inverse or return_if_dim_and_cpu:
358
+ inverse = arg.new_empty(arg.shape if dim is None else (arg.shape[dim],))
359
+ else:
360
+ inverse = arg.new_empty(0)
361
+ ret.append(inverse)
362
+
363
+ if return_counts or return_if_dim_and_cpu:
364
+ counts = arg.new_empty(ret[0].shape if dim is None else (ret[0].shape[dim],))
365
+ else:
366
+ counts = arg.new_empty(0)
367
+ ret.append(counts)
368
+
369
+ return tuple(ret)
370
+
371
+
372
+ @register_op_impl(aten._unique2.default)
373
+ def unique2(
374
+ fake_mode, func, arg, sorted=True, return_inverse=False, return_counts=False
375
+ ):
376
+ return _unique(fake_mode, func, arg, None, sorted, return_inverse, return_counts)
377
+
378
+
379
+ @register_op_impl(aten.select.int)
380
+ def meta_select(fake_mode, func, self, dim, index):
381
+ from torch.fx.experimental.symbolic_shapes import guard_or_false
382
+
383
+ if self.is_sparse:
384
+ return NotImplemented
385
+
386
+ ndim = self.dim()
387
+ torch._check_index(
388
+ ndim != 0,
389
+ lambda: "select() cannot be applied to a 0-dim tensor.",
390
+ )
391
+
392
+ dim = dim if dim >= 0 else dim + ndim
393
+ size = self.size(dim)
394
+
395
+ new_size = list(self.size())
396
+ new_stride = list(self.stride())
397
+
398
+ new_storage_offset = None
399
+ if guard_or_false(index >= 0):
400
+ new_storage_offset = self.storage_offset() + index * new_stride[dim]
401
+ elif guard_or_false(index < 0):
402
+ new_storage_offset = self.storage_offset() + (index + size) * new_stride[dim]
403
+
404
+ if new_storage_offset is None:
405
+ if fake_mode.shape_env is None or (
406
+ not fake_mode.shape_env.allow_scalar_outputs
407
+ and not fake_mode.allow_scalar_outputs
408
+ ):
409
+ raise DataDependentOutputException(func)
410
+
411
+ # index is data-dependent, we do not know which index we are accessing it could be index or index+size!
412
+ # we assign a new data-dependent symbol for the storage offset.
413
+ new_storage_offset = fake_mode.shape_env.create_unbacked_symint()
414
+
415
+ del new_size[dim]
416
+ del new_stride[dim]
417
+ assert new_storage_offset is not None
418
+ return self.as_strided(new_size, new_stride, new_storage_offset)
419
+
420
+
421
+ @register_op_impl(aten.unique_dim.default)
422
+ def unique_dim(
423
+ fake_mode, func, arg, dim, sorted=True, return_inverse=False, return_counts=False
424
+ ):
425
+ return _unique(
426
+ fake_mode,
427
+ func,
428
+ arg,
429
+ # normalize dim to be non-negative
430
+ dim if dim >= 0 else dim % max(arg.ndim, 1),
431
+ sorted,
432
+ return_inverse,
433
+ return_counts,
434
+ )
435
+
436
+
437
+ @register_op_impl(aten.unique_consecutive.default)
438
+ def _(fake_mode, func, arg, return_inverse=False, return_counts=False, dim=None):
439
+ return _unique(
440
+ fake_mode,
441
+ func,
442
+ arg,
443
+ dim,
444
+ False,
445
+ return_inverse,
446
+ return_counts,
447
+ unique_consecutive=True,
448
+ )
449
+
450
+
451
+ # This function is python match of computeStride_impl in TensorUtils.cpp
452
+ def _compute_stride(old_shape, old_stride, new_shape, size_oblivious=False):
453
+ from torch.fx.experimental.symbolic_shapes import (
454
+ guard_or_false,
455
+ guard_or_true,
456
+ sym_eq,
457
+ )
458
+
459
+ def maybe_guard_or_false(x):
460
+ if size_oblivious:
461
+ return guard_or_false(x)
462
+
463
+ return x
464
+
465
+ def maybe_guard_or_true(x):
466
+ if size_oblivious:
467
+ return guard_or_true(x)
468
+
469
+ return x
470
+
471
+ if len(old_shape) == 0:
472
+ return [1] * len(new_shape)
473
+
474
+ numel = reduce(operator.mul, old_shape, 1)
475
+ zero_numel = maybe_guard_or_false(numel == 0)
476
+ if zero_numel and maybe_guard_or_false(sym_eq(old_shape, new_shape)):
477
+ return old_stride
478
+
479
+ new_stride = [0] * len(new_shape)
480
+
481
+ if zero_numel:
482
+ for view_d in range(len(new_shape) - 1, -1, -1):
483
+ if view_d == len(new_shape) - 1:
484
+ new_stride[view_d] = 1
485
+ else:
486
+ new_stride[view_d] = (
487
+ max(new_shape[view_d + 1], 1) * new_stride[view_d + 1]
488
+ )
489
+ return new_stride
490
+
491
+ view_d = len(new_shape) - 1
492
+ chunk_base_stride = old_stride[-1]
493
+ tensor_numel = 1
494
+ view_numel = 1
495
+
496
+ for tensor_d in range(len(old_shape) - 1, -1, -1):
497
+ tensor_numel *= old_shape[tensor_d]
498
+
499
+ if tensor_d == 0 or (
500
+ maybe_guard_or_true(old_shape[tensor_d - 1] != 1)
501
+ and maybe_guard_or_true(
502
+ old_stride[tensor_d - 1] != tensor_numel * chunk_base_stride
503
+ )
504
+ ):
505
+ while view_d >= 0 and (
506
+ maybe_guard_or_true(view_numel < tensor_numel)
507
+ or maybe_guard_or_false(new_shape[view_d] == 1)
508
+ ):
509
+ new_stride[view_d] = view_numel * chunk_base_stride
510
+ view_numel *= new_shape[view_d]
511
+ view_d -= 1
512
+
513
+ if maybe_guard_or_true(view_numel != tensor_numel):
514
+ return None
515
+
516
+ if tensor_d > 0:
517
+ chunk_base_stride = old_stride[tensor_d - 1]
518
+ tensor_numel = 1
519
+ view_numel = 1
520
+ if view_d != -1:
521
+ return None
522
+ return new_stride
523
+
524
+
525
+ def _view_has_unbacked_input(a, shape):
526
+ from torch.fx.experimental.symbolic_shapes import has_hint
527
+
528
+ shape = utils.extract_shape_from_varargs(shape, validate=False)
529
+
530
+ return (
531
+ any(not has_hint(s) for s in a.size())
532
+ or any(not has_hint(s) for s in a.stride())
533
+ or any(not has_hint(s) for s in shape)
534
+ )
535
+
536
+
537
+ def _view_unbacked_meta(a, shape, size_oblivious_enabled=True):
538
+ from torch._prims import view_of
539
+ from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq
540
+
541
+ # Creates a valid shape
542
+ shape = utils.extract_shape_from_varargs(shape, validate=False)
543
+
544
+ # Reshape may be given a shape with a -1 length
545
+ # This indicates that the dimension's length should be inferred
546
+ shape = utils.infer_size(shape, a.numel())
547
+
548
+ # Special-cases reshaping zero dim tensors
549
+ if a.ndim == 0:
550
+ _a = a
551
+ for length in shape:
552
+ torch._check(length == 1)
553
+ _a = torch._refs.unsqueeze(_a, -1)
554
+ if _a is a:
555
+ return view_of(a)
556
+ else:
557
+ return _a
558
+
559
+ # Special-cases reshaping to zero dim tensors
560
+ if len(shape) == 0:
561
+ _a = a
562
+ for length in a.shape:
563
+ torch._check(length == 1)
564
+ _a = torch._refs.squeeze(_a, -1)
565
+ if _a is a:
566
+ return view_of(a)
567
+ else:
568
+ return _a
569
+
570
+ shape_numel = reduce(operator.mul, shape, 1)
571
+
572
+ torch._check(
573
+ a.numel() == shape_numel,
574
+ lambda: f"Could not reshape a tensor with shape {a.shape} as a tensor with shape {shape}!",
575
+ )
576
+
577
+ if len(shape) == len(a.shape) and guard_or_false(sym_eq(shape, a.shape)):
578
+ return view_of(a)
579
+
580
+ if is_contiguous_or_false(a) if size_oblivious_enabled else is_contiguous(a):
581
+ strides = make_contiguous_strides_for(shape)
582
+ return a.as_strided(shape, strides)
583
+
584
+ new_strides = _compute_stride(
585
+ a.size(), a.stride(), shape, size_oblivious=size_oblivious_enabled
586
+ )
587
+
588
+ if new_strides is not None:
589
+ return a.as_strided(shape, new_strides)
590
+
591
+ # If we fail to do size oblivious view, and backed_size_oblivious was on,
592
+ # then we redo everything by looking at hints and guarding instead of failing.
593
+ # Also if the expression has unbacked symbols, then we run again with size_oblivious_enabled=False
594
+ # to throw a data dependent error.
595
+
596
+ if size_oblivious_enabled and (
597
+ torch.fx.experimental._config.backed_size_oblivious
598
+ or _view_has_unbacked_input(a, shape)
599
+ ):
600
+ return _view_unbacked_meta(a, shape, size_oblivious_enabled=False)
601
+
602
+ msg = f"Cannot view a tensor with shape {a.shape} and strides {a.stride()} as a tensor with shape {shape}!"
603
+ raise ValueError(msg)
604
+
605
+
606
+ @register_op_impl(aten._reshape_copy.default)
607
+ def _reshape_copy(fake_mode, func, a, *shape):
608
+ if a.is_sparse or a.is_mkldnn:
609
+ return NotImplemented
610
+
611
+ shape = utils.infer_size(*shape, a.numel())
612
+ if is_contiguous_or_false(a):
613
+ view = _view_meta(fake_mode, func, a, *shape)
614
+ return view.clone(memory_format=torch.contiguous_format)
615
+ else:
616
+ return _view_meta(
617
+ fake_mode, func, a.clone(memory_format=torch.contiguous_format), *shape
618
+ )
619
+
620
+
621
+ @register_op_impl(aten.view.default)
622
+ @register_op_impl(aten._unsafe_view.default)
623
+ def _view_meta(fake_mode, func, a, *shape):
624
+ if torch.fx.experimental._config.backed_size_oblivious or _view_has_unbacked_input(
625
+ a, shape
626
+ ):
627
+ return _view_unbacked_meta(a, shape)
628
+ else:
629
+ return torch._refs._reshape_view_helper(a, *shape, allow_copy=False)
630
+
631
+
632
+ @register_op_impl(aten.view_copy.default)
633
+ def _view_meta_copy(fake_mode, func, a, *shape, out=None):
634
+ result = _view_meta(fake_mode, func, a, *shape)
635
+ if out is not None:
636
+ return result
637
+
638
+ return pytree.tree_map(
639
+ lambda x: x.clone(memory_format=torch.contiguous_format),
640
+ result,
641
+ )
642
+
643
+
644
+ @register_op_impl(aten.repeat_interleave.Tensor)
645
+ def repeat_interleave_tensor(fake_mode, func, repeats, output_size=None):
646
+ if output_size is None:
647
+ if (
648
+ fake_mode.shape_env is None
649
+ or not fake_mode.shape_env.allow_dynamic_output_shape_ops
650
+ ):
651
+ raise DynamicOutputShapeException(func)
652
+
653
+ output_size = fake_mode.shape_env.create_unbacked_symint()
654
+
655
+ # Avoid importing sympy at a module level
656
+ from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size
657
+
658
+ _constrain_range_for_size(output_size)
659
+ # TODO: consider a memo
660
+ return repeats.new_empty(output_size)
661
+
662
+
663
+ @register_op_impl(torch.ops.aten.item.default)
664
+ @register_op_impl(torch.ops.aten._local_scalar_dense.default)
665
+ def local_scalar_dense(fake_mode, func, arg):
666
+ if (r := arg.item_memo) is not None:
667
+ return r
668
+ if fake_mode.shape_env is None or (
669
+ not fake_mode.shape_env.allow_scalar_outputs
670
+ and not fake_mode.allow_scalar_outputs
671
+ ):
672
+ # Without symints/symfloats, cannot handle this
673
+ raise DataDependentOutputException(func)
674
+ if is_float_dtype(arg.dtype):
675
+ r = fake_mode.shape_env.create_unbacked_symfloat()
676
+ elif is_integer_dtype(arg.dtype):
677
+ r = fake_mode.shape_env.create_unbacked_symint()
678
+ elif is_boolean_dtype(arg.dtype):
679
+ r = fake_mode.shape_env.create_unbacked_symbool()
680
+ else:
681
+ raise NotImplementedError(f"local_scalar_dense/item NYI for {arg.dtype}")
682
+ arg.item_memo = r
683
+ return r
684
+
685
+
686
+ @register_op_impl(torch.ops.aten.nonzero_numpy.default)
687
+ def nonzero_numpy(fake_mode, func, arg):
688
+ return torch.ops.aten.nonzero.default(arg).unbind(1)
689
+
690
+
691
+ @register_op_impl(torch.ops.aten.nonzero.default)
692
+ def nonzero(fake_mode, func, arg):
693
+ if (
694
+ fake_mode.shape_env is None
695
+ or not fake_mode.shape_env.allow_dynamic_output_shape_ops
696
+ ):
697
+ # Without symints/symfloats, cannot handle this
698
+ raise DynamicOutputShapeException(func)
699
+
700
+ if (nnz := arg.nonzero_memo) is None:
701
+ # Avoid importing sympy at a module level
702
+ from torch.fx.experimental.symbolic_shapes import (
703
+ _constrain_range_for_size,
704
+ has_free_symbols,
705
+ )
706
+ from torch.utils._sympy.numbers import IntInfinity
707
+ from torch.utils._sympy.value_ranges import bound_sympy
708
+
709
+ if not has_free_symbols(arg.numel()) and arg.numel() == 0:
710
+ # If numel is zero, then the output size must be zero.
711
+ # In this case, we must not allocate an unbacked SymInt,
712
+ # because if we do, it will immediately get refined to
713
+ # zero, but this will be inconsistent with size oblivious
714
+ # tests (which will continue to claim that the unbacked
715
+ # symint cannot equal zero). We could also unconditionally
716
+ # allocate an unbacked SymInt and not refine its range,
717
+ # but this seems more precise.
718
+ nnz = 0
719
+ else:
720
+ nnz = fake_mode.shape_env.create_unbacked_symint()
721
+
722
+ maxval = sys.maxsize - 1
723
+
724
+ if not has_free_symbols(arg.numel()):
725
+ maxval = int(arg.numel())
726
+ else:
727
+ prod_node = math.prod(arg.shape).node
728
+ prod_range = bound_sympy(
729
+ prod_node.expr, prod_node.shape_env.var_to_range
730
+ )
731
+ if isinstance(prod_range.upper, IntInfinity):
732
+ maxval = sys.maxsize - 1
733
+ else:
734
+ maxval = prod_range.upper
735
+
736
+ _constrain_range_for_size(nnz, max=maxval)
737
+
738
+ arg.nonzero_memo = nnz
739
+
740
+ return arg.new_empty_strided((nnz, arg.dim()), (1, nnz), dtype=torch.int64)
741
+
742
+
743
+ @register_op_impl(torch.ops.aten._padded_dense_to_jagged_forward.default)
744
+ def _padded_dense_to_jagged_forward(fake_mode, func, padded, offsets, total_L=None):
745
+ # only one jagged dim is supported for now
746
+ assert len(offsets) == 1
747
+
748
+ if not total_L:
749
+ if (
750
+ fake_mode.shape_env is None
751
+ or not fake_mode.shape_env.allow_dynamic_output_shape_ops
752
+ ):
753
+ # Without symints/symfloats, cannot handle this
754
+ raise DynamicOutputShapeException(func)
755
+
756
+ total_L = fake_mode.shape_env.create_unbacked_symint()
757
+
758
+ maxval = sys.maxsize - 1
759
+
760
+ # Avoid importing sympy at a module level
761
+ from torch.fx.experimental.symbolic_shapes import (
762
+ _constrain_range_for_size,
763
+ has_free_symbols,
764
+ )
765
+
766
+ if not has_free_symbols(padded.numel()):
767
+ maxval = int(padded.numel())
768
+
769
+ _constrain_range_for_size(total_L, min=0, max=maxval)
770
+
771
+ output_shape = (total_L, *padded.shape[2:])
772
+ return padded.new_empty(output_shape)
773
+
774
+
775
+ def _compute_slice_index(size, index):
776
+ from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_and
777
+
778
+ if guard_or_false(sym_and(index >= 0, index <= size)):
779
+ return index
780
+ elif guard_or_false(sym_and(index < 0, index >= -size)):
781
+ return index + size
782
+ elif guard_or_false(index < -size):
783
+ return 0
784
+ elif guard_or_false(index > size):
785
+ return size
786
+ return None
787
+
788
+
789
+ @register_op_impl(torch.ops.aten.slice.Tensor)
790
+ def slice_forward(
791
+ fake_mode,
792
+ func,
793
+ self,
794
+ dim: int = 0,
795
+ start: Optional[int] = None,
796
+ end: Optional[int] = None,
797
+ step: int = 1,
798
+ ):
799
+ from torch.fx.experimental.symbolic_shapes import (
800
+ guard_or_false,
801
+ statically_known_true,
802
+ )
803
+
804
+ shape_env = fake_mode.shape_env
805
+
806
+ ndim = self.dim()
807
+ if ndim == 0:
808
+ raise RuntimeError("slice() cannot be applied to a 0-dim tensor.")
809
+ dim = canonicalize_dim(self.dim(), dim)
810
+ sizes = list(self.size())
811
+ strides = list(self.stride())
812
+
813
+ if step <= 0:
814
+ raise RuntimeError("slice step must be positive")
815
+
816
+ # start, end
817
+ start_index = 0 if start is None else _compute_slice_index(sizes[dim], start)
818
+ end_index = (
819
+ sizes[dim]
820
+ if statically_known_true(end == sys.maxsize) or end is None
821
+ else _compute_slice_index(sizes[dim], end)
822
+ )
823
+
824
+ # size
825
+ new_size = None
826
+ if start_index is not None and end_index is not None:
827
+ if guard_or_false(end_index >= start_index):
828
+ new_size = (end_index - start_index + step - 1) // step
829
+ elif guard_or_false(start_index >= end_index):
830
+ new_size = 0
831
+
832
+ # create unbacked if case unknown
833
+ if new_size is None:
834
+ new_size = shape_env.create_unbacked_symint()
835
+ torch._check(new_size >= 0)
836
+ torch._check(new_size <= sizes[dim])
837
+
838
+ # stride
839
+ new_stride = strides[dim] * step
840
+
841
+ # storage offset
842
+ if start_index is not None:
843
+ storage_offset = self.storage_offset() + start_index * strides[dim]
844
+ else:
845
+ storage_offset = shape_env.create_unbacked_symint()
846
+ torch._check(storage_offset >= 0)
847
+
848
+ sizes[dim] = new_size
849
+ strides[dim] = new_stride
850
+ if self.is_quantized:
851
+ raise NotImplementedError(
852
+ "Slice decomposition for quantized tensors aren't implemented"
853
+ )
854
+ else:
855
+ return self.as_strided(sizes, strides, storage_offset)
856
+
857
+
858
+ @register_op_impl(torch.ops.aten.masked_select.default)
859
+ def masked_select(fake_mode, func, self, mask):
860
+ if (
861
+ fake_mode.shape_env is None
862
+ or not fake_mode.shape_env.allow_dynamic_output_shape_ops
863
+ ):
864
+ # Without symints/symfloats, cannot handle this
865
+ raise DynamicOutputShapeException(func)
866
+
867
+ nnz = fake_mode.shape_env.create_unbacked_symint()
868
+
869
+ # see nonzero for commentary
870
+ maxval = sys.maxsize - 1
871
+
872
+ # Avoid importing sympy at a module level
873
+ from torch.fx.experimental.symbolic_shapes import (
874
+ _constrain_range_for_size,
875
+ has_free_symbols,
876
+ )
877
+ from torch.utils._sympy.numbers import IntInfinity
878
+ from torch.utils._sympy.value_ranges import bound_sympy
879
+
880
+ # If num elements is expressed symbolically, calculate
881
+ # the concrete value based on upper bounds. Otherwise,
882
+ # we can set max val directly.
883
+ if not has_free_symbols(self.numel()):
884
+ num_elements = int(self.numel())
885
+ else:
886
+ prod_node = math.prod(self.shape).node
887
+ prod_range = bound_sympy(prod_node.expr, prod_node.shape_env.var_to_range)
888
+ if isinstance(prod_range.upper, IntInfinity):
889
+ num_elements = sys.maxsize - 1
890
+ else:
891
+ num_elements = prod_range.upper
892
+ if num_elements > 2:
893
+ maxval = num_elements
894
+
895
+ _constrain_range_for_size(nnz, max=maxval)
896
+
897
+ return self.new_empty((nnz,))
898
+
899
+
900
+ @register_op_impl(torch.ops.aten._assert_tensor_metadata.default)
901
+ def assert_tensor_metadata(
902
+ fake_mode,
903
+ func,
904
+ t,
905
+ sizes=None,
906
+ strides=None,
907
+ dtype=None,
908
+ *,
909
+ device=None,
910
+ layout=None,
911
+ ) -> None:
912
+ if sizes is not None:
913
+ assert t.size() == sizes, (
914
+ f"Tensor sizes mismatch! Expected: {sizes}, Got: {t.size()}"
915
+ )
916
+ if strides is not None:
917
+ assert t.stride() == strides, (
918
+ f"Tensor strides mismatch! Expected: {strides}, Got: {t.stride()}"
919
+ )
920
+ if dtype is not None:
921
+ assert t.dtype == dtype, (
922
+ f"Tensor dtype mismatch! Expected: {dtype}, Got: {t.dtype}"
923
+ )
924
+ if layout is not None:
925
+ assert t.layout == layout, (
926
+ f"Tensor layout mismatch! Expected: {layout}, Got: {t.layout()}"
927
+ )
928
+ if device is not None:
929
+ assert t.device == device, (
930
+ f"Tensor device mismatch! Expected: {device}, Got: {t.device}"
931
+ )
932
+
933
+
934
+ # NB: this must be ordered after local_scalar_dense
935
+ @register_op_impl(lambda func: torch.Tag.data_dependent_output in func.tags)
936
+ def data_dep(fake_mode, func, *args, **kwargs):
937
+ raise DataDependentOutputException(func)
938
+
939
+
940
+ # Bool Indices get Expanded as Masks
941
+ # See: IndexingUtils.h:expandTensors
942
+ def check_no_bool_index_tensors(func, self, indices):
943
+ for index in indices:
944
+ if index is not None and index.dtype in (torch.bool, torch.uint8):
945
+ raise DynamicOutputShapeException(func)
946
+
947
+
948
+ def run_and_return_new_tensor_of_input_device(fake_mode, func, args, kwargs):
949
+ _, new_kwargs = normalize_function(
950
+ func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True
951
+ )
952
+
953
+ out_device = new_kwargs["input"].device
954
+ with in_kernel_invocation_manager(fake_mode):
955
+ out = func(*args, **kwargs)
956
+ if not is_noncontiguous_supported(out_device):
957
+ out = out.new_empty(out.shape)
958
+
959
+ if out is new_kwargs["input"]:
960
+ return out # copy_
961
+ return FakeTensor(fake_mode, out, out_device)
962
+
963
+
964
+ _is_builtin_namespaces = ordered_set("aten", "prims", "prim")
965
+
966
+
967
+ def is_builtin(op):
968
+ return op.namespace in _is_builtin_namespaces
969
+
970
+
971
+ def has_meta(func):
972
+ return torch._C._dispatch_has_computed_kernel_for_dispatch_key(func.name(), "Meta")
973
+
974
+
975
+ # These are for the `torch._foreach_...` ops like `torch._foreach_add`.
976
+ @register_op_impl(
977
+ lambda func: is_builtin(func)
978
+ and func.name().startswith("aten::_foreach_")
979
+ and has_meta(func)
980
+ )
981
+ def foreach_run_and_map_input_device(fake_mode, func, *args, **kwargs):
982
+ tensor_lists = [
983
+ arg
984
+ for arg in itertools.chain(args, kwargs.values())
985
+ if isinstance(arg, (list, tuple))
986
+ and len(arg)
987
+ and isinstance(arg[0], torch.Tensor)
988
+ ]
989
+
990
+ try:
991
+ with in_kernel_invocation_manager(fake_mode):
992
+ out_meta = func(*args, **kwargs)
993
+ except NotImplementedError:
994
+ return NotImplemented
995
+
996
+ if not out_meta:
997
+ return out_meta
998
+
999
+ assert tensor_lists
1000
+ out_fake = []
1001
+
1002
+ for i, meta_t in enumerate(out_meta):
1003
+ device, _ = FakeTensor._find_common_device(func, [tl[i] for tl in tensor_lists])
1004
+ out_fake.append(
1005
+ fake_mode.fake_tensor_converter.from_meta_and_device(
1006
+ fake_mode, meta_t, device
1007
+ )
1008
+ )
1009
+
1010
+ return out_fake
1011
+
1012
+
1013
+ # Dont default to default device handling,
1014
+ # Since op can take in non-zero sized cpu
1015
+ # index tensors with cuda self
1016
+ @register_op_impl(aten.index.Tensor)
1017
+ def index_tensor(fake_mode, func, *args, **kwargs):
1018
+ from torch._meta_registrations import meta_index_Tensor
1019
+
1020
+ _, new_kwargs = normalize_function(
1021
+ func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True
1022
+ )
1023
+
1024
+ out_device = new_kwargs["input"].device
1025
+ # ensure nonzero call goes to fake tensor
1026
+ with fake_mode:
1027
+ out = meta_index_Tensor(*args, **kwargs)
1028
+ return out.to(out_device)
1029
+
1030
+
1031
+ # Can take mixed meta/non-meta arguments; the meta registration
1032
+ # will roughly do the right thing even when given real devices
1033
+ @register_op_impl(aten._embedding_bag.default)
1034
+ def embedding_bag(fake_mode, func, *args, **kwargs):
1035
+ from torch._meta_registrations import meta_embedding_bag
1036
+
1037
+ with fake_mode:
1038
+ return meta_embedding_bag(*args, **kwargs)
1039
+
1040
+
1041
+ # takes in multiple-devices, dont default to default device handling
1042
+ @register_op_impl(aten._unsafe_index_put.default)
1043
+ @register_op_impl(aten.copy.default)
1044
+ @register_op_impl(aten.copy_.default)
1045
+ @register_op_impl(aten.slice_scatter.default)
1046
+ def multi_device_op_default(fake_mode, func, *args, **kwargs):
1047
+ return run_and_return_new_tensor_of_input_device(fake_mode, func, args, kwargs)
1048
+
1049
+
1050
+ # same with multi_device_op_default, but return the input
1051
+ @register_op_impl(aten.copy.out)
1052
+ @register_op_impl(aten.slice_scatter.out)
1053
+ def multi_device_op_out(fake_mode, func, *args, **kwargs):
1054
+ with in_kernel_invocation_manager(fake_mode):
1055
+ func(*args, **kwargs)
1056
+
1057
+ _, new_kwargs = normalize_function(
1058
+ func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True
1059
+ )
1060
+
1061
+ return new_kwargs["input"]
1062
+
1063
+
1064
+ @register_op_impl(aten.index_put.default)
1065
+ @register_op_impl(aten.index_put_.default)
1066
+ def index_put_impl(fake_mode, func, *args, **kwargs):
1067
+ _, new_kwargs = normalize_function(
1068
+ func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True
1069
+ )
1070
+
1071
+ values = new_kwargs["values"]
1072
+ self_device = new_kwargs["input"].fake_device
1073
+ torch._check(
1074
+ self_device == values.fake_device or (values.ndim == 0 and values.numel() == 1),
1075
+ lambda: f"Mismatching {func} device between self ({self_device}) and values ({values.device})",
1076
+ )
1077
+
1078
+ out = run_and_return_new_tensor_of_input_device(fake_mode, func, args, kwargs)
1079
+ if func is aten.index_put_.default:
1080
+ return new_kwargs["input"]
1081
+ else:
1082
+ return out
1083
+
1084
+
1085
+ @register_op_impl(aten._nested_tensor_from_tensor_list.default)
1086
+ @register_op_impl(aten._nested_tensor_from_tensor_list.out)
1087
+ @register_op_impl(aten._nested_view_from_buffer.default)
1088
+ @register_op_impl(aten._nested_view_from_buffer_copy.default)
1089
+ def nested_tensors_unsupported(fake_mode, func, *args, **kwargs):
1090
+ raise UnsupportedOperatorException(
1091
+ "torch.compile does not support strided NestedTensor"
1092
+ )
1093
+
1094
+
1095
+ @register_op_impl(
1096
+ [
1097
+ x
1098
+ for x in _device_not_kwarg_ops
1099
+ if x
1100
+ not in (
1101
+ # these are already registered elsewhere
1102
+ aten.is_pinned.default,
1103
+ aten.to.device,
1104
+ aten.to.prim_Device,
1105
+ aten._nested_tensor_from_tensor_list.default,
1106
+ aten._nested_tensor_from_tensor_list.out,
1107
+ )
1108
+ ]
1109
+ )
1110
+ def nyi(fake_mode, func, *args, **kwargs):
1111
+ assert func not in _device_not_kwarg_ops, f"NYI: {func}"
1112
+
1113
+
1114
+ @register_op_impl([aten.convolution.default, aten.convolution_backward.default])
1115
+ def conv(fake_mode, func, *args, **kwargs):
1116
+ _, kwargs = normalize_function(
1117
+ func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True
1118
+ )
1119
+ device = kwargs["input"].fake_device
1120
+ # need to re-enable mode so the tensors report fake device
1121
+ with fake_mode:
1122
+ # if the input is unsqueezed is done in Convolution.cpp we get segfault
1123
+ k = kwargs["weight"].ndim
1124
+ batch = kwargs["input"].shape[0]
1125
+
1126
+ # Avoid importing sympy at a module level
1127
+ from torch.fx.experimental.symbolic_shapes import has_hint
1128
+
1129
+ if not has_hint(batch):
1130
+ # TODO: We can make this a little more faithful with best effort
1131
+ # channels last detection (but only if it's statically obvious!)
1132
+ mem_fmt = None
1133
+ else:
1134
+ if func is aten.convolution.default:
1135
+ conv_backend = torch._C._select_conv_backend(**kwargs)
1136
+ else:
1137
+ conv_backend = torch._C._select_conv_backend(
1138
+ kwargs["input"],
1139
+ kwargs["weight"],
1140
+ bias=None,
1141
+ stride=kwargs["stride"],
1142
+ padding=kwargs["padding"],
1143
+ dilation=kwargs["dilation"],
1144
+ transposed=kwargs["transposed"],
1145
+ output_padding=kwargs["output_padding"],
1146
+ groups=kwargs["groups"],
1147
+ bias_sizes=kwargs["bias_sizes"],
1148
+ )
1149
+ # Expand 1d -> 2d.
1150
+ # Note: Avoid expanding before calling _select_conv_backend,
1151
+ # as the function handles 2D expansion internally.
1152
+ if k == 3 and not kwargs["input"].is_mkldnn and not kwargs["input"].is_xpu:
1153
+ # Note: Using input.to(memory_format=contiguous) does not work.
1154
+ kwargs["input"] = kwargs["input"].contiguous().unsqueeze(2)
1155
+ kwargs["weight"] = kwargs["weight"].unsqueeze(2)
1156
+ if len(kwargs["stride"]) == 1:
1157
+ kwargs["stride"].insert(0, 1)
1158
+ kwargs["padding"].insert(0, 0)
1159
+ kwargs["dilation"].insert(0, 1)
1160
+ kwargs["output_padding"].insert(0, 0)
1161
+ mem_fmt = torch._C._conv_determine_backend_memory_format(
1162
+ kwargs["input"], kwargs["weight"], conv_backend
1163
+ )
1164
+ # revert 2d -> 1d
1165
+ if k == 3 and not kwargs["input"].is_mkldnn and not kwargs["input"].is_xpu:
1166
+ kwargs["input"] = kwargs["input"].squeeze(2)
1167
+ kwargs["weight"] = kwargs["weight"].squeeze(2)
1168
+ if len(kwargs["stride"]) == 2:
1169
+ kwargs["stride"].pop(0)
1170
+ kwargs["padding"].pop(0)
1171
+ kwargs["dilation"].pop(0)
1172
+ kwargs["output_padding"].pop(0)
1173
+
1174
+ def convert(t, mem_fmt):
1175
+ if t is None:
1176
+ return t
1177
+ if mem_fmt is not None:
1178
+ # channels last only support 4d, try to expand dim then convert it back later.
1179
+ if t.dim() == 3 and mem_fmt == torch.channels_last:
1180
+ t = t.unsqueeze(2).to(memory_format=mem_fmt).squeeze(2)
1181
+ else:
1182
+ t = t.to(memory_format=mem_fmt)
1183
+ return FakeTensor(fake_mode, t, device)
1184
+
1185
+ with in_kernel_invocation_manager(fake_mode):
1186
+ out = func(**kwargs)
1187
+
1188
+ if func is aten.convolution.default:
1189
+ return convert(out, mem_fmt)
1190
+ else:
1191
+ return (
1192
+ convert(out[0], mem_fmt),
1193
+ convert(out[1], mem_fmt),
1194
+ convert(out[2], None),
1195
+ )
1196
+
1197
+
1198
+ @register_op_impl(torch.ops.aten.bincount.default)
1199
+ def bincount(fake_mode, func, inputs, weights=None, minlength=0):
1200
+ if (
1201
+ fake_mode.shape_env is None
1202
+ or not fake_mode.shape_env.allow_dynamic_output_shape_ops
1203
+ ):
1204
+ # Without symints/symfloats, cannot handle this
1205
+ raise DynamicOutputShapeException(func)
1206
+
1207
+ new_size = fake_mode.shape_env.create_unbacked_symint()
1208
+
1209
+ from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size
1210
+
1211
+ _constrain_range_for_size(new_size)
1212
+ torch._check(new_size >= minlength)
1213
+ return inputs.new_empty(new_size)
1214
+
1215
+
1216
+ @register_op_impl(torch.ops.aten._pack_padded_sequence.default)
1217
+ def _pack_padded_sequence(fake_mode, func, inputs, lengths, batch_first):
1218
+ if (
1219
+ fake_mode.shape_env is None
1220
+ or not fake_mode.shape_env.allow_dynamic_output_shape_ops
1221
+ ):
1222
+ # Without symints/symfloats, cannot handle this
1223
+ raise DynamicOutputShapeException(func)
1224
+
1225
+ new_batch_size = fake_mode.shape_env.create_unbacked_symint()
1226
+
1227
+ from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size
1228
+
1229
+ _constrain_range_for_size(new_batch_size)
1230
+
1231
+ if not batch_first:
1232
+ # Inputs should have shape (batch_size, seq_len, *)
1233
+ inputs = inputs.transpose(0, 1)
1234
+
1235
+ res_size = inputs.shape[1:]
1236
+ packed_data = inputs.new_empty(res_size)
1237
+ batch_size = inputs.new_empty((new_batch_size,))
1238
+ return (packed_data, batch_size)
1239
+
1240
+
1241
+ FAST_OP_IMPLEMENTATIONS = {}
1242
+
1243
+
1244
+ # Unlike register_op_impl, these don't do the slow iteration for
1245
+ # run_impl_check, and these run BEFORE decompositions
1246
+ def register_fast_op_impl(func: OpOverload):
1247
+ def impl_decorator(op_impl):
1248
+ FAST_OP_IMPLEMENTATIONS[func] = op_impl
1249
+ return op_impl
1250
+
1251
+ return impl_decorator
1252
+
1253
+
1254
+ # infer_size_impl in ExpandUtils
1255
+ def infer_size(a, b):
1256
+ from torch.fx.experimental.symbolic_shapes import guard_or_false
1257
+
1258
+ dimsA = len(a)
1259
+ dimsB = len(b)
1260
+ ndim = max(dimsA, dimsB)
1261
+ expandedSizes = [0] * ndim
1262
+ for i in range(ndim - 1, -1, -1):
1263
+ offset = ndim - 1 - i
1264
+ dimA = dimsA - 1 - offset
1265
+ dimB = dimsB - 1 - offset
1266
+ sizeA = a[dimA] if dimA >= 0 else 1
1267
+ sizeB = b[dimB] if dimB >= 0 else 1
1268
+
1269
+ # NB: It is very important to test for broadcasting, before testing
1270
+ # sizeA == sizeB. This is because the broadcasting tests are likely
1271
+ # to be statically known (in particular, if sizeA/sizeB is unbacked
1272
+ # but size-like, we will unsoundly assume they never equal 1), but
1273
+ # the sizeA == sizeB test may not be statically known. However, once
1274
+ # we have established that no broadcasting is happening, the
1275
+ # sizeA == sizeB is now expect_true and we can defer it as a runtime
1276
+ # assert (this works because Python will return the terminal
1277
+ # expression of an or statement as-is, without bool()'ing it; if this
1278
+ # were not the case, we'd need to write this using torch.sym_or() or
1279
+ # something like that).
1280
+ torch._check(
1281
+ guard_or_false(sizeA == 1) or guard_or_false(sizeB == 1) or sizeA == sizeB,
1282
+ lambda: f"The size of tensor a ({sizeA}) "
1283
+ f"must match the size of tensor b ({sizeB}) "
1284
+ f"at non-singleton dimension {i})",
1285
+ )
1286
+ expandedSizes[i] = sizeB if guard_or_false(sizeA == 1) else sizeA
1287
+ return tuple(expandedSizes)
1288
+
1289
+
1290
+ def make_fast_binary_impl(
1291
+ slow_ref, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
1292
+ ):
1293
+ def fast_binary_impl(mode, *args, **kwargs):
1294
+ def slow(msg):
1295
+ count_label(f"slow {msg}")
1296
+ with mode:
1297
+ return slow_ref(*args, **kwargs)
1298
+
1299
+ count_label("attempt fast")
1300
+
1301
+ # Fast path (based off of TensorIterator fast path).
1302
+ # Unfortunately, there is no way to easily deduplicate
1303
+ # this with either the TensorIterator C++ implementation
1304
+ # (which we don't want to SymIntify, and also the algorithm
1305
+ # here is slightly different from TensorIterator to allow
1306
+ # for broadcasting), nor the PrimTorch implementation
1307
+ # (which does not actually implement a fast path.)
1308
+
1309
+ operands = args
1310
+
1311
+ # compute_shape
1312
+ final_shape = None
1313
+ for op in operands:
1314
+ shape = op.shape if isinstance(op, torch.Tensor) else ()
1315
+ if final_shape is None:
1316
+ final_shape = shape
1317
+ # TODO: Minor optimization: track if the shapes
1318
+ # were equal so you can skip the equality check
1319
+ # below if unnecessary
1320
+ final_shape = infer_size(final_shape, shape)
1321
+ assert final_shape is not None
1322
+
1323
+ from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq
1324
+
1325
+ # Do some extra safety checks to see if the output
1326
+ # stride is obvious
1327
+ for op in operands:
1328
+ if (
1329
+ isinstance(op, torch.Tensor)
1330
+ and len(op.shape) == len(final_shape)
1331
+ # take the slow path if result is not determined.
1332
+ and guard_or_false(sym_eq(op.shape, final_shape))
1333
+ ):
1334
+ break
1335
+ else:
1336
+ # if we never break in the for loop above we take the slow path.
1337
+ return slow("both tensors nontrivially broadcast")
1338
+
1339
+ # compute_types
1340
+ cpu = torch.device("cpu")
1341
+ common_device = cpu
1342
+ common_dtype = None
1343
+ has_different_input_dtypes = False
1344
+ for op in operands:
1345
+ if not isinstance(op, torch.Tensor):
1346
+ # Use elementwise_dtypes for the tricky case
1347
+ has_different_input_dtypes = True
1348
+ continue
1349
+ if common_device == cpu and op.device.type != "cpu":
1350
+ common_device = op.device
1351
+ if common_dtype is None:
1352
+ if type_promotion_kind != ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT:
1353
+ has_different_input_dtypes = True
1354
+ else:
1355
+ common_dtype = op.dtype
1356
+ elif common_dtype != op.dtype:
1357
+ has_different_input_dtypes = True
1358
+
1359
+ if has_different_input_dtypes:
1360
+ # compute promotion
1361
+ # TODO: we don't need the compute type
1362
+ _, common_dtype = elementwise_dtypes(
1363
+ *operands, type_promotion_kind=type_promotion_kind
1364
+ )
1365
+
1366
+ # check all tensors on same device
1367
+ # cpu scalars are assumed allow
1368
+ current_cpu_scalars_on_non_cpu = 0
1369
+ max_cpu_scalars_on_non_cpu = 1 # hard coded atm
1370
+ for op in operands:
1371
+ if not isinstance(op, torch.Tensor):
1372
+ continue
1373
+ if common_device != cpu and op.dim() == 0 and op.device == cpu:
1374
+ if current_cpu_scalars_on_non_cpu >= max_cpu_scalars_on_non_cpu:
1375
+ return slow("error")
1376
+ current_cpu_scalars_on_non_cpu += 1
1377
+ elif op.device != common_device:
1378
+ return slow("error")
1379
+
1380
+ # compute_fast_setup_type
1381
+ definitely_contiguous = True
1382
+ definitely_channels_last = True
1383
+
1384
+ # TODO: is_non-overlapping_and_dense not bound from Python
1385
+ # no inplace, no out, everything defined
1386
+
1387
+ if is_noncontiguous_supported(common_device):
1388
+ for op in operands:
1389
+ if not isinstance(op, torch.Tensor):
1390
+ continue
1391
+ definitely_contiguous = (
1392
+ definitely_contiguous
1393
+ and is_contiguous_for_memory_format_or_false(
1394
+ op, memory_format=torch.contiguous_format
1395
+ )
1396
+ )
1397
+ definitely_channels_last = (
1398
+ definitely_channels_last
1399
+ and is_contiguous_for_memory_format_or_false(
1400
+ op, memory_format=torch.channels_last
1401
+ )
1402
+ )
1403
+ if definitely_contiguous:
1404
+ # do contiguous
1405
+ count_label("fast is_contiguous")
1406
+ return FakeTensor(
1407
+ mode,
1408
+ torch.empty(
1409
+ final_shape,
1410
+ dtype=common_dtype,
1411
+ device="meta",
1412
+ memory_format=torch.contiguous_format,
1413
+ ),
1414
+ device=common_device,
1415
+ )
1416
+ if definitely_channels_last:
1417
+ count_label("fast channels_last")
1418
+ # do channels last
1419
+ return FakeTensor(
1420
+ mode,
1421
+ torch.empty(
1422
+ final_shape,
1423
+ dtype=common_dtype,
1424
+ device="meta",
1425
+ memory_format=torch.channels_last,
1426
+ ),
1427
+ device=common_device,
1428
+ )
1429
+
1430
+ return slow("no contiguity match")
1431
+
1432
+ return fast_binary_impl
1433
+
1434
+
1435
+ # disable the python dispatcher to avoid decomposing detach() further
1436
+ # (proxy_mode should still decompose detach() though)
1437
+ def fast_detach(fake_mode, x, include_real=False):
1438
+ with no_python_dispatcher(), in_kernel_invocation_manager(fake_mode):
1439
+ out = torch.ops.aten.detach.default(x)
1440
+ if include_real:
1441
+ return FakeTensor(fake_mode, out, x.device, real_tensor=x.real_tensor)
1442
+ return FakeTensor(fake_mode, out, x.device)
1443
+
1444
+
1445
+ @functools.cache
1446
+ def get_fast_op_impls():
1447
+ import torch._refs
1448
+
1449
+ register_fast_op_impl(torch.ops.aten.add.Tensor)(
1450
+ make_fast_binary_impl(torch._refs.add)
1451
+ )
1452
+ register_fast_op_impl(torch.ops.aten.sub.Tensor)(
1453
+ make_fast_binary_impl(torch._refs.sub)
1454
+ )
1455
+ register_fast_op_impl(torch.ops.aten.mul.Tensor)(
1456
+ make_fast_binary_impl(torch._refs.mul)
1457
+ ) # type: ignore[has-type]
1458
+ register_fast_op_impl(torch.ops.aten.div.Tensor)(
1459
+ make_fast_binary_impl(
1460
+ torch._refs.div,
1461
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
1462
+ )
1463
+ )
1464
+ register_fast_op_impl(torch.ops.aten.detach.default)(fast_detach)
1465
+ return FAST_OP_IMPLEMENTATIONS
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/fake_utils.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import functools
4
+ import warnings
5
+ from collections.abc import Callable
6
+ from typing import Any, Union
7
+
8
+ import torch
9
+ import torch.utils._pytree as pytree
10
+ from torch._ops import OpOverload
11
+ from torch._subclasses.fake_tensor import (
12
+ FakeTensor,
13
+ FakeTensorMode,
14
+ MetadataMismatchError,
15
+ tree_flatten_only,
16
+ UnsupportedFakeTensorException,
17
+ )
18
+ from torch.utils._python_dispatch import TorchDispatchMode
19
+
20
+
21
+ aten = torch._ops.ops.aten
22
+
23
+
24
+ def outputs_alias_inputs(outputs, inputs):
25
+ input_storages = {
26
+ inp._typed_storage()._cdata
27
+ for inp in tree_flatten_only(torch.Tensor, inputs)
28
+ if torch._C._has_storage(inp)
29
+ }
30
+ return any(
31
+ torch._C._has_storage(out) and out._typed_storage()._cdata in input_storages
32
+ for out in tree_flatten_only(torch.Tensor, outputs)
33
+ )
34
+
35
+
36
+ def outputs_are_inputs(outputs, inputs):
37
+ input_ids = {id(inp) for inp in tree_flatten_only(torch.Tensor, inputs)}
38
+ return any(id(out) in input_ids for out in tree_flatten_only(torch.Tensor, outputs))
39
+
40
+
41
+ def output_alias_each_other(outputs):
42
+ storages = set()
43
+ for out in tree_flatten_only(torch.Tensor, outputs):
44
+ if not torch._C._has_storage(out):
45
+ continue
46
+ stor = out._typed_storage()._cdata
47
+ if stor in storages:
48
+ return True
49
+ storages.add(stor)
50
+ return False
51
+
52
+
53
+ def _check_alias_info(context, real_out, real_in, fake_out, fake_in):
54
+ r_aliasing = outputs_alias_inputs(real_out, real_in)
55
+ f_aliasing = outputs_alias_inputs(fake_out, fake_in)
56
+ if r_aliasing != f_aliasing:
57
+ raise MetadataMismatchError(
58
+ f"{context} mismatch in outputs_alias_inputs check {f_aliasing} != {r_aliasing}"
59
+ )
60
+
61
+ r_identity_eq = outputs_are_inputs(real_out, real_in)
62
+ f_identity_eq = outputs_are_inputs(fake_out, fake_in)
63
+ if r_identity_eq != f_identity_eq:
64
+ raise MetadataMismatchError(
65
+ f"{context} mismatch in outputs_are_inputs check {f_identity_eq} != {r_identity_eq}"
66
+ )
67
+
68
+ r_output_alias_each_other = output_alias_each_other(real_out)
69
+ f_output_alias_each_other = output_alias_each_other(fake_out)
70
+ if r_output_alias_each_other != f_output_alias_each_other:
71
+ raise MetadataMismatchError(
72
+ f"{context} mismatch in outputs_alias_each_other check "
73
+ f"{f_output_alias_each_other} != {r_output_alias_each_other}"
74
+ )
75
+
76
+
77
+ def is_sdpa_error(func, idx, e):
78
+ if (
79
+ (
80
+ func is aten._scaled_dot_product_flash_attention.default
81
+ or func is aten._flash_attention_forward.default
82
+ )
83
+ and idx in (6, 7)
84
+ and "Devices" in repr(e)
85
+ ):
86
+ return True
87
+ if (
88
+ (
89
+ func is aten._scaled_dot_product_efficient_attention.default
90
+ or func is aten._efficient_attention_forward.default
91
+ )
92
+ and idx in (2, 3)
93
+ and "Devices" in repr(e)
94
+ ):
95
+ return True
96
+ if (
97
+ func is aten._scaled_dot_product_cudnn_attention.default
98
+ and idx in (6, 7)
99
+ and "Devices" in repr(e)
100
+ ):
101
+ return True
102
+ return False
103
+
104
+
105
+ def try_convert_fake_to_real(
106
+ ten_list: list[Union[FakeTensor, Any]],
107
+ ) -> list[Union[FakeTensor, torch.Tensor, Any]]:
108
+ """
109
+ Attempt to convert fake tensors to a corresponding real tensor with the correct underlying storage by looking up
110
+ the FakeTensorMode meta to real storage mapping. On failure to find the storage mapping, the FakeTensor will
111
+ remain in the list.
112
+
113
+ Note: this is not currently optimized (makes copies of the meta converter internal dictionaries)
114
+ """
115
+
116
+ fake_tensor = next(
117
+ (item for item in ten_list if isinstance(item, FakeTensor)), None
118
+ )
119
+ if fake_tensor is None:
120
+ return ten_list
121
+
122
+ fake_mode = fake_tensor.fake_mode
123
+ meta_converter = fake_mode.fake_tensor_converter.meta_converter
124
+ desc = meta_converter.describer
125
+
126
+ storage_to_key = {v: k for k, v in meta_converter.storage_memo.items()}
127
+ key_to_real_storage = {v: k for k, v in desc.lookup_storage.items()}
128
+ out = []
129
+ for t in ten_list:
130
+ if not isinstance(t, FakeTensor) or t.layout != torch.strided:
131
+ out.append(t)
132
+ continue
133
+
134
+ key = storage_to_key.get(t.untyped_storage())
135
+ real_storage = None if key is None else key_to_real_storage.get(key)
136
+ if real_storage is None:
137
+ out.append(t)
138
+ continue
139
+
140
+ unhinted = False
141
+
142
+ def map_symint(s):
143
+ nonlocal unhinted
144
+ if not isinstance(s, torch.SymInt):
145
+ return s
146
+ unhinted = unhinted if not unhinted else s.node.has_hint()
147
+ return s.node.hint
148
+
149
+ stor_offset = map_symint(t.storage_offset())
150
+ size = [map_symint(s) for s in t.shape]
151
+ stride = [map_symint(s) for s in t.stride()]
152
+
153
+ if unhinted:
154
+ out.append(t)
155
+ continue
156
+
157
+ new_tensor = torch.empty(
158
+ [],
159
+ dtype=t.dtype,
160
+ device=t.device,
161
+ )
162
+ new_tensor.set_(
163
+ real_storage,
164
+ storage_offset=stor_offset,
165
+ size=size,
166
+ stride=stride,
167
+ )
168
+ out.append(new_tensor.clone())
169
+
170
+ return out
171
+
172
+
173
+ def _check_fake_real_tensors(
174
+ real_out: torch.Tensor,
175
+ fake_out: FakeTensor,
176
+ context="",
177
+ sizes=True,
178
+ strides=False,
179
+ storage_offset=True,
180
+ requires_grad=True,
181
+ ):
182
+ if requires_grad:
183
+ if real_out.requires_grad != fake_out.requires_grad:
184
+ raise MetadataMismatchError(
185
+ f"{context} mismatched requires_grad-ness of outputs. "
186
+ f"This usually means that you have added autograd support "
187
+ f"for your operator at a dispatch key other than Autograd, "
188
+ f"which will lead to problems"
189
+ )
190
+
191
+ if torch._C._has_storage(real_out):
192
+ r_offset = real_out.storage_offset()
193
+ f_offset = fake_out.storage_offset()
194
+ if r_offset != f_offset:
195
+ raise MetadataMismatchError(f"{context} mismatched storage offset")
196
+
197
+ torch._prims.utils.compare_tensor_meta(
198
+ real_out,
199
+ fake_out,
200
+ check_sizes=sizes,
201
+ check_strides=strides,
202
+ allow_rhs_unbacked=True,
203
+ )
204
+
205
+
206
+ class CrossRefFakeMode(TorchDispatchMode):
207
+ def __init__(
208
+ self,
209
+ ignore_op_fn: Union[Callable[[OpOverload], bool], None] = None,
210
+ *,
211
+ check_strides=True,
212
+ check_aliasing=True,
213
+ only_check_ops_with_meta=True,
214
+ ):
215
+ super().__init__()
216
+ self.ignore_op_fn = (
217
+ ignore_op_fn if ignore_op_fn is not None else lambda fn: False
218
+ )
219
+ self.check_strides = check_strides
220
+ self.check_aliasing = check_aliasing
221
+ self.only_check_ops_with_meta = only_check_ops_with_meta
222
+
223
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):
224
+ kwargs = kwargs or {}
225
+
226
+ fake_r = None
227
+
228
+ # empty_like excluded for now due to sparse complex
229
+ # aten._to_dense.default this one is getting called with csc
230
+ if (
231
+ func
232
+ not in (
233
+ aten.lift_fresh.default,
234
+ aten.lift_fresh_copy.default,
235
+ aten.set_.source_Storage_storage_offset,
236
+ )
237
+ and not self.ignore_op_fn(func)
238
+ and (
239
+ not self.only_check_ops_with_meta
240
+ or torch._subclasses.fake_impls.has_meta(func)
241
+ )
242
+ and torch.Tag.dynamic_output_shape not in func.tags
243
+ and torch.Tag.inplace_view not in func.tags
244
+ and torch.Tag.data_dependent_output not in func.tags
245
+ ):
246
+ # Do not import symbolic_shapes at the top of the module as it imports sympy and that's slow
247
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv
248
+
249
+ try:
250
+ # TODO: enable_python_dispatcher() here
251
+ with FakeTensorMode(shape_env=ShapeEnv()) as fake_mode:
252
+ fake_args, fake_kwargs = pytree.tree_map_only(
253
+ torch.Tensor,
254
+ functools.partial(fake_mode.from_tensor, static_shapes=True),
255
+ (args, kwargs),
256
+ )
257
+ with warnings.catch_warnings():
258
+ fake_r = func(*fake_args, **fake_kwargs)
259
+ except UnsupportedFakeTensorException:
260
+ pass
261
+
262
+ context = (
263
+ f"When comparing the output of {func} on FakeTensor and concrete Tensors, "
264
+ f"found"
265
+ )
266
+ r = func(*args, **kwargs)
267
+ if fake_r is not None:
268
+ r_flat = pytree.tree_leaves(r)
269
+ f_flat = pytree.tree_leaves(fake_r)
270
+ assert len(f_flat) == len(r_flat), (
271
+ f"{context} mismatch in number of returns {len(f_flat)} != {len(r_flat)}"
272
+ )
273
+
274
+ if self.check_aliasing:
275
+ _check_alias_info(
276
+ context, r, (args, kwargs), fake_r, (fake_args, fake_kwargs)
277
+ )
278
+
279
+ for idx, (r_out, f_out) in enumerate(
280
+ zip(pytree.tree_leaves(r), pytree.tree_leaves(fake_r))
281
+ ):
282
+ r_is_ten = isinstance(r_out, torch.Tensor)
283
+ assert r_is_ten == isinstance(f_out, torch.Tensor), (
284
+ f"{context} mismatched number of tensor outputs"
285
+ )
286
+ if r_is_ten:
287
+ try:
288
+ _check_fake_real_tensors(
289
+ r_out,
290
+ f_out,
291
+ sizes=True,
292
+ strides=self.check_strides,
293
+ storage_offset=True,
294
+ requires_grad=True,
295
+ )
296
+ except Exception as e:
297
+ if is_sdpa_error(func, idx, e):
298
+ continue
299
+ error_message = (
300
+ f"{context} mismatched tensor metadata: {e}"
301
+ if len(r_flat) == 1
302
+ else f"{context} mismatched tensor metadata for output[{idx}]: {e}"
303
+ )
304
+ raise MetadataMismatchError(error_message) from e
305
+ return r
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/functional_tensor.py ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import warnings
4
+ import weakref
5
+ from abc import ABC, abstractmethod
6
+ from collections.abc import Callable
7
+ from contextlib import AbstractContextManager
8
+ from typing import Any, Optional, Union
9
+
10
+ import torch
11
+ import torch.fx.traceback as fx_traceback
12
+ import torch.utils._pytree as pytree
13
+ from torch._C import _functionalization_reapply_views_tls as _reapply_views
14
+ from torch._ops import _get_dispatch_mode_pre_dispatch, TorchBindOpOverload
15
+ from torch._subclasses.meta_utils import is_sparse_any
16
+ from torch.utils._python_dispatch import (
17
+ _detect_infra_mode,
18
+ _disable_infra_mode,
19
+ autograd_would_have_decomposed,
20
+ return_and_correct_aliasing,
21
+ TorchDispatchMode,
22
+ )
23
+
24
+
25
+ not_implemented_log = torch._logging.getArtifactLogger(__name__, "not_implemented")
26
+
27
+
28
+ # NOTE Some special handling for tensor conversion during export is needed.
29
+ # Normally, when tracing through the model with tensor.to(), the maybe-aliasing
30
+ # relationship between input and output tensors will be baked into the graph.
31
+ # For example, if we got a tensor with device cpu and call tensor.to("cpu"),
32
+ # it will become a no-op in the graph. For a whole graph capture, this is not
33
+ # sound so we need to do something different. Instead, in export we will try to
34
+ # preserve the tensor conversion by forcing a non-semantic-breaking aten::_to_copy
35
+ # operator to be traced in the graph, and subsequently banning mutations on all
36
+ # such converted tensors.
37
+ # In addition to patching .to() method call in functionalization, we will have to
38
+ # patch other similar methods like float() and cpu(), because they intentionally
39
+ # don't fall back to .to() methods, but have the same behavior as .to() according to
40
+ # pytorch document. https://pytorch.org/docs/stable/generated/torch.Tensor.float.html
41
+ # thus we simply force them to go through .to() call.
42
+ def _conversion_method_template(**extra_kwargs):
43
+ def _(self, *args, **kwargs):
44
+ return self.to(*args, **{**kwargs, **extra_kwargs})
45
+
46
+ return _
47
+
48
+
49
+ class FunctionalTensor(torch.Tensor):
50
+ """
51
+ Functional tensors represent tensors that will remove mutations
52
+ from a program. If you perform a mutable operation on a functional tensor,
53
+ it will re-dispatch to the functional variant of that operation.
54
+
55
+ Historically, functionalization is implemented in C++ in the dispatcher.
56
+ This class is a lightweight python shim around the C++ functionalization logic.
57
+
58
+ FunctionalTensor is required to be used with a corresponding
59
+ FunctionalTensormode active, because it relies
60
+ on using the mode for dispatch (which can properly handle factory functions).
61
+ """
62
+
63
+ elem: torch.Tensor
64
+ # Indicates to our torch_dispatch dispatching infra that
65
+ # this is an "infra" mode with lower dispatching precedence.
66
+ _mode_key = torch._C._TorchDispatchModeKey.FUNCTIONAL
67
+
68
+ # Note: The reason we add these extra keys to our FunctionalTensor subclass
69
+ # is to mirror the behavior of C++ functionalization (we can choose to change this
70
+ # later, as long as it doesn't break anything).
71
+ # FunctionalTensorWrapper copies **all** dispatch keys from the inner tensor
72
+ # to the wrapper, excluding functorch and python dispatch keys.
73
+ # Here I'm trying to reuse the keyset the functorch wrapper subclasses copy,
74
+ # except that they don't include ZeroTensor so I'm manually adding it in.
75
+ _extra_dispatch_keys = torch._C._additional_keys_to_prop_for_wrapper_tensors.add(
76
+ torch._C.DispatchKey.ZeroTensor
77
+ )
78
+
79
+ # These are all aten ops that correspond to metadata queries.
80
+ # We want FunctionalTensor to be able to handle them directly.
81
+ metadata_fns = [
82
+ torch.ops.aten.is_contiguous.default, # type: ignore[has-type]
83
+ torch.ops.aten.is_contiguous.memory_format, # type: ignore[has-type]
84
+ torch.ops.aten.is_strides_like_format.default, # type: ignore[has-type]
85
+ torch.ops.aten.is_non_overlapping_and_dense.default, # type: ignore[has-type]
86
+ torch.ops.aten.size.default, # type: ignore[has-type]
87
+ torch.ops.aten.sym_size.default, # type: ignore[has-type]
88
+ torch.ops.aten.stride.default, # type: ignore[has-type]
89
+ torch.ops.aten.sym_stride.default, # type: ignore[has-type]
90
+ torch.ops.aten.storage_offset.default, # type: ignore[has-type]
91
+ torch.ops.aten.sym_storage_offset.default, # type: ignore[has-type]
92
+ torch.ops.aten.numel.default, # type: ignore[has-type]
93
+ torch.ops.aten.sym_numel.default, # type: ignore[has-type]
94
+ torch.ops.aten.dim.default, # type: ignore[has-type]
95
+ torch.ops.prim.device.default, # type: ignore[has-type]
96
+ ]
97
+
98
+ # Used by auto_functionalize to determine base of tensors during inference mode.
99
+ _inference_mode_base: Optional["FunctionalTensor"] = None
100
+
101
+ def __new__(cls, elem, mode):
102
+ assert torch._is_functional_tensor(elem)
103
+
104
+ # In general, we'd like our functional tensor subclass to only be in charge of functionalization,
105
+ # and defer to the inner subclass for all other functionality.
106
+ # Example: If our inner tensor is a ZeroTensor, we would want to defer running the ZeroTensor fallback
107
+ # until after we redispatch to our inner ZeroTensor.
108
+ # However, there are a few keys that we need to mirror between the inner and outer tensors.
109
+ # Conjugate
110
+ # Negative
111
+ # Why? These keys are used to test metadata queries, like `.is_conj()` and `.is_neg()`.
112
+ # We **need** calls to is_conj() to return the same thing on the outer and inner tensors,
113
+ # Because user code / framework code that branches like so needs to do the same thing
114
+ # when it sees the outer FunctionalTensor:
115
+ # if (x.is_conj()) {
116
+ # return at::view_as_real(x.resolve_conj());
117
+ # } else {
118
+ # return at::view_as_real(x);
119
+ # }
120
+ extra_dispatch_keys = (
121
+ FunctionalTensor._extra_dispatch_keys & torch._C._dispatch_keys(elem)
122
+ )
123
+
124
+ out = torch.Tensor._make_wrapper_subclass(
125
+ # TODO: right now, _make_wrapper_subclass's dynamic shape interaction is not great.
126
+ # Calling the overload that has kwargs causes us to go down the first overload path,
127
+ # which will **always** specialize sizes.
128
+ # We should probably eventually fix this so that the first overload can just handle dynamic shapes.
129
+ cls,
130
+ elem.shape, # sizes
131
+ elem.stride() if not is_sparse_any(elem) else None, # strides
132
+ (
133
+ elem.storage_offset() if not is_sparse_any(elem) else None
134
+ ), # storage_offset
135
+ None, # memory_format
136
+ elem.dtype, # dtype
137
+ elem.layout, # layout
138
+ elem.device, # device
139
+ False, # pin_memory
140
+ elem.requires_grad, # requires_grad
141
+ None, # dispatch_sizes_strides_policy
142
+ False, # dispatch_device
143
+ False, # dispatch_layout
144
+ extra_dispatch_keys, # _extra_dispatch_keys
145
+ )
146
+ torch._C._set_throw_on_mutable_data_ptr(out)
147
+ out.elem = elem
148
+
149
+ if (
150
+ torch._export.config.enable_auto_functionalized_v2_for_export
151
+ and torch.is_inference_mode_enabled()
152
+ and torch._inductor.config.enable_auto_functionalized_v2
153
+ ):
154
+ if out.is_base_tensor():
155
+ out._inference_mode_base = None
156
+ # This assumes that the FunctionalTensor.elem does not change its storage after this point.
157
+ # Otherwise this would be invalid.
158
+ mode._storage_to_base[out.elem.untyped_storage()] = out
159
+ else:
160
+ out._inference_mode_base = mode._storage_to_base[
161
+ out.elem.untyped_storage()
162
+ ]
163
+ assert out._inference_mode_base is not None
164
+ return out
165
+
166
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None): # type: ignore[override]
167
+ unrecognized_types = [
168
+ t
169
+ for t in types
170
+ if t not in [torch.Tensor, torch._subclasses.FakeTensor, FunctionalTensor]
171
+ ]
172
+ if unrecognized_types:
173
+ not_implemented_log.debug(
174
+ "FunctionalTensor unrecognized subclass(es): %s", unrecognized_types
175
+ )
176
+ return NotImplemented
177
+
178
+ if kwargs is None:
179
+ kwargs = {}
180
+
181
+ # FunctionalTensor needs to plumb all metadata requests to the inner tensor.
182
+ # In theory we don't have to do this - but if we want to service metadata requests here,
183
+ # we need to carefully make sure all metadata is accurate (including metadata mutations)
184
+ if func in FunctionalTensor.metadata_fns:
185
+ # All metadata accesses should be plumbed to the inner tensor, that way we don't have to worry
186
+ # about the problem of keeping metadata in sync between the wrapper and inner tensor.
187
+ # This also alleviates us from having to manually handle metadata mutations on the wrapper.
188
+ assert len(kwargs) == 0
189
+ if func in [
190
+ torch.ops.aten.is_strides_like_format.default,
191
+ torch.ops.aten.is_contiguous.memory_format,
192
+ ]:
193
+ assert len(args) == 2 and isinstance(args[0], FunctionalTensor)
194
+ return func(torch._from_functional_tensor(args[0].elem), args[1])
195
+ assert len(args) == 1 and isinstance(args[0], FunctionalTensor)
196
+
197
+ return func(torch._from_functional_tensor(args[0].elem))
198
+ # Originally I tried to implement my subclass without giving it a torch_dispatch, but I gave up:
199
+ # - _make_wrapper_subclass requires a __torch_dispatch__
200
+ # - If we want to use _make_subclass(), we have a problem: the subclass will share a TensorImpl with the inner tensor,
201
+ # which is of type FunctionalTensorWrapper! We explicitly do not want our wrapper to be a FunctionalTensorWrapper.
202
+ # - If we use the default tensor.__new__(), we have another problem: it returns inner_tensor.alias(),
203
+ # which causes every subclass created above autograd to have autograd view metadata
204
+ # (in addition to also being a FunctionalTensorWrapper).
205
+ raise RuntimeError(
206
+ "Attempting to use FunctionalTensor on its own. Instead, please use it with a corresponding FunctionalTensorMode()"
207
+ )
208
+
209
+ def __repr__(self) -> str: # type: ignore[override]
210
+ return f"FunctionalTensor({repr(self.elem)})"
211
+
212
+ @staticmethod
213
+ def to_functional(x):
214
+ # We will do the wrapping for the user.
215
+
216
+ assert not torch._is_functional_tensor(x)
217
+ # The only autograd metadata we care about on the FunctionalTensor is:
218
+ # - requires_grad (so autograd runs)
219
+ # - is_leaf (so that mutations on graph inputs that are not leaves are allowed by the autograd engine)
220
+ # this is handled by FunctionalTensor.to_functional
221
+ x_functional = torch._to_functional_tensor(x)
222
+ # Technically the FunctionalTensormode here is unnecessary,
223
+ # but it avoids spurious NotImplemented logs during `ProxyTorchDispatchMode` tracing.
224
+ # _mirror_autograd_meta_to queries tensor sizes,
225
+ # and otherwise the sym_size() call will go to the proxy mode before hitting
226
+ # FunctionalTensor.__torch_dispatch__
227
+
228
+ functional_mode = _detect_infra_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL)
229
+ assert functional_mode is not None
230
+
231
+ with functional_mode:
232
+ torch._mirror_autograd_meta_to(x, x_functional) # type: ignore[attr-defined]
233
+ out = FunctionalTensor(x_functional, functional_mode)
234
+ torch._mirror_autograd_meta_to(x_functional, out) # type: ignore[attr-defined]
235
+ return out
236
+
237
+ def from_functional(self):
238
+ torch._sync(self)
239
+ return torch._from_functional_tensor(self.elem)
240
+
241
+ def is_base_tensor(self) -> bool:
242
+ return torch._is_functional_tensor_base(self.elem)
243
+
244
+ def replace_(self, output) -> None:
245
+ torch._functionalize_replace(self.elem, output)
246
+
247
+ def commit_update(self) -> None:
248
+ torch._functionalize_commit_update(self.elem)
249
+
250
+ def sync(self) -> None:
251
+ torch._functionalize_sync(self.elem)
252
+
253
+ def mark_mutation_hidden_from_autograd(self) -> None:
254
+ torch._functionalize_mark_mutation_hidden_from_autograd(self.elem)
255
+
256
+ def tolist(self) -> Any:
257
+ if self.elem.dim() == 0:
258
+ return self.elem.item()
259
+ elif self.elem.dim() == 1:
260
+ return [elem.item() for elem in self.elem]
261
+ else:
262
+ return [elem.tolist() for elem in self.elem]
263
+
264
+ def to(self, *args, **kwargs):
265
+ if _detect_infra_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL).export:
266
+ torch.ops.aten._assert_tensor_metadata(
267
+ self,
268
+ dtype=self.dtype,
269
+ device=self.device,
270
+ layout=self.layout,
271
+ )
272
+ # pyrefly: ignore [not-iterable]
273
+ return super().to(*args, **kwargs)
274
+
275
+ def cuda(self, device=None, *args, **kwargs):
276
+ device = device or torch.cuda.current_device()
277
+ if len(args) > 0:
278
+ return self.to(device, *args, **kwargs)
279
+ else:
280
+ return self.to(device=device, **kwargs)
281
+
282
+ char = _conversion_method_template(dtype=torch.int8)
283
+ cpu = _conversion_method_template(device=torch.device("cpu"))
284
+ bfloat16 = _conversion_method_template(dtype=torch.bfloat16)
285
+ byte = _conversion_method_template(dtype=torch.uint8)
286
+ double = _conversion_method_template(dtype=torch.float64)
287
+ float = _conversion_method_template(dtype=torch.float32)
288
+ bool = _conversion_method_template(dtype=torch.bool)
289
+ half = _conversion_method_template(dtype=torch.float16)
290
+ int = _conversion_method_template(dtype=torch.int32)
291
+ long = _conversion_method_template(dtype=torch.int64)
292
+
293
+ # TODO(sparse-team): fixes #133174 but can we do without the relay?
294
+ def to_dense(self): # type: ignore[override]
295
+ return self.elem.to_dense()
296
+
297
+ @property
298
+ def layout(self): # type: ignore[override]
299
+ return self.elem.layout
300
+
301
+ def __bool__(self):
302
+ return bool(self.item())
303
+
304
+
305
+ class FunctionalTensorMode(TorchDispatchMode):
306
+ def __init__(self, pre_dispatch=False, export=False, _allow_token_discovery=False):
307
+ super().__init__()
308
+ self.export = export
309
+ self.is_on_stack = False
310
+ self.enter_stack = []
311
+ # Indicates to our torch_dispatch dispatching infra that
312
+ # this is an "infra" mode with lower dispatching precedence.
313
+ self._mode_key = torch._C._TorchDispatchModeKey.FUNCTIONAL
314
+ self.pre_dispatch = pre_dispatch
315
+ # This will be turned off later for pre-dispatch functionalization
316
+ self._dispatch_key = torch._C.DispatchKey.PreDispatch if pre_dispatch else None # type: ignore[attr-defined]
317
+ # Map of effect type (ex. _EffectType.ORDERED) to a token. The tokens help keep
318
+ # track of the ordering between side effectful operations.
319
+ self._tokens: dict[Any, torch.Tensor] = {}
320
+
321
+ # Filled after forward tracing.
322
+ self._tokens_forward_output: dict[Any, torch.Tensor] = {}
323
+
324
+ # Functionalization runs twice in AOTAutograd, once in
325
+ # `run_functionalized_fw_and_collect_metadata` to collect metadata to
326
+ # see which tensors need to be functionalized and discover how many
327
+ # tokens we need, and another time in `make_fx` which does the actual
328
+ # tracing to replace ops with their functional variants and handling
329
+ # side-effectful ops. In the second stage there should be no token
330
+ # discovery. This flag distinguishes between the two stages.
331
+ self._allow_token_discovery = _allow_token_discovery
332
+
333
+ self._storage_to_base: weakref.WeakKeyDictionary[
334
+ torch.storage.UntypedStorage, Optional[FunctionalTensor]
335
+ ] = weakref.WeakKeyDictionary()
336
+
337
+ # No-op if FunctionalTensorMode is already in use
338
+ def __enter__(self):
339
+ def _get_prev_mode():
340
+ if self._dispatch_key == torch._C.DispatchKey.PreDispatch:
341
+ return _get_dispatch_mode_pre_dispatch(
342
+ torch._C._TorchDispatchModeKey.FUNCTIONAL
343
+ )
344
+ return torch._C._get_dispatch_mode(
345
+ torch._C._TorchDispatchModeKey.FUNCTIONAL
346
+ )
347
+
348
+ if _get_prev_mode() is None:
349
+ self.enter_stack.append(True)
350
+ return super().__enter__()
351
+ else:
352
+ self.enter_stack.append(False)
353
+ return self
354
+
355
+ def __exit__(self, a, b, c):
356
+ is_on_stack = self.enter_stack.pop()
357
+ if is_on_stack:
358
+ super().__exit__(a, b, c)
359
+
360
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):
361
+ if kwargs is None:
362
+ kwargs = {}
363
+
364
+ unrecognized_types = [
365
+ t
366
+ for t in types
367
+ if not issubclass(t, torch._subclasses.FakeTensor)
368
+ and t not in [torch.Tensor, FunctionalTensor]
369
+ ]
370
+
371
+ if unrecognized_types:
372
+ not_implemented_log.debug(
373
+ "FunctionalTensor unrecognized subclass(es): %s", unrecognized_types
374
+ )
375
+ return NotImplemented
376
+
377
+ def _can_decompose(func):
378
+ # See https://github.com/pytorch/pytorch/pull/115258#issuecomment-1900755832
379
+ # Never decompose dropout in export
380
+ if self.export and func is torch.ops.aten.dropout.default:
381
+ return False
382
+
383
+ # We unconditionally decompose ops that are maybe aliasing or mutating ops
384
+ from torch._decomp import _should_decompose_because_unsafe_op
385
+
386
+ if _should_decompose_because_unsafe_op(func):
387
+ return True
388
+
389
+ # (1) we unconditionally decompose maybe-aliasing or maybe-mutating ops,
390
+ # because we must know statically of an op mutates or aliasing in order to functionalize it properly
391
+ # (2) for mutating ops that have CompositeImplicit decomps, we choose to decompose them today.
392
+ # In theory, we could walk this back and avoid decomposing them later if we need to.
393
+ alias_info_present = any(arg.alias_info for arg in func._schema.arguments)
394
+ if alias_info_present or func._schema.is_mutable:
395
+ return True
396
+
397
+ # If we are here, it means we are seeing functional composite op.
398
+ # For pre-dispatch IR, we don't want to decompose this op
399
+ # For post-dispatch IR, we do want to decompose this op. it is fine
400
+ # to decompose here even if you want to preserve a CIA in post-dispatch export
401
+ # because we already override decompose behaviour so it will do the
402
+ # right thing.
403
+ if self.export:
404
+ if self.pre_dispatch:
405
+ # If it is CIA custom op, we warn that we are assuming this op is indeed functional.
406
+ if func.namespace not in ["aten", "prim"] and func._can_decompose():
407
+ warnings.warn(
408
+ f"At pre-dispatch tracing, we assume that any custom op marked with "
409
+ f"CompositeImplicitAutograd and have functional schema are safe to not decompose. "
410
+ f"Found {func} to be one such op.",
411
+ stacklevel=2,
412
+ )
413
+ return False
414
+ return True
415
+
416
+ # in normal torch.compile IR, we only decompose an op if autograd
417
+ # would have decomposed it (NB: autograd may have been skipped if
418
+ # we are in inference mode)
419
+ # TODO: the flatten here can potentially be deduped with the
420
+ # unwrapping pytree_map later
421
+ flat_args_kwargs, _ = pytree.tree_flatten((args, kwargs))
422
+ return autograd_would_have_decomposed(func, flat_args_kwargs)
423
+
424
+ if (
425
+ func not in FunctionalTensor.metadata_fns
426
+ and _can_decompose(func)
427
+ # Not all funcs from __torch_dispatch__ are actual dispatcher ops,
428
+ # e.g. prim.device
429
+ and torch._C._dispatch_has_kernel(func.name())
430
+ ):
431
+ with self:
432
+ r = func.decompose(*args, **kwargs)
433
+ if r is not NotImplemented:
434
+ return r
435
+
436
+ def wrap(x):
437
+ # Only wrap our outputs in subclasses if the inner functionalization call
438
+ # also wrapped outputs into FunctionalTensorWrappers.
439
+ # When can this happen? e.g. `torch.div(2, 2)`
440
+ assert not isinstance(x, FunctionalTensor)
441
+ if isinstance(x, torch.Tensor) and torch._is_functional_tensor(x):
442
+ return FunctionalTensor(x, self)
443
+ return x
444
+
445
+ def unwrap(x):
446
+ return x.elem
447
+
448
+ from torch._higher_order_ops.auto_functionalize import (
449
+ can_auto_functionalize,
450
+ do_auto_functionalize,
451
+ do_auto_functionalize_v2,
452
+ )
453
+
454
+ if can_auto_functionalize(
455
+ func
456
+ ) and not torch._C._dispatch_has_kernel_for_dispatch_key(
457
+ func.name(), torch._C.DispatchKey.Functionalize
458
+ ):
459
+ import torch._export.config as export_config
460
+ import torch._inductor.config as inductor_config
461
+
462
+ if torch.compiler.is_exporting():
463
+ if export_config.enable_auto_functionalized_v2_for_export:
464
+ return do_auto_functionalize_v2(self, func, args, kwargs)
465
+
466
+ return do_auto_functionalize(self, func, args, kwargs)
467
+
468
+ if inductor_config.enable_auto_functionalized_v2:
469
+ return do_auto_functionalize_v2(self, func, args, kwargs)
470
+ return do_auto_functionalize(self, func, args, kwargs)
471
+
472
+ from torch._higher_order_ops.effects import handle_effects, has_effects
473
+
474
+ if has_effects(func):
475
+ assert not torch._C._dispatch_has_kernel_for_dispatch_key(
476
+ func.name(), torch._C.DispatchKey.Functionalize
477
+ )
478
+ return handle_effects(
479
+ self._allow_token_discovery, self._tokens, func, args, kwargs
480
+ )
481
+
482
+ args_unwrapped, kwargs_unwrapped = pytree.tree_map_only(
483
+ FunctionalTensor, unwrap, (args, kwargs)
484
+ )
485
+
486
+ # Expectation: functionalization should not **already** be enabled above our mode.
487
+ # Why would that be bad? when we return a FunctionalTensor here, we don't want functionalization
488
+ # to run above this mode and further wrap that output in **another** C++ FunctionalTensorWrapper.
489
+ is_included = torch._C._dispatch_tls_is_dispatch_key_included(
490
+ torch._C.DispatchKey.Functionalize
491
+ )
492
+ is_excluded = torch._C._dispatch_tls_is_dispatch_key_excluded(
493
+ torch._C.DispatchKey.Functionalize
494
+ )
495
+ assert is_excluded or not is_included
496
+ include_to_set = (
497
+ torch._C._dispatch_tls_local_include_set()
498
+ | torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
499
+ )
500
+ exclude_to_set = (
501
+ torch._C._dispatch_tls_local_exclude_set().remove(
502
+ torch._C.DispatchKey.Functionalize
503
+ )
504
+ - FunctionalTensor._extra_dispatch_keys
505
+ )
506
+
507
+ if isinstance(func, TorchBindOpOverload):
508
+ # When the function is a TorchBindOpOverload, meaning some of the
509
+ # inputs are FakeScriptObjects, we need to skip c++ dispatcher and
510
+ # dispatch in python because C++ dispatcher will check the schema
511
+ # and cannot recognize FakeScriptObject.
512
+ ctx = PythonFunctionalizeAPI()
513
+ fully_unwrapped_args = ctx.unwrap_tensors(args)
514
+ fully_unwrapped_kwargs = ctx.unwrap_tensors(
515
+ kwargs # pyrefly: ignore[bad-argument-type]
516
+ )
517
+ outs_unwrapped = func(
518
+ *fully_unwrapped_args,
519
+ **fully_unwrapped_kwargs,
520
+ )
521
+ outs_wrapped = ctx.wrap_tensors(outs_unwrapped)
522
+ else:
523
+ # All we want to do here is reuse the existing C++ functionalization logic.
524
+ # This requires swizzling our TLS dispatch keys so that the Functionalize key is active.
525
+ with torch._C._ForceDispatchKeyGuard(include_to_set, exclude_to_set):
526
+ try:
527
+ # By default for python functionalization (for AOTAutograd), we reapply views.
528
+ old_apply_views = torch._functionalize_enable_reapply_views(True) # type: ignore[attr-defined]
529
+
530
+ # Sometimes these functions cannot be directly dispatched to functionalize key
531
+ # because args are sometimes not functional tensors for some reason?
532
+ if func in FunctionalTensor.metadata_fns:
533
+ outs_unwrapped = func(*args_unwrapped, **kwargs_unwrapped)
534
+ outs_wrapped = pytree.tree_map_only(
535
+ torch.Tensor, wrap, outs_unwrapped
536
+ )
537
+ else:
538
+ # Note: [Functionalization View Replay Annotation]
539
+ # When functionalization encounters a mutation, it handles aliases by lazily regenerating the aliases
540
+ # at the first time they are next used.
541
+ # This is a problem when plumbing user annotations during tracing. We want the view ops from view replay
542
+ # to have the same annotation that the user specified on the original views. But view replay in
543
+ # functionalization happens the next time the alias is used (e.g. second_op(alias_with_pending_mutation)),
544
+ # so when we regenerate views before calling into second_op, those views will end up getting the metadata
545
+ # for second_op!
546
+ #
547
+ # Instead, we need to remember the node metadata from the original views, and ensure that this node metadata
548
+ # is globally set when we lazily perform view replay.
549
+ # The globally set metadata will be used to populate the fx node created for the replayed operation.
550
+ if m := torch._C._get_dispatch_mode(
551
+ torch._C._TorchDispatchModeKey.PROXY
552
+ ):
553
+ for a in pytree.tree_leaves([args, kwargs]):
554
+ if not isinstance(a, FunctionalTensor):
555
+ continue
556
+ curr_node = m.tracer.tensor_tracker[
557
+ torch._from_functional_tensor(a.elem)
558
+ ].proxy.node
559
+ with fx_traceback.set_current_replay_node(curr_node):
560
+ torch._sync(a)
561
+
562
+ # When we dispatch to the C++ functionalization kernel, we might need to jump back to the
563
+ # PreDispatch mode stack afterwards, to handle any other PreDispatch modes underneath
564
+ # FunctionalTensorMode. If we call func() directly, we would need to exclude PreDispatch
565
+ # from the TLS in order to avoid infinite looping, but this would prevent us from coming
566
+ # back to PreDispatch later
567
+ outs_unwrapped = func._op_dk(
568
+ torch._C.DispatchKey.Functionalize,
569
+ *args_unwrapped,
570
+ **kwargs_unwrapped,
571
+ )
572
+
573
+ if self.export:
574
+ if func is torch.ops.aten.dropout.default:
575
+ torch._freeze_functional_tensor(outs_unwrapped) # type: ignore[attr-defined]
576
+ outs_wrapped = pytree.tree_map_only(
577
+ torch.Tensor, wrap, outs_unwrapped
578
+ )
579
+ finally:
580
+ torch._disable_functionalization()
581
+ torch._functionalize_enable_reapply_views(old_apply_views) # type: ignore[attr-defined]
582
+
583
+ is_included = torch._C._dispatch_tls_is_dispatch_key_included(
584
+ torch._C.DispatchKey.Functionalize
585
+ )
586
+ is_excluded = torch._C._dispatch_tls_is_dispatch_key_excluded(
587
+ torch._C.DispatchKey.Functionalize
588
+ )
589
+ assert is_excluded or not is_included
590
+
591
+ if (
592
+ # If no outputs are our functional subclass, then don't try to fix up aliasing
593
+ not any(
594
+ isinstance(x, FunctionalTensor)
595
+ for x in pytree.tree_leaves(outs_wrapped)
596
+ )
597
+ # Since lift_fresh lifts its argument into a functional tensor, we can skip the
598
+ # aliasing correction step. Otherwise, we would be setting the storage of a
599
+ # lifted tensor to that of an unlifted tensor.
600
+ # Ref: https://github.com/pytorch/pytorch/issues/111506
601
+ or func is torch.ops.aten.lift_fresh.default
602
+ ):
603
+ return outs_wrapped
604
+ # for metadata mutations, need to manually mutate the metadata of the FunctionalTensor wrapper
605
+ if (
606
+ torch.Tag.inplace_view in func.tags
607
+ and func is not torch.ops.aten.set_.source_Tensor
608
+ ):
609
+ with torch.utils._mode_utils.no_dispatch():
610
+ func(*args, **kwargs)
611
+ # Wrapper tensor subclasses do not have correct aliasing info! Use this util to manually correct the output aliasing.
612
+ # inplace ops like `aten.add_()` are expected to return inputs **directly**, instead of creating fresh tensor objects.
613
+ # Use this util to figure out the right thing to return.
614
+ # If none of our inputs were wrapped, then we have no FunctionalTensor outputs that we need to fix up storages for.
615
+ return return_and_correct_aliasing(func, args, kwargs, outs_wrapped)
616
+
617
+ @classmethod
618
+ def is_infra_mode(cls) -> bool:
619
+ return True
620
+
621
+
622
+ @contextlib.contextmanager
623
+ def disable_functional_mode():
624
+ return _disable_infra_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL)
625
+
626
+
627
+ # This is similar to torch.func.functionalize, but:
628
+ # - It uses FunctionalTensorMode, and FunctionalTensor (a python subclass).
629
+ # One important advantage to using this mode is that it will let us
630
+ # run functionalization underneath __torch_dispatch__,
631
+ # which we need in AOTAutograd.
632
+ # - Doing so means that it does not automatically compose with other
633
+ # functorch transforms, since these transforms always run above __torch_dispatch__.
634
+ # That's why this util lives here, and not in functorch.
635
+ def dispatch_functionalize(func, mode: FunctionalTensorMode = FunctionalTensorMode()):
636
+ # TODO: pull these from aot autograd
637
+ def to_fun(t):
638
+ if isinstance(t, torch.Tensor):
639
+ return FunctionalTensor.to_functional(t)
640
+ return t
641
+
642
+ def from_fun(t):
643
+ if not isinstance(t, FunctionalTensor):
644
+ # quick sanity assert
645
+ if isinstance(t, torch.Tensor):
646
+ assert not torch._is_functional_tensor(t)
647
+ return t
648
+ torch._sync(t)
649
+ return torch._from_functional_tensor(t.elem)
650
+
651
+ def inner(*args, **kwargs):
652
+ disable_above = torch._C._ExcludeDispatchKeyGuard(
653
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
654
+ )
655
+ with disable_above, mode:
656
+ func_args = pytree.tree_map_only(torch.Tensor, to_fun, args)
657
+ func_kwargs = pytree.tree_map_only(torch.Tensor, to_fun, kwargs)
658
+ func_outputs = func(*func_args, **func_kwargs)
659
+ outputs = pytree.tree_map_only(FunctionalTensor, from_fun, func_outputs)
660
+
661
+ return outputs
662
+
663
+ return inner
664
+
665
+
666
+ class BaseFunctionalizeAPI(ABC):
667
+ @abstractmethod
668
+ def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]:
669
+ pass
670
+
671
+ @abstractmethod
672
+ def unwrap_tensors(
673
+ self, args: Union[torch.Tensor, tuple[torch.Tensor, ...]]
674
+ ) -> Any:
675
+ pass
676
+
677
+ @abstractmethod
678
+ def functionalize(self, inner_f: Callable) -> Callable:
679
+ pass
680
+
681
+ @abstractmethod
682
+ def redispatch_to_next(self) -> AbstractContextManager:
683
+ pass
684
+
685
+ @abstractmethod
686
+ def replace(self, input_tensor, output_tensor) -> None:
687
+ pass
688
+
689
+ @abstractmethod
690
+ def commit_update(self, tensor) -> None:
691
+ pass
692
+
693
+ @abstractmethod
694
+ def sync(self, tensor) -> None:
695
+ pass
696
+
697
+ @abstractmethod
698
+ def mark_mutation_hidden_from_autograd(self, tensor) -> None:
699
+ pass
700
+
701
+
702
+ class PythonFunctionalizeAPI(BaseFunctionalizeAPI):
703
+ def __init__(
704
+ self, mode: Optional[FunctionalTensorMode] = None, pre_dispatch: bool = False
705
+ ) -> None:
706
+ super().__init__()
707
+ self.mode = mode if mode else FunctionalTensorMode()
708
+ self.pre_dispatch = pre_dispatch
709
+
710
+ def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]:
711
+ with self.mode:
712
+ return torch.utils._pytree.tree_map_only(
713
+ torch.Tensor, FunctionalTensor.to_functional, args
714
+ )
715
+
716
+ def unwrap_tensors(
717
+ self, args: Union[torch.Tensor, tuple[torch.Tensor, ...], list[torch.Tensor]]
718
+ ) -> Any:
719
+ return torch.utils._pytree.tree_map_only(
720
+ FunctionalTensor, FunctionalTensor.from_functional, args
721
+ )
722
+
723
+ def functionalize(self, inner_f: Callable) -> Callable:
724
+ return dispatch_functionalize(inner_f, self.mode)
725
+
726
+ def redispatch_to_next(self) -> AbstractContextManager:
727
+ # [NOTE] We don't do anything here because at the time
728
+ # we exercise this path, we would have already popped the
729
+ # FunctionalTensorMode from mode stack. Since FunctionalTensorMode
730
+ # is now stateful, it is better to explicitly pass in correct mode
731
+ # directly instead of globally setting it.
732
+ return contextlib.nullcontext()
733
+
734
+ def replace(self, input_tensor, output_tensor) -> None:
735
+ assert isinstance(input_tensor, FunctionalTensor)
736
+ assert not isinstance(output_tensor, FunctionalTensor)
737
+ input_tensor.replace_(output_tensor)
738
+
739
+ def commit_update(self, tensor) -> None:
740
+ assert isinstance(tensor, FunctionalTensor)
741
+ tensor.commit_update()
742
+
743
+ def sync(self, tensor) -> None:
744
+ assert isinstance(tensor, FunctionalTensor)
745
+ tensor.sync()
746
+
747
+ def mark_mutation_hidden_from_autograd(self, tensor) -> None:
748
+ assert isinstance(tensor, FunctionalTensor)
749
+ tensor.mark_mutation_hidden_from_autograd()
750
+
751
+
752
+ class CppFunctionalizeAPI(BaseFunctionalizeAPI):
753
+ def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]:
754
+ from torch._functorch.eager_transforms import _wrap_all_tensors_to_functional
755
+
756
+ return _wrap_all_tensors_to_functional(args, level=0)
757
+
758
+ def unwrap_tensors(
759
+ self, args: Union[torch.Tensor, tuple[torch.Tensor, ...]]
760
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, ...]]:
761
+ from torch._functorch.eager_transforms import (
762
+ _unwrap_all_tensors_from_functional,
763
+ )
764
+
765
+ return _unwrap_all_tensors_from_functional(args, reapply_views=_reapply_views())
766
+
767
+ def functionalize(self, inner_f: Callable) -> Callable:
768
+ return torch.func.functionalize(inner_f)
769
+
770
+ def redispatch_to_next(self) -> AbstractContextManager:
771
+ return torch._C._ExcludeDispatchKeyGuard(
772
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
773
+ )
774
+
775
+ def replace(self, input_tensor, output_tensor) -> None:
776
+ torch._functionalize_replace(input_tensor, output_tensor)
777
+
778
+ def commit_update(self, tensor) -> None:
779
+ torch._functionalize_commit_update(tensor)
780
+
781
+ def sync(self, tensor) -> None:
782
+ torch._functionalize_sync(tensor)
783
+
784
+ def mark_mutation_hidden_from_autograd(self, tensor) -> None:
785
+ torch._functionalize_mark_mutation_hidden_from_autograd(tensor)
786
+
787
+
788
+ class FunctorchFunctionalizeAPI(BaseFunctionalizeAPI):
789
+ def __init__(self, interpreter):
790
+ self.interpreter = interpreter
791
+
792
+ def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]:
793
+ from torch._functorch.eager_transforms import _wrap_all_tensors_to_functional
794
+
795
+ return _wrap_all_tensors_to_functional(args, level=self.interpreter.level())
796
+
797
+ def unwrap_tensors(
798
+ self, args: Union[torch.Tensor, tuple[torch.Tensor, ...]]
799
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, ...]]:
800
+ from torch._functorch.eager_transforms import (
801
+ _unwrap_all_tensors_from_functional,
802
+ )
803
+
804
+ return _unwrap_all_tensors_from_functional(
805
+ args, reapply_views=self.interpreter.functionalize_add_back_views()
806
+ )
807
+
808
+ def functionalize(self, inner_f: Callable) -> Callable:
809
+ return torch.func.functionalize(
810
+ inner_f,
811
+ remove=(
812
+ "mutations_and_views"
813
+ if self.interpreter.functionalize_add_back_views()
814
+ else "mutations"
815
+ ),
816
+ )
817
+
818
+ def redispatch_to_next(self) -> AbstractContextManager:
819
+ return self.interpreter.lower()
820
+
821
+ def replace(self, input_tensor, output_tensor) -> None:
822
+ torch._functionalize_replace(input_tensor, output_tensor)
823
+
824
+ def commit_update(self, tensor) -> None:
825
+ torch._functionalize_commit_update(tensor)
826
+
827
+ def sync(self, tensor) -> None:
828
+ torch._functionalize_sync(tensor)
829
+
830
+ def mark_mutation_hidden_from_autograd(self, tensor) -> None:
831
+ torch._functionalize_mark_mutation_hidden_from_autograd(tensor)
832
+
833
+
834
+ def mb_unwrap_functional_tensor(tensor: torch.Tensor):
835
+ if isinstance(tensor, FunctionalTensor):
836
+ return torch._from_functional_tensor(tensor.elem)
837
+ return tensor
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/meta_utils.py ADDED
@@ -0,0 +1,1972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dataclasses
5
+ import functools
6
+ import threading
7
+ import typing
8
+ import weakref
9
+ from abc import abstractmethod
10
+ from contextlib import AbstractContextManager, contextmanager
11
+ from dataclasses import dataclass
12
+ from typing import (
13
+ Any,
14
+ ClassVar,
15
+ Generic,
16
+ NewType,
17
+ Optional,
18
+ Protocol,
19
+ TYPE_CHECKING,
20
+ TypeGuard,
21
+ TypeVar,
22
+ Union,
23
+ )
24
+ from typing_extensions import override, TypedDict, TypeIs, Unpack
25
+
26
+ import torch
27
+ from torch._C._autograd import CreationMeta
28
+ from torch._C._functorch import (
29
+ _add_batch_dim,
30
+ _unwrap_functional_tensor,
31
+ _wrap_functional_tensor,
32
+ get_unwrapped,
33
+ is_batchedtensor,
34
+ is_functorch_wrapped_tensor,
35
+ is_gradtrackingtensor,
36
+ is_legacy_batchedtensor,
37
+ maybe_get_bdim,
38
+ maybe_get_level,
39
+ peek_interpreter_stack,
40
+ )
41
+ from torch._dispatch.python import enable_python_dispatcher
42
+ from torch._logging import trace_structured
43
+ from torch.utils._mode_utils import no_dispatch
44
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
45
+ from torch.utils.weak import WeakIdKeyDictionary
46
+
47
+
48
+ if TYPE_CHECKING:
49
+ from collections.abc import Callable, Generator
50
+
51
+ from torch._C._functorch import CInterpreter
52
+ from torch._guards import Source
53
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
54
+
55
+ # Import here to avoid cycle
56
+ # Import the following modules during type checking to enable code intelligence features,
57
+ # Do not import unconditionally, as they import sympy and importing sympy is very slow
58
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv, SymbolicContext
59
+
60
+
61
+ def _is_fake_tensor(t: object) -> TypeIs[FakeTensor]:
62
+ from torch._subclasses.fake_tensor import FakeTensor
63
+
64
+ return isinstance(t, FakeTensor)
65
+
66
+
67
+ DimList = list
68
+ _TensorLikeT = TypeVar("_TensorLikeT", "MetaTensorDesc", torch.Tensor)
69
+ _T = TypeVar("_T")
70
+ _TensorT = TypeVar("_TensorT", bound=torch.Tensor)
71
+ _TensorT_cov = TypeVar("_TensorT_cov", bound=torch.Tensor, covariant=True)
72
+
73
+
74
+ def safe_is_leaf(t: Union[MetaTensorDesc, torch.Tensor]) -> bool:
75
+ try:
76
+ return t.is_leaf
77
+ except RuntimeError:
78
+ # inference mode can trigger this
79
+ return False
80
+
81
+
82
+ def safe_grad(t: _TensorLikeT) -> Optional[_TensorLikeT]:
83
+ with torch._logging.hide_warnings(torch._logging._internal.safe_grad_filter):
84
+ # pyrefly: ignore [bad-return]
85
+ return t.grad
86
+
87
+
88
+ def _expect_safe_grad(t: _TensorLikeT) -> _TensorLikeT:
89
+ grad = safe_grad(t)
90
+ assert grad is not None
91
+ return grad
92
+
93
+
94
+ def assert_eq(a: _T, b: _T) -> None:
95
+ assert a == b, f"{a} != {b}"
96
+
97
+
98
+ tls = threading.local()
99
+ # Turns off inference mode for fake tensor propagation. This is turned to True
100
+ # only for `torch.compile`. Also look at
101
+ # _dynamo.config.fake_tensor_disable_inference_mode
102
+ tls.disable_inference_mode = False
103
+
104
+
105
+ @contextmanager
106
+ def disable_inference_mode_for_fake_prop() -> Generator[None, None, None]:
107
+ prior = getattr(tls, "disable_inference_mode", False)
108
+ tls.disable_inference_mode = True
109
+ try:
110
+ yield
111
+ finally:
112
+ tls.disable_inference_mode = prior
113
+
114
+
115
+ def assert_metadata_eq(
116
+ assert_eq: Callable[[object, object], None],
117
+ m1: Union[MetaTensorDesc, torch.Tensor],
118
+ m2: torch.Tensor,
119
+ *,
120
+ skip_symbolic: bool = False,
121
+ skip_leaf: bool = False,
122
+ ) -> None:
123
+ m1 = (
124
+ MetaTensorDescriber().describe_tensor(m1)
125
+ if isinstance(m1, torch.Tensor)
126
+ else m1
127
+ )
128
+
129
+ def go(m1: MetaTensorDesc, m2: torch.Tensor) -> None:
130
+ assert_eq(m1.dtype, m2.dtype)
131
+ if not skip_symbolic:
132
+ assert_eq(m1.shape, m2.shape)
133
+ assert_eq(m1.requires_grad, m2.requires_grad)
134
+ if not skip_leaf:
135
+ assert_eq(m1.is_leaf, m2.is_leaf)
136
+ # MetaTensorDesc doesn't store grad_fn; inferred from leaf
137
+ # assert_eq(m1.grad_fn is None, m2.grad_fn is None)
138
+ assert_eq(m1.is_sparse, m2.is_sparse)
139
+ if not getattr(tls, "disable_inference_mode", False):
140
+ assert_eq(m1.is_inference, m2.is_inference())
141
+ else:
142
+ assert_eq(m1.is_inference, False)
143
+ assert_eq(m1.is_conj, m2.is_conj())
144
+ assert_eq(m1.is_neg, m2.is_neg())
145
+ assert_eq(m1.grad is not None, safe_grad(m2) is not None)
146
+ if m1.grad is not None:
147
+ go(m1.grad, _expect_safe_grad(m2))
148
+ # TODO: move "assert_eq(m1.layout, m2.layout)" out of sparse
149
+ # branches (but not ready for prime time yet)...
150
+ if m1.is_sparse:
151
+ assert_eq(m1.layout, m2.layout)
152
+ assert_eq(m1.dense_dim, m2.dense_dim())
153
+ assert_eq(m1.sparse_dim, m2.sparse_dim())
154
+ assert_eq(m1.is_coalesced, m2.is_coalesced())
155
+ elif is_sparse_compressed(m1):
156
+ assert_eq(m1.layout, m2.layout)
157
+ assert_eq(m1.dense_dim, m2.dense_dim())
158
+ assert_eq(m1.sparse_dim, m2.sparse_dim())
159
+ else:
160
+ if not skip_symbolic:
161
+ assert_eq(m1.stride, m2.stride())
162
+ assert_eq(m1.storage_offset, m2.storage_offset())
163
+ assert_eq(m1.is_view, m2._is_view())
164
+ if m1.is_view:
165
+ assert m1.base is not None
166
+ assert m2._base is not None
167
+ go(m1.base, m2._base)
168
+ # TODO: test if is resizable (no direct query for this atm)
169
+ # TODO: audit AutogradMeta to see if it matches
170
+ # TODO: test forward AD
171
+
172
+ return go(m1, m2)
173
+
174
+
175
+ # TypeGuard (not TypeIs): False does not imply !torch.Tensor
176
+ def is_sparse_coo(t: object) -> TypeGuard[torch.Tensor]:
177
+ return isinstance(t, torch.Tensor) and t.layout is torch.sparse_coo
178
+
179
+
180
+ def is_sparse_compressed_layout(layout: torch.layout) -> bool:
181
+ return layout in {
182
+ torch.sparse_csr,
183
+ torch.sparse_csc,
184
+ torch.sparse_bsr,
185
+ torch.sparse_bsc,
186
+ }
187
+
188
+
189
+ # TypeGuard (not TypeIs): False does not imply !torch.Tensor
190
+ def is_sparse_compressed(t: object) -> TypeGuard[torch.Tensor]:
191
+ return isinstance(t, torch.Tensor) and is_sparse_compressed_layout(t.layout)
192
+
193
+
194
+ # TypeGuard (not TypeIs): False does not imply !torch.Tensor
195
+ def is_sparse_any(t: object) -> TypeGuard[torch.Tensor]:
196
+ return is_sparse_coo(t) or is_sparse_compressed(t)
197
+
198
+
199
+ def _checked_cast(ty: type[_T], obj: object) -> _T:
200
+ assert isinstance(obj, ty), f"expected {ty} but got {type(obj)}"
201
+ return obj
202
+
203
+
204
+ def _get_real_storage(base: torch.UntypedStorage) -> torch.UntypedStorage:
205
+ return base.real_storage # type: ignore[attr-defined]
206
+
207
+
208
+ def _set_real_storage(
209
+ base: torch.UntypedStorage, real_storage: torch.UntypedStorage
210
+ ) -> None:
211
+ base.real_storage = real_storage # type: ignore[attr-defined]
212
+
213
+
214
+ # Don't use id() directly, because those can get reallocated over time.
215
+ MetaStorageId = NewType("MetaStorageId", int)
216
+ MetaTensorId = NewType("MetaTensorId", int)
217
+
218
+
219
+ _DescriberId = NewType("_DescriberId", int)
220
+ DESCRIBER_NEXT_ID = _DescriberId(0)
221
+
222
+
223
+ class MetaTensorDescriber:
224
+ """
225
+ Given a Tensor/Storage, generate a MetaTensorDesc/MetaStorageDesc
226
+ for it, which is enough information to reconstruct a meta tensor/fake tensor
227
+ corresponding to a Tensor as faithfully as possible.
228
+
229
+ This is a stateful conversion object because we keep track of the IDs
230
+ of the tensors/storages passed to us, so we can consistently give
231
+ the same ID when we see the same tensor/storage.
232
+ """
233
+
234
+ def __init__(self, *, copy_data: bool = False) -> None:
235
+ global DESCRIBER_NEXT_ID
236
+ self.id = DESCRIBER_NEXT_ID
237
+ DESCRIBER_NEXT_ID = _DescriberId(DESCRIBER_NEXT_ID + 1)
238
+ self.next_tensor_id: MetaTensorId = MetaTensorId(0)
239
+ self.next_storage_id: MetaStorageId = MetaStorageId(0)
240
+ # Tensor -> int
241
+ self.lookup_tensor = WeakIdKeyDictionary()
242
+ # Storage -> int
243
+ self.lookup_storage = WeakIdKeyDictionary()
244
+ self.copy_data = copy_data
245
+ self.traced_tensors: set[int] = set()
246
+ self.traced_storages: set[int] = set()
247
+
248
+ def get_tensor_id(self, t: torch.Tensor) -> MetaTensorId:
249
+ if t not in self.lookup_tensor:
250
+ self.lookup_tensor[t] = self.next_tensor_id
251
+ self.next_tensor_id = MetaTensorId(self.next_tensor_id + 1)
252
+ return self.lookup_tensor[t]
253
+
254
+ def get_storage_id(self, s: torch.UntypedStorage) -> MetaStorageId:
255
+ if s not in self.lookup_storage:
256
+ self.lookup_storage[s] = self.next_storage_id
257
+ self.next_storage_id = MetaStorageId(self.next_storage_id + 1)
258
+ return self.lookup_storage[s]
259
+
260
+ def describe_storage(
261
+ self, s: torch.UntypedStorage, *, trace: bool = False
262
+ ) -> MetaStorageDesc:
263
+ r = MetaStorageDesc(
264
+ id=self.get_storage_id(s),
265
+ size=s.size(),
266
+ # NB: We don't do the copy yet; copy happens when we start
267
+ # creating the new storages
268
+ data=s if self.copy_data else None,
269
+ )
270
+ if trace and r.id not in self.traced_storages:
271
+ trace_structured(
272
+ "describe_storage",
273
+ metadata_fn=lambda: r.as_json(self.id),
274
+ )
275
+ self.traced_storages.add(r.id)
276
+ return r
277
+
278
+ def describe_tensor(
279
+ self, t: torch.Tensor, *, recurse: bool = True, trace: bool = False
280
+ ) -> MetaTensorDesc:
281
+ is_leaf = safe_is_leaf(t)
282
+ is_view = t._is_view()
283
+ is_sparse = t.is_sparse
284
+ layout = t.layout
285
+ is_nested = t.is_nested
286
+ is_traceable_wrapper_subclass_v = is_traceable_wrapper_subclass(t)
287
+ is_functorch_wrapped = is_functorch_wrapped_tensor(t)
288
+ is_mkldnn = t.is_mkldnn
289
+ is_batchedtensor_v = is_batchedtensor(t)
290
+ is_legacy_batchedtensor_v = is_legacy_batchedtensor(t)
291
+ is_gradtrackingtensor_v = is_gradtrackingtensor(t)
292
+ is_functional = torch._is_functional_tensor(t)
293
+
294
+ storage = None
295
+ # NB: For compatibility, I default this to zero, as sometimes people
296
+ # still have stuffed zero into storage offset even though the tensor
297
+ # doesn't meaningfully have an offset
298
+ storage_offset = 0
299
+ if not (
300
+ is_sparse
301
+ or is_sparse_compressed_layout(layout)
302
+ or (is_nested and not is_traceable_wrapper_subclass_v)
303
+ or is_mkldnn
304
+ # TODO: TBH, functorch wrapped tensors probably should have
305
+ # storage associated with them
306
+ or is_functorch_wrapped
307
+ or is_legacy_batchedtensor_v
308
+ ):
309
+ # NB: We actually don't use storage to do views, but might as well
310
+ # put it in for accuracy
311
+ storage = self.describe_storage(t.untyped_storage(), trace=trace)
312
+ storage_offset = t.storage_offset() # type: ignore[assignment]
313
+
314
+ stride = None
315
+ if not (
316
+ is_sparse
317
+ or is_sparse_compressed_layout(layout)
318
+ or (is_nested and not is_traceable_wrapper_subclass_v)
319
+ ):
320
+ # stride/storage_offset are called from is_functorch_wrapped,
321
+ # view_from_base, empty_create_subclass,
322
+ # sym_sizes_strides_storage_offset (empty_create)
323
+ stride = t.stride()
324
+
325
+ # NB: this technically should refer to functorch unwrapped tensor, but
326
+ # I am (perhaps abusively) using it to store both the functorch and
327
+ # non-functorch functional tensor
328
+ unwrapped = None
329
+ autograd_meta_from = None
330
+ current_level = None
331
+ if is_batchedtensor_v or is_gradtrackingtensor_v:
332
+ unwrapped = self.describe_tensor(get_unwrapped(t), trace=trace)
333
+ # xla and lazy tensors present as functional tensors, but we want them
334
+ # to be handled specially
335
+ elif is_functional and t.device.type not in ("xla", "lazy"):
336
+ if t._is_view():
337
+ raise RuntimeError(
338
+ "Cannot safely fakify a view because this process drops the view information right now."
339
+ )
340
+ if not is_functorch_wrapped:
341
+ torch._sync(t)
342
+ unwrapped = self.describe_tensor(
343
+ torch._from_functional_tensor(t), trace=trace
344
+ )
345
+ autograd_meta_from = t
346
+ else:
347
+ reapply_views = torch._C._functionalization_reapply_views_tls()
348
+ # NB: has side effects!
349
+ unwrapped = self.describe_tensor(
350
+ _unwrap_functional_tensor(t, reapply_views), trace=trace
351
+ )
352
+ # TODO: It's pretty suspicious that functional tensors don't have
353
+ # valid level and thus we just grab whatever the current level
354
+ # is
355
+ current_level = torch._C._functorch.current_level()
356
+
357
+ maybe_functorch_stack = None
358
+ if is_functorch_wrapped:
359
+ with (
360
+ torch._functorch.pyfunctorch.temporarily_clear_interpreter_stack()
361
+ ) as maybe_functorch_stack:
362
+ pass
363
+
364
+ attrs = None
365
+ ctx = None
366
+ type_v = None
367
+ if is_traceable_wrapper_subclass_v:
368
+ assert hasattr(t, "__tensor_flatten__")
369
+ raw_attrs, ctx = t.__tensor_flatten__()
370
+ attrs = {
371
+ attr: self.describe_tensor(getattr(t, attr), trace=trace)
372
+ for attr in raw_attrs
373
+ }
374
+ type_v = type(t)
375
+
376
+ from torch.nested._internal.nested_tensor import _tensor_symint_registry
377
+
378
+ view_func = ViewFunc.from_tensor(t)
379
+
380
+ # TODO: Is it important to enable torch.inference_mode before querying
381
+ # these values?
382
+ is_inference_mode_disabled = getattr(tls, "disable_inference_mode", False)
383
+ r: MetaTensorDesc = MetaTensorDesc(
384
+ id=self.get_tensor_id(t),
385
+ storage=storage,
386
+ is_inference=False if is_inference_mode_disabled else t.is_inference(),
387
+ is_leaf=is_leaf,
388
+ requires_grad=t.requires_grad,
389
+ # NB: ndim should be OK too but there is a disaster at
390
+ # python test/dynamo/test_subclasses.py -k test_user_overridden_property_unsupported
391
+ # Actually, this means that we have a little bit of a problem
392
+ # here, which is that there is some sensitivity to how exactly an
393
+ # access is done if you have a __torch_function__ subclass. Maybe
394
+ # should disable torch function before doing accesses?
395
+ ndim=t.dim(),
396
+ dtype=t.dtype,
397
+ is_sparse=is_sparse,
398
+ is_mkldnn=is_mkldnn,
399
+ is_functorch_wrapped=is_functorch_wrapped,
400
+ is_batchedtensor=is_batchedtensor_v,
401
+ is_legacy_batchedtensor=is_legacy_batchedtensor_v,
402
+ is_gradtrackingtensor=is_gradtrackingtensor_v,
403
+ is_view=is_view,
404
+ is_conj=t.is_conj(),
405
+ is_neg=t.is_neg(),
406
+ is_parameter=isinstance(t, torch.nn.Parameter),
407
+ is_traceable_wrapper_subclass=is_traceable_wrapper_subclass_v,
408
+ is_nested=is_nested,
409
+ nested_int=(
410
+ _tensor_symint_registry[t].node.nested_int()
411
+ if t in _tensor_symint_registry
412
+ else None
413
+ ),
414
+ is_functional=is_functional,
415
+ layout=layout,
416
+ device=t.device,
417
+ size=t.size(),
418
+ stride=stride,
419
+ # pyrefly: ignore [bad-argument-type]
420
+ storage_offset=storage_offset,
421
+ dynamo_dynamic_indices=list(getattr(t, "_dynamo_dynamic_indices", set())),
422
+ dynamo_hint_overrides=getattr(t, "_dynamo_hint_overrides", {}),
423
+ sparse_dim=(
424
+ t.sparse_dim() if t.is_sparse or is_sparse_compressed(t) else None
425
+ ),
426
+ dense_dim=t.dense_dim() if t.is_sparse or is_sparse_compressed(t) else None,
427
+ is_coalesced=t.is_coalesced() if t.is_sparse else None,
428
+ # TODO: I actually think recursing here is correct, but we have at
429
+ # least an infinite cycle from base -> values -> base
430
+ # https://github.com/pytorch/pytorch/issues/122089
431
+ crow_indices=(
432
+ self.describe_tensor(t.crow_indices(), recurse=False, trace=trace)
433
+ if recurse and t.layout in {torch.sparse_csr, torch.sparse_bsr}
434
+ else None
435
+ ),
436
+ col_indices=(
437
+ self.describe_tensor(t.col_indices(), recurse=False, trace=trace)
438
+ if recurse and t.layout in {torch.sparse_csr, torch.sparse_bsr}
439
+ else None
440
+ ),
441
+ ccol_indices=(
442
+ self.describe_tensor(t.ccol_indices(), recurse=False, trace=trace)
443
+ if recurse and t.layout in {torch.sparse_csc, torch.sparse_bsc}
444
+ else None
445
+ ),
446
+ row_indices=(
447
+ self.describe_tensor(t.row_indices(), recurse=False, trace=trace)
448
+ if recurse and t.layout in {torch.sparse_csc, torch.sparse_bsc}
449
+ else None
450
+ ),
451
+ values=(
452
+ self.describe_tensor(t.values(), recurse=False, trace=trace)
453
+ if recurse and is_sparse_compressed(t)
454
+ else None
455
+ ),
456
+ grad=(
457
+ self.describe_tensor(grad, trace=trace)
458
+ if (grad := safe_grad(t)) is not None
459
+ else None
460
+ ),
461
+ creation_meta=(
462
+ torch._C._autograd._get_creation_meta(t) if t._is_view() else None
463
+ ),
464
+ unwrapped=unwrapped,
465
+ level=(
466
+ maybe_get_level(t)
467
+ if is_batchedtensor_v or is_gradtrackingtensor_v
468
+ else None
469
+ ),
470
+ bdim=maybe_get_bdim(t) if is_batchedtensor_v else None,
471
+ base=(
472
+ self.describe_tensor(t._base, trace=trace)
473
+ if recurse and t._is_view() and t._base is not None
474
+ else None
475
+ ),
476
+ fake_mode=torch._subclasses.fake_tensor.maybe_get_fake_mode(t),
477
+ view_func=view_func,
478
+ attrs=attrs,
479
+ ctx=ctx,
480
+ type=type_v,
481
+ # NB: even if functorch is enabled, don't actually save the
482
+ # interpreter stack here unless we are actually functorch wrapped;
483
+ # it's irrelevant for non-functorch stuff
484
+ functorch_stack=maybe_functorch_stack,
485
+ autograd_meta_from=autograd_meta_from,
486
+ current_level=current_level,
487
+ data=t if self.copy_data else None,
488
+ )
489
+ if trace and r.id not in self.traced_tensors:
490
+ trace_structured(
491
+ "describe_tensor",
492
+ metadata_fn=lambda: r.as_json(self.id),
493
+ )
494
+ self.traced_tensors.add(r.id)
495
+ return r
496
+
497
+
498
+ @dataclass(frozen=True)
499
+ class MetaStorageDesc:
500
+ id: MetaStorageId
501
+ size: int
502
+ # NB: this is only populated with copy_data True, it is not directly
503
+ # serializable in JSON, you want to do something special here anyway
504
+ data: Optional[torch.UntypedStorage]
505
+
506
+ def as_json(self, describer_id: _DescriberId) -> dict[str, object]:
507
+ return {
508
+ "id": self.id,
509
+ "describer_id": describer_id,
510
+ "size": self.size if isinstance(self.size, int) else repr(self.size),
511
+ }
512
+
513
+
514
+ @dataclass(frozen=True)
515
+ class ViewFunc(Generic[_TensorT]):
516
+ @abstractmethod
517
+ def apply(
518
+ self,
519
+ t: _TensorT,
520
+ new_base: _TensorT,
521
+ symint_visitor_fn: Optional[Callable[[int], int]] = None,
522
+ tensor_visitor_fn: Optional[Callable[[torch.Tensor], _TensorT]] = None,
523
+ ) -> _TensorT: ...
524
+
525
+ @staticmethod
526
+ def from_tensor(t: torch.Tensor) -> ViewFunc:
527
+ if _is_fake_tensor(t):
528
+ return _FakeTensorViewFunc()
529
+ else:
530
+ return _CustomViewFunc(t._view_func_unsafe)
531
+
532
+
533
+ @dataclass(frozen=True)
534
+ class _FakeTensorViewFunc(ViewFunc["FakeTensor"]):
535
+ @override
536
+ def apply(
537
+ self,
538
+ t: torch.Tensor,
539
+ new_base: torch.Tensor,
540
+ symint_visitor_fn: Optional[Callable[[int], int]] = None,
541
+ tensor_visitor_fn: Optional[Callable[[torch.Tensor], FakeTensor]] = None,
542
+ ) -> FakeTensor:
543
+ return torch._subclasses.fake_tensor.FakeTensor._view_func_unsafe(
544
+ # pyrefly: ignore [bad-argument-type]
545
+ t,
546
+ new_base,
547
+ symint_visitor_fn,
548
+ tensor_visitor_fn,
549
+ )
550
+
551
+
552
+ @dataclass(frozen=True)
553
+ class _CustomViewFunc(ViewFunc[_TensorT], Generic[_TensorT]):
554
+ func: Callable[
555
+ [
556
+ torch.Tensor,
557
+ Optional[Callable[[int], int]],
558
+ Optional[Callable[[torch.Tensor], _TensorT]],
559
+ ],
560
+ _TensorT,
561
+ ]
562
+
563
+ @override
564
+ def apply(
565
+ self,
566
+ t: torch.Tensor,
567
+ new_base: torch.Tensor,
568
+ symint_visitor_fn: Optional[Callable[[int], int]] = None,
569
+ tensor_visitor_fn: Optional[Callable[[torch.Tensor], _TensorT]] = None,
570
+ ) -> _TensorT:
571
+ # ignore `t`
572
+ return self.func(new_base, symint_visitor_fn, tensor_visitor_fn)
573
+
574
+
575
+ # A callback where the device is either optional or required.
576
+ # All of these satisfy this protocol:
577
+ # def mk(arg: Callable[[], torch.Tensor], device: Union[torch.device, str])
578
+ # def mk(arg: Callable[[], torch.Tensor], device: Union[torch.device, str] = "meta")
579
+ # def mk(arg: Callable[[], torch.Tensor], device: Optional[Union[torch.device, str]] = None)
580
+ class _MetaTensorCallback(Protocol, Generic[_TensorT_cov]):
581
+ def __call__(
582
+ self, arg: Callable[[], torch.Tensor], /, *, device: Union[torch.device, str]
583
+ ) -> _TensorT_cov: ...
584
+
585
+
586
+ class _MetaTensorCallbackKwargs(TypedDict, total=False):
587
+ device: Union[torch.device, str]
588
+
589
+
590
+ # A callback where the device may not be provided (is optional).
591
+ # All of these satisfy this protocol:
592
+ # def mk(arg: Callable[[], torch.Tensor], device: Union[torch.device, str] = "meta")
593
+ # def mk(arg: Callable[[], torch.Tensor], device: Optional[Union[torch.device, str]] = None)
594
+ class _MetaTensorCallbackOptDevice(Protocol, Generic[_TensorT_cov]):
595
+ def __call__(
596
+ self,
597
+ arg: Callable[[], torch.Tensor],
598
+ /,
599
+ **kwargs: Unpack[_MetaTensorCallbackKwargs],
600
+ ) -> _TensorT_cov: ...
601
+
602
+
603
+ @dataclass(frozen=True)
604
+ class MetaTensorDesc(Generic[_TensorT]):
605
+ id: MetaTensorId
606
+ ndim: int
607
+ dtype: torch.dtype
608
+ device: torch.device
609
+
610
+ # NB: Sometimes, size, stride and storage_offset contain SymInt, in which
611
+ # case this is NOT serializable. That only happens when you're
612
+ # re-fakeifying a fake tensor with an existing ShapeEnv... maybe we
613
+ # can get rid of this use case entirely. Notably, even if we are
614
+ # fakeifying a real tensor into a fake tensor with symbolic shapes, the
615
+ # size here is NOT dynamic
616
+ # NB: These also contain SymInt because wrap_meta_outputs_with_default_device_logic
617
+ # goes through this codepath. But it really should not LOL.
618
+ # NB: size could potentially be None as you can override it and make it
619
+ # throw an error, but we don't currently have any subclasses that do this
620
+ # except C++ nested tensor but we're going to have nested int to make this
621
+ # defined on NJT
622
+ size: tuple[int, ...]
623
+ dynamo_dynamic_indices: list[int]
624
+ dynamo_hint_overrides: dict[int, int]
625
+
626
+ layout: torch.layout = torch.strided
627
+ is_inference: bool = False
628
+ is_leaf: bool = False
629
+ requires_grad: bool = False
630
+ is_sparse: bool = False
631
+ is_mkldnn: bool = False
632
+ is_functorch_wrapped: bool = False
633
+ is_batchedtensor: bool = False
634
+ is_legacy_batchedtensor: bool = False
635
+ is_gradtrackingtensor: bool = False
636
+ is_view: bool = False
637
+ is_nested: bool = False
638
+ # We eagerly symbolicize the associated nested int for e.g. offsets / lengths
639
+ # metadata if that offsets is already associated with a nested int.
640
+ # See test_construct_from_jagged_with_input_offsets_mixed_case.
641
+ nested_int: Optional[int] = None
642
+ is_traceable_wrapper_subclass: bool = False
643
+ is_functional: bool = False
644
+ is_conj: bool = False
645
+ is_neg: bool = False
646
+ is_parameter: bool = False
647
+ stride: Optional[tuple[int, ...]] = None
648
+ storage_offset: int = 0
649
+ # NB: We have a choice whether or not to store the id or a direct pointer
650
+ # to the data structure. For ease of use, we store the data structure,
651
+ # but this means that when we serialize, we have to swizzle these pointers
652
+ # back into ids (so we have accurate aliasing relationships)
653
+ storage: Optional[MetaStorageDesc] = None
654
+ sparse_dim: Optional[int] = None # is_sparse, is_sparse_compressed
655
+ dense_dim: Optional[int] = None # is_sparse, is_sparse_compressed
656
+ is_coalesced: Optional[bool] = None # is_sparse
657
+ crow_indices: Optional[MetaTensorDesc] = None # is_sparse_compressed
658
+ col_indices: Optional[MetaTensorDesc] = None # is_sparse_compressed
659
+ ccol_indices: Optional[MetaTensorDesc] = None # is_sparse_compressed
660
+ row_indices: Optional[MetaTensorDesc] = None # is_sparse_compressed
661
+ values: Optional[MetaTensorDesc] = None # is_sparse_compressed
662
+ unwrapped: Optional[MetaTensorDesc] = None # is_functorch_wrapped
663
+ bdim: Optional[int] = None # is_functorch_wrapped
664
+ base: Optional[MetaTensorDesc] = None # is_view
665
+ attrs: Optional[dict[str, MetaTensorDesc]] = None # is_traceable_wrapper_subclass
666
+ creation_meta: Optional[CreationMeta] = None
667
+ grad: Optional[MetaTensorDesc] = None
668
+
669
+ # Everything below is NOT serializable, need some more work
670
+
671
+ _UNSERIALIZABLE: ClassVar[set[str]] = {
672
+ "ctx",
673
+ "type",
674
+ "fake_mode",
675
+ # view_func isn't serializable when it's a _CustomViewFunc
676
+ "view_func",
677
+ "level",
678
+ "current_level",
679
+ "functorch_stack",
680
+ "autograd_meta_from",
681
+ "data",
682
+ "nested_int",
683
+ }
684
+
685
+ ctx: Optional[object] = None # is_traceable_wrapper_subclass
686
+ type: Optional[type] = None # is_traceable_wrapper_subclass
687
+ fake_mode: Optional[FakeTensorMode] = None
688
+ view_func: Optional[ViewFunc] = None
689
+ # level looks serializable, but actually it is meaningless without
690
+ # the functorch_stack below
691
+ level: Optional[int] = None # is_functorch_wrapped
692
+ current_level: Optional[int] = None
693
+ functorch_stack: Optional[list[CInterpreter]] = None
694
+ autograd_meta_from: Optional[torch.Tensor] = None
695
+
696
+ # This is only populated on copy_data, and typically is not used at all,
697
+ # except for some of our meta-ification paths that don't properly use
698
+ # storage (pro-tip: you should use storage)
699
+ data: Optional[torch.Tensor] = None
700
+
701
+ # Faithfully serializing functorch tensors will not be too difficult.
702
+ # We only need to consider grad/vmap interpreters, and their internal
703
+ # state is only bools (mostly what the grad enabled/disabled state
704
+ # should be in the lower layer). Beyond that, tensors just need to
705
+ # precisely indicate which particular interpreter they correspond
706
+ # to (we then replace level with a pointer to the interpreter stack.)
707
+ # However, this use of functorch is very "non-lexical" so it's not
708
+ # entirely clear how to make it all lexical again, so we haven't done
709
+ # it for now.
710
+
711
+ # NB: This will reference numeric IDs, and it is assumed that you've
712
+ # already serialized everything this recursively references
713
+ def as_json(self, describer_id: _DescriberId) -> dict[str, object]:
714
+ def json(k: str, v: object) -> object:
715
+ # Some best-effort debugging serialization for unserializable
716
+ # fields (feel free to add other special cases as appropriate)
717
+ if k in ["data", "autograd_meta_from"]:
718
+ return None # never repr these
719
+ if k in MetaTensorDesc._UNSERIALIZABLE:
720
+ return repr(v)
721
+ if isinstance(v, (torch.device, torch.dtype, torch.layout)):
722
+ return repr(v)
723
+ if isinstance(v, torch.SymInt):
724
+ return repr(v)
725
+ if isinstance(v, (tuple, list)):
726
+ return [json(k, v1) for v1 in v]
727
+ if isinstance(v, (MetaStorageDesc, MetaTensorDesc)):
728
+ return v.id
729
+ if isinstance(v, CreationMeta):
730
+ return str(v)
731
+ if k == "attrs" and isinstance(v, dict):
732
+ return {k1: v1.id for k1, v1 in v.items()}
733
+ return v
734
+
735
+ r = {
736
+ field.name: json(field.name, getattr(self, field.name))
737
+ for field in dataclasses.fields(self)
738
+ if not (
739
+ getattr(self, field.name) is field.default
740
+ or (
741
+ field.name == "dynamo_dynamic_indices"
742
+ and not getattr(self, field.name)
743
+ )
744
+ )
745
+ }
746
+ r.update({"describer_id": describer_id})
747
+ return r
748
+
749
+ @property
750
+ def shape(self) -> tuple[int, ...]:
751
+ return self.size
752
+
753
+
754
+ # A more faithful reproduction would do a copy on the entire
755
+ # storage, but this needs to be done carefully because the
756
+ # underlying storage could have larger extent than is implied
757
+ # by size/stride. The real fix is to properly call
758
+ # meta_storage recursively here.
759
+ #
760
+ # These "safe" functions are intended to be used under no_dispatch() mode.
761
+ # The no_dispatch() here is intended to prevent ambient fake tensor mode from
762
+ # fakeifying the operation. But if we are given an honest to goodness
763
+ # FakeTensor as src, we MUST NOT run the copy/clone operation. A better way
764
+ # to do this would be to not use no_dispatch and instead just disable fake
765
+ # tensor mode only (allowing for subclass dispatch to occur)
766
+ def _safe_copy(dst: torch.Tensor, src: Optional[torch.Tensor]) -> None:
767
+ if type(src) is not torch.Tensor:
768
+ return
769
+ dst.copy_(src)
770
+
771
+
772
+ def _safe_clone(src: torch.Tensor) -> Optional[torch.Tensor]:
773
+ if type(src) is not torch.Tensor:
774
+ return None
775
+ return src.clone()
776
+
777
+
778
+ # This is a class for converting multiple tensors into meta tensors which
779
+ # share the same view/storage structure. The operation model is you allocate
780
+ # one of these, and then call it repeatedly on all the tensors you want to
781
+ # convert. It's important to use the same object for tensors you want to
782
+ # share storage because this is how we correlate shared storages to the same
783
+ # meta storages. This class will hold weak references to cached tenosrs
784
+ # and tensor storages.
785
+ class MetaConverter(Generic[_TensorT]):
786
+ def __init__(self, *, copy_data: bool = False) -> None:
787
+ # Maps MetaStorageId to UntypedStorage
788
+ self.storage_memo: weakref.WeakValueDictionary[
789
+ MetaStorageId, torch.UntypedStorage
790
+ ] = weakref.WeakValueDictionary()
791
+ # Maps MetaTensorId to torch.Tensor (typically a meta tensor or
792
+ # FakeTensor)
793
+ self.tensor_memo: weakref.WeakValueDictionary[MetaTensorId, _TensorT] = (
794
+ weakref.WeakValueDictionary()
795
+ )
796
+ self.hit = 0
797
+ self.miss = 0
798
+ self.del_hook = None
799
+ self.arg_cnt = 0
800
+ # Ensures real_storage/real_tensor are populated on the resulting
801
+ # metaified storage/tensor. The naming of this attribute is load
802
+ # bearing: FakeTensor relies on real tensor being set to exactly this
803
+ # value
804
+ self.copy_data = copy_data
805
+ self.describer = MetaTensorDescriber(copy_data=copy_data)
806
+
807
+ def successful(self) -> bool:
808
+ return self.hit > 0 and self.miss == 0
809
+
810
+ def get_tensor_memo(self, t: MetaTensorDesc) -> Optional[torch.Tensor]:
811
+ return self.tensor_memo.get(t.id, None)
812
+
813
+ def _checked_get_tensor_memo(self, t: MetaTensorDesc) -> _TensorT:
814
+ r = self.tensor_memo.get(t.id, None)
815
+ assert r is not None
816
+ return r
817
+
818
+ def set_tensor_memo(self, t: MetaTensorDesc, v: _TensorT) -> None:
819
+ self.tensor_memo[t.id] = v
820
+
821
+ def get_storage_memo(self, s: MetaStorageDesc) -> Optional[torch.UntypedStorage]:
822
+ return self.storage_memo.get(s.id, None)
823
+
824
+ def set_storage_memo(self, s: MetaStorageDesc, v: torch.UntypedStorage) -> None:
825
+ self.storage_memo[s.id] = v
826
+
827
+ def meta_storage(
828
+ self,
829
+ s: MetaStorageDesc,
830
+ callback: Callable[[Callable[[], torch.Tensor]], _TensorT],
831
+ ) -> torch.UntypedStorage:
832
+ # If we are fakeifying a tensor that has a secretly-zero-sized storage,
833
+ # Need to make sure to resize the meta storage too.
834
+ if (memo := self.get_storage_memo(s)) is None:
835
+ r_s = callback(
836
+ lambda: torch.empty(s.size, dtype=torch.uint8, device="meta"),
837
+ ).untyped_storage()
838
+ if self.copy_data:
839
+ # NB: no_dispatch is needed because internally storage copy is
840
+ # implemented as Tensor operations
841
+ with torch.no_grad(), no_dispatch():
842
+ assert s.data is not None
843
+ _set_real_storage(r_s, s.data.clone())
844
+ self.set_storage_memo(s, r_s)
845
+ return r_s
846
+ else:
847
+ return memo
848
+
849
+ @classmethod
850
+ def _checked_cast_tensor_t(cls, t: torch.Tensor) -> _TensorT:
851
+ # TODO: how to check _TensorT?
852
+ return typing.cast(_TensorT, t)
853
+
854
+ @classmethod
855
+ def _identity_callable(
856
+ cls,
857
+ t: Callable[[], torch.Tensor],
858
+ device: Optional[Union[torch.device, str]] = None,
859
+ ) -> _TensorT:
860
+ return cls._checked_cast_tensor_t(t())
861
+
862
+ @classmethod
863
+ def _backward_error(cls, t: _TensorT) -> _TensorT:
864
+ errfn = torch._C._functions.DelayedError(
865
+ "Internal error: Tried to backward() through example input",
866
+ 1,
867
+ )
868
+ err = errfn(t)
869
+ return typing.cast(_TensorT, err)
870
+
871
+ # This function assumes that it's possible to do the conversion
872
+ # NB: name here is used in a conventional way by Dynamo; it corresponds
873
+ # precisely to the Source.name of the tensor we're fakeifying and
874
+ # corresponds to a valid Python expression. When we construct sub-names
875
+ # as part of this process, we will maintain this invariant! (Even though
876
+ # other users of this may not need it this property to be upheld.)
877
+ def meta_tensor(
878
+ self,
879
+ t: MetaTensorDesc,
880
+ shape_env: Optional[ShapeEnv],
881
+ callback_: _MetaTensorCallback[_TensorT],
882
+ source: Optional[Source],
883
+ symbolic_context: Optional[SymbolicContext],
884
+ ) -> _TensorT:
885
+ callback: _MetaTensorCallbackOptDevice = functools.partial(
886
+ callback_, device=t.device
887
+ )
888
+ if source is None:
889
+ from torch._dynamo.source import ConstantSource
890
+
891
+ # TODO: make a dedicated UnknownSource for this?
892
+ source = ConstantSource(
893
+ f"__meta_utils_unknown_tensor{len(self.tensor_memo)}"
894
+ )
895
+
896
+ msg = (
897
+ " This indicates you set no_dispatch() before calling into this"
898
+ " function. This is an error: we may be creating fake tensors and"
899
+ " will perform operations on them which need fake tensor mode to"
900
+ " be active. You will segfault if you are in a no_dispatch() block."
901
+ )
902
+ assert not torch._C._dispatch_tls_local_exclude_set().has(
903
+ torch._C.DispatchKey.Python
904
+ ), msg
905
+ self.arg_cnt += 1
906
+
907
+ # When we make as_strided calls, we end up generating a guard
908
+ # that the new as_strided tensor is in bounds for the old storage
909
+ # for the base (since as_strided calls can "bust" out of their
910
+ # bounding box.) This guard is unnecessary: if a user is able
911
+ # to provide us a tensor with the view base setup this way, we
912
+ # don't need to produce a guard, because the fact that they
913
+ # were able to produce the view base means its in bounds.
914
+ #
915
+ # Now, ordinarily, this guard would be harmless. However, the
916
+ # generated guard refers to variables bound on the base variable.
917
+ # At the moment, Dynamo doesn't actually guard on x._base, because
918
+ # according to Voz this results in a lot of spurious invalidations,
919
+ # and also if the user doesn't directly make use of _base, its
920
+ # pointless anyway (because programs should be parametric over
921
+ # whether or not the input tensor is a view or not--unless you're
922
+ # mutating the input, but that's a whole 'nother ballgame). So
923
+ # for expediency, we suppress these guards so we don't have to
924
+ # deal with this (yet, anyway.)
925
+ #
926
+ # NB: An old version of this code suppressed guards for ALL operations
927
+ # happening during meta conversion, not just as_strided calls.
928
+ # This is too aggressive: we do duck sizing and 0/1 simplification
929
+ # as we allocate variables, and we do need to register guards for
930
+ # these cases.
931
+ maybe_suppress: Callable[[], Any] = contextlib.nullcontext
932
+ if shape_env is not None:
933
+ maybe_suppress = shape_env.suppress_guards
934
+
935
+ def sym_sizes_strides_storage_offset(
936
+ t: MetaTensorDesc,
937
+ src: torch._guards.Source,
938
+ symbolic_context: Optional[
939
+ torch.fx.experimental.symbolic_shapes.SymbolicContext
940
+ ] = symbolic_context,
941
+ ) -> tuple[tuple[int, ...], tuple[int, ...], int]:
942
+ assert t.stride is not None
943
+ if shape_env is not None:
944
+ fake_mode = t.fake_mode
945
+ if fake_mode is not None and fake_mode.shape_env is shape_env:
946
+ # Don't reallocate the sizes; the shape envs are the same,
947
+ # so reuse the old sizes/strides/etc
948
+ return (t.size, t.stride, t.storage_offset)
949
+ else:
950
+ # TODO: deduplicate this
951
+ t_size = tuple(
952
+ shape_env._maybe_specialize_sym_int_with_hint(sz)
953
+ for sz in t.size
954
+ )
955
+ t_stride = tuple(
956
+ shape_env._maybe_specialize_sym_int_with_hint(sd)
957
+ for sd in t.stride
958
+ )
959
+ t_storage_offset = shape_env._maybe_specialize_sym_int_with_hint(
960
+ t.storage_offset
961
+ )
962
+ return shape_env._create_symbolic_sizes_strides_storage_offset(
963
+ t_size,
964
+ t_stride,
965
+ t_storage_offset,
966
+ [d in t.dynamo_dynamic_indices for d in range(t.ndim)],
967
+ src,
968
+ symbolic_context=symbolic_context,
969
+ hint_overrides=t.dynamo_hint_overrides,
970
+ )
971
+ else:
972
+ return (t.size, t.stride, t.storage_offset)
973
+
974
+ def empty_create(
975
+ inner_t: MetaTensorDesc,
976
+ inner_src: torch._guards.Source,
977
+ symbolic_context: Optional[
978
+ torch.fx.experimental.symbolic_shapes.SymbolicContext
979
+ ] = symbolic_context,
980
+ ) -> torch.Tensor:
981
+ (
982
+ inner_sizes,
983
+ inner_strides,
984
+ _inner_storage_offset,
985
+ ) = sym_sizes_strides_storage_offset(inner_t, inner_src, symbolic_context)
986
+ return torch.empty_strided(
987
+ inner_sizes,
988
+ inner_strides,
989
+ dtype=inner_t.dtype,
990
+ device="meta",
991
+ )
992
+
993
+ # Creates a subclass instance with empty inner tensors according to the specified
994
+ # symbolic context.
995
+ def empty_create_subclass(
996
+ t: MetaTensorDesc,
997
+ outer_size: tuple[int, ...],
998
+ outer_stride: tuple[int, ...],
999
+ symbolic_context: Optional[
1000
+ torch.fx.experimental.symbolic_shapes.SymbolicContext
1001
+ ] = symbolic_context,
1002
+ source: Optional[torch._guards.Source] = source,
1003
+ ) -> _TensorT:
1004
+ from torch._dynamo.source import AttrSource
1005
+ from torch.fx.experimental.symbolic_shapes import SubclassSymbolicContext
1006
+
1007
+ assert t.attrs is not None
1008
+ assert t.type is not None
1009
+ # NB: t.ctx could be None if the subclass in question has no
1010
+ # meaningful context
1011
+
1012
+ # Note: transform_subclass will use __tensor_unflatten__ to generate
1013
+ # a fresh subclass wrapper with outer sizes / strides according to the
1014
+ # outer symbolic context (passed in to this function). Inner size / stride
1015
+ # / storage offset symbols are allocated according to the appropriate inner
1016
+ # symbolic contexts, after which the checks in transform_subclass() will
1017
+ # relate them to the outer metadata as possible.
1018
+ #
1019
+ # Morally, the code here is same as transform_subclass, but we've
1020
+ # written it from scratch to read EmptyCreateSubclass
1021
+ outer_size = outer_size if outer_size is not None else t.size
1022
+ # pyrefly: ignore [bad-assignment]
1023
+ outer_stride = outer_stride if outer_stride is not None else t.stride
1024
+
1025
+ assert symbolic_context is None or isinstance(
1026
+ symbolic_context, SubclassSymbolicContext
1027
+ )
1028
+
1029
+ def _empty_create_subclass(
1030
+ t: MetaTensorDesc,
1031
+ outer_size: Optional[tuple[int, ...]],
1032
+ outer_stride: Optional[tuple[int, ...]],
1033
+ symbolic_context: Optional[
1034
+ torch.fx.experimental.symbolic_shapes.SymbolicContext
1035
+ ],
1036
+ callback: _MetaTensorCallbackOptDevice[_TensorT],
1037
+ source: torch._guards.Source,
1038
+ ) -> _TensorT:
1039
+ # We are hitting plain meta_desc tensor so actually
1040
+ # create a tensor here.
1041
+ if t.attrs is None:
1042
+ return self.meta_tensor(
1043
+ t,
1044
+ shape_env,
1045
+ callback,
1046
+ source,
1047
+ symbolic_context,
1048
+ )
1049
+
1050
+ inner_tensors = {}
1051
+ for attr, meta_tensor_desc in t.attrs.items():
1052
+ current_context = None
1053
+ if symbolic_context is not None:
1054
+ assert isinstance(symbolic_context, SubclassSymbolicContext)
1055
+ if (
1056
+ current_context_ := symbolic_context.inner_contexts[attr]
1057
+ ) is not None:
1058
+ current_context = _checked_cast(
1059
+ torch.fx.experimental.symbolic_shapes.SymbolicContext,
1060
+ current_context_,
1061
+ )
1062
+
1063
+ current_source = AttrSource(source, attr)
1064
+ inner_callback = functools.partial(
1065
+ callback, device=meta_tensor_desc.device
1066
+ )
1067
+ new_empty_tensor = _empty_create_subclass(
1068
+ meta_tensor_desc,
1069
+ meta_tensor_desc.size,
1070
+ meta_tensor_desc.stride,
1071
+ current_context,
1072
+ inner_callback,
1073
+ current_source,
1074
+ )
1075
+ inner_tensors[attr] = new_empty_tensor
1076
+
1077
+ assert t.type is not None
1078
+ return t.type.__tensor_unflatten__( # type: ignore[attr-defined]
1079
+ inner_tensors, t.ctx, outer_size, outer_stride
1080
+ )
1081
+
1082
+ assert source is not None
1083
+ sub = _empty_create_subclass(
1084
+ t, outer_size, outer_stride, symbolic_context, callback, source
1085
+ )
1086
+
1087
+ # NB: Purposefully guard here to simplify the inner / outer symbols.
1088
+ # Using sym_eq() for symbolic comparison can result in an expression that's too
1089
+ # difficult to guard on, so we use == here.
1090
+ assert sub.shape == outer_size, (
1091
+ f"Expected return value from {t.type}__tensor_unflatten__() to have "
1092
+ f"shape equal to {outer_size}, but got: {sub.shape}"
1093
+ )
1094
+ assert sub.stride() == outer_stride, (
1095
+ f"Expected return value from {t.type}__tensor_unflatten__() to have "
1096
+ f"stride equal to {outer_stride}, but got: {sub.stride()}"
1097
+ )
1098
+
1099
+ return sub
1100
+
1101
+ # Returns an all-dynamic symbolic context used for metafying the given tensor with
1102
+ # fully dynamic dims. This is useful when fake-ifying intermediate tensors in
1103
+ # closed-over ViewFunc state, as we don't have symbolic contexts for them, but we
1104
+ # don't want to over-specialize during view replay.
1105
+ def all_dynamic_symbolic_context(
1106
+ t: MetaTensorDesc,
1107
+ source: torch._guards.Source,
1108
+ shape_env: Optional[torch.fx.experimental.symbolic_shapes.ShapeEnv],
1109
+ callback: _MetaTensorCallback[_TensorT],
1110
+ ) -> torch.fx.experimental.symbolic_shapes.SymbolicContext:
1111
+ from torch._dynamo.source import AttrSource
1112
+ from torch.fx.experimental.symbolic_shapes import (
1113
+ DimDynamic,
1114
+ StatelessSymbolicContext,
1115
+ SubclassSymbolicContext,
1116
+ )
1117
+
1118
+ view_base_context: Optional[
1119
+ torch.fx.experimental.symbolic_shapes.SymbolicContext
1120
+ ] = None
1121
+ if t.is_view:
1122
+ assert t.base is not None
1123
+ view_base_context = all_dynamic_symbolic_context(
1124
+ t.base, AttrSource(source, "_base"), shape_env, callback
1125
+ )
1126
+
1127
+ t_symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext
1128
+ t_dynamic_sizes = [DimDynamic.DYNAMIC] * t.ndim
1129
+ if t.is_traceable_wrapper_subclass:
1130
+ assert t.attrs is not None
1131
+ inner_contexts: dict[
1132
+ str, torch.fx.experimental.symbolic_shapes.SymbolicContext
1133
+ ] = {}
1134
+ for attr, inner in t.attrs.items():
1135
+ assert isinstance(attr, str)
1136
+ inner_contexts[attr] = all_dynamic_symbolic_context(
1137
+ inner, AttrSource(source, attr), shape_env, callback
1138
+ )
1139
+ t_symbolic_context = SubclassSymbolicContext(
1140
+ dynamic_sizes=t_dynamic_sizes,
1141
+ constraint_sizes=[None] * t.ndim,
1142
+ inner_contexts=inner_contexts, # type: ignore[arg-type]
1143
+ tensor_source=source,
1144
+ view_base_context=view_base_context,
1145
+ )
1146
+ else:
1147
+ t_symbolic_context = StatelessSymbolicContext(
1148
+ dynamic_sizes=t_dynamic_sizes,
1149
+ constraint_sizes=[None] * t.ndim,
1150
+ view_base_context=view_base_context,
1151
+ )
1152
+
1153
+ return t_symbolic_context
1154
+
1155
+ # Returns a fake-ified version of an input view tensor t, given an already fake-ified
1156
+ # base. At a high level, we want two things:
1157
+ # 1. fake_t should have the same view relationship to the given fake base as the
1158
+ # input t has to its _base.
1159
+ # 2. fake_t should have symbolic sizes / strides / storage offset according to the
1160
+ # appropriate symbolic context (i.e. from the automatic dynamic algorithm).
1161
+ #
1162
+ # We currently take different strategies across view types:
1163
+ # * For dense -> dense views, accomplish both (1) and (2) simultaneously via an
1164
+ # as_strided() call on the fake-ified base, passing symbolic metadata.
1165
+ # * For views involving subclasses, perform view replay using view funcs to
1166
+ # achieve (1). It's necessary for (2) to swap out any closed-over state in
1167
+ # the view funcs with symbolicized SymInts and fake-ified tensors. Doing this
1168
+ # avoids specialization (and thus over-eager simplification of symbols) that
1169
+ # could occur during view replay on the fake-ified base.
1170
+ #
1171
+ # Examples:
1172
+ # * t.unsqueeze(-1) with dense t is a dense -> dense view. It can be modeled
1173
+ # with an as_strided() call on the fake base passing symbolic metadata.
1174
+ # * sub.select(dim=0, index=3) is a subclass -> subclass view. The index arg
1175
+ # is made symbolic to avoid invalid specialization and view replay is then
1176
+ # done to reconstruct the view.
1177
+ # * _nested_from_jagged(values, offsets) is a dense -> subclass view
1178
+ # that returns a subclass instance from a dense values tensor. The offsets
1179
+ # tensor is closed over in the view func, as it can be considered view metadata.
1180
+ # First, the offsets tensor is fake-ified according to the inner symbolic
1181
+ # context and with the correct relationship to the outer size / stride metadata.
1182
+ # Then view replay is done, swapping in the fake offsets so the view replay output
1183
+ # is fully fake with no invalid specialization.
1184
+ def view_from_base(
1185
+ base: _TensorT,
1186
+ t: MetaTensorDesc,
1187
+ shape_env: Optional[
1188
+ torch.fx.experimental.symbolic_shapes.ShapeEnv
1189
+ ] = shape_env,
1190
+ ) -> _TensorT:
1191
+ with enable_python_dispatcher():
1192
+ # fake-ify t's metadata according to the outer symbolic context
1193
+ (sizes, strides, storage_offset) = sym_sizes_strides_storage_offset(
1194
+ t, source
1195
+ )
1196
+ if (
1197
+ not t.is_traceable_wrapper_subclass
1198
+ and not is_traceable_wrapper_subclass(base)
1199
+ ):
1200
+ # Dense -> Dense view case uses as_strided() to construct view relationship.
1201
+ # TODO: Change this logic to use view replay for consistency?
1202
+ # It's likely there is no view func available.
1203
+ with maybe_suppress():
1204
+ return self._checked_cast_tensor_t(
1205
+ base.as_strided(sizes, strides, storage_offset)
1206
+ )
1207
+
1208
+ from torch._dynamo.source import EphemeralSource
1209
+ from torch.fx.experimental.symbolic_shapes import (
1210
+ StatelessSymbolicContext,
1211
+ sym_eq,
1212
+ )
1213
+
1214
+ def symint_visitor_fn(s: int) -> int:
1215
+ nonlocal symbolic_context
1216
+ from torch.fx.experimental.symbolic_shapes import DimDynamic
1217
+
1218
+ all_static_sizes = (
1219
+ symbolic_context is not None
1220
+ and isinstance(symbolic_context, StatelessSymbolicContext)
1221
+ and all(
1222
+ x is DimDynamic.STATIC
1223
+ for x in symbolic_context.dynamic_sizes
1224
+ )
1225
+ )
1226
+ # Can't just rely on shape env being None - dynamo always initializes it
1227
+ if all_static_sizes or shape_env is None:
1228
+ return s
1229
+
1230
+ # NB: The symbol here is expected to be simplified out because we a priori
1231
+ # allocate inner and outer symbols according to the appropriate symbolic
1232
+ # contexts and prefer those over this symbol during symbol simplification
1233
+ # (via usage of EphemeralSource below). This -shouldn't- happen, but if
1234
+ # this symbol somehow leaks out beyond the view tensor's shape metadata, our
1235
+ # assumption of it being simplified out will fail and it may be guarded on,
1236
+ # which will hard error.
1237
+ sym_source = EphemeralSource("symint_visitor_fn")
1238
+
1239
+ symbol = shape_env.create_symbol(s, sym_source, positive=None)
1240
+ return shape_env.create_symintnode(
1241
+ symbol, hint=s, source=sym_source
1242
+ )
1243
+
1244
+ real_to_fake_mapping = {}
1245
+ if t.is_traceable_wrapper_subclass:
1246
+ assert t.attrs is not None
1247
+ # NB: t.ctx could be None if the subclass in question has no
1248
+ # meaningful context
1249
+ assert t.type is not None
1250
+
1251
+ # Fake-ify t naively here; this is only done so we can get fake-ified inner
1252
+ # tensors with the correct relationships to the outer sizes / strides for use
1253
+ # in view replay. It's done beforehand here because it's not easy to do when
1254
+ # visiting tensors one-by-one during view replay.
1255
+ #
1256
+ # Example:
1257
+ # Consider a Dense -> NJT view. NJT has (values, offsets) components and we
1258
+ # want a view of values with the offsets closed over. As the offsets component
1259
+ # is needed to describe the output view, it's important that it's fakeified
1260
+ # correctly.
1261
+ fake_t: _TensorT = empty_create_subclass(
1262
+ t, outer_size=sizes, outer_stride=strides
1263
+ )
1264
+ attrs, _ = fake_t.__tensor_flatten__() # type: ignore[attr-defined]
1265
+ for attr in attrs:
1266
+ real_to_fake_mapping[t.attrs[attr].id] = getattr(fake_t, attr)
1267
+
1268
+ def tensor_visitor_fn(
1269
+ visited_t: torch.Tensor,
1270
+ # These arguments are never passed, we just use them to close
1271
+ # over these relevant values
1272
+ shape_env: Optional[
1273
+ torch.fx.experimental.symbolic_shapes.ShapeEnv
1274
+ ] = shape_env,
1275
+ callback: _MetaTensorCallbackOptDevice[_TensorT] = callback,
1276
+ ) -> torch.Tensor:
1277
+ # It's possible to close over an undefined tensor (e.g. NJT's lengths).
1278
+ if visited_t is None:
1279
+ # pyrefly: ignore [bad-return]
1280
+ return None
1281
+
1282
+ # NB: visited_t being a Tensor here is very naughty! Should
1283
+ # have already been described
1284
+
1285
+ # Fake inner tensors of view subclasses will come from the mapping built above.
1286
+ visited_id = self.describer.get_tensor_id(visited_t)
1287
+ fake_visited_t = real_to_fake_mapping.get(visited_id)
1288
+ if fake_visited_t is not None:
1289
+ return fake_visited_t
1290
+
1291
+ visited_desc = self.describer.describe_tensor(visited_t)
1292
+
1293
+ # For other closed-over tensor state, fake-ify it as all dynamic with an
1294
+ # ephemeral source. This avoids invalid specialization during view replay.
1295
+ # If we find that in practice the usage of ephemeral sources isn't enough
1296
+ # to guarantee that we don't have guards on these symbols, we may need to
1297
+ # explicitly suppress guards (as is done for _base in the dense -> dense
1298
+ # view case).
1299
+ temp_source = EphemeralSource("tensor_visitor_fn")
1300
+ return self.meta_tensor(
1301
+ visited_desc,
1302
+ shape_env,
1303
+ callback,
1304
+ temp_source,
1305
+ all_dynamic_symbolic_context(
1306
+ visited_desc, temp_source, shape_env, callback
1307
+ ),
1308
+ )
1309
+
1310
+ # Replay the view, swapping out any non-symbolic SymInts or real tensors
1311
+ # for symbolic SymInts or fake tensors.
1312
+ assert t.view_func is not None
1313
+ # NB: we do NOT suppress guards here, we need to remove ephemeral
1314
+ # sources
1315
+ fake_t = t.view_func.apply(
1316
+ t, base, symint_visitor_fn, tensor_visitor_fn
1317
+ )
1318
+
1319
+ # Ensure the output has symbolic shapes according to the outer symbolic context.
1320
+ # These checks should simplify out any symbols created for closed-over view func
1321
+ # SymInts.
1322
+ torch._check(sym_eq(fake_t.size(), sizes))
1323
+ torch._check(sym_eq(fake_t.stride(), strides))
1324
+ torch._check(sym_eq(fake_t.storage_offset(), storage_offset))
1325
+ return fake_t
1326
+
1327
+ if self.get_tensor_memo(t) is None:
1328
+ GRAD_TENSOR_SENTINEL_VALUE = -2
1329
+
1330
+ with torch.inference_mode(t.is_inference):
1331
+ if t.is_sparse:
1332
+ is_leaf = t.is_leaf
1333
+
1334
+ # The lambda function below is similar to
1335
+ # `t.to(device='meta')` except the latter
1336
+ # preserves nnz value
1337
+ r = callback(
1338
+ lambda: torch.ops.aten._sparse_coo_tensor_with_dims(
1339
+ t.sparse_dim,
1340
+ t.dense_dim,
1341
+ t.size,
1342
+ dtype=t.dtype,
1343
+ layout=torch.sparse_coo,
1344
+ device="meta",
1345
+ )
1346
+ )
1347
+ if self.copy_data:
1348
+ # Pray that sparse clone doesn't lose information
1349
+ assert t.data is not None
1350
+ with torch.no_grad(), no_dispatch():
1351
+ assert _is_fake_tensor(r)
1352
+ r.real_tensor = _safe_clone(t.data)
1353
+ assert safe_is_leaf(r), "the callback you passed in doesn't detach"
1354
+ # Note [is_coalesced is dispatched]
1355
+ # Strangely enough, is_coalesced() is a dispatched operator,
1356
+ # which means that it will get caught by fake tensor mode.
1357
+ # Ordinarily this would error, but there's some logic in
1358
+ # fake tensor ensure this doesn't happen.
1359
+ r._coalesced_(bool(t.is_coalesced))
1360
+ if t.requires_grad:
1361
+ r.requires_grad = True
1362
+ if t.requires_grad and not is_leaf:
1363
+ # This should probably use DelayedError,
1364
+ # but clone is fine for now for sparse tensors.
1365
+ # (DelayedError does not work for sparse because it causes
1366
+ # the Fake sparse tensor to "lose" its fakeness)
1367
+ r = self._checked_cast_tensor_t(r.clone())
1368
+ with torch.enable_grad():
1369
+ r._coalesced_(bool(t.is_coalesced))
1370
+ elif is_sparse_compressed_layout(t.layout):
1371
+ is_leaf = t.is_leaf
1372
+
1373
+ if t.layout in {torch.sparse_bsr, torch.sparse_bsc}:
1374
+ assert t.sparse_dim is not None
1375
+ assert t.dense_dim is not None
1376
+ assert t.values is not None
1377
+ batch_dim = t.ndim - t.sparse_dim - t.dense_dim
1378
+ blocksize = t.values.shape[batch_dim + 1 : batch_dim + 3]
1379
+ else:
1380
+ blocksize = ()
1381
+ if t.layout in {torch.sparse_csr, torch.sparse_bsr}:
1382
+ assert t.crow_indices is not None
1383
+ index_dtype = t.crow_indices.dtype
1384
+ else:
1385
+ assert t.ccol_indices is not None
1386
+ index_dtype = t.ccol_indices.dtype
1387
+
1388
+ r = callback(
1389
+ lambda: torch.ops.aten._sparse_compressed_tensor_with_dims(
1390
+ 0,
1391
+ t.dense_dim,
1392
+ t.shape,
1393
+ blocksize,
1394
+ index_dtype,
1395
+ layout=t.layout,
1396
+ dtype=t.dtype,
1397
+ device="meta",
1398
+ )
1399
+ )
1400
+ if self.copy_data:
1401
+ # Pray sparse clone doesn't lose information
1402
+ assert t.data is not None
1403
+ with torch.no_grad(), no_dispatch():
1404
+ assert _is_fake_tensor(r)
1405
+ r.real_tensor = _safe_clone(t.data)
1406
+ assert safe_is_leaf(r), "the callback you passed in doesn't detach"
1407
+ if t.requires_grad:
1408
+ r.requires_grad = True
1409
+ if t.requires_grad and not is_leaf:
1410
+ # pyrefly: ignore [bad-argument-type]
1411
+ r = self._backward_error(r)
1412
+ elif t.is_nested and not t.is_traceable_wrapper_subclass:
1413
+ # TODO: Handle this better in Dynamo?
1414
+ # There are checks there now, but this can still be triggered by a dense
1415
+ # tensor graph input that is a view of a strided NT.
1416
+ from torch._dynamo.exc import unimplemented
1417
+
1418
+ # NOTE this graph break will NOT be present in Dynamo's graph break registry
1419
+ unimplemented(
1420
+ gb_type="attempted to apply meta conversion to strided nested tensor",
1421
+ context=str(t),
1422
+ explanation="This is not supported.",
1423
+ hints=[],
1424
+ )
1425
+ elif t.is_mkldnn:
1426
+ is_leaf = t.is_leaf
1427
+ (
1428
+ sizes,
1429
+ strides,
1430
+ _storage_offset,
1431
+ ) = sym_sizes_strides_storage_offset(t, source)
1432
+ # TODO: This doesn't seem right, where's the MKLDNN'ness
1433
+ # lol
1434
+ r = callback(
1435
+ lambda: torch.empty_strided(
1436
+ sizes, strides, dtype=t.dtype, device="meta"
1437
+ )
1438
+ )
1439
+ if self.copy_data:
1440
+ with torch.no_grad(), no_dispatch():
1441
+ assert t.size is not None
1442
+ assert t.stride is not None
1443
+ assert _is_fake_tensor(r)
1444
+ r.real_tensor = torch.empty_strided(
1445
+ t.size, t.stride, dtype=t.dtype, device=t.device
1446
+ )
1447
+ assert t.data is not None
1448
+ _safe_copy(r.real_tensor, t.data)
1449
+ assert safe_is_leaf(r), "the callback you passed in doesn't detach"
1450
+ if t.requires_grad:
1451
+ r.requires_grad = True
1452
+ if t.requires_grad and not is_leaf:
1453
+ # pyrefly: ignore [bad-argument-type]
1454
+ r = self._backward_error(r)
1455
+ elif t.is_functorch_wrapped:
1456
+ if t.is_view:
1457
+ from torch._dynamo.exc import unimplemented
1458
+
1459
+ unimplemented(
1460
+ gb_type="attempted to apply meta conversion to view functorch tensor",
1461
+ context=str(t),
1462
+ explanation="This is not supported.",
1463
+ hints=[],
1464
+ )
1465
+
1466
+ # Wraps a functorch tensor class (BatchedTensor, GradTrackingTensor)
1467
+ # in a FakeTensor
1468
+ def _to_fake_tensor(t: MetaTensorDesc) -> _TensorT:
1469
+ # TODO: why aren't the recursive calls going to
1470
+ # meta_tensor
1471
+ r: _TensorT
1472
+ if t.is_batchedtensor:
1473
+ assert t.unwrapped is not None
1474
+ assert t.level is not None
1475
+ assert t.bdim is not None
1476
+ ft = _to_fake_tensor(t.unwrapped)
1477
+ lvl = t.level
1478
+ bdim = t.bdim
1479
+ # You cannot create functorch tensors without
1480
+ # having the ambient funtorch interpreter stack
1481
+ # available, as the level refers to things in the
1482
+ # stack
1483
+ with torch._functorch.pyfunctorch.temporarily_restore_interpreter_stack(
1484
+ t.functorch_stack
1485
+ ):
1486
+ r = self._checked_cast_tensor_t(
1487
+ _add_batch_dim(ft, bdim, lvl)
1488
+ )
1489
+ elif t.is_gradtrackingtensor:
1490
+ assert t.unwrapped is not None
1491
+ assert t.level is not None
1492
+ disable_functorch = torch._C._DisableFuncTorch
1493
+ with disable_functorch():
1494
+ ft = _to_fake_tensor(t.unwrapped)
1495
+ lvl = t.level
1496
+ if lvl == GRAD_TENSOR_SENTINEL_VALUE:
1497
+ r = ft
1498
+ else:
1499
+ with torch._functorch.pyfunctorch.temporarily_restore_interpreter_stack(
1500
+ t.functorch_stack
1501
+ ):
1502
+ r = self._checked_cast_tensor_t(
1503
+ torch._C._functorch._wrap_for_grad(ft, lvl),
1504
+ )
1505
+
1506
+ is_leaf = t.is_leaf
1507
+ if t.requires_grad and safe_is_leaf(r):
1508
+ r.requires_grad = True
1509
+ elif t.requires_grad and not is_leaf:
1510
+ r = self._backward_error(r)
1511
+ elif t.is_functional:
1512
+ assert t.unwrapped is not None
1513
+ assert t.current_level is not None
1514
+ ft = self.meta_tensor(
1515
+ t.unwrapped,
1516
+ shape_env,
1517
+ callback,
1518
+ # NB: reuse these exactly, we treat the
1519
+ # functional tensor as "invisible".
1520
+ # TODO: Actually this all probably doesn't
1521
+ # work, take a closer look.
1522
+ source,
1523
+ symbolic_context,
1524
+ )
1525
+ r = self._checked_cast_tensor_t(
1526
+ _wrap_functional_tensor(ft, t.current_level),
1527
+ )
1528
+ # TODO: is_leaf/requires_grad?
1529
+ else:
1530
+ assert t.stride is not None
1531
+
1532
+ sizes = t.size
1533
+ strides = t.stride
1534
+ r = callback(
1535
+ lambda: torch.empty_strided(
1536
+ sizes,
1537
+ strides,
1538
+ dtype=t.dtype,
1539
+ device="meta",
1540
+ ),
1541
+ # device="meta",
1542
+ )
1543
+ if self.copy_data:
1544
+ with torch.no_grad(), no_dispatch():
1545
+ r.real_tensor = torch.empty_strided( # type: ignore[attr-defined]
1546
+ t.size,
1547
+ t.stride,
1548
+ dtype=t.dtype,
1549
+ device=t.device,
1550
+ )
1551
+ assert t.data is not None
1552
+ _safe_copy(r.real_tensor, t.data) # type: ignore[attr-defined]
1553
+ # pyrefly: ignore [bad-return]
1554
+ return r
1555
+
1556
+ r = _to_fake_tensor(t)
1557
+
1558
+ elif t.is_functional and t.device.type not in ["xla", "lazy"]:
1559
+ assert t.unwrapped is not None
1560
+ assert not t.is_functorch_wrapped # handled above
1561
+ unwrapped = self.meta_tensor(
1562
+ t.unwrapped,
1563
+ shape_env,
1564
+ callback,
1565
+ source,
1566
+ symbolic_context,
1567
+ )
1568
+ r = self._checked_cast_tensor_t(
1569
+ torch._to_functional_tensor(unwrapped)
1570
+ )
1571
+ torch._mirror_autograd_meta_to(t.autograd_meta_from, r) # type: ignore[attr-defined]
1572
+
1573
+ elif t.is_view:
1574
+ # Construct views in two steps: recursively meta-fy their
1575
+ # base, and then create view(s) off that. NB: doing it
1576
+ # directly from storage is WRONG because this won't cause
1577
+ # version counters to get shared.
1578
+
1579
+ assert t.base is not None
1580
+
1581
+ base_symbolic_context = None
1582
+ if shape_env and symbolic_context is not None:
1583
+ from torch.fx.experimental.symbolic_shapes import (
1584
+ StatelessSymbolicContext,
1585
+ )
1586
+
1587
+ assert isinstance(symbolic_context, StatelessSymbolicContext)
1588
+ # NB: This should generally be set when the input is a view,
1589
+ # but the exception right now is for fake-ifying grads, which is
1590
+ # a work in progress.
1591
+ if symbolic_context.view_base_context is not None:
1592
+ base_symbolic_context = symbolic_context.view_base_context
1593
+
1594
+ base = self.meta_tensor(
1595
+ t.base,
1596
+ shape_env,
1597
+ callback,
1598
+ torch._dynamo.source.AttrSource(source, "_base"),
1599
+ base_symbolic_context,
1600
+ )
1601
+
1602
+ def is_c_of_r(
1603
+ complex_dtype: torch.dtype, real_dtype: torch.dtype
1604
+ ) -> bool:
1605
+ return (
1606
+ utils.is_complex_dtype(complex_dtype)
1607
+ and utils.corresponding_real_dtype(complex_dtype)
1608
+ == real_dtype
1609
+ )
1610
+
1611
+ # In some situations, MetaConverter may be called in a
1612
+ # context where autograd is disabled. For the _is_view
1613
+ # assert to pass, we have to setup the autograd view
1614
+ # metadata anyway. Do this by reenabling the
1615
+ # ADInplaceOrView key. This is kind of a hack.
1616
+ old_exclude = torch._C._dispatch_tls_is_dispatch_key_excluded(
1617
+ torch._C.DispatchKey.ADInplaceOrView
1618
+ )
1619
+ torch._C._dispatch_tls_set_dispatch_key_excluded(
1620
+ torch._C.DispatchKey.ADInplaceOrView, False
1621
+ )
1622
+ try:
1623
+ if base.dtype == t.dtype:
1624
+ pass
1625
+ elif is_c_of_r(base.dtype, t.dtype):
1626
+ base = self._checked_cast_tensor_t(torch.view_as_real(base))
1627
+ elif is_c_of_r(t.dtype, base.dtype):
1628
+ base = self._checked_cast_tensor_t(
1629
+ torch.view_as_complex(base)
1630
+ )
1631
+ else:
1632
+ # This is not guaranteed to succeed. If it fails, it
1633
+ # means there is another dtype-converting view function
1634
+ # that hasn't been handled here
1635
+ base = self._checked_cast_tensor_t(base.view(t.dtype))
1636
+
1637
+ # This is very tricky. Naively, you might expect this
1638
+ # to hold:
1639
+ #
1640
+ # if t.requires_grad and not safe_is_leaf(t)
1641
+ # assert t._base.requires_grad
1642
+ #
1643
+ # But it's not true! As you can see in the following
1644
+ # program:
1645
+ #
1646
+ # x = torch.zeros(4)
1647
+ # y = x.view(1, 4)
1648
+ # y.requires_grad = True
1649
+ # z = y.view(1, 1, 4)
1650
+ # assert z._base is x
1651
+ #
1652
+ # So we may have to do *two* views out of the base to
1653
+ # recreate this situation.
1654
+ if t.is_leaf:
1655
+ # Leaf views that track view metadata are created by
1656
+ # creating a view inside a no_grad block
1657
+ with torch.no_grad():
1658
+ r = view_from_base(base, t)
1659
+ # As it's a leaf, we can directly assign requires_grad
1660
+ r.requires_grad = t.requires_grad
1661
+ else:
1662
+ if t.base.requires_grad == t.requires_grad:
1663
+ # Easy case, just run the view op
1664
+ with torch.enable_grad():
1665
+ r = view_from_base(base, t)
1666
+
1667
+ # NB: We don't actually faithfully replicate
1668
+ # autograd connectivity, but that doesn't matter
1669
+ # today. See following for more info:
1670
+ # https://gist.github.com/soulitzer/e03f015b314c3f5fcf80888c69390913
1671
+ else:
1672
+ # Obscure case. Create a leaf view and give it the
1673
+ # correct requires_grad, then do the final view.
1674
+ # NB: Can't have a non-leaf without requiring grad!
1675
+ assert t.requires_grad
1676
+ with torch.no_grad(), enable_python_dispatcher():
1677
+ mid = self._checked_cast_tensor_t(
1678
+ base.view(base.shape)
1679
+ )
1680
+ mid.requires_grad = t.requires_grad
1681
+ with torch.enable_grad():
1682
+ r = view_from_base(mid, t)
1683
+ # The CreationMeta influences whether or not inplace
1684
+ # mutation is an error or not. So we need to make
1685
+ # sure we properly propagate this as well.
1686
+ assert t.creation_meta is not None
1687
+ torch._C._autograd._set_creation_meta(r, t.creation_meta)
1688
+ finally:
1689
+ torch._C._dispatch_tls_set_dispatch_key_excluded(
1690
+ torch._C.DispatchKey.ADInplaceOrView, old_exclude
1691
+ )
1692
+
1693
+ r.fake_device = t.device # type: ignore[attr-defined]
1694
+
1695
+ else:
1696
+ is_leaf = t.is_leaf
1697
+
1698
+ # Graph-Break for wrapped tensors
1699
+ if (
1700
+ not (t.is_batchedtensor or t.is_gradtrackingtensor)
1701
+ and t.is_functorch_wrapped
1702
+ ) or t.is_legacy_batchedtensor:
1703
+ # pyrefly: ignore [bad-return]
1704
+ return NotImplemented
1705
+
1706
+ (
1707
+ sizes,
1708
+ strides,
1709
+ storage_offset,
1710
+ ) = sym_sizes_strides_storage_offset(t, source, symbolic_context)
1711
+
1712
+ # If we have a subclass that desugars into dense tensors,
1713
+ # perform our callback on each inner tensor.
1714
+ if t.is_traceable_wrapper_subclass:
1715
+ r = empty_create_subclass(
1716
+ t, outer_size=sizes, outer_stride=strides
1717
+ )
1718
+ else:
1719
+ r = callback(
1720
+ lambda: torch.empty_strided(
1721
+ sizes,
1722
+ strides,
1723
+ dtype=t.dtype,
1724
+ device="meta",
1725
+ )
1726
+ )
1727
+ if self.copy_data:
1728
+ with torch.no_grad(), no_dispatch():
1729
+ assert t.size is not None
1730
+ assert t.stride is not None
1731
+ assert _is_fake_tensor(r)
1732
+ r.real_tensor = torch.empty_strided(
1733
+ t.size, t.stride, dtype=t.dtype, device=t.device
1734
+ )
1735
+ _safe_copy(r.real_tensor, t.data)
1736
+
1737
+ assert safe_is_leaf(r), "the callback you passed in doesn't detach"
1738
+ if t.requires_grad:
1739
+ r.requires_grad = t.requires_grad
1740
+ if not is_leaf:
1741
+ # Fake up some autograd history.
1742
+ # Note: we *used* to call .clone() here to mock up some autograd history.
1743
+ # This is bad for subclasses.
1744
+ # Consider the case where you have a wrapper subclass that is contiguous,
1745
+ # but its inner tensor is noncontiguous().
1746
+ # .clone() (or other ops) will have the side effect of changing
1747
+ # the metadata of the inner tensor.
1748
+ # So instead, we now have a dedicated fn to set autograd history,
1749
+ # without inadvertently changing other metadata.
1750
+ # pyrefly: ignore [bad-argument-type]
1751
+ r = self._backward_error(r)
1752
+
1753
+ s = t.storage
1754
+ assert s is not None
1755
+ if s.id not in self.storage_memo and (
1756
+ r.is_nested
1757
+ or (
1758
+ r.stride() == strides
1759
+ and r.storage_offset() == storage_offset
1760
+ )
1761
+ ):
1762
+ # You're normal and happy, install the fresh storage into the memo
1763
+ self.set_storage_memo(s, r.untyped_storage())
1764
+ if self.copy_data:
1765
+ assert _is_fake_tensor(r)
1766
+ assert r.real_tensor is not None
1767
+ _set_real_storage(
1768
+ r.untyped_storage(), r.real_tensor.untyped_storage()
1769
+ )
1770
+ else:
1771
+ # You're in crazy town; somehow you gave us a tensor
1772
+ # that wasn't a view, but had nonzero storage offset,
1773
+ # nontrivial strides (such that clone() couldn't
1774
+ # preserve them), or already aliases with another
1775
+ # tensor's storage. The most typical way to end
1776
+ # up here is with set_. So use set_ to bludgeon this
1777
+ # in.
1778
+ r_s = self.meta_storage(s, callback=callback)
1779
+ # NB: In principle, this should always work, but there
1780
+ # is some subtle difference in the autograd metadata
1781
+ # that means we will backprop the set_ call, even if
1782
+ # r is declared as an input to grad.
1783
+ # See https://github.com/pytorch/pytorch/issues/87956
1784
+ # for the reproducer.
1785
+ # NB: The in_kernel_invocation_manager here is necessary
1786
+ # for fake tensor. If we run the set_ call with fake
1787
+ # tensor on, r will improperly report that it is NOT a
1788
+ # meta tensor but a cpu tensor, and then the set_ call
1789
+ # will fail due to device mismatch. no_dispatch() is
1790
+ # not enough, because the fake tensor will still claim
1791
+ # to be a CPU tensor and you'll end up in the CPU
1792
+ # kernel. Arguably this is a hack; a cleaner way to
1793
+ # solve this is to have a FakeStorage concept which
1794
+ # would report it's CPU device--no problem now! But
1795
+ # this is difficult to do because we don't have storage
1796
+ # subclasses. Relevant test is
1797
+ # DynamicShapesFunctionTests::test_add_dynamic_shapes in
1798
+ # test/dynamo/test_dynamic_shapes.py
1799
+ maybe_fake_mgr: AbstractContextManager[None] = (
1800
+ contextlib.nullcontext()
1801
+ )
1802
+ from torch._subclasses.fake_tensor import (
1803
+ in_kernel_invocation_manager,
1804
+ maybe_get_fake_mode,
1805
+ )
1806
+
1807
+ mb_fake_mode = maybe_get_fake_mode(r)
1808
+ if mb_fake_mode is not None:
1809
+ maybe_fake_mgr = in_kernel_invocation_manager(mb_fake_mode)
1810
+ with torch.no_grad(), maybe_suppress():
1811
+ with maybe_fake_mgr:
1812
+ r.set_(r_s, storage_offset, sizes, strides)
1813
+ if self.copy_data:
1814
+ with torch.no_grad(), no_dispatch():
1815
+ assert _is_fake_tensor(r)
1816
+ assert r.real_tensor is not None
1817
+ assert t.stride is not None
1818
+ r.real_tensor.set_(
1819
+ _get_real_storage(r_s),
1820
+ t.storage_offset,
1821
+ t.size,
1822
+ t.stride,
1823
+ )
1824
+
1825
+ if t.grad is not None:
1826
+ from torch._dynamo.source import AttrSource
1827
+
1828
+ # TODO: Use a valid grad-specific symbolic context instead of recycling
1829
+ # the one from t. This isn't correct if e.g. t._is_view() != t.grad._is_view().
1830
+ # pyrefly: ignore [unbound-name]
1831
+ r.grad = self.meta_tensor(
1832
+ t.grad,
1833
+ shape_env,
1834
+ callback,
1835
+ AttrSource(source, "grad"),
1836
+ symbolic_context,
1837
+ )
1838
+ # pyrefly: ignore [unbound-name]
1839
+ torch._C._set_conj(r, t.is_conj)
1840
+ # pyrefly: ignore [unbound-name]
1841
+ torch._C._set_neg(r, t.is_neg)
1842
+ # This can be skipped if necessary for performance reasons
1843
+ skip_leaf = (
1844
+ t.is_gradtrackingtensor and t.level == GRAD_TENSOR_SENTINEL_VALUE
1845
+ )
1846
+ # pyrefly: ignore [unbound-name]
1847
+ assert_metadata_eq(assert_eq, t, r, skip_symbolic=True, skip_leaf=skip_leaf)
1848
+ # Thanks to storage resizing, it's possible to end up with a tensor
1849
+ # that advertises a real size, but has a storage that actually has zero bytes.
1850
+ # Need to reflect this in the generated FakeTensor.
1851
+ from torch.fx.experimental.symbolic_shapes import guard_or_false
1852
+
1853
+ if t.storage is not None and guard_or_false(t.storage.size == 0):
1854
+ # pyrefly: ignore [unbound-name]
1855
+ r.untyped_storage().resize_(0)
1856
+
1857
+ if t.is_parameter:
1858
+ # pyrefly: ignore [unbound-name]
1859
+ r._is_param = True
1860
+
1861
+ # See Note: [Creating symbolic nested int]
1862
+ if t.nested_int is not None:
1863
+ # pyrefly: ignore [unbound-name]
1864
+ assert _is_fake_tensor(r)
1865
+ # pyrefly: ignore [unbound-name]
1866
+ r.nested_int_memo = r.fake_mode.create_symbolic_nested_int(
1867
+ nt_tensor_id=t.nested_int
1868
+ )
1869
+
1870
+ # pyrefly: ignore [bad-argument-type, unbound-name]
1871
+ self.set_tensor_memo(t, r)
1872
+
1873
+ return self._checked_get_tensor_memo(t)
1874
+
1875
+ def __call__(
1876
+ self,
1877
+ t: torch.Tensor,
1878
+ shape_env: Optional[ShapeEnv] = None,
1879
+ *,
1880
+ callback: Optional[_MetaTensorCallback[_TensorT]] = None,
1881
+ source: Optional[Source] = None,
1882
+ symbolic_context: Optional[SymbolicContext] = None,
1883
+ # Controls whether or not we should dump the tensor metadata to structured logs
1884
+ # when source is not None. Because we refakify after Dynamo is done,
1885
+ # we don't want to dump info again from AOTAutograd, it is redundant.
1886
+ trace: bool = True,
1887
+ ) -> _TensorT:
1888
+ callback_: _MetaTensorCallback[_TensorT]
1889
+ if callback is None:
1890
+ callback_ = self._identity_callable
1891
+ else:
1892
+ callback_ = callback
1893
+ # TODO: zero tensors? We appear to have eliminated them by
1894
+ # excluding complex for now
1895
+
1896
+ # Filter out cases we don't support
1897
+ # TODO: This can probably be simplified quite a bit
1898
+ if isinstance(t, torch.Tensor):
1899
+ if (
1900
+ # Lazy tensors are not supported. Note that XLA is
1901
+ # implemented on top of lazy tensor, not excluded here; we
1902
+ # have some special handling for it; this is for XLA Dynamo
1903
+ # integration
1904
+ t.device.type == "lazy"
1905
+ or
1906
+ # Quantization is not supported
1907
+ t.is_quantized
1908
+ or
1909
+ # Views out of sparse tensors not currently supported (plain
1910
+ # sparse is supported htough)
1911
+ (t._is_view() and t._base is not None and t._base.is_sparse)
1912
+ ):
1913
+ self.miss += 1
1914
+ # pyrefly: ignore [bad-return]
1915
+ return NotImplemented
1916
+ else:
1917
+ self.hit += 1
1918
+ elif torch.overrides.is_tensor_like(t):
1919
+ self.miss += 1
1920
+ # pyrefly: ignore [bad-return]
1921
+ return NotImplemented
1922
+ else:
1923
+ # non-Tensor types don't count as hit or miss
1924
+ return t
1925
+
1926
+ if source is None:
1927
+ trace = False
1928
+
1929
+ # Describe the tensor. NB: do NOT disable ambient modes, we may need
1930
+ # to query them when figuring out what to put in here
1931
+ t_desc = self.describer.describe_tensor(t, trace=trace)
1932
+
1933
+ if trace:
1934
+ assert source is not None
1935
+ trace_structured(
1936
+ "describe_source",
1937
+ metadata_fn=lambda: {
1938
+ "describer_id": self.describer.id,
1939
+ "id": t_desc.id,
1940
+ "source": source.name,
1941
+ },
1942
+ )
1943
+
1944
+ # Do the meta-fication. Here, we disable all the ambient modes, to
1945
+ # better simulate what would be like to re-fakeify from a fresh
1946
+ # process
1947
+ with contextlib.ExitStack() as exit_stack:
1948
+ exit_stack.enter_context(torch._dispatch.python.suspend_functionalization())
1949
+ st = peek_interpreter_stack()
1950
+ if st is not None:
1951
+ exit_stack.enter_context(
1952
+ torch._functorch.pyfunctorch.temporarily_clear_interpreter_stack()
1953
+ )
1954
+
1955
+ r = self.meta_tensor(
1956
+ t_desc,
1957
+ shape_env,
1958
+ callback_,
1959
+ source,
1960
+ symbolic_context,
1961
+ )
1962
+
1963
+ if type(t) is torch.nn.Parameter:
1964
+ # NB: Cannot directly use Parameter constructor
1965
+ # because that would force a detach, not desirable
1966
+ r._is_param = True
1967
+
1968
+ # TODO: return the description for later
1969
+ return r
1970
+
1971
+
1972
+ import torch._prims_common as utils
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_subclasses/schema_check_mode.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ from collections import namedtuple
4
+ from copy import deepcopy
5
+ from itertools import combinations
6
+
7
+ import torch
8
+ from torch.fx.operator_schemas import normalize_function
9
+ from torch.utils import _pytree as pytree
10
+ from torch.utils._python_dispatch import TorchDispatchMode
11
+ from torch.utils._pytree import tree_map
12
+
13
+
14
+ # Named Tuples used within SchemaCheckMode
15
+ Mutation = namedtuple("Mutation", ["op_name", "arg_name"])
16
+ Aliasing = namedtuple("Aliasing", ["op_name", "arg_name", "output_number"])
17
+
18
+ # Simplified naming for C++ classes
19
+ SchemaArgument = torch._C._SchemaArgument
20
+ SchemaArgType = torch._C._SchemaArgType
21
+ SchemaInfo = torch._C._SchemaInfo
22
+
23
+ # This TorchDispatchMode Subclass is used to verify op schemas
24
+ # This TorchDispatchMode Scubclass currently:
25
+ # - Records the called ops
26
+ # - Checks for mutations on all inputs
27
+ # - Checks for aliasing on all inputs
28
+
29
+
30
+ # move these 2 functions here to avoid numpy dependency in testing/_internal/common_utils.py
31
+
32
+
33
+ def is_iterable_of_tensors(iterable):
34
+ # Tensor itself is iterable so we check this first
35
+ if isinstance(iterable, torch.Tensor):
36
+ return False
37
+ try:
38
+ if len(iterable) == 0:
39
+ return False
40
+ for t in iter(iterable):
41
+ if not isinstance(t, torch.Tensor):
42
+ return False
43
+ except TypeError:
44
+ return False
45
+ return True
46
+
47
+
48
+ def clone_inputs(args):
49
+ inputs = []
50
+
51
+ for arg in args:
52
+ if isinstance(arg, torch.Tensor):
53
+ inputs.append(arg.detach().clone())
54
+ elif is_iterable_of_tensors(arg):
55
+ inputs.append([t.detach().clone() for t in arg])
56
+ else:
57
+ inputs.append(arg)
58
+
59
+ return inputs
60
+
61
+
62
+ class SchemaCheckMode(TorchDispatchMode):
63
+ def __init__(self) -> None:
64
+ # Information recorded for testing purposes. For example:
65
+ # - incorrect schemas
66
+ # - overly conservative schemas
67
+ self.ops = []
68
+ self.mutated = []
69
+ self.aliasing = []
70
+
71
+ def reset_cache(self):
72
+ self.ops.clear()
73
+ self.mutated.clear()
74
+ self.aliasing.clear()
75
+
76
+ def display_ops(self):
77
+ print(*self.ops, sep=",")
78
+
79
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):
80
+ def bitwise_equal(lhs, rhs):
81
+ if lhs.is_quantized:
82
+ # TODO: This is only OK if can't have NaN quantized; idk if
83
+ # this is actually true
84
+ return torch.equal(lhs, rhs)
85
+ else:
86
+ return torch.allclose(lhs, rhs, equal_nan=True)
87
+
88
+ def has_mutated(before, after, md):
89
+ are_tensors = type(before) is torch.Tensor and type(after) is torch.Tensor
90
+ if (
91
+ are_tensors
92
+ and before.layout != torch.sparse_csr
93
+ and after.layout != torch.sparse_csr
94
+ ):
95
+ return not (
96
+ before.size() == after.size()
97
+ and bitwise_equal(before, after)
98
+ and md[0] == after.stride()
99
+ and md[1] == after._typed_storage()._cdata
100
+ )
101
+ return False
102
+
103
+ def has_aliased(lhs, rhs):
104
+ try:
105
+ return torch._C._overlaps(lhs, rhs)
106
+ except Exception as exception:
107
+ if str(exception).startswith("Cannot inspect value of type "):
108
+ return False
109
+ else:
110
+ raise exception
111
+
112
+ def standardize_name(name):
113
+ return name if name != "self" else "input"
114
+
115
+ def unwrap(e):
116
+ if isinstance(e, torch.Tensor) and type(e) is not torch.Tensor:
117
+ try:
118
+ return e.elem
119
+ except AttributeError:
120
+ return e
121
+ return e
122
+
123
+ def parse_metadata(e):
124
+ if isinstance(e, torch.Tensor):
125
+ if type(e) is not torch.Tensor:
126
+ try:
127
+ current = e.elem
128
+ return (
129
+ deepcopy(current.stride()),
130
+ current._typed_storage()._cdata,
131
+ )
132
+ except AttributeError:
133
+ return None
134
+ # Sparse CSR tensors do not have strides or storage
135
+ elif e.layout != torch.sparse_csr:
136
+ return (deepcopy(e.stride()), e._typed_storage()._cdata)
137
+ return None
138
+
139
+ self.ops.append(func._schema.name)
140
+
141
+ # Clone and process arguments and outputs
142
+ pre_arguments = normalize_function(
143
+ func, args, kwargs, normalize_to_only_use_kwargs=True
144
+ ).kwargs
145
+
146
+ c_p_args = dict(zip(pre_arguments.keys(), clone_inputs(pre_arguments.values())))
147
+ cloned_arguments = {
148
+ name: tree_map(unwrap, c_p_args.get(name)) for name in c_p_args
149
+ }
150
+ cloned_metadata = {
151
+ name: [
152
+ parse_metadata(a) for a in pytree.tree_leaves(pre_arguments.get(name))
153
+ ]
154
+ for name in pre_arguments
155
+ }
156
+
157
+ out = func(*args, **kwargs)
158
+ arguments = {
159
+ name: tree_map(unwrap, pre_arguments.get(name)) for name in pre_arguments
160
+ }
161
+ tuple_out = out if isinstance(out, tuple) else (out,)
162
+ tuple_out = tree_map(unwrap, tuple_out)
163
+
164
+ schema_info = SchemaInfo(func._schema)
165
+ schema_info.add_argument_values(pre_arguments)
166
+
167
+ # Process arguments with outputs
168
+ for i in range(len(func._schema.arguments)):
169
+ arg = func._schema.arguments[i]
170
+ name = standardize_name(arg.name)
171
+ if arguments.get(name) is not None:
172
+ before = cloned_arguments.get(name)
173
+ md = cloned_metadata.get(name)
174
+ after = arguments.get(name)
175
+ for j in range(len(tuple_out)):
176
+ # aten::_unsafe_view is intended to have incorrect aliasing notation (hence unsafe)
177
+ unsafe_ops = ("aten::_unsafe_view", "aten::unsafe_split")
178
+ if (
179
+ has_aliased(tuple_out[j], after)
180
+ and func._schema.name not in unsafe_ops
181
+ ):
182
+ if not schema_info.may_contain_alias(
183
+ SchemaArgument(SchemaArgType.output, j),
184
+ SchemaArgument(SchemaArgType.input, i),
185
+ ):
186
+ raise RuntimeError(
187
+ f"Argument {name} is not defined to alias output but was aliasing"
188
+ )
189
+ else:
190
+ self.aliasing.append(
191
+ Aliasing(func._schema.name, name, f"output_{j}")
192
+ )
193
+ if after is tuple_out[j] and isinstance(after, torch.Tensor):
194
+ # Only mutable ops e.g. (add_, add.out) are allowed to directly return inputs.
195
+ if not schema_info.is_mutable(
196
+ SchemaArgument(SchemaArgType.input, i)
197
+ ) and func not in [
198
+ torch.ops.aten.lift.default,
199
+ torch.ops.aten.lift_fresh.default,
200
+ ]:
201
+ raise RuntimeError(
202
+ f"""\
203
+ Dispatcher operators below autograd are not allowed to directly return inputs.
204
+ However, we found that `outputs[{str(j)}] is {name}"""
205
+ )
206
+ if any(
207
+ has_mutated(a, b, c)
208
+ for a, b, c in zip(
209
+ pytree.tree_leaves(before), pytree.tree_leaves(after), md
210
+ )
211
+ ):
212
+ if not schema_info.is_mutable(
213
+ SchemaArgument(SchemaArgType.input, i)
214
+ ):
215
+ raise RuntimeError(
216
+ f"Argument {name} is not defined as mutable but was mutated"
217
+ )
218
+ else:
219
+ self.mutated.append(Mutation(func._schema.name, name))
220
+
221
+ # Aliasing between outputs
222
+ for i, j in combinations(range(len(func._schema.returns)), 2):
223
+ if has_aliased(tuple_out[i], tuple_out[j]):
224
+ if not schema_info.may_contain_alias(
225
+ SchemaArgument(SchemaArgType.output, i),
226
+ SchemaArgument(SchemaArgType.output, j),
227
+ ):
228
+ raise RuntimeError(f"Outputs {i} and {j} alias unexpectedly")
229
+
230
+ return out
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vendor/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/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__
miniconda3/envs/active_proaction/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()
miniconda3/envs/active_proaction/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
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/accelerator/__init__.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ This package introduces support for the current :ref:`accelerator<accelerators>` in python.
3
+ """
4
+
5
+ from functools import cache
6
+ from typing import Any
7
+ from typing_extensions import deprecated
8
+
9
+ import torch
10
+
11
+ from ._utils import _device_t, _get_device_index
12
+ from .memory import (
13
+ empty_cache,
14
+ get_memory_info,
15
+ max_memory_allocated,
16
+ max_memory_reserved,
17
+ memory_allocated,
18
+ memory_reserved,
19
+ memory_stats,
20
+ reset_accumulated_memory_stats,
21
+ reset_peak_memory_stats,
22
+ )
23
+
24
+
25
+ __all__ = [
26
+ "current_accelerator",
27
+ "current_device_idx", # deprecated
28
+ "current_device_index",
29
+ "get_device_capability",
30
+ "current_stream",
31
+ "device_count",
32
+ "device_index",
33
+ "empty_cache",
34
+ "get_memory_info",
35
+ "is_available",
36
+ "max_memory_allocated",
37
+ "max_memory_reserved",
38
+ "memory_allocated",
39
+ "memory_reserved",
40
+ "memory_stats",
41
+ "reset_accumulated_memory_stats",
42
+ "reset_peak_memory_stats",
43
+ "set_device_idx", # deprecated
44
+ "set_device_index",
45
+ "set_stream",
46
+ "synchronize",
47
+ ]
48
+
49
+
50
+ def device_count() -> int:
51
+ r"""Return the number of current :ref:`accelerator<accelerators>` available.
52
+
53
+ Returns:
54
+ int: the number of the current :ref:`accelerator<accelerators>` available.
55
+ If there is no available accelerators, return 0.
56
+
57
+ .. note:: This API delegates to the device-specific version of `device_count`.
58
+ On CUDA, this API will NOT poison fork if NVML discovery succeeds.
59
+ Otherwise, it will. For more details, see :ref:`multiprocessing-poison-fork-note`.
60
+ """
61
+ acc = current_accelerator()
62
+ if acc is None:
63
+ return 0
64
+
65
+ mod = torch.get_device_module(acc)
66
+ return mod.device_count()
67
+
68
+
69
+ def is_available() -> bool:
70
+ r"""Check if the current accelerator is available at runtime: it was build, all the
71
+ required drivers are available and at least one device is visible.
72
+ See :ref:`accelerator<accelerators>` for details.
73
+
74
+ Returns:
75
+ bool: A boolean indicating if there is an available :ref:`accelerator<accelerators>`.
76
+
77
+ .. note:: This API delegates to the device-specific version of `is_available`.
78
+ On CUDA, when the environment variable ``PYTORCH_NVML_BASED_CUDA_CHECK=1`` is set,
79
+ this function will NOT poison fork. Otherwise, it will. For more details, see
80
+ :ref:`multiprocessing-poison-fork-note`.
81
+
82
+ Example::
83
+
84
+ >>> assert torch.accelerator.is_available() "No available accelerators detected."
85
+ """
86
+ # Why not just check "device_count() > 0" like other is_available call?
87
+ # Because device like CUDA have a python implementation of is_available that is
88
+ # non-poisoning and some features like Dataloader rely on it.
89
+ # So we are careful to delegate to the Python version of the accelerator here
90
+ acc = current_accelerator()
91
+ if acc is None:
92
+ return False
93
+
94
+ mod = torch.get_device_module(acc)
95
+ return mod.is_available()
96
+
97
+
98
+ def current_accelerator(check_available: bool = False) -> torch.device | None:
99
+ r"""Return the device of the accelerator available at compilation time.
100
+ If no accelerator were available at compilation time, returns None.
101
+ See :ref:`accelerator<accelerators>` for details.
102
+
103
+ Args:
104
+ check_available (bool, optional): if True, will also do a runtime check to see
105
+ if the device :func:`torch.accelerator.is_available` on top of the compile-time
106
+ check.
107
+ Default: ``False``
108
+
109
+ Returns:
110
+ torch.device: return the current accelerator as :class:`torch.device`.
111
+
112
+ .. note:: The index of the returned :class:`torch.device` will be ``None``, please use
113
+ :func:`torch.accelerator.current_device_index` to know the current index being used.
114
+ This API does NOT poison fork. For more details, see :ref:`multiprocessing-poison-fork-note`.
115
+
116
+ Example::
117
+
118
+ >>> # xdoctest:
119
+ >>> # If an accelerator is available, sent the model to it
120
+ >>> model = torch.nn.Linear(2, 2)
121
+ >>> if (current_device := current_accelerator(check_available=True)) is not None:
122
+ >>> model.to(current_device)
123
+ """
124
+ if (acc := torch._C._accelerator_getAccelerator()) is not None:
125
+ if (not check_available) or (check_available and is_available()):
126
+ return acc
127
+ return None
128
+
129
+
130
+ def current_device_index() -> int:
131
+ r"""Return the index of a currently selected device for the current :ref:`accelerator<accelerators>`.
132
+
133
+ Returns:
134
+ int: the index of a currently selected device.
135
+ """
136
+ return torch._C._accelerator_getDeviceIndex()
137
+
138
+
139
+ current_device_idx = deprecated(
140
+ "Use `current_device_index` instead.",
141
+ category=FutureWarning,
142
+ )(current_device_index)
143
+
144
+ current_device_idx.__doc__ = r"""
145
+ (Deprecated) Return the index of a currently selected device for the current :ref:`accelerator<accelerators>`.
146
+
147
+ Returns:
148
+ int: the index of a currently selected device.
149
+
150
+ .. warning::
151
+
152
+ :func:`torch.accelerator.current_device_idx` is deprecated in favor of :func:`torch.accelerator.current_device_index`
153
+ and will be removed in a future PyTorch release.
154
+ """
155
+
156
+
157
+ @cache
158
+ def get_device_capability(device: _device_t = None, /) -> dict[str, Any]:
159
+ r"""Return the capability of the currently selected device.
160
+
161
+ Args:
162
+ device (:class:`torch.device`, str, int, optional): The device to query capabilities for
163
+ :ref:`accelerator<accelerators>` device type. If not given,
164
+ use :func:`torch.accelerator.current_device_index` by default.
165
+
166
+ Returns:
167
+ dict[str, Any]: A dictionary containing device capability information. The dictionary includes:
168
+ - ``supported_dtypes`` (set(torch.dtype)): Set of PyTorch data types supported by the device
169
+
170
+ Examples:
171
+ >>> # xdoctest: +SKIP("requires cuda")
172
+ >>> # Query capabilities for current device
173
+ >>> capabilities = torch.accelerator.get_device_capability("cuda:0")
174
+ >>> print("Supported dtypes:", capabilities["supported_dtypes"])
175
+ """
176
+ device_index = _get_device_index(device, optional=True)
177
+ return torch._C._accelerator_getDeviceCapability(device_index)
178
+
179
+
180
+ def set_device_index(device: _device_t, /) -> None:
181
+ r"""Set the current device index to a given device.
182
+
183
+ Args:
184
+ device (:class:`torch.device`, str, int): a given device that must match the current
185
+ :ref:`accelerator<accelerators>` device type.
186
+
187
+ .. note:: This function is a no-op if this device index is negative.
188
+ """
189
+ device_index = _get_device_index(device, optional=False)
190
+ torch._C._accelerator_setDeviceIndex(device_index)
191
+
192
+
193
+ set_device_idx = deprecated(
194
+ "Use `set_device_index` instead.",
195
+ category=FutureWarning,
196
+ )(set_device_index)
197
+
198
+ set_device_idx.__doc__ = r"""
199
+ (Deprecated) Set the current device index to a given device.
200
+
201
+ Args:
202
+ device (:class:`torch.device`, str, int): a given device that must match the current
203
+ :ref:`accelerator<accelerators>` device type.
204
+
205
+ .. warning::
206
+
207
+ :func:`torch.accelerator.set_device_idx` is deprecated in favor of :func:`torch.accelerator.set_device_index`
208
+ and will be removed in a future PyTorch release.
209
+ """
210
+
211
+
212
+ def current_stream(device: _device_t = None, /) -> torch.Stream:
213
+ r"""Return the currently selected stream for a given device.
214
+
215
+ Args:
216
+ device (:class:`torch.device`, str, int, optional): a given device that must match the current
217
+ :ref:`accelerator<accelerators>` device type. If not given,
218
+ use :func:`torch.accelerator.current_device_index` by default.
219
+
220
+ Returns:
221
+ torch.Stream: the currently selected stream for a given device.
222
+ """
223
+ device_index = _get_device_index(device, optional=True)
224
+ return torch._C._accelerator_getStream(device_index)
225
+
226
+
227
+ def set_stream(stream: torch.Stream) -> None:
228
+ r"""Set the current stream to a given stream.
229
+
230
+ Args:
231
+ stream (torch.Stream): a given stream that must match the current :ref:`accelerator<accelerators>` device type.
232
+
233
+ .. note:: This function will set the current device index to the device index of the given stream.
234
+ """
235
+ torch._C._accelerator_setStream(stream)
236
+
237
+
238
+ def synchronize(device: _device_t = None, /) -> None:
239
+ r"""Wait for all kernels in all streams on the given device to complete.
240
+
241
+ Args:
242
+ device (:class:`torch.device`, str, int, optional): device for which to synchronize. It must match
243
+ the current :ref:`accelerator<accelerators>` device type. If not given,
244
+ use :func:`torch.accelerator.current_device_index` by default.
245
+
246
+ .. note:: This function is a no-op if the current :ref:`accelerator<accelerators>` is not initialized.
247
+
248
+ Example::
249
+
250
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
251
+ >>> assert torch.accelerator.is_available() "No available accelerators detected."
252
+ >>> start_event = torch.Event(enable_timing=True)
253
+ >>> end_event = torch.Event(enable_timing=True)
254
+ >>> start_event.record()
255
+ >>> tensor = torch.randn(100, device=torch.accelerator.current_accelerator())
256
+ >>> sum = torch.sum(tensor)
257
+ >>> end_event.record()
258
+ >>> torch.accelerator.synchronize()
259
+ >>> elapsed_time_ms = start_event.elapsed_time(end_event)
260
+ """
261
+ device_index = _get_device_index(device, optional=True)
262
+ torch._C._accelerator_synchronizeDevice(device_index)
263
+
264
+
265
+ class device_index:
266
+ r"""Context manager to set the current device index for the current :ref:`accelerator<accelerators>`.
267
+ Temporarily changes the current device index to the specified value for the duration
268
+ of the context, and automatically restores the previous device index when exiting
269
+ the context.
270
+
271
+ Args:
272
+ device (Optional[int]): a given device index to temporarily set. If None,
273
+ no device index switching occurs.
274
+
275
+ Examples:
276
+
277
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
278
+ >>> # Set device 0 as the current device temporarily
279
+ >>> with torch.accelerator.device_index(0):
280
+ ... # Code here runs with device 0 as the current device
281
+ ... pass
282
+ >>> # Original device is now restored
283
+ >>> # No-op when None is passed
284
+ >>> with torch.accelerator.device_index(None):
285
+ ... # No device switching occurs
286
+ ... pass
287
+ """
288
+
289
+ def __init__(self, device: int | None, /) -> None:
290
+ self.idx = device
291
+ self.prev_idx = -1
292
+
293
+ def __enter__(self) -> None:
294
+ if self.idx is not None:
295
+ self.prev_idx = torch._C._accelerator_exchangeDevice(self.idx)
296
+
297
+ def __exit__(self, *exc_info: object) -> None:
298
+ if self.idx is not None:
299
+ torch._C._accelerator_maybeExchangeDevice(self.prev_idx)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/accelerator/_utils.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.types import Device as _device_t
3
+
4
+
5
+ def _get_device_index(device: _device_t, optional: bool = False) -> int:
6
+ if isinstance(device, int):
7
+ return device
8
+ if isinstance(device, str):
9
+ device = torch.device(device)
10
+ device_index: int | None = None
11
+ if isinstance(device, torch.device):
12
+ acc = torch.accelerator.current_accelerator()
13
+ if acc is None:
14
+ raise RuntimeError("Accelerator expected")
15
+ if acc.type != device.type:
16
+ raise ValueError(
17
+ f"{device.type} doesn't match the current accelerator {acc}."
18
+ )
19
+ device_index = device.index
20
+ if device_index is None:
21
+ if not optional:
22
+ raise ValueError(
23
+ f"Expected a torch.device with a specified index or an integer, but got:{device}"
24
+ )
25
+ return torch.accelerator.current_device_index()
26
+ return device_index
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/accelerator/memory.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Any
3
+
4
+ import torch
5
+
6
+ from ._utils import _device_t, _get_device_index
7
+
8
+
9
+ __all__ = [
10
+ "empty_cache",
11
+ "get_memory_info",
12
+ "max_memory_allocated",
13
+ "max_memory_reserved",
14
+ "memory_allocated",
15
+ "memory_reserved",
16
+ "memory_stats",
17
+ "reset_accumulated_memory_stats",
18
+ "reset_peak_memory_stats",
19
+ ]
20
+
21
+
22
+ def empty_cache() -> None:
23
+ r"""Release all unoccupied cached memory currently held by the caching
24
+ allocator so that those can be used in other application.
25
+
26
+ .. note:: This function is a no-op if the memory allocator for the current
27
+ :ref:`accelerator <accelerators>` has not been initialized.
28
+ """
29
+ if not torch._C._accelerator_isAllocatorInitialized():
30
+ return
31
+ torch._C._accelerator_emptyCache()
32
+
33
+
34
+ def memory_stats(device_index: _device_t = None, /) -> OrderedDict[str, Any]:
35
+ r"""Return a dictionary of accelerator device memory allocator statistics for a given device index.
36
+
37
+ The return value of this function is a dictionary of statistics, each of
38
+ which is a non-negative integer.
39
+
40
+ Core statistics:
41
+
42
+ - ``"allocated.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
43
+ number of allocation requests received by the memory allocator.
44
+ - ``"allocated_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
45
+ amount of allocated memory.
46
+ - ``"segment.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
47
+ number of reserved segments from device memory allocation.
48
+ - ``"reserved_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
49
+ amount of reserved memory.
50
+ - ``"active.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
51
+ number of active memory blocks.
52
+ - ``"active_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
53
+ amount of active memory.
54
+ - ``"inactive_split.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
55
+ number of inactive, non-releasable memory blocks.
56
+ - ``"inactive_split_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
57
+ amount of inactive, non-releasable memory.
58
+
59
+ For these core statistics, values are broken down as follows.
60
+
61
+ Pool type:
62
+
63
+ - ``all``: combined statistics across all memory pools.
64
+ - ``large_pool``: statistics for the large allocation pool
65
+ (as of June 2025, for size >= 1MB allocations).
66
+ - ``small_pool``: statistics for the small allocation pool
67
+ (as of June 2025, for size < 1MB allocations).
68
+
69
+ Metric type:
70
+
71
+ - ``current``: current value of this metric.
72
+ - ``peak``: maximum value of this metric.
73
+ - ``allocated``: historical total increase in this metric.
74
+ - ``freed``: historical total decrease in this metric.
75
+
76
+ In addition to the core statistics, we also provide some simple event
77
+ counters:
78
+
79
+ - ``"num_alloc_retries"``: number of failed device memory allocation calls that
80
+ result in a cache flush and retry.
81
+ - ``"num_ooms"``: number of out-of-memory errors thrown.
82
+ - ``"num_sync_all_streams"``: number of ``synchronize_and_free_events`` calls.
83
+ - ``"num_device_alloc"``: number of device memory allocation calls.
84
+ - ``"num_device_free"``: number of device memory free calls.
85
+
86
+ Args:
87
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
88
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
89
+ If a :class:`torch.device` or str is provided, its type must match the current
90
+ :ref:`accelerator<accelerators>` device type.
91
+
92
+ Returns:
93
+ OrderedDict[str, Any]: an ordered dictionary mapping statistic names to their values.
94
+ """
95
+ if not torch._C._accelerator_isAllocatorInitialized():
96
+ return OrderedDict()
97
+ device_index = _get_device_index(device_index, optional=True)
98
+ stats = torch._C._accelerator_getDeviceStats(device_index)
99
+ flat_stats = []
100
+
101
+ def flatten(prefix: str, value: Any) -> None:
102
+ if isinstance(value, dict):
103
+ for k, v in value.items():
104
+ nested_prefix = f"{prefix}.{k}" if prefix else k
105
+ flatten(nested_prefix, v)
106
+ else:
107
+ flat_stats.append((prefix, value))
108
+
109
+ flatten("", stats)
110
+ flat_stats.sort()
111
+ # pyrefly: ignore [no-matching-overload]
112
+ return OrderedDict(flat_stats)
113
+
114
+
115
+ def memory_allocated(device_index: _device_t = None, /) -> int:
116
+ r"""Return the current :ref:`accelerator<accelerators>` device memory occupied by tensors
117
+ in bytes for a given device index.
118
+
119
+ Args:
120
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
121
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
122
+ If a :class:`torch.device` or str is provided, its type must match the current
123
+ :ref:`accelerator<accelerators>` device type.
124
+
125
+ Returns:
126
+ int: the current memory occupied by live tensors (in bytes) within the current process.
127
+ """
128
+ return memory_stats(device_index).get("allocated_bytes.all.current", 0)
129
+
130
+
131
+ def max_memory_allocated(device_index: _device_t = None, /) -> int:
132
+ r"""Return the current :ref:`accelerator<accelerators>` maximum device memory occupied by tensors
133
+ in bytes for a given device index.
134
+
135
+ By default, this returns the peak allocated memory since the beginning of
136
+ this program. :func:`~torch.accelerator.reset_peak_memory_stats` can be used to
137
+ reset the starting point in tracking this metric.
138
+
139
+ Args:
140
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
141
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
142
+ If a :class:`torch.device` or str is provided, its type must match the current
143
+ :ref:`accelerator<accelerators>` device type.
144
+
145
+ Returns:
146
+ int: the peak memory occupied by live tensors (in bytes) within the current process.
147
+ """
148
+ return memory_stats(device_index).get("allocated_bytes.all.peak", 0)
149
+
150
+
151
+ def memory_reserved(device_index: _device_t = None, /) -> int:
152
+ r"""Return the current :ref:`accelerator<accelerators>` device memory managed by the caching allocator
153
+ in bytes for a given device index.
154
+
155
+ Args:
156
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
157
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
158
+ If a :class:`torch.device` or str is provided, its type must match the current
159
+ :ref:`accelerator<accelerators>` device type.
160
+
161
+ Returns:
162
+ int: the current memory reserved by PyTorch (in bytes) within the current process.
163
+ """
164
+ return memory_stats(device_index).get("reserved_bytes.all.current", 0)
165
+
166
+
167
+ def max_memory_reserved(device_index: _device_t = None, /) -> int:
168
+ r"""Return the current :ref:`accelerator<accelerators>` maximum device memory managed by the caching allocator
169
+ in bytes for a given device index.
170
+
171
+ By default, this returns the peak cached memory since the beginning of this
172
+ program. :func:`~torch.accelerator.reset_peak_memory_stats` can be used to reset
173
+ the starting point in tracking this metric.
174
+
175
+ Args:
176
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
177
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
178
+ If a :class:`torch.device` or str is provided, its type must match the current
179
+ :ref:`accelerator<accelerators>` device type.
180
+
181
+ Returns:
182
+ int: the peak memory reserved by PyTorch (in bytes) within the current process.
183
+ """
184
+ return memory_stats(device_index).get("reserved_bytes.all.peak", 0)
185
+
186
+
187
+ def reset_accumulated_memory_stats(device_index: _device_t = None, /) -> None:
188
+ r"""Reset the "accumulated" (historical) stats tracked by the current :ref:`accelerator<accelerators>`
189
+ memory allocator for a given device index.
190
+
191
+ Args:
192
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
193
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
194
+ If a :class:`torch.device` or str is provided, its type must match the current
195
+ :ref:`accelerator<accelerators>` device type.
196
+
197
+ .. note:: This function is a no-op if the memory allocator for the current
198
+ :ref:`accelerator <accelerators>` has not been initialized.
199
+ """
200
+ device_index = _get_device_index(device_index, optional=True)
201
+ return torch._C._accelerator_resetAccumulatedStats(device_index)
202
+
203
+
204
+ def reset_peak_memory_stats(device_index: _device_t = None, /) -> None:
205
+ r"""Reset the "peak" stats tracked by the current :ref:`accelerator<accelerators>`
206
+ memory allocator for a given device index.
207
+
208
+ Args:
209
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
210
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
211
+ If a :class:`torch.device` or str is provided, its type must match the current
212
+ :ref:`accelerator<accelerators>` device type.
213
+
214
+ .. note:: This function is a no-op if the memory allocator for the current
215
+ :ref:`accelerator <accelerators>` has not been initialized.
216
+ """
217
+ device_index = _get_device_index(device_index, optional=True)
218
+ return torch._C._accelerator_resetPeakStats(device_index)
219
+
220
+
221
+ def get_memory_info(device_index: _device_t = None, /) -> tuple[int, int]:
222
+ r"""Return the current device memory information for a given device index.
223
+
224
+ Args:
225
+ device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
226
+ If not given, use :func:`torch.accelerator.current_device_index` by default.
227
+ If a :class:`torch.device` or str is provided, its type must match the current
228
+ :ref:`accelerator<accelerators>` device type.
229
+
230
+ Returns:
231
+ tuple[int, int]: a tuple of two integers (free_memory, total_memory) in bytes.
232
+ The first value is the free memory on the device (available across all processes and applications),
233
+ The second value is the device's total hardware memory capacity.
234
+ """
235
+ device_index = _get_device_index(device_index, optional=True)
236
+ return torch._C._accelerator_getMemoryInfo(device_index)
miniconda3/envs/active_proaction/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
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/amp/autocast_mode.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert self.fast_dtype is not None
240
+ return
241
+ self.device = device_type
242
+ if not is_autocast_available(self.device):
243
+ raise RuntimeError(
244
+ f"User specified an unsupported autocast device_type '{self.device}'"
245
+ )
246
+
247
+ device_supported_dtypes = [torch.bfloat16, torch.float16]
248
+
249
+ self.custom_backend_name = torch._C._get_privateuse1_backend_name()
250
+ if self.device == self.custom_backend_name:
251
+ necessary_funcs = [
252
+ "get_amp_supported_dtype",
253
+ ]
254
+ message = f"Tried to use AMP with the `{self.custom_backend_name}` backend, but the backend has not "
255
+ message += "registered a module or the module miss some necessary funcs. The backend should register "
256
+ message += "a module by `torch._register_device_module`, and the module must have these funcs: \n"
257
+ message += "`get_amp_supported_dtype() -> List[torch.dtype]`. \n"
258
+
259
+ assert hasattr(torch, self.custom_backend_name), message
260
+ self.custom_device_mod = getattr(torch, self.custom_backend_name)
261
+ for func in necessary_funcs:
262
+ assert hasattr(self.custom_device_mod, func), (
263
+ message + f"But the func `{func}` is missing. \n"
264
+ )
265
+ device_supported_dtypes = self.custom_device_mod.get_amp_supported_dtype()
266
+
267
+ self._cache_enabled = (
268
+ torch.is_autocast_cache_enabled()
269
+ if cache_enabled is None
270
+ else cache_enabled
271
+ )
272
+
273
+ device_name = (
274
+ self.device
275
+ if self.device == self.custom_backend_name
276
+ else self.device.upper()
277
+ )
278
+ if enabled:
279
+ # Special case for CUDA AMP and bfloat16 support
280
+ if self.device == "cuda":
281
+ if torch.cuda.amp.common.amp_definitely_not_available():
282
+ warnings.warn(
283
+ "CUDA is not available or torch_xla is imported. Disabling autocast.",
284
+ stacklevel=2,
285
+ )
286
+ enabled = False
287
+ elif (
288
+ self.fast_dtype == torch.bfloat16
289
+ and not torch.cuda.is_bf16_supported()
290
+ ):
291
+ raise RuntimeError(
292
+ "Current CUDA Device does not support bfloat16. Please switch dtype to float16."
293
+ )
294
+ elif self.fast_dtype not in device_supported_dtypes:
295
+ error_message = (
296
+ f"In {device_name} autocast, but the target dtype is not supported. Disabling autocast.\n"
297
+ f"{device_name} Autocast only supports dtypes of "
298
+ + ", ".join(map(str, device_supported_dtypes))
299
+ + " currently."
300
+ )
301
+ warnings.warn(error_message, stacklevel=2)
302
+ enabled = False
303
+ # Special case for MPS bfloat16 support on macOS < 14
304
+ if (
305
+ self.device == "mps"
306
+ and self.fast_dtype == torch.bfloat16
307
+ and not torch.backends.mps.is_macos_or_newer(14, 0)
308
+ ):
309
+ error_message = (
310
+ "In MPS autocast, but the target dtype torch.bfloat16 is not supported "
311
+ "on macOS versions below 14. Disabling autocast."
312
+ )
313
+ warnings.warn(error_message, stacklevel=2)
314
+ enabled = False
315
+ self._enabled = enabled
316
+
317
+ def __enter__(self):
318
+ if torch._jit_internal.is_scripting():
319
+ assert self.fast_dtype is not None
320
+ return self
321
+
322
+ self.prev_cache_enabled = torch.is_autocast_cache_enabled()
323
+ self.prev = torch.is_autocast_enabled(self.device)
324
+ self.prev_fastdtype = torch.get_autocast_dtype(self.device)
325
+ torch.set_autocast_enabled(self.device, self._enabled)
326
+ torch.set_autocast_dtype(self.device, self.fast_dtype) # type: ignore[arg-type]
327
+ torch.autocast_increment_nesting()
328
+ torch.set_autocast_cache_enabled(self._cache_enabled)
329
+
330
+ # only dispatch to PreDispatchTorchFunctionMode to avoid exposing this
331
+ # API to other functional modes. We only expose to PreDispatchTorchFunctionMode
332
+ # for preserving autocast in torch.export.export.
333
+ if torch._C._is_torch_function_mode_enabled():
334
+ stacks = torch.overrides._get_current_function_mode_stack()
335
+ for mode in stacks:
336
+ if isinstance(
337
+ mode,
338
+ torch.fx.experimental.proxy_tensor.PreDispatchTorchFunctionMode,
339
+ ):
340
+ args = (
341
+ self.device,
342
+ self.fast_dtype,
343
+ self._enabled,
344
+ self._cache_enabled,
345
+ )
346
+ mode.__torch_function__(torch.amp._enter_autocast, (), args)
347
+ return self
348
+
349
+ return self
350
+
351
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any): # type: ignore[override]
352
+ if torch._jit_internal.is_scripting():
353
+ return
354
+
355
+ # Drop the cache when we exit to a nesting level that's outside any instance of autocast.
356
+ if torch.autocast_decrement_nesting() == 0:
357
+ torch.clear_autocast_cache()
358
+ torch.set_autocast_enabled(self.device, self.prev)
359
+ torch.set_autocast_dtype(self.device, self.prev_fastdtype)
360
+ torch.set_autocast_cache_enabled(self.prev_cache_enabled)
361
+
362
+ # only dispatch to PreDispatchTorchFunctionMode to avoid exposing this
363
+ # API to other functional modes. We only expose to PreDispatchTorchFunctionMode
364
+ # for preserving autocast in torch.export.export.
365
+ if torch._C._is_torch_function_mode_enabled():
366
+ stacks = torch.overrides._get_current_function_mode_stack()
367
+ for mode in stacks:
368
+ if isinstance(
369
+ mode,
370
+ torch.fx.experimental.proxy_tensor.PreDispatchTorchFunctionMode,
371
+ ):
372
+ mode.__torch_function__(torch.amp._exit_autocast, (), ())
373
+ # This is very important because the above line actually doesn't
374
+ # run exit code so it end up swallowing exceptions.
375
+ return False
376
+ return False
377
+
378
+ def __call__(self, func):
379
+ if torch._jit_internal.is_scripting():
380
+ return func
381
+ return autocast_decorator(self, func)
382
+
383
+
384
+ # These functions aren't meant for public usage.
385
+ # They are what we trace into a graph during pre_dispatch tracing
386
+ # when we encounter an autocast context manager.
387
+ def _enter_autocast(*vals):
388
+ # For pre-dispatch tracing, if a TorchFunction mode is active, we'll want to trace this into a graph.
389
+ if torch._C._is_torch_function_mode_enabled():
390
+ return torch.overrides.handle_torch_function(
391
+ torch.amp._enter_autocast, [], *vals
392
+ )
393
+ mode = torch.amp.autocast(*vals)
394
+ mode.__enter__()
395
+ return mode
396
+
397
+
398
+ def _exit_autocast(mode):
399
+ if torch._C._is_torch_function_mode_enabled():
400
+ return torch.overrides.handle_torch_function(torch.amp._exit_autocast, [], mode)
401
+ mode.__exit__(None, None, None)
402
+
403
+
404
+ # Casts Tensors and containers of Tensors. Special-cases passthroughs for strings and np.ndarrays, which
405
+ # may be falsely detected as "Iterables."
406
+ def _cast(value, device_type: str, dtype: _dtype):
407
+ if isinstance(value, torch.Tensor):
408
+ is_eligible = (
409
+ value.is_floating_point()
410
+ and value.device.type == device_type
411
+ and (value.dtype is not torch.float64)
412
+ )
413
+ return value.to(dtype) if is_eligible else value
414
+ elif isinstance(value, (str, bytes)):
415
+ return value
416
+ elif HAS_NUMPY and isinstance(
417
+ value,
418
+ # pyrefly: ignore [missing-attribute]
419
+ np.ndarray,
420
+ ):
421
+ return value
422
+ elif isinstance(value, collections.abc.Mapping):
423
+ return {
424
+ _cast(k, device_type, dtype): _cast(v, device_type, dtype)
425
+ for k, v in value.items()
426
+ }
427
+ elif isinstance(value, collections.abc.Iterable):
428
+ iterable = (_cast(v, device_type, dtype) for v in value)
429
+ if isinstance(value, (list, tuple)):
430
+ return type(value)(iterable)
431
+ else:
432
+ return iterable
433
+ else:
434
+ return value
435
+
436
+
437
+ def custom_fwd(
438
+ fwd=None,
439
+ *,
440
+ device_type: str,
441
+ cast_inputs: Optional[_dtype] = None,
442
+ ):
443
+ """
444
+ Create a helper decorator for ``forward`` methods of custom autograd functions.
445
+
446
+ Autograd functions are subclasses of :class:`torch.autograd.Function`.
447
+ See the :ref:`example page<amp-custom-examples>` for more detail.
448
+
449
+ Args:
450
+ device_type(str): Device type to use. 'cuda', 'cpu', 'mtia', 'maia', 'xpu' and so on.
451
+ The type is the same as the `type` attribute of a :class:`torch.device`.
452
+ Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
453
+ cast_inputs (:class:`torch.dtype` or None, optional, default=None): If not ``None``,
454
+ when ``forward`` runs in an autocast-enabled region, casts incoming
455
+ floating-point Tensors to the target dtype (non-floating-point Tensors are not affected),
456
+ then executes ``forward`` with autocast disabled.
457
+ If ``None``, ``forward``'s internal ops execute with the current autocast state.
458
+
459
+ .. note::
460
+ If the decorated ``forward`` is called outside an autocast-enabled region,
461
+ :func:`custom_fwd<custom_fwd>` is a no-op and ``cast_inputs`` has no effect.
462
+ """
463
+ if not isinstance(device_type, str):
464
+ raise ValueError(
465
+ f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
466
+ )
467
+ if fwd is None:
468
+ return functools.partial(
469
+ custom_fwd, device_type=device_type, cast_inputs=cast_inputs
470
+ )
471
+
472
+ @functools.wraps(fwd)
473
+ def decorate_fwd(*args, **kwargs):
474
+ args[0]._dtype = torch.get_autocast_dtype(device_type)
475
+ if cast_inputs is None:
476
+ args[0]._fwd_used_autocast = torch.is_autocast_enabled(device_type)
477
+ return fwd(*args, **kwargs) # pyrefly: ignore [not-callable]
478
+ else:
479
+ autocast_context = torch.is_autocast_enabled(device_type)
480
+ args[0]._fwd_used_autocast = False
481
+ if autocast_context:
482
+ with autocast(device_type=device_type, enabled=False):
483
+ return fwd( # pyrefly: ignore # not-callable
484
+ *_cast(args, device_type, cast_inputs),
485
+ **_cast(kwargs, device_type, cast_inputs),
486
+ )
487
+ else:
488
+ return fwd(*args, **kwargs) # pyrefly: ignore [not-callable]
489
+
490
+ return decorate_fwd
491
+
492
+
493
+ # Autograd ensures incoming gradients are the same type as forward outputs. Allowing a separate
494
+ # cast_inputs argument on custom_bwd is unnecessary and could cause errors if it doesn't match
495
+ # cast_inputs supplied to custom_fwd.
496
+ def custom_bwd(bwd=None, *, device_type: str):
497
+ """Create a helper decorator for backward methods of custom autograd functions.
498
+
499
+ Autograd functions are subclasses of :class:`torch.autograd.Function`.
500
+ Ensures that ``backward`` executes with the same autocast state as ``forward``.
501
+ See the :ref:`example page<amp-custom-examples>` for more detail.
502
+
503
+ Args:
504
+ device_type(str): Device type to use. 'cuda', 'cpu', 'mtia', 'maia', 'xpu' and so on.
505
+ The type is the same as the `type` attribute of a :class:`torch.device`.
506
+ Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
507
+ """
508
+
509
+ if not isinstance(device_type, str):
510
+ raise ValueError(
511
+ f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
512
+ )
513
+ if bwd is None:
514
+ return functools.partial(custom_bwd, device_type=device_type)
515
+
516
+ @functools.wraps(bwd)
517
+ def decorate_bwd(*args, **kwargs):
518
+ with autocast(
519
+ device_type=device_type,
520
+ enabled=args[0]._fwd_used_autocast,
521
+ dtype=args[0]._dtype,
522
+ ):
523
+ return bwd(*args, **kwargs) # pyrefly: ignore [not-callable]
524
+
525
+ return decorate_bwd
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/amp/grad_scaler.py ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert growth_factor > 1.0, "The growth factor must be > 1.0."
144
+ assert backoff_factor < 1.0, "The backoff factor must be < 1.0."
145
+
146
+ self._init_scale = init_scale
147
+ # self._scale will be lazily initialized during the first call to scale()
148
+ self._scale: Optional[torch.Tensor] = None
149
+ self._growth_factor = growth_factor
150
+ self._backoff_factor = backoff_factor
151
+ self._growth_interval = growth_interval
152
+ self._init_growth_tracker = 0
153
+ # self._growth_tracker will be lazily initialized during the first call to scale()
154
+ self._growth_tracker: Optional[torch.Tensor] = None
155
+ self._per_optimizer_states: dict[int, dict[str, Any]] = defaultdict(
156
+ _refresh_per_optimizer_state
157
+ )
158
+
159
+ def _check_scale_growth_tracker(
160
+ self, funcname: str
161
+ ) -> tuple[torch.Tensor, torch.Tensor]:
162
+ fix = "This may indicate your script did not use scaler.scale(loss or outputs) earlier in the iteration."
163
+ assert self._scale is not None, (
164
+ f"Attempted {funcname} but _scale is None. " + fix
165
+ )
166
+ assert self._growth_tracker is not None, (
167
+ f"Attempted {funcname} but _growth_tracker is None. " + fix
168
+ )
169
+ return (self._scale, self._growth_tracker)
170
+
171
+ def _lazy_init_scale_growth_tracker(self, dev: torch.device) -> None:
172
+ assert self._growth_tracker is None, "_growth_tracker initialized before _scale"
173
+ self._scale = torch.full((), self._init_scale, dtype=torch.float32, device=dev)
174
+ self._growth_tracker = torch.full(
175
+ (), self._init_growth_tracker, dtype=torch.int32, device=dev
176
+ )
177
+
178
+ @overload
179
+ def scale(self, outputs: torch.Tensor) -> torch.Tensor: ...
180
+
181
+ @overload
182
+ def scale(self, outputs: list[torch.Tensor]) -> list[torch.Tensor]: ...
183
+
184
+ @overload
185
+ def scale(self, outputs: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]: ...
186
+
187
+ @overload
188
+ def scale(self, outputs: Iterable[torch.Tensor]) -> Iterable[torch.Tensor]: ...
189
+
190
+ def scale(
191
+ self,
192
+ outputs: Union[torch.Tensor, Iterable[torch.Tensor]],
193
+ ) -> Union[torch.Tensor, Iterable[torch.Tensor]]:
194
+ """
195
+ Multiplies ('scales') a tensor or list of tensors by the scale factor.
196
+
197
+ Returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, outputs are returned
198
+ unmodified.
199
+
200
+ Args:
201
+ outputs (Tensor or iterable of Tensors): Outputs to scale.
202
+ """
203
+ if not self._enabled:
204
+ return outputs
205
+
206
+ # Short-circuit for the common case.
207
+ if isinstance(outputs, torch.Tensor):
208
+ if self._scale is None:
209
+ self._lazy_init_scale_growth_tracker(outputs.device)
210
+ assert self._scale is not None
211
+ return outputs * self._scale.to(device=outputs.device, non_blocking=True)
212
+
213
+ # Invoke the more complex machinery only if we're treating multiple outputs.
214
+ stash: list[
215
+ _MultiDeviceReplicator
216
+ ] = [] # holds a reference that can be overwritten by apply_scale
217
+
218
+ def apply_scale(val: Union[torch.Tensor, Iterable[torch.Tensor]]):
219
+ if isinstance(val, torch.Tensor):
220
+ if len(stash) == 0:
221
+ if self._scale is None:
222
+ self._lazy_init_scale_growth_tracker(val.device)
223
+ assert self._scale is not None
224
+ stash.append(_MultiDeviceReplicator(self._scale))
225
+ return val * stash[0].get(val.device)
226
+ if isinstance(val, abc.Iterable):
227
+ iterable = map(apply_scale, val)
228
+ if isinstance(val, (list, tuple)):
229
+ return type(val)(iterable)
230
+ return iterable
231
+ raise ValueError("outputs must be a Tensor or an iterable of Tensors")
232
+
233
+ return apply_scale(outputs)
234
+
235
+ def _unscale_grads_(
236
+ self,
237
+ optimizer: torch.optim.Optimizer,
238
+ inv_scale: torch.Tensor,
239
+ found_inf: torch.Tensor,
240
+ allow_fp16: bool,
241
+ ) -> dict[torch.device, torch.Tensor]:
242
+ per_device_inv_scale = _MultiDeviceReplicator(inv_scale)
243
+ per_device_found_inf = _MultiDeviceReplicator(found_inf)
244
+
245
+ # To set up _amp_foreach_non_finite_check_and_unscale_, split grads by device and dtype.
246
+ # There could be hundreds of grads, so we'd like to iterate through them just once.
247
+ # However, we don't know their devices or dtypes in advance.
248
+
249
+ # https://stackoverflow.com/questions/5029934/defaultdict-of-defaultdict
250
+ # Google says mypy struggles with defaultdicts type annotations.
251
+ per_device_and_dtype_grads: dict[
252
+ torch.device, dict[torch.dtype, list[torch.Tensor]]
253
+ ] = defaultdict(lambda: defaultdict(list))
254
+ with torch.no_grad():
255
+ for group in optimizer.param_groups:
256
+ for param in group["params"]:
257
+ assert isinstance(param, torch.Tensor)
258
+ if param.grad is None:
259
+ continue
260
+ if (not allow_fp16) and param.grad.dtype == torch.float16:
261
+ raise ValueError("Attempting to unscale FP16 gradients.")
262
+ if param.grad.is_sparse:
263
+ # is_coalesced() == False means the sparse grad has values with duplicate indices.
264
+ # coalesce() deduplicates indices and adds all values that have the same index.
265
+ # For scaled fp16 values, there's a good chance coalescing will cause overflow,
266
+ # so we should check the coalesced _values().
267
+ if param.grad.dtype is torch.float16:
268
+ param.grad = param.grad.coalesce()
269
+ to_unscale = param.grad._values()
270
+ else:
271
+ to_unscale = param.grad
272
+
273
+ # TODO: is there a way to split by device and dtype without appending in the inner loop?
274
+ per_device_and_dtype_grads[to_unscale.device][
275
+ to_unscale.dtype
276
+ ].append(to_unscale)
277
+
278
+ for device, per_dtype_grads in per_device_and_dtype_grads.items():
279
+ for grads in per_dtype_grads.values():
280
+ torch._amp_foreach_non_finite_check_and_unscale_(
281
+ grads,
282
+ per_device_found_inf.get(device),
283
+ per_device_inv_scale.get(device),
284
+ )
285
+
286
+ return per_device_found_inf._per_device_tensors
287
+
288
+ def unscale_(self, optimizer: torch.optim.Optimizer) -> None:
289
+ """
290
+ Divides ("unscales") the optimizer's gradient tensors by the scale factor.
291
+
292
+ :meth:`unscale_` is optional, serving cases where you need to
293
+ :ref:`modify or inspect gradients<working-with-unscaled-gradients>`
294
+ between the backward pass(es) and :meth:`step`.
295
+ If :meth:`unscale_` is not called explicitly, gradients will be unscaled automatically during :meth:`step`.
296
+
297
+ Simple example, using :meth:`unscale_` to enable clipping of unscaled gradients::
298
+
299
+ ...
300
+ scaler.scale(loss).backward()
301
+ scaler.unscale_(optimizer)
302
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
303
+ scaler.step(optimizer)
304
+ scaler.update()
305
+
306
+ Args:
307
+ optimizer (torch.optim.Optimizer): Optimizer that owns the gradients to be unscaled.
308
+
309
+ .. note::
310
+ :meth:`unscale_` does not incur a CPU-GPU sync.
311
+
312
+ .. warning::
313
+ :meth:`unscale_` should only be called once per optimizer per :meth:`step` call,
314
+ and only after all gradients for that optimizer's assigned parameters have been accumulated.
315
+ Calling :meth:`unscale_` twice for a given optimizer between each :meth:`step` triggers a RuntimeError.
316
+
317
+ .. warning::
318
+ :meth:`unscale_` may unscale sparse gradients out of place, replacing the ``.grad`` attribute.
319
+ """
320
+ if not self._enabled:
321
+ return
322
+
323
+ self._check_scale_growth_tracker("unscale_")
324
+
325
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
326
+
327
+ if optimizer_state["stage"] is OptState.UNSCALED:
328
+ raise RuntimeError(
329
+ "unscale_() has already been called on this optimizer since the last update()."
330
+ )
331
+ elif optimizer_state["stage"] is OptState.STEPPED:
332
+ raise RuntimeError("unscale_() is being called after step().")
333
+
334
+ # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
335
+ assert self._scale is not None
336
+ inv_scale = (
337
+ self._scale.double().reciprocal().float()
338
+ if self._scale.device != torch.device("mps:0")
339
+ else self._scale.reciprocal()
340
+ )
341
+ found_inf = torch.full((), 0.0, dtype=torch.float32, device=self._scale.device)
342
+
343
+ optimizer_state["found_inf_per_device"] = self._unscale_grads_(
344
+ optimizer, inv_scale, found_inf, False
345
+ )
346
+ optimizer_state["stage"] = OptState.UNSCALED
347
+
348
+ def _maybe_opt_step(
349
+ self,
350
+ optimizer: torch.optim.Optimizer,
351
+ optimizer_state: dict[str, Any],
352
+ *args: Any,
353
+ **kwargs: Any,
354
+ ) -> Optional[float]:
355
+ retval: Optional[float] = None
356
+ if not sum(v.item() for v in optimizer_state["found_inf_per_device"].values()):
357
+ retval = optimizer.step(*args, **kwargs)
358
+ return retval
359
+
360
+ def step(
361
+ self, optimizer: torch.optim.Optimizer, *args: Any, **kwargs: Any
362
+ ) -> Optional[float]:
363
+ """Invoke ``unscale_(optimizer)`` followed by parameter update, if gradients are not infs/NaN.
364
+
365
+ :meth:`step` carries out the following two operations:
366
+
367
+ 1. Internally invokes ``unscale_(optimizer)`` (unless :meth:`unscale_` was explicitly called for ``optimizer``
368
+ earlier in the iteration). As part of the :meth:`unscale_`, gradients are checked for infs/NaNs.
369
+ 2. If no inf/NaN gradients are found, invokes ``optimizer.step()`` using the unscaled
370
+ gradients. Otherwise, ``optimizer.step()`` is skipped to avoid corrupting the params.
371
+
372
+ ``*args`` and ``**kwargs`` are forwarded to ``optimizer.step()``.
373
+
374
+ Returns the return value of ``optimizer.step(*args, **kwargs)``.
375
+
376
+ Args:
377
+ optimizer (torch.optim.Optimizer): Optimizer that applies the gradients.
378
+ args: Any arguments.
379
+ kwargs: Any keyword arguments.
380
+
381
+ .. warning::
382
+ Closure use is not currently supported.
383
+ """
384
+ if not self._enabled:
385
+ return optimizer.step(*args, **kwargs)
386
+
387
+ if "closure" in kwargs:
388
+ raise RuntimeError(
389
+ "Closure use is not currently supported if GradScaler is enabled."
390
+ )
391
+
392
+ self._check_scale_growth_tracker("step")
393
+
394
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
395
+
396
+ if optimizer_state["stage"] is OptState.STEPPED:
397
+ raise RuntimeError(
398
+ "step() has already been called since the last update()."
399
+ )
400
+
401
+ retval: Optional[float] = None
402
+
403
+ if getattr(optimizer, "_step_supports_amp_scaling", False):
404
+ # This optimizer has customized scale-handling logic, so we can call optimizer.step() directly.
405
+ # The contract with custom optimizers is that their step() should accept an additional,
406
+ # optional grad_scaler kwarg. We append self to the kwargs so the custom optimizer has full information:
407
+ # it can query its own state, invoke unscale_ on itself, etc
408
+ # The contract above is being deprecated to avoid introducing `grad_scaler: GradScaler` argument
409
+ # to `Optimizer.step`. The new behavior is going to add two Tensor attributes of `grad_scale`
410
+ # and `found_inf` to the passed optimizer so that the optimizer can utilize those
411
+ # to skip the parameter updates or unscale gradients before updating parameters in
412
+ # the fused kernel, e.g. `FusedAdamMathFunctor`.
413
+ # In this behavior, `GradScaler._check_inf_per_device` is called if `OptState.READY`,
414
+ # while the method is expected to be called by users side, i.e. their optimizers.
415
+ kwargs_ = kwargs
416
+ has_grad_scaler_kwarg = (
417
+ "grad_scaler" in inspect.signature(optimizer.step).parameters
418
+ )
419
+ if has_grad_scaler_kwarg:
420
+ warnings.warn(
421
+ "GradScaler is going to stop passing itself as a keyword argument to the passed "
422
+ "optimizer. In the near future GradScaler registers `grad_scale: Tensor` and "
423
+ "`found_inf: Tensor` to the passed optimizer and let the optimizer use them directly.",
424
+ FutureWarning,
425
+ stacklevel=2,
426
+ )
427
+ kwargs_.update({"grad_scaler": self})
428
+ else:
429
+ if optimizer_state["stage"] is OptState.READY:
430
+ self._check_inf_per_device(optimizer)
431
+ scaler = self._get_scale_async()
432
+ assert scaler is not None
433
+ found_inf = cast(
434
+ torch.Tensor,
435
+ sum(
436
+ [ # noqa: C419
437
+ t.to(scaler.device, non_blocking=True)
438
+ for t in optimizer_state["found_inf_per_device"].values()
439
+ ]
440
+ ),
441
+ )
442
+ # Take the product of the scales, if the user has already set `optimizer.grad_scale`.
443
+ optimizer.grad_scale = ( # type: ignore[attr-defined]
444
+ getattr(optimizer, "grad_scale", None)
445
+ if optimizer_state["stage"] == OptState.UNSCALED
446
+ else scaler * getattr(optimizer, "grad_scale", 1)
447
+ )
448
+ optimizer.found_inf = found_inf # type: ignore[attr-defined]
449
+ retval = optimizer.step(*args, **kwargs_)
450
+ optimizer_state["stage"] = OptState.STEPPED
451
+ if not has_grad_scaler_kwarg:
452
+ del optimizer.grad_scale # type: ignore[attr-defined]
453
+ del optimizer.found_inf # type: ignore[attr-defined]
454
+ return retval
455
+
456
+ if optimizer_state["stage"] is OptState.READY:
457
+ self.unscale_(optimizer)
458
+
459
+ assert len(optimizer_state["found_inf_per_device"]) > 0, (
460
+ "No inf checks were recorded for this optimizer."
461
+ )
462
+
463
+ retval = self._maybe_opt_step(optimizer, optimizer_state, *args, **kwargs)
464
+
465
+ optimizer_state["stage"] = OptState.STEPPED
466
+
467
+ return retval
468
+
469
+ def update(self, new_scale: Optional[Union[float, torch.Tensor]] = None) -> None:
470
+ """Update the scale factor.
471
+
472
+ If any optimizer steps were skipped the scale is multiplied by ``backoff_factor``
473
+ to reduce it. If ``growth_interval`` unskipped iterations occurred consecutively,
474
+ the scale is multiplied by ``growth_factor`` to increase it.
475
+
476
+ Passing ``new_scale`` sets the new scale value manually. (``new_scale`` is not
477
+ used directly, it's used to fill GradScaler's internal scale tensor. So if
478
+ ``new_scale`` was a tensor, later in-place changes to that tensor will not further
479
+ affect the scale GradScaler uses internally.)
480
+
481
+ Args:
482
+ new_scale (float or :class:`torch.Tensor`, optional, default=None): New scale factor.
483
+
484
+ .. warning::
485
+ :meth:`update` should only be called at the end of the iteration, after ``scaler.step(optimizer)`` has
486
+ been invoked for all optimizers used this iteration.
487
+
488
+ .. warning::
489
+ For performance reasons, we do not check the scale factor value to avoid synchronizations,
490
+ so the scale factor is not guaranteed to be above 1. If the scale falls below 1 and/or
491
+ you are seeing NaNs in your gradients or loss, something is likely wrong. For example,
492
+ bf16-pretrained models are often incompatible with AMP/fp16 due to differing dynamic ranges.
493
+ """
494
+ if not self._enabled:
495
+ return
496
+
497
+ _scale, _growth_tracker = self._check_scale_growth_tracker("update")
498
+
499
+ if new_scale is not None:
500
+ assert self._scale is not None
501
+ # Accept a new user-defined scale.
502
+ if isinstance(new_scale, float):
503
+ self._scale.fill_(new_scale)
504
+ else:
505
+ reason = (
506
+ "new_scale should be a float or a 1-element torch.cuda.FloatTensor or "
507
+ "torch.FloatTensor with requires_grad=False."
508
+ )
509
+ assert new_scale.device.type == self._device, reason
510
+ assert new_scale.numel() == 1, reason
511
+ assert new_scale.requires_grad is False, reason
512
+ self._scale.copy_(new_scale)
513
+ else:
514
+ # Consume shared inf/nan data collected from optimizers to update the scale.
515
+ # If all found_inf tensors are on the same device as self._scale, this operation is asynchronous.
516
+ found_infs = [
517
+ found_inf.to(device=_scale.device, non_blocking=True)
518
+ for state in self._per_optimizer_states.values()
519
+ for found_inf in state["found_inf_per_device"].values()
520
+ ]
521
+
522
+ assert len(found_infs) > 0, "No inf checks were recorded prior to update."
523
+
524
+ found_inf_combined = found_infs[0]
525
+ if len(found_infs) > 1:
526
+ for i in range(1, len(found_infs)):
527
+ found_inf_combined += found_infs[i]
528
+
529
+ torch._amp_update_scale_(
530
+ _scale,
531
+ _growth_tracker,
532
+ found_inf_combined,
533
+ self._growth_factor,
534
+ self._backoff_factor,
535
+ self._growth_interval,
536
+ )
537
+
538
+ # To prepare for next iteration, clear the data collected from optimizers this iteration.
539
+ self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
540
+
541
+ def _get_scale_async(self) -> Optional[torch.Tensor]:
542
+ return self._scale
543
+
544
+ def get_scale(self) -> float:
545
+ """Return a Python float containing the current scale, or 1.0 if scaling is disabled.
546
+
547
+ .. warning::
548
+ :meth:`get_scale` incurs a CPU-GPU sync.
549
+ """
550
+ if self._enabled:
551
+ return (
552
+ self._init_scale
553
+ if (scale := self._get_scale_async()) is None
554
+ else cast(float, scale.item())
555
+ )
556
+ return 1.0
557
+
558
+ def get_growth_factor(self) -> float:
559
+ r"""Return a Python float containing the scale growth factor."""
560
+ return self._growth_factor
561
+
562
+ def set_growth_factor(self, new_factor: float) -> None:
563
+ r"""Set a new scale growth factor.
564
+
565
+ Args:
566
+ new_scale (float): Value to use as the new scale growth factor.
567
+ """
568
+ self._growth_factor = new_factor
569
+
570
+ def get_backoff_factor(self) -> float:
571
+ r"""Return a Python float containing the scale backoff factor."""
572
+ return self._backoff_factor
573
+
574
+ def set_backoff_factor(self, new_factor: float) -> None:
575
+ r"""Set a new scale backoff factor.
576
+
577
+ Args:
578
+ new_scale (float): Value to use as the new scale backoff factor.
579
+ """
580
+ self._backoff_factor = new_factor
581
+
582
+ def get_growth_interval(self) -> int:
583
+ r"""Return a Python int containing the growth interval."""
584
+ return self._growth_interval
585
+
586
+ def set_growth_interval(self, new_interval: int) -> None:
587
+ r"""Set a new growth interval.
588
+
589
+ Args:
590
+ new_interval (int): Value to use as the new growth interval.
591
+ """
592
+ self._growth_interval = new_interval
593
+
594
+ def _get_growth_tracker(self) -> int:
595
+ if self._enabled:
596
+ return (
597
+ self._init_growth_tracker
598
+ if self._growth_tracker is None
599
+ else cast(int, self._growth_tracker.item())
600
+ )
601
+ return 0
602
+
603
+ def is_enabled(self) -> bool:
604
+ r"""Return a bool indicating whether this instance is enabled."""
605
+ return self._enabled
606
+
607
+ def state_dict(self) -> dict[str, Any]:
608
+ r"""Return the state of the scaler as a :class:`dict`.
609
+
610
+ It contains five entries:
611
+
612
+ * ``"scale"`` - a Python float containing the current scale
613
+ * ``"growth_factor"`` - a Python float containing the current growth factor
614
+ * ``"backoff_factor"`` - a Python float containing the current backoff factor
615
+ * ``"growth_interval"`` - a Python int containing the current growth interval
616
+ * ``"_growth_tracker"`` - a Python int containing the number of recent consecutive unskipped steps.
617
+
618
+ If this instance is not enabled, returns an empty dict.
619
+
620
+ .. note::
621
+ If you wish to checkpoint the scaler's state after a particular iteration, :meth:`state_dict`
622
+ should be called after :meth:`update`.
623
+ """
624
+ if self._enabled:
625
+ return {
626
+ "scale": self.get_scale(),
627
+ "growth_factor": self._growth_factor,
628
+ "backoff_factor": self._backoff_factor,
629
+ "growth_interval": self._growth_interval,
630
+ "_growth_tracker": self._get_growth_tracker(),
631
+ }
632
+ return {}
633
+
634
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
635
+ r"""Load the scaler state.
636
+
637
+ If this instance is disabled, :meth:`load_state_dict` is a no-op.
638
+
639
+ Args:
640
+ state_dict(dict): scaler state. Should be an object returned from a call to :meth:`state_dict`.
641
+ """
642
+ if not self._enabled:
643
+ return
644
+
645
+ if len(state_dict) == 0:
646
+ raise RuntimeError(
647
+ "The source state dict is empty, possibly because it was saved "
648
+ "from a disabled instance of GradScaler."
649
+ )
650
+
651
+ self._init_scale = cast(float, state_dict["scale"])
652
+ if self._scale is not None:
653
+ self._scale.fill_(state_dict["scale"])
654
+ self._growth_factor = cast(float, state_dict["growth_factor"])
655
+ self._backoff_factor = cast(float, state_dict["backoff_factor"])
656
+ self._growth_interval = cast(int, state_dict["growth_interval"])
657
+ self._init_growth_tracker = cast(int, state_dict["_growth_tracker"])
658
+ if self._growth_tracker is not None:
659
+ self._growth_tracker.fill_(state_dict["_growth_tracker"])
660
+
661
+ def __getstate__(self) -> dict[str, Any]:
662
+ state = self.__dict__.copy()
663
+ if self._enabled:
664
+ assert len(self._per_optimizer_states) == 0, (
665
+ "A GradScaler instance may only be pickled at the beginning "
666
+ "of an iteration, or at the end after scaler.update()."
667
+ )
668
+ # Pickling _scale and _growth_tracker Tensors directly triggers
669
+ # "warnings.warn("pickle support for Storage will be removed in 1.5..."
670
+ # so instead, we set the unpickled instance up to reinitialize them lazily.
671
+ state["_init_scale"] = self.get_scale()
672
+ state["_init_growth_tracker"] = self._get_growth_tracker()
673
+ state["_scale"] = None
674
+ state["_growth_tracker"] = None
675
+ return state
676
+
677
+ def __setstate__(self, state: dict[str, Any]) -> None:
678
+ self.__dict__.update(state)
679
+
680
+ def _check_inf_per_device(self, optimizer: torch.optim.Optimizer) -> dict[str, Any]:
681
+ _scale, _ = self._check_scale_growth_tracker("_check_inf_per_device")
682
+
683
+ dummy_inv_scale = torch.full((), 1.0, dtype=torch.float32, device=_scale.device)
684
+ found_inf = torch.full((), 0.0, dtype=torch.float32, device=_scale.device)
685
+
686
+ self._per_optimizer_states[id(optimizer)]["found_inf_per_device"] = (
687
+ self._unscale_grads_(optimizer, dummy_inv_scale, found_inf, True)
688
+ )
689
+
690
+ return self._per_optimizer_states[id(optimizer)]["found_inf_per_device"]
691
+
692
+ def _found_inf_per_device(self, optimizer: torch.optim.Optimizer) -> dict[str, Any]:
693
+ return self._per_optimizer_states[id(optimizer)]["found_inf_per_device"]
miniconda3/envs/active_proaction/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}")
miniconda3/envs/active_proaction/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}")
miniconda3/envs/active_proaction/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}")
miniconda3/envs/active_proaction/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
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/modules/fused.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert (
48
+ type_before_parametrizations(conv) == Conv1d
49
+ and type_before_parametrizations(relu) == ReLU
50
+ ), (
51
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
52
+ f"{type_before_parametrizations(relu)}"
53
+ )
54
+ super().__init__(conv, relu)
55
+
56
+
57
+ class ConvReLU2d(_FusedModule):
58
+ r"""This is a sequential container which calls the Conv2d and ReLU modules.
59
+ During quantization this will be replaced with the corresponding fused module."""
60
+
61
+ def __init__(self, conv, relu):
62
+ assert (
63
+ type_before_parametrizations(conv) == Conv2d
64
+ and type_before_parametrizations(relu) == ReLU
65
+ ), (
66
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
67
+ f"{type_before_parametrizations(relu)}"
68
+ )
69
+ super().__init__(conv, relu)
70
+
71
+
72
+ class ConvReLU3d(_FusedModule):
73
+ r"""This is a sequential container which calls the Conv3d and ReLU modules.
74
+ During quantization this will be replaced with the corresponding fused module."""
75
+
76
+ def __init__(self, conv, relu):
77
+ assert (
78
+ type_before_parametrizations(conv) == Conv3d
79
+ and type_before_parametrizations(relu) == ReLU
80
+ ), (
81
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
82
+ f"{type_before_parametrizations(relu)}"
83
+ )
84
+ super().__init__(conv, relu)
85
+
86
+
87
+ class LinearReLU(_FusedModule):
88
+ r"""This is a sequential container which calls the Linear and ReLU modules.
89
+ During quantization this will be replaced with the corresponding fused module."""
90
+
91
+ def __init__(self, linear, relu):
92
+ assert (
93
+ type_before_parametrizations(linear) == Linear
94
+ and type_before_parametrizations(relu) == ReLU
95
+ ), (
96
+ f"Incorrect types for input modules{type_before_parametrizations(linear)}"
97
+ f"{type_before_parametrizations(relu)}"
98
+ )
99
+ super().__init__(linear, relu)
100
+
101
+
102
+ class ConvBn1d(_FusedModule):
103
+ r"""This is a sequential container which calls the Conv 1d and Batch Norm 1d modules.
104
+ During quantization this will be replaced with the corresponding fused module."""
105
+
106
+ def __init__(self, conv, bn):
107
+ assert (
108
+ type_before_parametrizations(conv) == Conv1d
109
+ and type_before_parametrizations(bn) == BatchNorm1d
110
+ ), (
111
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
112
+ f"{type_before_parametrizations(bn)}"
113
+ )
114
+ super().__init__(conv, bn)
115
+
116
+
117
+ class ConvBn2d(_FusedModule):
118
+ r"""This is a sequential container which calls the Conv 2d and Batch Norm 2d modules.
119
+ During quantization this will be replaced with the corresponding fused module."""
120
+
121
+ def __init__(self, conv, bn):
122
+ assert (
123
+ type_before_parametrizations(conv) == Conv2d
124
+ and type_before_parametrizations(bn) == BatchNorm2d
125
+ ), (
126
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
127
+ f"{type_before_parametrizations(bn)}"
128
+ )
129
+ super().__init__(conv, bn)
130
+
131
+
132
+ class ConvBnReLU1d(_FusedModule):
133
+ r"""This is a sequential container which calls the Conv 1d, Batch Norm 1d, and ReLU modules.
134
+ During quantization this will be replaced with the corresponding fused module."""
135
+
136
+ def __init__(self, conv, bn, relu):
137
+ assert (
138
+ type_before_parametrizations(conv) == Conv1d
139
+ and type_before_parametrizations(bn) == BatchNorm1d
140
+ and type_before_parametrizations(relu) == ReLU
141
+ ), (
142
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
143
+ f"{type_before_parametrizations(bn)}"
144
+ f"{type_before_parametrizations(relu)}"
145
+ )
146
+ super().__init__(conv, bn, relu)
147
+
148
+
149
+ class ConvBnReLU2d(_FusedModule):
150
+ r"""This is a sequential container which calls the Conv 2d, Batch Norm 2d, and ReLU modules.
151
+ During quantization this will be replaced with the corresponding fused module."""
152
+
153
+ def __init__(self, conv, bn, relu):
154
+ assert (
155
+ type_before_parametrizations(conv) == Conv2d
156
+ and type_before_parametrizations(bn) == BatchNorm2d
157
+ and type_before_parametrizations(relu) == ReLU
158
+ ), (
159
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
160
+ f"{type_before_parametrizations(bn)}"
161
+ f"{type_before_parametrizations(relu)}"
162
+ )
163
+ super().__init__(conv, bn, relu)
164
+
165
+
166
+ class ConvBn3d(_FusedModule):
167
+ r"""This is a sequential container which calls the Conv 3d and Batch Norm 3d modules.
168
+ During quantization this will be replaced with the corresponding fused module."""
169
+
170
+ def __init__(self, conv, bn):
171
+ assert (
172
+ type_before_parametrizations(conv) == Conv3d
173
+ and type_before_parametrizations(bn) == BatchNorm3d
174
+ ), (
175
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
176
+ f"{type_before_parametrizations(bn)}"
177
+ )
178
+ super().__init__(conv, bn)
179
+
180
+
181
+ class ConvBnReLU3d(_FusedModule):
182
+ r"""This is a sequential container which calls the Conv 3d, Batch Norm 3d, and ReLU modules.
183
+ During quantization this will be replaced with the corresponding fused module."""
184
+
185
+ def __init__(self, conv, bn, relu):
186
+ assert (
187
+ type_before_parametrizations(conv) == Conv3d
188
+ and type_before_parametrizations(bn) == BatchNorm3d
189
+ and type_before_parametrizations(relu) == ReLU
190
+ ), (
191
+ f"Incorrect types for input modules{type_before_parametrizations(conv)}"
192
+ f"{type_before_parametrizations(bn)}"
193
+ f"{type_before_parametrizations(relu)}"
194
+ )
195
+ super().__init__(conv, bn, relu)
196
+
197
+
198
+ class BNReLU2d(_FusedModule):
199
+ r"""This is a sequential container which calls the BatchNorm 2d and ReLU modules.
200
+ During quantization this will be replaced with the corresponding fused module."""
201
+
202
+ def __init__(self, batch_norm, relu):
203
+ assert (
204
+ type_before_parametrizations(batch_norm) == BatchNorm2d
205
+ and type_before_parametrizations(relu) == ReLU
206
+ ), (
207
+ f"Incorrect types for input modules{type_before_parametrizations(batch_norm)}"
208
+ f"{type_before_parametrizations(relu)}"
209
+ )
210
+ super().__init__(batch_norm, relu)
211
+
212
+
213
+ class BNReLU3d(_FusedModule):
214
+ r"""This is a sequential container which calls the BatchNorm 3d and ReLU modules.
215
+ During quantization this will be replaced with the corresponding fused module."""
216
+
217
+ def __init__(self, batch_norm, relu):
218
+ assert (
219
+ type_before_parametrizations(batch_norm) == BatchNorm3d
220
+ and type_before_parametrizations(relu) == ReLU
221
+ ), (
222
+ f"Incorrect types for input modules{type_before_parametrizations(batch_norm)}"
223
+ f"{type_before_parametrizations(relu)}"
224
+ )
225
+ super().__init__(batch_norm, relu)
226
+
227
+
228
+ class LinearBn1d(_FusedModule):
229
+ r"""This is a sequential container which calls the Linear and BatchNorm1d modules.
230
+ During quantization this will be replaced with the corresponding fused module."""
231
+
232
+ def __init__(self, linear, bn):
233
+ assert (
234
+ type_before_parametrizations(linear) == Linear
235
+ and type_before_parametrizations(bn) == BatchNorm1d
236
+ ), (
237
+ f"Incorrect types for input modules{type_before_parametrizations(linear)}"
238
+ f"{type_before_parametrizations(bn)}"
239
+ )
240
+ super().__init__(linear, bn)
241
+
242
+
243
+ class LinearLeakyReLU(_FusedModule):
244
+ r"""This is a sequential container which calls the Linear and LeakyReLU modules.
245
+ During quantization this will be replaced with the corresponding fused module."""
246
+
247
+ def __init__(self, linear, leaky_relu):
248
+ assert type(linear) is Linear and type(leaky_relu) is torch.nn.LeakyReLU, (
249
+ f"Incorrect types for input modules{type(linear)}{type(leaky_relu)}"
250
+ )
251
+ super().__init__(linear, leaky_relu)
252
+
253
+
254
+ class LinearTanh(_FusedModule):
255
+ r"""This is a sequential container which calls the Linear and Tanh modules.
256
+ During quantization this will be replaced with the corresponding fused module."""
257
+
258
+ def __init__(self, linear, tanh):
259
+ assert type(linear) is Linear and type(tanh) is torch.nn.Tanh, (
260
+ f"Incorrect types for input modules{type(linear)}{type(tanh)}"
261
+ )
262
+ super().__init__(linear, tanh)
263
+
264
+
265
+ class ConvAdd2d(_FusedModule):
266
+ r"""This is a sequential container which calls the Conv2d modules with extra Add.
267
+ During quantization this will be replaced with the corresponding fused module."""
268
+
269
+ def __init__(self, conv, add):
270
+ super().__init__(conv)
271
+ self.add = add
272
+
273
+ def forward(self, x1, x2): # type: ignore[override]
274
+ r"""Applies convolution to x1 and adds the result to x2."""
275
+ return self.add(self[0](x1), x2)
276
+
277
+
278
+ class ConvAddReLU2d(_FusedModule):
279
+ r"""This is a sequential container which calls the Conv2d, add, Relu.
280
+ During quantization this will be replaced with the corresponding fused module."""
281
+
282
+ def __init__(self, conv, add, relu):
283
+ super().__init__(conv)
284
+ self.add = add
285
+ self.relu = relu
286
+
287
+ def forward(self, x1, x2): # type: ignore[override]
288
+ r"""Applies convolution to x1, adds the result to x2, and applies ReLU."""
289
+ return self.relu(self.add(self[0](x1), x2))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modules import * # noqa: F403
miniconda3/envs/active_proaction/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
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/conv_fused.py ADDED
@@ -0,0 +1,958 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert qconfig, "qconfig must be provided for QAT module"
80
+ self.qconfig = qconfig
81
+ self.freeze_bn = freeze_bn if self.training else True
82
+ self.bn = _BN_CLASS_MAP[dim](out_channels, eps, momentum, True, True)
83
+ self.weight_fake_quant = self.qconfig.weight()
84
+ if bias:
85
+ self.bias = Parameter(torch.empty(out_channels))
86
+ else:
87
+ self.register_parameter("bias", None)
88
+ self.reset_bn_parameters()
89
+
90
+ # this needs to be called after reset_bn_parameters,
91
+ # as they modify the same state
92
+ if self.training:
93
+ if freeze_bn:
94
+ self.freeze_bn_stats()
95
+ else:
96
+ self.update_bn_stats()
97
+ else:
98
+ self.freeze_bn_stats()
99
+
100
+ self._enable_slow_path_for_better_numerical_stability = False
101
+
102
+ def reset_running_stats(self):
103
+ self.bn.reset_running_stats()
104
+
105
+ def reset_bn_parameters(self):
106
+ self.bn.reset_running_stats()
107
+ init.uniform_(self.bn.weight)
108
+ init.zeros_(self.bn.bias)
109
+ # note: below is actually for conv, not BN
110
+ if self.bias is not None:
111
+ fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
112
+ bound = 1 / math.sqrt(fan_in)
113
+ init.uniform_(self.bias, -bound, bound)
114
+
115
+ def update_bn_stats(self):
116
+ self.freeze_bn = False
117
+ self.bn.training = True
118
+ return self
119
+
120
+ def freeze_bn_stats(self):
121
+ self.freeze_bn = True
122
+ self.bn.training = False
123
+ return self
124
+
125
+ def _forward(self, input):
126
+ if self._enable_slow_path_for_better_numerical_stability:
127
+ return self._forward_slow(input)
128
+ return self._forward_approximate(input)
129
+
130
+ def _forward_approximate(self, input):
131
+ """Approximated method to fuse conv and bn. It requires only one forward pass.
132
+ conv_orig = conv / scale_factor where scale_factor = bn.weight / running_std
133
+ """
134
+ assert self.bn.running_var is not None
135
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
136
+ scale_factor = self.bn.weight / running_std
137
+ weight_shape = [1] * len(self.weight.shape)
138
+ weight_shape[0] = -1
139
+ bias_shape = [1] * len(self.weight.shape)
140
+ bias_shape[1] = -1
141
+ scaled_weight = self.weight_fake_quant(
142
+ self.weight * scale_factor.reshape(weight_shape)
143
+ )
144
+ # using zero bias here since the bias for original conv
145
+ # will be added later
146
+ if self.bias is not None:
147
+ zero_bias = torch.zeros_like(self.bias, dtype=input.dtype)
148
+ else:
149
+ zero_bias = torch.zeros(
150
+ self.out_channels, device=scaled_weight.device, dtype=input.dtype
151
+ )
152
+ conv = self._conv_forward(input, scaled_weight, zero_bias)
153
+ conv_orig = conv / scale_factor.reshape(bias_shape)
154
+ if self.bias is not None:
155
+ conv_orig = conv_orig + self.bias.reshape(bias_shape)
156
+ conv = self.bn(conv_orig)
157
+ return conv
158
+
159
+ def _forward_slow(self, input):
160
+ """
161
+ A more accurate but slow method to compute conv bn fusion, following https://arxiv.org/pdf/1806.08342.pdf
162
+ It requires two forward passes but handles the case bn.weight == 0
163
+
164
+ Conv: Y = WX + B_c
165
+ Conv without bias: Y0 = WX = Y - B_c, Y = Y0 + B_c
166
+
167
+ Batch statistics:
168
+ mean_Y = Y.mean()
169
+ = Y0.mean() + B_c
170
+ var_Y = (Y - mean_Y)^2.mean()
171
+ = (Y0 - Y0.mean())^2.mean()
172
+ BN (r: bn.weight, beta: bn.bias):
173
+ Z = r * (Y - mean_Y) / sqrt(var_Y + eps) + beta
174
+ = r * (Y0 - Y0.mean()) / sqrt(var_Y + eps) + beta
175
+
176
+ Fused Conv BN training (std_Y = sqrt(var_Y + eps)):
177
+ Z = (r * W / std_Y) * X + r * (B_c - mean_Y) / std_Y + beta
178
+ = (r * W / std_Y) * X - r * Y0.mean() / std_Y + beta
179
+
180
+ Fused Conv BN inference (running_std = sqrt(running_var + eps)):
181
+ Z = (r * W / running_std) * X - r * (running_mean - B_c) / running_std + beta
182
+
183
+ QAT with fused conv bn:
184
+ Z_train = fake_quant(r * W / running_std) * X * (running_std / std_Y) - r * Y0.mean() / std_Y + beta
185
+ = conv(X, fake_quant(r * W / running_std)) * (running_std / std_Y) - r * Y0.mean() / std_Y + beta
186
+ Z_inference = conv(X, fake_quant(r * W / running_std)) - r * (running_mean - B_c) / running_std + beta
187
+ """
188
+
189
+ assert self.bn.running_var is not None
190
+ assert self.bn.running_mean is not None
191
+
192
+ # using zero bias here since the bias for original conv
193
+ # will be added later
194
+ zero_bias = torch.zeros(
195
+ self.out_channels, device=self.weight.device, dtype=input.dtype
196
+ )
197
+
198
+ weight_shape = [1] * len(self.weight.shape)
199
+ weight_shape[0] = -1
200
+ bias_shape = [1] * len(self.weight.shape)
201
+ bias_shape[1] = -1
202
+
203
+ if self.bn.training:
204
+ # needed to compute batch mean/std
205
+ conv_out = self._conv_forward(input, self.weight, zero_bias)
206
+ # update bn statistics
207
+ with torch.no_grad():
208
+ conv_out_bias = (
209
+ conv_out
210
+ if self.bias is None
211
+ else conv_out + self.bias.reshape(bias_shape)
212
+ )
213
+ self.bn(conv_out_bias)
214
+
215
+ # fused conv + bn without bias using bn running statistics
216
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
217
+ scale_factor = self.bn.weight / running_std
218
+ scaled_weight = self.weight_fake_quant(
219
+ self.weight * scale_factor.reshape(weight_shape)
220
+ )
221
+ # fused conv without bias for inference: (r * W / running_std) * X
222
+ conv_bn = self._conv_forward(input, scaled_weight, zero_bias)
223
+
224
+ avg_dims = [0] + list(range(2, len(self.weight.shape)))
225
+ batch_mean = conv_out.mean(avg_dims)
226
+ batch_var = torch.square(conv_out - batch_mean.reshape(bias_shape)).mean(
227
+ avg_dims
228
+ )
229
+ batch_std = torch.sqrt(batch_var + self.bn.eps)
230
+
231
+ # scale to use batch std in training mode
232
+ # conv(X, r * W / std_Y) = conv(X, r * W / running_std) * (running_std / std_Y)
233
+ unscale_factor = running_std / batch_std
234
+ conv_bn *= unscale_factor.reshape(bias_shape)
235
+
236
+ fused_mean = batch_mean
237
+ fused_std = batch_std
238
+ else:
239
+ # fused conv + bn without bias using bn running statistics
240
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
241
+ scale_factor = self.bn.weight / running_std
242
+ scaled_weight = self.weight_fake_quant(
243
+ self.weight * scale_factor.reshape(weight_shape)
244
+ )
245
+ # fused conv without bias for inference: (r * W / running_std) * X
246
+ conv_bn = self._conv_forward(input, scaled_weight, zero_bias)
247
+
248
+ fused_mean = self.bn.running_mean - (
249
+ self.bias if self.bias is not None else 0
250
+ )
251
+ fused_std = running_std
252
+
253
+ # fused bias = beta - r * mean / std
254
+ fused_bias = self.bn.bias - self.bn.weight * fused_mean / fused_std
255
+ conv_bn += fused_bias.reshape(bias_shape)
256
+
257
+ # HACK to let conv bias participate in loss to avoid DDP error (parameters
258
+ # were not used in producing loss)
259
+ if self.bias is not None:
260
+ conv_bn += (self.bias - self.bias).reshape(bias_shape)
261
+
262
+ return conv_bn
263
+
264
+ def forward(self, input):
265
+ return self._forward(input)
266
+
267
+ def train(self, mode=True):
268
+ """
269
+ Batchnorm's training behavior is using the self.training flag. Prevent
270
+ changing it if BN is frozen. This makes sure that calling `model.train()`
271
+ on a model with a frozen BN will behave properly.
272
+ """
273
+ self.training = mode
274
+ if not self.freeze_bn:
275
+ for module in self.children():
276
+ module.train(mode)
277
+ return self
278
+
279
+ # ===== Serialization version history =====
280
+ #
281
+ # Version 1/None
282
+ # self
283
+ # |--- weight : Tensor
284
+ # |--- bias : Tensor
285
+ # |--- gamma : Tensor
286
+ # |--- beta : Tensor
287
+ # |--- running_mean : Tensor
288
+ # |--- running_var : Tensor
289
+ # |--- num_batches_tracked : Tensor
290
+ #
291
+ # Version 2
292
+ # self
293
+ # |--- weight : Tensor
294
+ # |--- bias : Tensor
295
+ # |--- bn : Module
296
+ # |--- weight : Tensor (moved from v1.self.gamma)
297
+ # |--- bias : Tensor (moved from v1.self.beta)
298
+ # |--- running_mean : Tensor (moved from v1.self.running_mean)
299
+ # |--- running_var : Tensor (moved from v1.self.running_var)
300
+ # |--- num_batches_tracked : Tensor (moved from v1.self.num_batches_tracked)
301
+ def _load_from_state_dict(
302
+ self,
303
+ state_dict,
304
+ prefix,
305
+ local_metadata,
306
+ strict,
307
+ missing_keys,
308
+ unexpected_keys,
309
+ error_msgs,
310
+ ):
311
+ version = local_metadata.get("version", None)
312
+ if version is None or version == 1:
313
+ # BN related parameters and buffers were moved into the BN module for v2
314
+ v2_to_v1_names = {
315
+ "bn.weight": "gamma",
316
+ "bn.bias": "beta",
317
+ "bn.running_mean": "running_mean",
318
+ "bn.running_var": "running_var",
319
+ "bn.num_batches_tracked": "num_batches_tracked",
320
+ }
321
+ for v2_name, v1_name in v2_to_v1_names.items():
322
+ if prefix + v1_name in state_dict:
323
+ state_dict[prefix + v2_name] = state_dict[prefix + v1_name]
324
+ state_dict.pop(prefix + v1_name)
325
+ elif prefix + v2_name in state_dict:
326
+ # there was a brief period where forward compatibility
327
+ # for this module was broken (between
328
+ # https://github.com/pytorch/pytorch/pull/38478
329
+ # and https://github.com/pytorch/pytorch/pull/38820)
330
+ # and modules emitted the v2 state_dict format while
331
+ # specifying that version == 1. This patches the forward
332
+ # compatibility issue by allowing the v2 style entries to
333
+ # be used.
334
+ pass
335
+ elif strict:
336
+ missing_keys.append(prefix + v2_name)
337
+
338
+ super()._load_from_state_dict(
339
+ state_dict,
340
+ prefix,
341
+ local_metadata,
342
+ strict,
343
+ missing_keys,
344
+ unexpected_keys,
345
+ error_msgs,
346
+ )
347
+
348
+ @classmethod
349
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
350
+ r"""Create a qat module from a float module or qparams_dict
351
+
352
+ Args: `mod` a float module, either produced by torch.ao.quantization utilities
353
+ or directly from user
354
+ """
355
+ # The ignore is because _FLOAT_MODULE is a TypeVar here where the bound
356
+ # has no __name__ (code is fine though)
357
+ assert type(mod) is cls._FLOAT_MODULE, (
358
+ "qat."
359
+ + cls.__name__
360
+ + ".from_float only works for "
361
+ + cls._FLOAT_MODULE.__name__
362
+ )
363
+ assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
364
+ assert mod.qconfig, "Input float module must have a valid qconfig"
365
+ qconfig = mod.qconfig
366
+ conv, bn = mod[0], mod[1] # type: ignore[index]
367
+ qat_convbn = cls(
368
+ conv.in_channels,
369
+ conv.out_channels,
370
+ conv.kernel_size,
371
+ conv.stride,
372
+ conv.padding,
373
+ conv.dilation,
374
+ conv.groups,
375
+ conv.bias is not None,
376
+ conv.padding_mode,
377
+ bn.eps,
378
+ bn.momentum,
379
+ False,
380
+ qconfig,
381
+ )
382
+ qat_convbn.weight = conv.weight
383
+ qat_convbn.bias = conv.bias
384
+ qat_convbn.bn.weight = bn.weight
385
+ qat_convbn.bn.bias = bn.bias
386
+ qat_convbn.bn.running_mean = bn.running_mean
387
+ qat_convbn.bn.running_var = bn.running_var
388
+ # mypy error: Cannot determine type of 'num_batches_tracked'
389
+ qat_convbn.bn.num_batches_tracked = bn.num_batches_tracked
390
+ return qat_convbn
391
+
392
+ def to_float(self):
393
+ cls = type(self)
394
+ conv = cls._FLOAT_CONV_MODULE( # type: ignore[attr-defined]
395
+ self.in_channels,
396
+ self.out_channels,
397
+ self.kernel_size,
398
+ self.stride,
399
+ self.padding,
400
+ self.dilation,
401
+ self.groups,
402
+ self.bias is not None,
403
+ self.padding_mode,
404
+ )
405
+ conv.weight = torch.nn.Parameter(self.weight.detach())
406
+ if self.bias is not None:
407
+ conv.bias = torch.nn.Parameter(self.bias.detach())
408
+
409
+ if cls._FLOAT_BN_MODULE: # type: ignore[attr-defined]
410
+ # fuse bn into conv
411
+ assert self.bn.running_var is not None and self.bn.running_mean is not None
412
+ conv.weight, conv.bias = fuse_conv_bn_weights(
413
+ conv.weight,
414
+ conv.bias,
415
+ self.bn.running_mean,
416
+ self.bn.running_var,
417
+ self.bn.eps,
418
+ self.bn.weight,
419
+ self.bn.bias,
420
+ )
421
+
422
+ if cls._FLOAT_RELU_MODULE: # type: ignore[attr-defined]
423
+ modules = []
424
+ modules.append(conv)
425
+ relu = cls._FLOAT_RELU_MODULE() # type: ignore[attr-defined]
426
+ modules.append(relu)
427
+ conv_relu = cls._FUSED_FLOAT_MODULE(*modules) # type: ignore[attr-defined]
428
+ conv_relu.train(self.training)
429
+ return conv_relu
430
+ else:
431
+ conv.train(self.training)
432
+ return conv
433
+
434
+
435
+ class ConvBn1d(_ConvBnNd, nn.Conv1d):
436
+ r"""
437
+ A ConvBn1d module is a module fused from Conv1d and BatchNorm1d,
438
+ attached with FakeQuantize modules for weight,
439
+ used in quantization aware training.
440
+
441
+ We combined the interface of :class:`torch.nn.Conv1d` and
442
+ :class:`torch.nn.BatchNorm1d`.
443
+
444
+ Similar to :class:`torch.nn.Conv1d`, with FakeQuantize modules initialized
445
+ to default.
446
+
447
+ Attributes:
448
+ freeze_bn:
449
+ weight_fake_quant: fake quant module for weight
450
+
451
+ """
452
+
453
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm1d]] = nn.BatchNorm1d
454
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
455
+ _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvBn1d # type: ignore[assignment]
456
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
457
+
458
+ def __init__(
459
+ self,
460
+ # Conv1d args
461
+ in_channels,
462
+ out_channels,
463
+ kernel_size,
464
+ stride=1,
465
+ padding=0,
466
+ dilation=1,
467
+ groups=1,
468
+ bias=None,
469
+ padding_mode="zeros",
470
+ # BatchNorm1d args
471
+ # num_features: out_channels
472
+ eps=1e-05,
473
+ momentum=0.1,
474
+ # affine: True
475
+ # track_running_stats: True
476
+ # Args for this module
477
+ freeze_bn=False,
478
+ qconfig=None,
479
+ ):
480
+ kernel_size = _single(kernel_size)
481
+ stride = _single(stride)
482
+ padding = _single(padding)
483
+ dilation = _single(dilation)
484
+ _ConvBnNd.__init__(
485
+ self,
486
+ in_channels,
487
+ out_channels,
488
+ kernel_size,
489
+ stride,
490
+ padding,
491
+ dilation,
492
+ False,
493
+ _single(0),
494
+ groups,
495
+ bias,
496
+ padding_mode,
497
+ eps,
498
+ momentum,
499
+ freeze_bn,
500
+ qconfig,
501
+ dim=1,
502
+ )
503
+
504
+
505
+ class ConvBnReLU1d(ConvBn1d):
506
+ r"""
507
+ A ConvBnReLU1d module is a module fused from Conv1d, BatchNorm1d and ReLU,
508
+ attached with FakeQuantize modules for weight,
509
+ used in quantization aware training.
510
+
511
+ We combined the interface of :class:`torch.nn.Conv1d` and
512
+ :class:`torch.nn.BatchNorm1d` and :class:`torch.nn.ReLU`.
513
+
514
+ Similar to `torch.nn.Conv1d`, with FakeQuantize modules initialized to
515
+ default.
516
+
517
+ Attributes:
518
+ weight_fake_quant: fake quant module for weight
519
+
520
+ """
521
+
522
+ # base class defines _FLOAT_MODULE as "ConvBn1d"
523
+ _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvBnReLU1d
524
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
525
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm1d]] = nn.BatchNorm1d
526
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
527
+ # module class after fusing bn into conv
528
+ _FUSED_FLOAT_MODULE: ClassVar[type[nn.Module] | None] = nni.ConvReLU1d
529
+
530
+ def forward(self, input):
531
+ r"""Performs forward pass through fused Conv1d, BatchNorm1d, and ReLU."""
532
+ return F.relu(self._forward(input))
533
+
534
+ @classmethod
535
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
536
+ r"""Creates a QAT module from a floating point module."""
537
+ return super().from_float(mod, use_precomputed_fake_quant)
538
+
539
+
540
+ class ConvReLU1d(nnqat.Conv1d, nni._FusedModule):
541
+ r"""A ConvReLU1d module is a fused module of Conv1d and ReLU, attached with
542
+ FakeQuantize modules for weight for
543
+ quantization aware training.
544
+
545
+ We combined the interface of :class:`~torch.nn.Conv1d` and
546
+ :class:`~torch.nn.BatchNorm1d`.
547
+
548
+ Attributes:
549
+ weight_fake_quant: fake quant module for weight
550
+
551
+ """
552
+
553
+ _FLOAT_MODULE: ClassVar[type[nni.ConvReLU1d]] = nni.ConvReLU1d # type: ignore[assignment]
554
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
555
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
556
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
557
+
558
+ def __init__(
559
+ self,
560
+ in_channels,
561
+ out_channels,
562
+ kernel_size,
563
+ stride=1,
564
+ padding=0,
565
+ dilation=1,
566
+ groups=1,
567
+ bias=True,
568
+ padding_mode="zeros",
569
+ qconfig=None,
570
+ ):
571
+ super().__init__(
572
+ in_channels,
573
+ out_channels,
574
+ kernel_size,
575
+ stride=stride,
576
+ padding=padding,
577
+ dilation=dilation,
578
+ groups=groups,
579
+ bias=bias,
580
+ # pyrefly: ignore [bad-argument-type]
581
+ padding_mode=padding_mode,
582
+ qconfig=qconfig,
583
+ )
584
+ assert qconfig, "qconfig must be provided for QAT module"
585
+ self.qconfig = qconfig
586
+ self.weight_fake_quant = self.qconfig.weight()
587
+
588
+ def forward(self, input):
589
+ r"""Performs forward pass through fused Conv1d and ReLU."""
590
+ return F.relu(
591
+ self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
592
+ )
593
+
594
+ @classmethod
595
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
596
+ r"""Creates a QAT module from a floating point module."""
597
+ return super().from_float(
598
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
599
+ )
600
+
601
+
602
+ class ConvBn2d(_ConvBnNd, nn.Conv2d):
603
+ r"""
604
+ A ConvBn2d module is a module fused from Conv2d and BatchNorm2d,
605
+ attached with FakeQuantize modules for weight,
606
+ used in quantization aware training.
607
+
608
+ We combined the interface of :class:`torch.nn.Conv2d` and
609
+ :class:`torch.nn.BatchNorm2d`.
610
+
611
+ Similar to :class:`torch.nn.Conv2d`, with FakeQuantize modules initialized
612
+ to default.
613
+
614
+ Attributes:
615
+ freeze_bn:
616
+ weight_fake_quant: fake quant module for weight
617
+
618
+ """
619
+
620
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBn2d]] = nni.ConvBn2d # type: ignore[assignment]
621
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
622
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = nn.BatchNorm2d
623
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
624
+
625
+ def __init__(
626
+ self,
627
+ # ConvNd args
628
+ in_channels,
629
+ out_channels,
630
+ kernel_size,
631
+ stride=1,
632
+ padding=0,
633
+ dilation=1,
634
+ groups=1,
635
+ bias=None,
636
+ padding_mode="zeros",
637
+ # BatchNorm2d args
638
+ # num_features: out_channels
639
+ eps=1e-05,
640
+ momentum=0.1,
641
+ # affine: True
642
+ # track_running_stats: True
643
+ # Args for this module
644
+ freeze_bn=False,
645
+ qconfig=None,
646
+ ):
647
+ kernel_size = _pair(kernel_size)
648
+ stride = _pair(stride)
649
+ padding = _pair(padding)
650
+ dilation = _pair(dilation)
651
+ _ConvBnNd.__init__(
652
+ self,
653
+ in_channels,
654
+ out_channels,
655
+ kernel_size,
656
+ stride,
657
+ padding,
658
+ dilation,
659
+ False,
660
+ _pair(0),
661
+ groups,
662
+ bias,
663
+ padding_mode,
664
+ eps,
665
+ momentum,
666
+ freeze_bn,
667
+ qconfig,
668
+ dim=2,
669
+ )
670
+
671
+
672
+ class ConvBnReLU2d(ConvBn2d):
673
+ r"""
674
+ A ConvBnReLU2d module is a module fused from Conv2d, BatchNorm2d and ReLU,
675
+ attached with FakeQuantize modules for weight,
676
+ used in quantization aware training.
677
+
678
+ We combined the interface of :class:`torch.nn.Conv2d` and
679
+ :class:`torch.nn.BatchNorm2d` and :class:`torch.nn.ReLU`.
680
+
681
+ Similar to `torch.nn.Conv2d`, with FakeQuantize modules initialized to
682
+ default.
683
+
684
+ Attributes:
685
+ weight_fake_quant: fake quant module for weight
686
+
687
+ """
688
+
689
+ # base class defines _FLOAT_MODULE as "ConvBn2d"
690
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBnReLU2d]] = nni.ConvBnReLU2d # type: ignore[assignment]
691
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
692
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm2d]] = nn.BatchNorm2d
693
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
694
+ # module class after fusing bn into conv
695
+ _FUSED_FLOAT_MODULE: ClassVar[type[nni.ConvReLU2d] | None] = nni.ConvReLU2d
696
+
697
+ def forward(self, input):
698
+ r"""Performs forward pass through fused Conv2d, BatchNorm2d, and ReLU."""
699
+ return F.relu(self._forward(input))
700
+
701
+ @classmethod
702
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
703
+ r"""Creates a QAT module from a floating point module."""
704
+ return super().from_float(mod, use_precomputed_fake_quant)
705
+
706
+
707
+ class ConvReLU2d(nnqat.Conv2d, nni._FusedModule):
708
+ r"""A ConvReLU2d module is a fused module of Conv2d and ReLU, attached with
709
+ FakeQuantize modules for weight for
710
+ quantization aware training.
711
+
712
+ We combined the interface of :class:`~torch.nn.Conv2d` and
713
+ :class:`~torch.nn.BatchNorm2d`.
714
+
715
+ Attributes:
716
+ weight_fake_quant: fake quant module for weight
717
+
718
+ """
719
+
720
+ _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvReLU2d # type: ignore[assignment]
721
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
722
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
723
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
724
+
725
+ def __init__(
726
+ self,
727
+ in_channels,
728
+ out_channels,
729
+ kernel_size,
730
+ stride=1,
731
+ padding=0,
732
+ dilation=1,
733
+ groups=1,
734
+ bias=True,
735
+ padding_mode="zeros",
736
+ qconfig=None,
737
+ ):
738
+ super().__init__(
739
+ in_channels,
740
+ out_channels,
741
+ kernel_size,
742
+ stride=stride,
743
+ padding=padding,
744
+ dilation=dilation,
745
+ groups=groups,
746
+ bias=bias,
747
+ # pyrefly: ignore [bad-argument-type]
748
+ padding_mode=padding_mode,
749
+ qconfig=qconfig,
750
+ )
751
+ assert qconfig, "qconfig must be provided for QAT module"
752
+ self.qconfig = qconfig
753
+ self.weight_fake_quant = self.qconfig.weight()
754
+
755
+ def forward(self, input):
756
+ r"""Performs forward pass through fused Conv2d and ReLU."""
757
+ return F.relu(
758
+ self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
759
+ )
760
+
761
+ @classmethod
762
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
763
+ r"""Creates a QAT module from a floating point module."""
764
+ return super().from_float(
765
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
766
+ )
767
+
768
+
769
+ class ConvBn3d(_ConvBnNd, nn.Conv3d):
770
+ r"""
771
+ A ConvBn3d module is a module fused from Conv3d and BatchNorm3d,
772
+ attached with FakeQuantize modules for weight,
773
+ used in quantization aware training.
774
+
775
+ We combined the interface of :class:`torch.nn.Conv3d` and
776
+ :class:`torch.nn.BatchNorm3d`.
777
+
778
+ Similar to :class:`torch.nn.Conv3d`, with FakeQuantize modules initialized
779
+ to default.
780
+
781
+ Attributes:
782
+ freeze_bn:
783
+ weight_fake_quant: fake quant module for weight
784
+
785
+ """
786
+
787
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBn3d]] = nni.ConvBn3d # type: ignore[assignment]
788
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
789
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = nn.BatchNorm3d
790
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
791
+
792
+ def __init__(
793
+ self,
794
+ # ConvNd args
795
+ in_channels,
796
+ out_channels,
797
+ kernel_size,
798
+ stride=1,
799
+ padding=0,
800
+ dilation=1,
801
+ groups=1,
802
+ bias=None,
803
+ padding_mode="zeros",
804
+ # BatchNorm3d args
805
+ # num_features: out_channels
806
+ eps=1e-05,
807
+ momentum=0.1,
808
+ # affine: True
809
+ # track_running_stats: True
810
+ # Args for this module
811
+ freeze_bn=False,
812
+ qconfig=None,
813
+ ):
814
+ kernel_size = _triple(kernel_size)
815
+ stride = _triple(stride)
816
+ padding = _triple(padding)
817
+ dilation = _triple(dilation)
818
+ _ConvBnNd.__init__(
819
+ self,
820
+ in_channels,
821
+ out_channels,
822
+ kernel_size,
823
+ stride,
824
+ padding,
825
+ dilation,
826
+ False,
827
+ _triple(0),
828
+ groups,
829
+ bias,
830
+ padding_mode,
831
+ eps,
832
+ momentum,
833
+ freeze_bn,
834
+ qconfig,
835
+ dim=3,
836
+ )
837
+
838
+
839
+ class ConvBnReLU3d(ConvBn3d):
840
+ r"""
841
+ A ConvBnReLU3d module is a module fused from Conv3d, BatchNorm3d and ReLU,
842
+ attached with FakeQuantize modules for weight,
843
+ used in quantization aware training.
844
+
845
+ We combined the interface of :class:`torch.nn.Conv3d` and
846
+ :class:`torch.nn.BatchNorm3d` and :class:`torch.nn.ReLU`.
847
+
848
+ Similar to `torch.nn.Conv3d`, with FakeQuantize modules initialized to
849
+ default.
850
+
851
+ Attributes:
852
+ weight_fake_quant: fake quant module for weight
853
+
854
+ """
855
+
856
+ _FLOAT_MODULE: ClassVar[type[nni.ConvBnReLU3d]] = nni.ConvBnReLU3d # type: ignore[assignment]
857
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
858
+ _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm3d]] = nn.BatchNorm3d
859
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.ReLU] | None] = nn.ReLU
860
+ # module class after fusing bn into conv
861
+ _FUSED_FLOAT_MODULE: ClassVar[type[nni.ConvReLU3d] | None] = nni.ConvReLU3d
862
+
863
+ def forward(self, input):
864
+ r"""Performs forward pass through fused Conv3d, BatchNorm3d, and ReLU."""
865
+ return F.relu(ConvBn3d._forward(self, input))
866
+
867
+ @classmethod
868
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
869
+ r"""Creates a QAT module from a floating point module."""
870
+ return super().from_float(
871
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
872
+ )
873
+
874
+
875
+ class ConvReLU3d(nnqat.Conv3d, nni._FusedModule):
876
+ r"""A ConvReLU3d module is a fused module of Conv3d and ReLU, attached with
877
+ FakeQuantize modules for weight for
878
+ quantization aware training.
879
+
880
+ We combined the interface of :class:`~torch.nn.Conv3d` and
881
+ :class:`~torch.nn.BatchNorm3d`.
882
+
883
+ Attributes:
884
+ weight_fake_quant: fake quant module for weight
885
+
886
+ """
887
+
888
+ _FLOAT_MODULE: ClassVar[type[nni.ConvReLU3d]] = nni.ConvReLU3d # type: ignore[assignment]
889
+ _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
890
+ _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
891
+ _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
892
+
893
+ def __init__(
894
+ self,
895
+ in_channels,
896
+ out_channels,
897
+ kernel_size,
898
+ stride=1,
899
+ padding=0,
900
+ dilation=1,
901
+ groups=1,
902
+ bias=True,
903
+ padding_mode="zeros",
904
+ qconfig=None,
905
+ ):
906
+ super().__init__(
907
+ in_channels,
908
+ out_channels,
909
+ kernel_size,
910
+ stride=stride,
911
+ padding=padding,
912
+ dilation=dilation,
913
+ groups=groups,
914
+ bias=bias,
915
+ # pyrefly: ignore [bad-argument-type]
916
+ padding_mode=padding_mode,
917
+ qconfig=qconfig,
918
+ )
919
+ assert qconfig, "qconfig must be provided for QAT module"
920
+ self.qconfig = qconfig
921
+ self.weight_fake_quant = self.qconfig.weight()
922
+
923
+ def forward(self, input):
924
+ r"""Performs forward pass through fused Conv3d and ReLU."""
925
+ return F.relu(
926
+ self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
927
+ )
928
+
929
+ @classmethod
930
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
931
+ r"""Creates a QAT module from a floating point module."""
932
+ return super().from_float(
933
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
934
+ )
935
+
936
+
937
+ def update_bn_stats(mod):
938
+ if type(mod) in {
939
+ ConvBnReLU1d,
940
+ ConvBnReLU2d,
941
+ ConvBnReLU3d,
942
+ ConvBn1d,
943
+ ConvBn2d,
944
+ ConvBn3d,
945
+ }:
946
+ mod.update_bn_stats()
947
+
948
+
949
+ def freeze_bn_stats(mod):
950
+ if type(mod) in {
951
+ ConvBnReLU1d,
952
+ ConvBnReLU2d,
953
+ ConvBnReLU3d,
954
+ ConvBn1d,
955
+ ConvBn2d,
956
+ ConvBn3d,
957
+ }:
958
+ mod.freeze_bn_stats()
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_fused.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert qconfig, "qconfig must be provided for QAT module"
51
+ self.qconfig = qconfig
52
+ self.freeze_bn = freeze_bn if self.training else True
53
+ self.bn = nn.BatchNorm1d(out_features, eps, momentum, True, True)
54
+ self.weight_fake_quant = self.qconfig.weight()
55
+ if bias:
56
+ self.bias = Parameter(torch.empty(out_features))
57
+ else:
58
+ self.register_parameter("bias", None)
59
+ self.reset_bn_parameters()
60
+
61
+ # this needs to be called after reset_bn_parameters,
62
+ # as they modify the same state
63
+ if self.training:
64
+ if freeze_bn:
65
+ self.freeze_bn_stats()
66
+ else:
67
+ self.update_bn_stats()
68
+ else:
69
+ self.freeze_bn_stats()
70
+
71
+ def reset_running_stats(self):
72
+ self.bn.reset_running_stats()
73
+
74
+ def reset_bn_parameters(self):
75
+ self.bn.reset_running_stats()
76
+ init.uniform_(self.bn.weight)
77
+ init.zeros_(self.bn.bias)
78
+
79
+ def update_bn_stats(self):
80
+ self.freeze_bn = False
81
+ self.bn.training = True
82
+ return self
83
+
84
+ def freeze_bn_stats(self):
85
+ self.freeze_bn = True
86
+ self.bn.training = False
87
+ return self
88
+
89
+ def forward(self, input):
90
+ assert self.bn.running_var is not None
91
+
92
+ # Scale the linear weights by BN's running statistics to reduce
93
+ # weight jitter, see https://arxiv.org/pdf/1806.08342.pdf, page 18
94
+ # for motivation.
95
+ #
96
+ # Instead of
97
+ #
98
+ # x1 = F.linear(x0, fq(w), b)
99
+ # x2 = self.bn(x1)
100
+ #
101
+ # We have
102
+ #
103
+ # # scale the weight by previous batch's running statistics
104
+ # scale_factor = bn.w / bn.running_std_from_prev_batch
105
+ # # do the linear transformation without bias
106
+ # x1_scaled = F.linear(x0, fq(w * scale_factor), 0)
107
+ # # reverse the scaling and add original bias
108
+ # x1_orig = x1_scaled / scale_factor + b
109
+ # x2 = self.bn(x1_orig)
110
+
111
+ running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
112
+ scale_factor = self.bn.weight / running_std
113
+ weight_shape = [1] * len(self.weight.shape)
114
+ weight_shape[0] = -1
115
+ bias_shape = [1] * len(self.weight.shape)
116
+ bias_shape[1] = -1
117
+ scaled_weight = self.weight_fake_quant(
118
+ self.weight * scale_factor.reshape(weight_shape)
119
+ )
120
+ if self.bias is not None:
121
+ zero_bias = torch.zeros_like(self.bias)
122
+ else:
123
+ zero_bias = torch.zeros(self.out_features, device=scaled_weight.device)
124
+ linear_out = F.linear(input, scaled_weight, zero_bias)
125
+ linear_out_orig = linear_out / scale_factor.reshape(bias_shape)
126
+ if self.bias is not None:
127
+ linear_out_orig = linear_out_orig + self.bias.reshape(bias_shape)
128
+ bn_out = self.bn(linear_out_orig)
129
+ return bn_out
130
+
131
+ def train(self, mode=True):
132
+ """
133
+ Batchnorm's training behavior is using the self.training flag. Prevent
134
+ changing it if BN is frozen. This makes sure that calling `model.train()`
135
+ on a model with a frozen BN will behave properly.
136
+ """
137
+ self.training = mode
138
+ if not self.freeze_bn:
139
+ for module in self.children():
140
+ module.train(mode)
141
+ return self
142
+
143
+ @classmethod
144
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
145
+ r"""Create a qat module from a float module or qparams_dict
146
+
147
+ Args:
148
+ mod: A float module, either produced by torch.ao.quantization
149
+ utilities or directly from the user.
150
+ """
151
+ assert type(mod) is nni.LinearBn1d, (
152
+ "qat."
153
+ + cls.__name__
154
+ + ".from_float only works for "
155
+ + nni.LinearBn1d.__name__
156
+ )
157
+ assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
158
+ assert mod.qconfig, "Input float module must have a valid config"
159
+ qconfig = mod.qconfig
160
+ linear, bn = mod[0], mod[1]
161
+ qat_linearbn = cls(
162
+ linear.in_features,
163
+ linear.out_features,
164
+ linear.bias is not None,
165
+ bn.eps,
166
+ bn.momentum,
167
+ False,
168
+ qconfig,
169
+ )
170
+ qat_linearbn.weight = linear.weight # type: ignore[assignment]
171
+ qat_linearbn.bias = linear.bias # type: ignore[assignment]
172
+ qat_linearbn.bn.weight = bn.weight # type: ignore[assignment]
173
+ qat_linearbn.bn.bias = bn.bias # type: ignore[assignment]
174
+ qat_linearbn.bn.running_mean = bn.running_mean # type: ignore[assignment]
175
+ qat_linearbn.bn.running_var = bn.running_var # type: ignore[assignment]
176
+ qat_linearbn.bn.num_batches_tracked = bn.num_batches_tracked # type: ignore[assignment]
177
+ return qat_linearbn
178
+
179
+ def to_float(self):
180
+ linear = torch.nn.Linear(self.in_features, self.out_features)
181
+ assert self.bn.running_var is not None and self.bn.running_mean is not None
182
+ linear.weight, linear.bias = fuse_linear_bn_weights(
183
+ self.weight,
184
+ self.bias,
185
+ self.bn.running_mean,
186
+ self.bn.running_var,
187
+ self.bn.eps,
188
+ self.bn.weight,
189
+ self.bn.bias,
190
+ )
191
+ return linear
miniconda3/envs/active_proaction/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]
miniconda3/envs/active_proaction/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
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modules import * # noqa: F403
miniconda3/envs/active_proaction/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
+ ]
miniconda3/envs/active_proaction/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])
miniconda3/envs/active_proaction/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
+ ]
miniconda3/envs/active_proaction/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)
miniconda3/envs/active_proaction/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)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ assert mod.bn.running_var is not None and mod.bn.running_mean is not None
87
+ mod.weight, mod.bias = fuse_conv_bn_weights(
88
+ mod.weight,
89
+ mod.bias,
90
+ mod.bn.running_mean,
91
+ mod.bn.running_var,
92
+ mod.bn.eps,
93
+ mod.bn.weight,
94
+ mod.bn.bias,
95
+ )
96
+ return super().from_float(mod, use_precomputed_fake_quant)
97
+
98
+ @classmethod
99
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
100
+ r"""Creates a quantized module from a reference module."""
101
+ assert type(ref_qconv) is not torch.ao.nn.intrinsic.ConvBnReLU1d, (
102
+ "BatchNorm1d should be fused into Conv1d before converting to reference module"
103
+ )
104
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
105
+
106
+
107
+ class ConvReLU2d(nnq.Conv2d):
108
+ r"""
109
+ A ConvReLU2d module is a fused module of Conv2d and ReLU
110
+
111
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
112
+
113
+ Attributes:
114
+ Same as torch.ao.nn.quantized.Conv2d
115
+
116
+ """
117
+
118
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU2d # type: ignore[assignment]
119
+
120
+ def __init__(
121
+ self,
122
+ in_channels,
123
+ out_channels,
124
+ kernel_size,
125
+ stride=1,
126
+ padding=0,
127
+ dilation=1,
128
+ groups=1,
129
+ bias=True,
130
+ padding_mode="zeros",
131
+ device=None,
132
+ dtype=None,
133
+ ):
134
+ super().__init__(
135
+ in_channels,
136
+ out_channels,
137
+ kernel_size,
138
+ stride=stride,
139
+ padding=padding,
140
+ dilation=dilation,
141
+ groups=groups,
142
+ bias=bias,
143
+ padding_mode=padding_mode,
144
+ device=device,
145
+ dtype=dtype,
146
+ )
147
+
148
+ def forward(self, input):
149
+ r"""Applies fused quantized Conv2d and ReLU."""
150
+ # Temporarily using len(shape) instead of ndim due to JIT issue
151
+ # https://github.com/pytorch/pytorch/issues/23890
152
+ if len(input.shape) != 4:
153
+ raise ValueError("Input shape must be `(N, C, H, W)`!")
154
+ if self.padding_mode != "zeros":
155
+ _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
156
+ input = F.pad(
157
+ input, _reversed_padding_repeated_twice, mode=self.padding_mode
158
+ )
159
+ return torch.ops.quantized.conv2d_relu(
160
+ input, self._packed_params, self.scale, self.zero_point
161
+ )
162
+
163
+ def _get_name(self):
164
+ return "QuantizedConvReLU2d"
165
+
166
+ @classmethod
167
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
168
+ r"""Creates a quantized module from a float module."""
169
+ if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU2d:
170
+ assert mod.bn.running_var is not None and mod.bn.running_mean is not None
171
+ mod.weight, mod.bias = fuse_conv_bn_weights(
172
+ mod.weight,
173
+ mod.bias,
174
+ mod.bn.running_mean,
175
+ mod.bn.running_var,
176
+ mod.bn.eps,
177
+ mod.bn.weight,
178
+ mod.bn.bias,
179
+ )
180
+ return super().from_float(
181
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
182
+ )
183
+
184
+ @classmethod
185
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
186
+ r"""Creates a quantized module from a reference module."""
187
+ assert type(ref_qconv) is not torch.ao.nn.intrinsic.ConvBnReLU2d, (
188
+ "BatchNorm2d should be fused into Conv2d before converting to reference module"
189
+ )
190
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
191
+
192
+
193
+ class ConvReLU3d(nnq.Conv3d):
194
+ r"""
195
+ A ConvReLU3d module is a fused module of Conv3d and ReLU
196
+
197
+ We adopt the same interface as :class:`torch.ao.nn.quantized.Conv3d`.
198
+
199
+ Attributes: Same as torch.ao.nn.quantized.Conv3d
200
+
201
+ """
202
+
203
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU3d # type: ignore[assignment]
204
+
205
+ def __init__(
206
+ self,
207
+ in_channels,
208
+ out_channels,
209
+ kernel_size,
210
+ stride=1,
211
+ padding=0,
212
+ dilation=1,
213
+ groups=1,
214
+ bias=True,
215
+ padding_mode="zeros",
216
+ device=None,
217
+ dtype=None,
218
+ ):
219
+ assert padding_mode != "reflect", "Conv3d does not support reflection padding"
220
+ super().__init__(
221
+ in_channels,
222
+ out_channels,
223
+ kernel_size,
224
+ stride=stride,
225
+ padding=padding,
226
+ dilation=dilation,
227
+ groups=groups,
228
+ bias=bias,
229
+ padding_mode=padding_mode,
230
+ device=device,
231
+ dtype=dtype,
232
+ )
233
+
234
+ def forward(self, input):
235
+ r"""Applies fused quantized Conv3d and ReLU."""
236
+ # Temporarily using len(shape) instead of ndim due to JIT issue
237
+ # https://github.com/pytorch/pytorch/issues/23890
238
+ if len(input.shape) != 5:
239
+ raise ValueError("Input shape must be `(N, C, D, H, W)`!")
240
+ if self.padding_mode != "zeros":
241
+ _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
242
+ input = F.pad(
243
+ input, _reversed_padding_repeated_twice, mode=self.padding_mode
244
+ )
245
+ return torch.ops.quantized.conv3d_relu(
246
+ input, self._packed_params, self.scale, self.zero_point
247
+ )
248
+
249
+ def _get_name(self):
250
+ return "QuantizedConvReLU3d"
251
+
252
+ @classmethod
253
+ def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
254
+ r"""Creates a quantized module from a float module."""
255
+ if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU3d:
256
+ assert mod.bn.running_var is not None and mod.bn.running_mean is not None
257
+ mod.weight, mod.bias = fuse_conv_bn_weights(
258
+ mod.weight,
259
+ mod.bias,
260
+ mod.bn.running_mean,
261
+ mod.bn.running_var,
262
+ mod.bn.eps,
263
+ mod.bn.weight,
264
+ mod.bn.bias,
265
+ )
266
+ return super().from_float(
267
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
268
+ )
269
+
270
+ @classmethod
271
+ def from_reference(cls, ref_qconv, output_scale, output_zero_point):
272
+ r"""Creates a quantized module from a reference module."""
273
+ assert type(ref_qconv) is not torch.ao.nn.intrinsic.ConvBnReLU3d, (
274
+ "BatchNorm3d should be fused into Conv3d before converting to reference module"
275
+ )
276
+ return super().from_reference(ref_qconv[0], output_scale, output_zero_point)