FaustDerLegende commited on
Commit
a5592f1
·
verified ·
1 Parent(s): 3829c5f

Upload folder using huggingface_hub (part 22)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. .venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_kernels.cpython-312.pyc +0 -0
  3. .venv/lib/python3.12/site-packages/torch/_native/ops/topk/_common.py +71 -0
  4. .venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_impl.py +230 -0
  5. .venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_kernels.py +874 -0
  6. .venv/lib/python3.12/site-packages/torch/_native/registry.py +1147 -0
  7. .venv/lib/python3.12/site-packages/torch/_native/triton/__init__.py +4 -0
  8. .venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/__init__.cpython-312.pyc +0 -0
  9. .venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/const_tensor_wrapper.cpython-312.pyc +0 -0
  10. .venv/lib/python3.12/site-packages/torch/_native/triton/const_tensor_wrapper.py +62 -0
  11. .venv/lib/python3.12/site-packages/torch/_native/triton_utils.py +137 -0
  12. .venv/lib/python3.12/site-packages/torch/_numpy/__init__.py +34 -0
  13. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/__init__.cpython-312.pyc +0 -0
  14. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_binary_ufuncs_impl.cpython-312.pyc +0 -0
  15. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_casting_dicts.cpython-312.pyc +0 -0
  16. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes.cpython-312.pyc +0 -0
  17. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes_impl.cpython-312.pyc +0 -0
  18. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs.cpython-312.pyc +0 -0
  19. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs_impl.cpython-312.pyc +0 -0
  20. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_getlimits.cpython-312.pyc +0 -0
  21. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ndarray.cpython-312.pyc +0 -0
  22. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_normalizations.cpython-312.pyc +0 -0
  23. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_reductions_impl.cpython-312.pyc +0 -0
  24. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ufuncs.cpython-312.pyc +0 -0
  25. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_unary_ufuncs_impl.cpython-312.pyc +0 -0
  26. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_util.cpython-312.pyc +0 -0
  27. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/fft.cpython-312.pyc +0 -0
  28. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/linalg.cpython-312.pyc +0 -0
  29. .venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/random.cpython-312.pyc +0 -0
  30. .venv/lib/python3.12/site-packages/torch/_numpy/_binary_ufuncs_impl.py +85 -0
  31. .venv/lib/python3.12/site-packages/torch/_numpy/_casting_dicts.py +1368 -0
  32. .venv/lib/python3.12/site-packages/torch/_numpy/_dtypes.py +470 -0
  33. .venv/lib/python3.12/site-packages/torch/_numpy/_dtypes_impl.py +230 -0
  34. .venv/lib/python3.12/site-packages/torch/_numpy/_funcs.py +76 -0
  35. .venv/lib/python3.12/site-packages/torch/_numpy/_funcs_impl.py +2064 -0
  36. .venv/lib/python3.12/site-packages/torch/_numpy/_getlimits.py +15 -0
  37. .venv/lib/python3.12/site-packages/torch/_numpy/_ndarray.py +733 -0
  38. .venv/lib/python3.12/site-packages/torch/_numpy/_normalizations.py +349 -0
  39. .venv/lib/python3.12/site-packages/torch/_numpy/_reductions_impl.py +480 -0
  40. .venv/lib/python3.12/site-packages/torch/_numpy/_ufuncs.py +332 -0
  41. .venv/lib/python3.12/site-packages/torch/_numpy/_unary_ufuncs_impl.py +72 -0
  42. .venv/lib/python3.12/site-packages/torch/_numpy/_util.py +297 -0
  43. .venv/lib/python3.12/site-packages/torch/_numpy/fft.py +191 -0
  44. .venv/lib/python3.12/site-packages/torch/_numpy/linalg.py +267 -0
  45. .venv/lib/python3.12/site-packages/torch/_numpy/random.py +191 -0
  46. .venv/lib/python3.12/site-packages/torch/_numpy/testing/__init__.py +20 -0
  47. .venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/__init__.cpython-312.pyc +0 -0
  48. .venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/utils.cpython-312.pyc +0 -0
  49. .venv/lib/python3.12/site-packages/torch/_numpy/testing/utils.py +2453 -0
  50. .venv/lib/python3.12/site-packages/torch/_opaque_base.py +11 -0
.gitattributes CHANGED
@@ -549,3 +549,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
549
  .venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
550
  .venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
551
  .venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
549
  .venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
550
  .venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
551
  .venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
552
+ .venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
553
+ .venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
554
+ .venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
555
+ .venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_kernels.cpython-312.pyc ADDED
Binary file (39.6 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_native/ops/topk/_common.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared eligibility checks and reshape helpers for topk overrides.
2
+
3
+ Both the CuTeDSL and Triton paths operate on a 2D ``(M, N)`` fp32 row-major
4
+ view of ``self`` where ``dim`` points at the last axis. This module hosts the
5
+ checks the conds share (contiguity, dim normalisation, COW) and the reshape
6
+ helpers the impls share.
7
+ """
8
+
9
+ import math
10
+
11
+ import torch
12
+
13
+
14
+ def any_cow(*tensors: torch.Tensor) -> bool:
15
+ return any(
16
+ torch._C._is_cow_tensor(t) # pyrefly: ignore[missing-attribute]
17
+ for t in tensors
18
+ )
19
+
20
+
21
+ def normalise_dim(self: torch.Tensor, dim: int) -> int:
22
+ """Translate a possibly-negative dim into its non-negative form.
23
+
24
+ Returns ``-1`` if the dim is out of range (cond callers should reject
25
+ in that case).
26
+ """
27
+ if self.ndim == 0:
28
+ return -1
29
+ if dim < -self.ndim or dim >= self.ndim:
30
+ return -1
31
+ return dim % self.ndim
32
+
33
+
34
+ def last_dim_row_major_ok(self: torch.Tensor, dim: int) -> bool:
35
+ """True iff reducing over ``dim`` is equivalent to reducing over the last
36
+ axis of a 2D ``(prod(leading dims), N)`` row-major view.
37
+
38
+ Requires ``dim`` to be the last axis and ``self`` to be contiguous in the
39
+ standard row-major sense; together they ensure the flatten-to-2D view we
40
+ pass to the kernel is a view (not a copy) and has stride-1 on N.
41
+ """
42
+ norm = normalise_dim(self, dim)
43
+ if norm != self.ndim - 1:
44
+ return False
45
+ return self.is_contiguous()
46
+
47
+
48
+ def flatten_last_dim(self: torch.Tensor) -> torch.Tensor:
49
+ """View nD self as 2D ``(M, N)`` with ``N = self.shape[-1]``.
50
+
51
+ Caller must have verified ``last_dim_row_major_ok`` so this is a view.
52
+ """
53
+ if self.ndim == 2:
54
+ return self
55
+ if self.ndim == 1:
56
+ return self.view(1, self.shape[0])
57
+ N = self.shape[-1]
58
+ M = math.prod(self.shape[:-1])
59
+ return self.view(M, N)
60
+
61
+
62
+ def unflatten_last_dim(
63
+ flat_values: torch.Tensor, flat_indices: torch.Tensor, self: torch.Tensor, k: int
64
+ ) -> tuple[torch.Tensor, torch.Tensor]:
65
+ """Reshape the 2D ``(M, K)`` kernel outputs back into ``self``'s shape."""
66
+ if self.ndim == 2:
67
+ return flat_values, flat_indices
68
+ if self.ndim == 1:
69
+ return flat_values.view(k), flat_indices.view(k)
70
+ out_shape = self.shape[:-1] + (k,)
71
+ return flat_values.view(out_shape), flat_indices.view(out_shape)
.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_impl.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CuTeDSL override registrations for ``aten::topk``.
2
+
3
+ Two kernels, picked by (K, N) - see ``cutedsl_kernels.py``:
4
+
5
+ * Register-resident (small K, small N): K in {16, 32}, N a power of 2
6
+ in a per-K range (see ``_REGISTER_N_RANGE``). Each warp sorts one
7
+ row entirely in registers and writes only K outputs to gmem.
8
+ Bit-exact to aten on values; indices on ties land in
9
+ ``(value desc, idx asc)`` order which doesn't match aten's small-K
10
+ CUDA kernel - same gather invariant though.
11
+
12
+ * Fused radix-select (larger K): K in {64, 128, 256, 512, 1024}.
13
+ Four radix byte passes over smem histograms, then a cooperative
14
+ bitonic sort of the K survivors. Two phase-2/phase-3 specialisations:
15
+ - Deterministic (under ``torch.use_deterministic_algorithms``):
16
+ block-wide prefix-sum gather + lex ``(ord, -idx)`` sort.
17
+ Bit-exact match to aten on values and indices.
18
+ - Non-deterministic: smem atomic-counter gather + ord-only sort.
19
+ Faster (~5-10%); indices may differ across runs on threshold ties.
20
+
21
+ Common eligibility (see ``_cond``):
22
+ - fp32 input, CUDA, not COW
23
+ - ``largest=True``, ``sorted=True``
24
+ - reducing over the last axis, ``self`` contiguous (2D flatten is a view)
25
+ - row count at least one full wave of SMs (perf gate)
26
+
27
+ Per-kernel additional eligibility:
28
+ - register: K in {16, 32}, N pow2 in supported range above
29
+ - radix: K in {64, 128, 256, 512, 1024}, ``N >= MIN_N_MULT[k] * k``,
30
+ ``N % 4 == 0`` (128-bit vector loads)
31
+
32
+ Anything else falls through to aten.
33
+ """
34
+
35
+ import functools
36
+ import math
37
+
38
+ import torch
39
+
40
+ from ... import cutedsl_utils as cu
41
+ from ._common import (
42
+ any_cow,
43
+ flatten_last_dim,
44
+ last_dim_row_major_ok,
45
+ unflatten_last_dim,
46
+ )
47
+
48
+
49
+ _RADIX_KS: frozenset[int] = frozenset({64, 128, 256, 512, 1024})
50
+ _REGISTER_KS: frozenset[int] = frozenset({16, 32})
51
+ _SUPPORTED_KS: frozenset[int] = _RADIX_KS | _REGISTER_KS
52
+
53
+ # Per-K minimum N for the radix kernel below which aten wins on B200.
54
+ # At low N the radix sweep (4 passes + gather) has too many passes over
55
+ # too little data to beat aten's launch-bound multi-pass kernel.
56
+ # K=512 needs ~8*K, K=1024 needs ~32*K because their smem footprint
57
+ # drops occupancy.
58
+ _RADIX_MIN_N_MULTIPLIER: dict[int, int] = {
59
+ 64: 2,
60
+ 128: 2,
61
+ 256: 2,
62
+ 512: 8,
63
+ 1024: 32,
64
+ }
65
+
66
+ # Register kernel per-K (min, max) N range, both bounds powers of 2.
67
+ # Below the min, VEC = N/32 is too small (most lanes idle, bitonic
68
+ # overhead dominates) and aten wins at large M. Above the max, radix
69
+ # (K=32) or aten (K=16 N>2048) takes over.
70
+ # Tuned on B200: K=16 wins down to N=64 across all M; K=32 only beats
71
+ # both aten and radix at exactly N=256.
72
+ _REGISTER_N_RANGE: dict[int, tuple[int, int]] = {
73
+ 16: (64, 2048),
74
+ 32: (256, 256),
75
+ }
76
+
77
+
78
+ def _is_pow2(x: int) -> bool:
79
+ return x > 0 and (x & (x - 1)) == 0
80
+
81
+
82
+ def _kernel_for(k: int, n: int) -> str | None:
83
+ """Pick the kernel for (K, N): "register", "radix", or None (aten)."""
84
+ if k in _REGISTER_KS:
85
+ n_min, n_max = _REGISTER_N_RANGE[k]
86
+ if _is_pow2(n) and n_min <= n <= n_max:
87
+ return "register"
88
+ if k in _RADIX_KS:
89
+ if n >= _RADIX_MIN_N_MULTIPLIER[k] * k and (n % 4) == 0:
90
+ return "radix"
91
+ return None
92
+
93
+
94
+ @functools.cache
95
+ def _min_rows_for_full_wave(device_idx: int) -> int:
96
+ """Row threshold below which the one-CTA-per-row kernel underutilises
97
+ the GPU. A full wave is SM-count CTAs; below that, aten's multi-CTA
98
+ kernel gets more parallelism out of the same rows and wins."""
99
+ return torch.cuda.get_device_properties(device_idx).multi_processor_count
100
+
101
+
102
+ def _eligible(
103
+ self: torch.Tensor, k: int, dim: int, largest: bool, sorted_: bool
104
+ ) -> bool:
105
+ if not self.is_cuda or self.dtype != torch.float32:
106
+ return False
107
+ if any_cow(self):
108
+ return False
109
+ if not largest or not sorted_:
110
+ return False
111
+ if not last_dim_row_major_ok(self, dim):
112
+ return False
113
+ N = self.shape[-1] if self.ndim >= 1 else 0
114
+ if _kernel_for(k, N) is None:
115
+ return False
116
+ # Performance gate: reject shapes where aten is faster. One CTA per
117
+ # row (radix) or one warp per row (register) - either way row_count
118
+ # below SM_count leaves the GPU underutilised.
119
+ M = math.prod(self.shape[:-1]) if self.ndim >= 1 else 0
120
+ if M < _min_rows_for_full_wave(self.device.index or 0):
121
+ return False
122
+ return True
123
+
124
+
125
+ def _cond(
126
+ self: torch.Tensor,
127
+ k: int,
128
+ dim: int = -1,
129
+ largest: bool = True,
130
+ sorted: bool = True,
131
+ *args,
132
+ **kwargs,
133
+ ) -> bool:
134
+ return _eligible(self, int(k), int(dim), bool(largest), bool(sorted))
135
+
136
+
137
+ def _out_cond(
138
+ self: torch.Tensor,
139
+ k: int,
140
+ dim: int = -1,
141
+ largest: bool = True,
142
+ sorted: bool = True,
143
+ *,
144
+ values: torch.Tensor,
145
+ indices: torch.Tensor,
146
+ ) -> bool:
147
+ if not _cond(self, k, dim, largest, sorted):
148
+ return False
149
+ if any_cow(values, indices):
150
+ return False
151
+ expected_shape = self.shape[:-1] + (k,)
152
+ if values.dtype != torch.float32 or values.shape != expected_shape:
153
+ return False
154
+ if indices.dtype != torch.int64 or indices.shape != expected_shape:
155
+ return False
156
+ return True
157
+
158
+
159
+ def _run(self: torch.Tensor, k: int) -> tuple[torch.Tensor, torch.Tensor]:
160
+ from .cutedsl_kernels import topk_radix, topk_register
161
+
162
+ self_2d = flatten_last_dim(self)
163
+ N = self_2d.shape[-1]
164
+ kernel = _kernel_for(k, N)
165
+
166
+ def _launch() -> tuple[torch.Tensor, torch.Tensor]:
167
+ if kernel == "register":
168
+ return topk_register(self_2d, k)
169
+ # Pick the deterministic kernel under torch.use_deterministic_algorithms
170
+ # (kept off by default for perf; the non-det kernel still produces
171
+ # correct top-K values but indices may differ on ties).
172
+ deterministic = torch.are_deterministic_algorithms_enabled()
173
+ return topk_radix(self_2d, k, deterministic=deterministic)
174
+
175
+ # The Python-native dispatch path does not get an automatic CUDA device
176
+ # guard before launching the kernel (unlike the generated C++ ATen path),
177
+ # so the CuTeDSL kernel runs on the current device's stream. Guard the
178
+ # launch when the input is not already on the current device, while leaving
179
+ # the common already-current path direct to avoid the context-manager
180
+ # overhead. See #187983 for the same fix on the bmm override.
181
+ device = self.get_device()
182
+ if device == torch.cuda.current_device():
183
+ values_2d, indices_2d = _launch()
184
+ else:
185
+ with torch.cuda.device(device):
186
+ values_2d, indices_2d = _launch()
187
+ return unflatten_last_dim(values_2d, indices_2d, self, k)
188
+
189
+
190
+ def _impl(
191
+ self: torch.Tensor,
192
+ k: int,
193
+ dim: int = -1,
194
+ largest: bool = True,
195
+ sorted: bool = True,
196
+ *args,
197
+ **kwargs,
198
+ ) -> tuple[torch.Tensor, torch.Tensor]:
199
+ return _run(self, int(k))
200
+
201
+
202
+ def _out_impl(
203
+ self: torch.Tensor,
204
+ k: int,
205
+ dim: int = -1,
206
+ largest: bool = True,
207
+ sorted: bool = True,
208
+ *,
209
+ values: torch.Tensor,
210
+ indices: torch.Tensor,
211
+ ) -> tuple[torch.Tensor, torch.Tensor]:
212
+ v, i = _run(self, int(k))
213
+ values.copy_(v)
214
+ indices.copy_(i)
215
+ return values, indices
216
+
217
+
218
+ def register_to_dispatch() -> None:
219
+ for op_symbol, cond, impl in (
220
+ ("topk", _cond, _impl),
221
+ ("topk.values", _out_cond, _out_impl),
222
+ ):
223
+ cu.register_op_override(
224
+ "aten",
225
+ op_symbol,
226
+ "CUDA",
227
+ cond=cond,
228
+ impl=impl,
229
+ allow_multiple_override=True,
230
+ )
.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_kernels.py ADDED
@@ -0,0 +1,874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CuTeDSL fp32 top-K kernels.
2
+
3
+ Two kernels live here, picked by K and N in ``cutedsl_impl.py``:
4
+
5
+ ``topk_radix`` - fused radix-select for K in {64,128,256,512,1024}.
6
+ Layout per CTA (one row):
7
+ * Phase 1 - four radix byte passes (MSB to LSB) build shared-memory
8
+ histograms via smem atomic-add; thread 0 scans descending to locate
9
+ the bin that contains the k-th-largest ordinal.
10
+ * Phase 2 - gather elements at-or-above the radix threshold. Two
11
+ specialisations selected by the ``deterministic`` constexpr:
12
+ - True: per-step block-wide exclusive prefix sums hand each
13
+ thread an exact write slot, eq-tied elements stage in a side
14
+ buffer; first ``remaining_k`` of them are appended in input
15
+ order. Stable across runs.
16
+ - False: smem atomic counters claim slots on the fly. Cheaper
17
+ but indices on threshold ties depend on atomic resolution
18
+ order.
19
+ * Phase 3 - cooperative bitonic sort descending. Block size is
20
+ ``max(K, 256)``; K threads own one element each, the rest sit the
21
+ sort out but still reach every barrier. Comparator is lex
22
+ ``(ord, -idx)`` (deterministic) or ord-only (non-deterministic).
23
+ * Phase 4 - write (values, indices) to global memory.
24
+
25
+ ``topk_register`` - register-resident top-K for K in {16, 32} with
26
+ N a power of 2 in [K, 2048]. Each warp owns one row; ``ROWS_PER_CTA``
27
+ warps share a CTA. Per-thread VEC = N/32 elements held in registers,
28
+ encoded as Int64 ``(ord << 32) | ~idx`` keys so a descending sort gives
29
+ ``(value desc, idx asc)`` matching aten. Local bitonic sort, then a
30
+ warp-cooperative bitonic-topk merge across butterfly partners. No smem,
31
+ no global staging - only the final K writes hit gmem. Bit-exact to aten.
32
+
33
+ Both kernels do one launch; only loads/stores of the input and final
34
+ outputs hit global memory.
35
+ """
36
+
37
+ import math
38
+
39
+ import cuda.bindings.driver as cuda # pyrefly: ignore[missing-import]
40
+
41
+ import cutlass
42
+ import cutlass.cute as cute
43
+ from cutlass import const_expr, Float32, Int32, Int64
44
+ from cutlass._mlir.dialects import llvm
45
+ from cutlass.cutlass_dsl import dsl_user_op, T
46
+
47
+ import torch
48
+ from torch._native.instrumentation import instrumented_cutedsl_cache
49
+
50
+
51
+ _NEG_INF_BITS: int = 0xFF800000
52
+ _N_HIST_BINS: int = 256
53
+
54
+
55
+ def _num_threads_for_k(k: int) -> int:
56
+ """Pick block size for a given K.
57
+
58
+ Bitonic sort in phase 3 assigns one element per thread, so we need
59
+ at least K threads. Using ``max(K, _N_HIST_BINS)`` keeps the phase-1
60
+ histogram-zero loop one-shot for small K while letting K grow up to
61
+ the CUDA 1024-thread cap.
62
+ """
63
+ return max(k, _N_HIST_BINS)
64
+
65
+
66
+ @dsl_user_op
67
+ def _elem_ptr(x: cute.Tensor, coord, *, loc=None, ip=None) -> cute.Pointer:
68
+ return x.iterator + cute.crd2idx(coord, x.layout, loc=loc, ip=ip)
69
+
70
+
71
+ @dsl_user_op
72
+ def _bitcast_f32_to_i32(val, *, loc=None, ip=None) -> Int32:
73
+ return Int32(llvm.bitcast(T.i32(), Float32(val).ir_value()))
74
+
75
+
76
+ @dsl_user_op
77
+ def _bitcast_i32_to_f32(val, *, loc=None, ip=None) -> Float32:
78
+ return Float32(llvm.bitcast(T.f32(), Int32(val).ir_value()))
79
+
80
+
81
+ @cute.jit
82
+ def _f32_to_radix_ord(val: Float32) -> Int32:
83
+ """Map fp32 to a monotone Int32 ordinal whose unsigned MSB->LSB byte
84
+ order matches descending fp32 order. Negatives invert all bits;
85
+ non-negatives keep their bits. With the byte-0 xor of 0x80 (applied
86
+ at the histogram-bin level), this gives a total order suitable for
87
+ MSB-first radix select.
88
+
89
+ NaN of either sign maps to 0x7FFFFFFF (the largest ordinal under the
90
+ byte-0 xor), matching aten's TopKTypeConfig<float> behaviour: NaN
91
+ sorts at the very top of largest-first topk regardless of sign.
92
+ """
93
+ bits = _bitcast_f32_to_i32(val)
94
+ ord_ = bits ^ ((bits >> Int32(31)) & Int32(0x7FFFFFFF))
95
+ # NaN detection: bits with all-ones exponent and non-zero mantissa.
96
+ # Equivalent to ``val != val``, but the DSL doesn't expose that
97
+ # comparator; the bit test is exact for IEEE-754 fp32.
98
+ is_nan = (bits & Int32(0x7FFFFFFF)) > Int32(0x7F800000)
99
+ return Int32(0x7FFFFFFF) if is_nan else ord_
100
+
101
+
102
+ def _smem_scalar(smem: cutlass.utils.SmemAllocator, dtype) -> cute.Tensor:
103
+ """Allocate a single-element smem tensor (scalar bookkeeping slot)."""
104
+ return smem.allocate_tensor(dtype, cute.make_layout((1,)), byte_alignment=4)
105
+
106
+
107
+ @cute.jit
108
+ def _load_vec_f32(ptr: cute.Pointer, vec_elems: cutlass.Constexpr) -> cute.Tensor:
109
+ """Vectorized gmem -> rmem load of ``vec_elems`` contiguous fp32.
110
+
111
+ Cute picks the widest safe instruction (e.g. LDG.128 for a 4-wide
112
+ fp32 tile) from the static shape.
113
+ """
114
+ gsrc = cute.make_tensor(ptr, cute.make_layout(vec_elems))
115
+ rvals = cute.make_rmem_tensor(vec_elems, Float32)
116
+ cute.autovec_copy(gsrc, rvals)
117
+ return rvals
118
+
119
+
120
+ @cute.jit
121
+ def _warp_inclusive_prefix(val: Int32, lane: Int32) -> Int32:
122
+ """Inclusive Hillis-Steele prefix sum across a single warp."""
123
+ for i in cutlass.range_constexpr(int(math.log2(cute.arch.WARP_SIZE))):
124
+ offset = 1 << i
125
+ # mask_and_clamp=0 so lanes < offset get 0 (no contribution).
126
+ partial = cute.arch.shuffle_sync_up(val, offset=offset, mask_and_clamp=0)
127
+ if lane >= Int32(offset):
128
+ val = val + partial
129
+ return val
130
+
131
+
132
+ @cute.jit
133
+ def _block_excl_prefix_i32(
134
+ val: Int32,
135
+ scratch: cute.Tensor,
136
+ lane: Int32,
137
+ warp: Int32,
138
+ num_warps: cutlass.Constexpr,
139
+ ) -> tuple[Int32, Int32]:
140
+ """Block-wide exclusive prefix sum over per-thread ``val``.
141
+
142
+ Returns ``(excl_pfx, total)``: ``excl_pfx`` is this thread's
143
+ exclusive prefix; ``total`` is the sum across all threads in the
144
+ block. ``scratch`` must have at least ``num_warps + 1`` Int32 slots
145
+ and is clobbered.
146
+
147
+ Implementation: warp-level Hillis-Steele scan, then warp 0 scans
148
+ the per-warp totals to produce per-warp offsets, then add.
149
+ """
150
+ WARP_SIZE = const_expr(cute.arch.WARP_SIZE)
151
+ # Step 1: per-warp inclusive scan.
152
+ incl = _warp_inclusive_prefix(val, lane)
153
+ excl_intra = incl - val
154
+ # Step 2: last lane in each warp publishes warp's inclusive total.
155
+ if lane == Int32(WARP_SIZE - 1):
156
+ scratch[warp] = incl
157
+ cute.arch.barrier()
158
+ # Step 3: warp 0 prefix-sums the per-warp totals.
159
+ if warp == Int32(0):
160
+ warp_val = Int32(0)
161
+ if lane < Int32(num_warps):
162
+ warp_val = scratch[lane]
163
+ warp_incl = _warp_inclusive_prefix(warp_val, lane)
164
+ warp_excl = warp_incl - warp_val
165
+ if lane < Int32(num_warps):
166
+ scratch[lane] = warp_excl
167
+ # Stash the block total in a slot beyond the per-warp set so
168
+ # other warps can read it without a second reduction.
169
+ if lane == Int32(num_warps - 1):
170
+ scratch[num_warps] = warp_incl
171
+ cute.arch.barrier()
172
+ excl_pfx = scratch[warp] + excl_intra
173
+ total = scratch[num_warps]
174
+ cute.arch.barrier() # let everyone consume scratch before next call
175
+ return excl_pfx, total
176
+
177
+
178
+ class _RadixSelectTopK:
179
+ """One-CTA-per-row fused radix-select + bitonic sort.
180
+
181
+ ``N``, ``K`` and ``deterministic`` are specialised at compile time:
182
+ the JIT cache keys on ``(N, K, deterministic)`` so a row-length or
183
+ determinism-mode change forces a recompile.
184
+
185
+ When ``deterministic`` is True, phase 2 uses block-wide prefix-sum
186
+ scans for input-stable gather and phase 3's bitonic comparator uses
187
+ a lex ``(ord, -idx)`` key. Output matches aten bit-exactly.
188
+
189
+ When ``deterministic`` is False, phase 2 uses smem atomic counters
190
+ for the gather and phase 3 sorts by ord-only. Faster (no extra smem
191
+ bookkeeping, no per-step block barrier on the gather), but ties at
192
+ the threshold radix bin are resolved non-deterministically and
193
+ indices may differ across runs.
194
+ """
195
+
196
+ VEC: int = 4
197
+
198
+ def __init__(self, N: int, K: int, deterministic: bool = True):
199
+ self.N = N
200
+ self.K = K
201
+ self.deterministic = deterministic
202
+ self.NUM_THREADS = _num_threads_for_k(K)
203
+ self.NUM_STAGES = int(math.log2(K))
204
+ TILE = self.NUM_THREADS * self.VEC
205
+ self.VEC_ITERS = N // TILE
206
+ self.VEC_TAIL_START = self.VEC_ITERS * TILE
207
+ self.SCALAR_TAIL_ITERS = (
208
+ N - self.VEC_TAIL_START + self.NUM_THREADS - 1
209
+ ) // self.NUM_THREADS
210
+
211
+ @cute.jit
212
+ def __call__(
213
+ self,
214
+ mX: cute.Tensor,
215
+ mValues: cute.Tensor,
216
+ mIndices: cute.Tensor,
217
+ stream: cuda.CUstream,
218
+ ):
219
+ M = mX.shape[0]
220
+ self.kernel(mX, mValues, mIndices).launch(
221
+ grid=[M, 1, 1],
222
+ block=[self.NUM_THREADS, 1, 1],
223
+ stream=stream,
224
+ )
225
+
226
+ @cute.kernel
227
+ def kernel(self, mX: cute.Tensor, mValues: cute.Tensor, mIndices: cute.Tensor):
228
+ tidx, _, _ = cute.arch.thread_idx()
229
+ row, _, _ = cute.arch.block_idx()
230
+
231
+ N = const_expr(self.N)
232
+ K = const_expr(self.K)
233
+ NT = const_expr(self.NUM_THREADS)
234
+ VEC = const_expr(self.VEC)
235
+ VEC_ITERS = const_expr(self.VEC_ITERS)
236
+ VEC_TAIL_START = const_expr(self.VEC_TAIL_START)
237
+ SCALAR_TAIL_ITERS = const_expr(self.SCALAR_TAIL_ITERS)
238
+ N_HIST_BINS = const_expr(_N_HIST_BINS)
239
+
240
+ smem = cutlass.utils.SmemAllocator()
241
+ s_hist = smem.allocate_tensor(
242
+ Int32, cute.make_layout((256,)), byte_alignment=16
243
+ )
244
+ s_prefix = _smem_scalar(smem, Int32)
245
+ s_mask = _smem_scalar(smem, Int32)
246
+ s_rem_k = _smem_scalar(smem, Int32)
247
+ # Phase-2 bookkeeping. Non-deterministic gather uses two
248
+ # atomic-add counters; deterministic gather carries running
249
+ # totals in registers.
250
+ s_write_ctr = _smem_scalar(smem, Int32)
251
+ s_eq_ctr = _smem_scalar(smem, Int32)
252
+ s_vals = smem.allocate_tensor(
253
+ Float32, cute.make_layout((K,)), byte_alignment=16
254
+ )
255
+ s_ords = smem.allocate_tensor(Int32, cute.make_layout((K,)), byte_alignment=16)
256
+ s_idxs = smem.allocate_tensor(Int32, cute.make_layout((K,)), byte_alignment=16)
257
+ # Side buffer for equal-threshold elements (deterministic gather only).
258
+ # Always allocated to keep the smem layout straightforward;
259
+ # measurements show no occupancy benefit from making it conditional.
260
+ s_eq_vals = smem.allocate_tensor(
261
+ Float32, cute.make_layout((K,)), byte_alignment=16
262
+ )
263
+ s_eq_idxs = smem.allocate_tensor(
264
+ Int32, cute.make_layout((K,)), byte_alignment=16
265
+ )
266
+
267
+ if tidx == 0:
268
+ s_prefix[0] = Int32(0)
269
+ s_mask[0] = Int32(0)
270
+ s_rem_k[0] = Int32(K)
271
+ cute.arch.barrier()
272
+
273
+ # Phase 1: four radix byte passes, MSB to LSB.
274
+ for byte_pos in cutlass.range_constexpr(4):
275
+ shift = (3 - byte_pos) * 8
276
+ xor_val = 128 if byte_pos == 0 else 0
277
+
278
+ # Zero the 256-bin histogram. When NT > 256 (e.g. K=1024) only
279
+ # the first 256 threads participate; the histogram is always
280
+ # exactly 256 bins regardless of K.
281
+ if tidx < N_HIST_BINS:
282
+ s_hist[tidx] = Int32(0)
283
+ cute.arch.barrier()
284
+
285
+ prefix = s_prefix[0]
286
+ decided_mask = s_mask[0]
287
+
288
+ if byte_pos == 0:
289
+ # First pass: decided_mask==0, every element participates.
290
+ for step in cutlass.range(VEC_ITERS):
291
+ base = step * NT * VEC + tidx * VEC
292
+ rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC)
293
+ for vi in cutlass.range_constexpr(self.VEC):
294
+ ords = _f32_to_radix_ord(rvals[vi])
295
+ byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32(
296
+ xor_val
297
+ )
298
+ cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1))
299
+ for step in cutlass.range(SCALAR_TAIL_ITERS):
300
+ idx = VEC_TAIL_START + step * NT + tidx
301
+ if idx < N:
302
+ ords = _f32_to_radix_ord(mX[row, idx])
303
+ byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32(
304
+ xor_val
305
+ )
306
+ cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1))
307
+ else:
308
+ for step in cutlass.range(VEC_ITERS):
309
+ base = step * NT * VEC + tidx * VEC
310
+ rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC)
311
+ for vi in cutlass.range_constexpr(self.VEC):
312
+ ords = _f32_to_radix_ord(rvals[vi])
313
+ if (ords & decided_mask) == prefix:
314
+ byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32(
315
+ xor_val
316
+ )
317
+ cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1))
318
+ for step in cutlass.range(SCALAR_TAIL_ITERS):
319
+ idx = VEC_TAIL_START + step * NT + tidx
320
+ if idx < N:
321
+ ords = _f32_to_radix_ord(mX[row, idx])
322
+ if (ords & decided_mask) == prefix:
323
+ byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32(
324
+ xor_val
325
+ )
326
+ cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1))
327
+ cute.arch.barrier()
328
+
329
+ # Thread 0 picks the bin that contains the k-th-largest.
330
+ if tidx == 0:
331
+ remaining_k = s_rem_k[0]
332
+ acc = Int32(0)
333
+ found = Int32(0)
334
+ sel_bin = Int32(0)
335
+ elems_above = Int32(0)
336
+
337
+ for b in cutlass.range(256):
338
+ bin_idx = Int32(255) - b
339
+ count = s_hist[bin_idx]
340
+ if found == Int32(0):
341
+ if acc + count >= remaining_k:
342
+ sel_bin = bin_idx
343
+ elems_above = acc
344
+ found = Int32(1)
345
+ acc = acc + count
346
+
347
+ actual_byte = sel_bin ^ Int32(xor_val)
348
+ s_prefix[0] = prefix | (actual_byte << Int32(shift))
349
+ s_mask[0] = decided_mask | (Int32(255) << Int32(shift))
350
+ s_rem_k[0] = remaining_k - elems_above
351
+
352
+ cute.arch.barrier()
353
+
354
+ # Phase 2: gather elements at-or-above the radix threshold.
355
+ # Two implementations selected at compile time:
356
+ # * Deterministic: per-step block-wide exclusive prefix sums
357
+ # give each thread an exact write slot; eq-threshold ties
358
+ # stage in a side buffer and the first ``remaining_k`` get
359
+ # appended in input-index order.
360
+ # * Non-deterministic: smem atomic counters claim slots on
361
+ # the fly. Faster but tied elements at the threshold bin
362
+ # are picked in atomic-resolution order.
363
+ threshold = s_prefix[0]
364
+ remaining_k = s_rem_k[0]
365
+
366
+ if tidx == 0:
367
+ s_write_ctr[0] = Int32(0)
368
+ s_eq_ctr[0] = Int32(0)
369
+ if tidx < K:
370
+ s_vals[tidx] = _bitcast_i32_to_f32(Int32(_NEG_INF_BITS))
371
+ s_idxs[tidx] = Int32(0)
372
+ cute.arch.barrier()
373
+
374
+ if const_expr(self.deterministic):
375
+ WARP_SIZE = const_expr(cute.arch.WARP_SIZE)
376
+ NUM_WARPS = const_expr(NT // WARP_SIZE)
377
+ lane_idx = tidx % Int32(WARP_SIZE)
378
+ warp_idx = tidx // Int32(WARP_SIZE)
379
+
380
+ # --- Vec + scalar tail (deterministic) ---
381
+ # Pack (n_above, n_eq) into a single Int32 as (high16, low16) so
382
+ # we can run one block-wide prefix sum per step instead of two.
383
+ # Per-step bounds: above+eq counts <= VEC*NT = 4*1024 = 4096,
384
+ # comfortably below 2^16; the sums share no bits so the low-half
385
+ # never carries into the high half.
386
+ #
387
+ # Carry the running bases in registers (every thread has
388
+ # ``packed_step_total`` from the scan) instead of going through
389
+ # smem each step.
390
+ above_base = Int32(0)
391
+ eq_base = Int32(0)
392
+ for step in cutlass.range(VEC_ITERS):
393
+ base = step * NT * VEC + tidx * VEC
394
+ rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC)
395
+
396
+ # Hoist per-element classification into per-lane registers
397
+ # so the count pass and write pass don't redo the radix-ord
398
+ # transform and threshold compare.
399
+ # Class encoding: 2 = above, 1 = eq, 0 = below.
400
+ cls_reg = cute.make_rmem_tensor(VEC, Int32)
401
+ packed_local = Int32(0)
402
+ for vi in cutlass.range_constexpr(self.VEC):
403
+ o = _f32_to_radix_ord(rvals[vi])
404
+ if o > threshold:
405
+ cls_reg[vi] = Int32(2)
406
+ packed_local = packed_local + Int32(1 << 16)
407
+ elif o == threshold:
408
+ cls_reg[vi] = Int32(1)
409
+ packed_local = packed_local + Int32(1)
410
+ else:
411
+ cls_reg[vi] = Int32(0)
412
+
413
+ # Block-wide exclusive prefix sum. ``s_hist`` is reused as
414
+ # scratch for the warp-total scan (Phase 1 is done with it).
415
+ packed_pfx, packed_step_total = _block_excl_prefix_i32(
416
+ packed_local, s_hist, lane_idx, warp_idx, NUM_WARPS
417
+ )
418
+ above_pfx = packed_pfx >> Int32(16)
419
+ eq_pfx = packed_pfx & Int32(0xFFFF)
420
+
421
+ # Per-thread write offsets within this step.
422
+ my_above = above_base + above_pfx
423
+ my_eq = eq_base + eq_pfx
424
+ for vi in cutlass.range_constexpr(self.VEC):
425
+ val_f32 = rvals[vi]
426
+ cls = cls_reg[vi]
427
+ idx = base + Int32(vi)
428
+ if cls == Int32(2):
429
+ if my_above < Int32(K):
430
+ s_vals[my_above] = val_f32
431
+ s_idxs[my_above] = Int32(idx)
432
+ my_above = my_above + Int32(1)
433
+ elif cls == Int32(1):
434
+ if my_eq < remaining_k:
435
+ s_eq_vals[my_eq] = val_f32
436
+ s_eq_idxs[my_eq] = Int32(idx)
437
+ my_eq = my_eq + Int32(1)
438
+
439
+ # Advance running bases. Cap eq at remaining_k - we never
440
+ # need more. All threads update in registers; no smem.
441
+ above_base = above_base + (packed_step_total >> Int32(16))
442
+ eq_base = min(
443
+ remaining_k, eq_base + (packed_step_total & Int32(0xFFFF))
444
+ )
445
+
446
+ # --- Scalar tail ---
447
+ for step in cutlass.range(SCALAR_TAIL_ITERS):
448
+ idx = VEC_TAIL_START + step * NT + tidx
449
+ valid = idx < N
450
+ packed_local = Int32(0)
451
+ if valid:
452
+ ords = _f32_to_radix_ord(mX[row, idx])
453
+ if ords > threshold:
454
+ packed_local = Int32(1 << 16)
455
+ elif ords == threshold:
456
+ packed_local = Int32(1)
457
+
458
+ packed_pfx, packed_step_total = _block_excl_prefix_i32(
459
+ packed_local, s_hist, lane_idx, warp_idx, NUM_WARPS
460
+ )
461
+ above_pfx = packed_pfx >> Int32(16)
462
+ eq_pfx = packed_pfx & Int32(0xFFFF)
463
+
464
+ my_above = above_base + above_pfx
465
+ my_eq = eq_base + eq_pfx
466
+ if valid:
467
+ val_f32 = mX[row, idx]
468
+ ords = _f32_to_radix_ord(val_f32)
469
+ if ords > threshold:
470
+ if my_above < Int32(K):
471
+ s_vals[my_above] = val_f32
472
+ s_idxs[my_above] = Int32(idx)
473
+ elif ords == threshold:
474
+ if my_eq < remaining_k:
475
+ s_eq_vals[my_eq] = val_f32
476
+ s_eq_idxs[my_eq] = Int32(idx)
477
+
478
+ above_base = above_base + (packed_step_total >> Int32(16))
479
+ eq_base = min(
480
+ remaining_k, eq_base + (packed_step_total & Int32(0xFFFF))
481
+ )
482
+
483
+ # The eq-merge below has each thread read s_eq_vals[tidx - n_above],
484
+ # i.e. a slot written by some other thread during the gather above.
485
+ # The last barrier inside _block_excl_prefix_i32 fires *before* the
486
+ # final per-step writes to s_eq_vals, so cross-thread visibility of
487
+ # those writes isn't guaranteed without a fresh barrier here.
488
+ cute.arch.barrier()
489
+
490
+ # Append eq-bucket survivors after the above-bucket ones to
491
+ # fill ``s_vals`` / ``s_idxs`` to exactly K entries.
492
+ n_above = above_base
493
+ if tidx < K:
494
+ offset_into_eq = Int32(tidx) - n_above
495
+ if offset_into_eq >= Int32(0) and offset_into_eq < remaining_k:
496
+ s_vals[tidx] = s_eq_vals[offset_into_eq]
497
+ s_idxs[tidx] = s_eq_idxs[offset_into_eq]
498
+ cute.arch.barrier()
499
+ else:
500
+ # Non-deterministic atomic-counter gather.
501
+ for step in cutlass.range(VEC_ITERS):
502
+ base = step * NT * VEC + tidx * VEC
503
+ rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC)
504
+ for vi in cutlass.range_constexpr(self.VEC):
505
+ val_f32 = rvals[vi]
506
+ idx = base + Int32(vi)
507
+ ords = _f32_to_radix_ord(val_f32)
508
+ if ords > threshold:
509
+ pos = cute.arch.atomic_add(_elem_ptr(s_write_ctr, 0), Int32(1))
510
+ if pos < Int32(K):
511
+ s_vals[pos] = val_f32
512
+ s_idxs[pos] = Int32(idx)
513
+ elif ords == threshold:
514
+ eq_pos = cute.arch.atomic_add(_elem_ptr(s_eq_ctr, 0), Int32(1))
515
+ if eq_pos < remaining_k:
516
+ pos = cute.arch.atomic_add(
517
+ _elem_ptr(s_write_ctr, 0), Int32(1)
518
+ )
519
+ if pos < Int32(K):
520
+ s_vals[pos] = val_f32
521
+ s_idxs[pos] = Int32(idx)
522
+ for step in cutlass.range(SCALAR_TAIL_ITERS):
523
+ idx = VEC_TAIL_START + step * NT + tidx
524
+ if idx < N:
525
+ val_f32 = mX[row, idx]
526
+ ords = _f32_to_radix_ord(val_f32)
527
+ if ords > threshold:
528
+ pos = cute.arch.atomic_add(_elem_ptr(s_write_ctr, 0), Int32(1))
529
+ if pos < Int32(K):
530
+ s_vals[pos] = val_f32
531
+ s_idxs[pos] = Int32(idx)
532
+ elif ords == threshold:
533
+ eq_pos = cute.arch.atomic_add(_elem_ptr(s_eq_ctr, 0), Int32(1))
534
+ if eq_pos < remaining_k:
535
+ pos = cute.arch.atomic_add(
536
+ _elem_ptr(s_write_ctr, 0), Int32(1)
537
+ )
538
+ if pos < Int32(K):
539
+ s_vals[pos] = val_f32
540
+ s_idxs[pos] = Int32(idx)
541
+ cute.arch.barrier()
542
+
543
+ # Phase 3: cooperative bitonic sort (descending) on a composite
544
+ # ``(ord, ~idx)`` Int64 key so equal-value entries break ties by
545
+ # input index, matching aten's stable ordering.
546
+ # K lanes own one element each; lanes >= K clamp their smem
547
+ # index to a dummy slot so they can participate in barriers
548
+ # without OOB reads/writes. The writes from those lanes are
549
+ # discarded via the `tidx < K` guard on the store.
550
+ sort_tidx = tidx if tidx < Int32(K) else Int32(0)
551
+ if tidx < K:
552
+ s_ords[tidx] = _f32_to_radix_ord(s_vals[sort_tidx])
553
+ cute.arch.barrier()
554
+
555
+ for stage in cutlass.range_constexpr(self.NUM_STAGES):
556
+ for sub_rev in cutlass.range_constexpr(stage + 1):
557
+ sub = stage - sub_rev
558
+ step_size = 1 << sub
559
+
560
+ # Snapshot both participants before the barrier; after the
561
+ # barrier the other thread may have overwritten its slot,
562
+ # so we must read our own ord now. Inactive lanes clamp
563
+ # their partner index to 0 (a safe in-bounds read) - their
564
+ # resulting comparisons are discarded by the store guard.
565
+ partner = (tidx ^ Int32(step_size)) if tidx < Int32(K) else Int32(0)
566
+ my_o = s_ords[sort_tidx]
567
+ my_i = s_idxs[sort_tidx]
568
+ p_o = s_ords[partner]
569
+ p_v = s_vals[partner]
570
+ p_i = s_idxs[partner]
571
+ cute.arch.barrier()
572
+
573
+ # Comparator. Deterministic mode uses a lex
574
+ # ``(ord, -idx)`` tie-break so equal-ord entries land in
575
+ # ascending-idx order (matching aten). Non-deterministic
576
+ # mode skips the tiebreak (cheaper compare-exchange).
577
+ if const_expr(self.deterministic):
578
+ self_lt_partner = (my_o < p_o) or (my_o == p_o and my_i > p_i)
579
+ self_gt_partner = (my_o > p_o) or (my_o == p_o and my_i < p_i)
580
+ else:
581
+ self_lt_partner = my_o < p_o
582
+ self_gt_partner = my_o > p_o
583
+ block_dir = (tidx >> Int32(stage + 1)) & Int32(1)
584
+ if tidx < K:
585
+ if tidx < partner:
586
+ if block_dir == Int32(0):
587
+ if self_lt_partner:
588
+ s_ords[tidx] = p_o
589
+ s_vals[tidx] = p_v
590
+ s_idxs[tidx] = p_i
591
+ else:
592
+ if self_gt_partner:
593
+ s_ords[tidx] = p_o
594
+ s_vals[tidx] = p_v
595
+ s_idxs[tidx] = p_i
596
+ else:
597
+ if block_dir == Int32(0):
598
+ if self_gt_partner:
599
+ s_ords[tidx] = p_o
600
+ s_vals[tidx] = p_v
601
+ s_idxs[tidx] = p_i
602
+ else:
603
+ if self_lt_partner:
604
+ s_ords[tidx] = p_o
605
+ s_vals[tidx] = p_v
606
+ s_idxs[tidx] = p_i
607
+ cute.arch.barrier()
608
+
609
+ # Phase 4: results to gmem.
610
+ if tidx < K:
611
+ mValues[row, tidx] = s_vals[tidx]
612
+ mIndices[row, tidx] = s_idxs[tidx]
613
+
614
+
615
+ def _make_fake_tensor(dtype, shape, divisibility=1):
616
+ stride = tuple(
617
+ cute.sym_int64(divisibility=divisibility) if i != len(shape) - 1 else 1
618
+ for i in range(len(shape))
619
+ )
620
+ return cute.runtime.make_fake_tensor(
621
+ dtype,
622
+ shape,
623
+ stride=stride,
624
+ assumed_align=divisibility * dtype.width // 8,
625
+ )
626
+
627
+
628
+ @instrumented_cutedsl_cache(
629
+ "aten::topk",
630
+ key_fn=lambda N, K, deterministic: f"radix N={N} K={K} det={deterministic}",
631
+ )
632
+ def _compile_topk_radix(N: int, K: int, deterministic: bool):
633
+ batch_sym = cute.sym_int()
634
+ div_n = math.gcd(4, N)
635
+ div_k = math.gcd(4, K)
636
+ x_fake = _make_fake_tensor(Float32, (batch_sym, N), div_n)
637
+ v_fake = _make_fake_tensor(Float32, (batch_sym, K), div_k)
638
+ i_fake = _make_fake_tensor(Int32, (batch_sym, K), div_k)
639
+ return cute.compile(
640
+ _RadixSelectTopK(N, K, deterministic=deterministic),
641
+ x_fake,
642
+ v_fake,
643
+ i_fake,
644
+ cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True),
645
+ options="--enable-tvm-ffi",
646
+ )
647
+
648
+
649
+ def topk_radix(
650
+ x: torch.Tensor, k: int, *, deterministic: bool = True
651
+ ) -> tuple[torch.Tensor, torch.Tensor]:
652
+ """Fused radix-select top-K for fp32 2D contiguous ``x``.
653
+
654
+ Returns ``(values[M, K]: fp32, indices[M, K]: int64)`` with K sorted
655
+ descending per row. Caller must ensure ``k`` is in the supported set
656
+ (see ``cutedsl_impl.py``) and ``N % 4 == 0``.
657
+
658
+ ``deterministic`` controls the gather + sort tie-breaking strategy:
659
+ True (default) uses prefix-sum gather + lex comparator and matches
660
+ aten bit-exactly; False uses smem atomic gather + ord-only sort and
661
+ is faster but indices may differ on ties.
662
+ """
663
+ M, N = x.shape
664
+ out_v = torch.empty(M, k, dtype=torch.float32, device=x.device)
665
+ # Kernel writes int32 indices; widen before returning to match aten.
666
+ out_i_i32 = torch.empty(M, k, dtype=torch.int32, device=x.device)
667
+ _compile_topk_radix(N, k, deterministic)(x, out_v, out_i_i32)
668
+ return out_v, out_i_i32.to(torch.int64)
669
+
670
+
671
+ # ---------------------------------------------------------------------------
672
+ # Register-resident top-K (small K, small N).
673
+ # ---------------------------------------------------------------------------
674
+
675
+
676
+ @cute.jit
677
+ def _make_key(val: Float32, idx: Int32) -> Int64:
678
+ """Compose the descending-sort key: ``(ord_u32 << 32) | (~idx_u32)``.
679
+
680
+ Sorting this Int64 descending gives ``(value desc, idx asc)`` -
681
+ exactly aten's tie-break order. Real fp32 inputs (no NaN) keep keys
682
+ away from INT64_MIN, leaving that bit pattern free as a sentinel.
683
+ """
684
+ ord32 = _f32_to_radix_ord(val)
685
+ ord64 = Int64(ord32) & Int64(0xFFFFFFFF)
686
+ inv_idx64 = Int64(~idx) & Int64(0xFFFFFFFF)
687
+ return (ord64 << Int64(32)) | inv_idx64
688
+
689
+
690
+ @cute.jit
691
+ def _decode_key(key: Int64) -> tuple[Float32, Int32]:
692
+ ord32 = Int32(key >> Int64(32))
693
+ inv_idx = Int32(key & Int64(0xFFFFFFFF))
694
+ val_bits = ord32 ^ ((ord32 >> Int32(31)) & Int32(0x7FFFFFFF))
695
+ return Float32(llvm.bitcast(T.f32(), val_bits.ir_value())), ~inv_idx
696
+
697
+
698
+ @cute.jit
699
+ def _cas_desc(arr: cute.Tensor, i: cutlass.Constexpr, j: cutlass.Constexpr) -> None:
700
+ a = arr[i]
701
+ b = arr[j]
702
+ if a < b:
703
+ arr[i] = b
704
+ arr[j] = a
705
+
706
+
707
+ @cute.jit
708
+ def _bitonic_sort_desc(arr: cute.Tensor, n: cutlass.Constexpr) -> None:
709
+ if const_expr(n > 1):
710
+ num_stages = int(math.log2(n))
711
+ for s in cutlass.range_constexpr(num_stages):
712
+ for sub_rev in cutlass.range_constexpr(s + 1):
713
+ step = 1 << (s - sub_rev)
714
+ for i in cutlass.range_constexpr(n):
715
+ j = i ^ step
716
+ if j > i:
717
+ block_dir = (i >> (s + 1)) & 1
718
+ if block_dir == 0:
719
+ _cas_desc(arr, i, j)
720
+ else:
721
+ a = arr[i]
722
+ b = arr[j]
723
+ if a > b:
724
+ arr[i] = b
725
+ arr[j] = a
726
+
727
+
728
+ @cute.jit
729
+ def _bitonic_merge_desc(arr: cute.Tensor, n: cutlass.Constexpr) -> None:
730
+ """Merge a bitonic sequence of length n into descending sorted."""
731
+ if const_expr(n > 1):
732
+ num_levels = int(math.log2(n))
733
+ for level in cutlass.range_constexpr(num_levels):
734
+ length = n >> level
735
+ step = length // 2
736
+ for i in cutlass.range_constexpr(n // length):
737
+ start_i = i * length
738
+ for j in cutlass.range_constexpr(step):
739
+ _cas_desc(arr, start_i + j, start_i + j + step)
740
+
741
+
742
+ @cute.jit
743
+ def _topk_merge_desc(a: cute.Tensor, b: cute.Tensor, K: cutlass.Constexpr) -> None:
744
+ """Top-K of two K-sorted-descending sequences, in place into ``a``.
745
+
746
+ ``a[i] <- max(a[i], b[K-1-i])`` yields a bitonic sequence in ``a``;
747
+ one bitonic merge of length K finishes it.
748
+ """
749
+ for i in cutlass.range_constexpr(K):
750
+ x = a[i]
751
+ y = b[K - 1 - i]
752
+ if y > x:
753
+ a[i] = y
754
+ _bitonic_merge_desc(a, K)
755
+
756
+
757
+ class _RegisterTopK:
758
+ """Register-resident top-K. Each warp owns one row; ``ROWS_PER_CTA``
759
+ warps per CTA. K in {16, 32}, N a power of 2 in [K, 2048].
760
+ """
761
+
762
+ def __init__(self, N: int, K: int, rows_per_cta: int = 4):
763
+ self.N = N
764
+ self.K = K
765
+ self.VEC = N // 32
766
+ self.ROWS_PER_CTA = rows_per_cta
767
+ self.NUM_THREADS = 32 * rows_per_cta
768
+
769
+ @cute.jit
770
+ def __call__(
771
+ self,
772
+ mX: cute.Tensor,
773
+ mValues: cute.Tensor,
774
+ mIndices: cute.Tensor,
775
+ stream: cuda.CUstream,
776
+ ):
777
+ M = mX.shape[0]
778
+ ROWS = const_expr(self.ROWS_PER_CTA)
779
+ num_blocks = (M + ROWS - 1) // ROWS
780
+ self.kernel(mX, mValues, mIndices).launch(
781
+ grid=[num_blocks, 1, 1],
782
+ block=[self.NUM_THREADS, 1, 1],
783
+ stream=stream,
784
+ )
785
+
786
+ @cute.kernel
787
+ def kernel(self, mX: cute.Tensor, mValues: cute.Tensor, mIndices: cute.Tensor):
788
+ tidx, _, _ = cute.arch.thread_idx()
789
+ bidx, _, _ = cute.arch.block_idx()
790
+
791
+ K = const_expr(self.K)
792
+ VEC = const_expr(self.VEC)
793
+ ROWS = const_expr(self.ROWS_PER_CTA)
794
+ WARP_SIZE = const_expr(cute.arch.WARP_SIZE)
795
+
796
+ warp_idx = tidx // Int32(WARP_SIZE)
797
+ lane_idx = tidx % Int32(WARP_SIZE)
798
+ row = Int32(bidx) * Int32(ROWS) + warp_idx
799
+
800
+ M = mX.shape[0]
801
+ # CuTeDSL can't early-return on a dynamic predicate. Clamp the row
802
+ # for loads to keep them in-bounds, and gate the writes only.
803
+ row_safe = row if row < M else Int32(0)
804
+ in_bounds = row < M
805
+
806
+ # Per-thread Int64 keys covering this row's VEC-sized stripe.
807
+ keys = cute.make_rmem_tensor(VEC, Int64)
808
+ for i in cutlass.range_constexpr(VEC):
809
+ col = lane_idx * Int32(VEC) + Int32(i)
810
+ keys[i] = _make_key(mX[row_safe, col], col)
811
+
812
+ _bitonic_sort_desc(keys, VEC)
813
+
814
+ # Build per-thread top-K. If VEC < K, pad with INT64_MIN so the
815
+ # sentinel sorts strictly below any real key; if VEC >= K take the
816
+ # leading K (already sorted).
817
+ topk = cute.make_rmem_tensor(K, Int64)
818
+ if const_expr(VEC >= K):
819
+ for i in cutlass.range_constexpr(K):
820
+ topk[i] = keys[i]
821
+ else:
822
+ SENTINEL = const_expr(-(1 << 63))
823
+ for i in cutlass.range_constexpr(VEC):
824
+ topk[i] = keys[i]
825
+ for i in cutlass.range_constexpr(K - VEC):
826
+ topk[VEC + i] = Int64(SENTINEL)
827
+ _bitonic_sort_desc(topk, K)
828
+
829
+ # Warp-cooperative top-K merge via butterfly shuffles.
830
+ log2_warp = const_expr(int(math.log2(WARP_SIZE)))
831
+ for s in cutlass.range_constexpr(log2_warp):
832
+ other = cute.make_rmem_tensor(K, Int64)
833
+ for i in cutlass.range_constexpr(K):
834
+ other[i] = cute.arch.shuffle_sync_bfly(topk[i], offset=Int32(1 << s))
835
+ _topk_merge_desc(topk, other, K)
836
+
837
+ # Lane 0 of each warp now holds the row's top-K descending.
838
+ if lane_idx == Int32(0) and in_bounds:
839
+ for i in cutlass.range_constexpr(K):
840
+ v, idx = _decode_key(topk[i])
841
+ mValues[row, i] = v
842
+ mIndices[row, i] = idx
843
+
844
+
845
+ @instrumented_cutedsl_cache("aten::topk", key_fn=lambda N, K: f"register N={N} K={K}")
846
+ def _compile_topk_register(N: int, K: int):
847
+ batch_sym = cute.sym_int()
848
+ div_n = math.gcd(4, N)
849
+ div_k = math.gcd(4, K)
850
+ x_fake = _make_fake_tensor(Float32, (batch_sym, N), div_n)
851
+ v_fake = _make_fake_tensor(Float32, (batch_sym, K), div_k)
852
+ i_fake = _make_fake_tensor(Int32, (batch_sym, K), div_k)
853
+ return cute.compile(
854
+ _RegisterTopK(N, K),
855
+ x_fake,
856
+ v_fake,
857
+ i_fake,
858
+ cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True),
859
+ options="--enable-tvm-ffi",
860
+ )
861
+
862
+
863
+ def topk_register(x: torch.Tensor, k: int) -> tuple[torch.Tensor, torch.Tensor]:
864
+ """Register-resident top-K for fp32 2D contiguous ``x``.
865
+
866
+ Returns ``(values[M, K]: fp32, indices[M, K]: int64)``, descending,
867
+ bit-exact to aten on both values and indices. Caller must ensure
868
+ ``k`` in {16, 32} and ``N`` is a power of 2 in [k, 2048].
869
+ """
870
+ M, N = x.shape
871
+ out_v = torch.empty(M, k, dtype=torch.float32, device=x.device)
872
+ out_i_i32 = torch.empty(M, k, dtype=torch.int32, device=x.device)
873
+ _compile_topk_register(N, k)(x, out_v, out_i_i32)
874
+ return out_v, out_i_i32.to(torch.int64)
.venv/lib/python3.12/site-packages/torch/_native/registry.py ADDED
@@ -0,0 +1,1147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from collections.abc import Callable, Iterable
3
+ from dataclasses import dataclass, field
4
+ from typing import ParamSpec, TypeVar
5
+
6
+ import torch.library
7
+
8
+
9
+ __all__ = [
10
+ "UserOrderingFn",
11
+ "register_op_override",
12
+ "reorder_graphs_from_user_function",
13
+ "reenable_op_overrides",
14
+ "deregister_op_overrides",
15
+ "get_dsl_operations",
16
+ "native_decomp_table",
17
+ ]
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+ P = ParamSpec("P")
22
+ R = TypeVar("R")
23
+
24
+ _OpCondFn = Callable[P, bool]
25
+ _OpImplFn = Callable[P, R]
26
+
27
+
28
+ @dataclass
29
+ class _OverrideNode:
30
+ """Track function override data."""
31
+
32
+ dsl_name: str
33
+ op_symbol: str
34
+ dispatch_key: str
35
+ cond_fn: _OpCondFn
36
+ impl_fn: _OpImplFn
37
+ # Identifier of the opaque `_native::<node_id>` op that carries this
38
+ # override's impl. Assigned once at registration time and never reused --
39
+ # reorder / deregister / reenable do not change it, so the cached
40
+ # `_defined_native_ops` entry remains valid.
41
+ node_id: str
42
+ unconditional_override: bool = False
43
+ active: bool = True
44
+
45
+
46
+ UserOrderingFn = Callable[[str, str, list[_OverrideNode]], list[_OverrideNode]]
47
+
48
+
49
+ @dataclass
50
+ class _FilterState:
51
+ """Manages filtering state for override nodes."""
52
+
53
+ _dsl_names: set[str] = field(default_factory=set)
54
+ _op_symbols: set[str] = field(default_factory=set)
55
+ _dispatch_keys: set[str] = field(default_factory=set)
56
+
57
+ def check_enabled(self, node: _OverrideNode) -> bool:
58
+ """
59
+ Check if a node is enabled based on current filter state.
60
+
61
+ Args:
62
+ node: The override node to check
63
+
64
+ Returns:
65
+ bool: True if the node should be enabled, False if filtered out
66
+ """
67
+ if node.dsl_name in self._dsl_names:
68
+ return False
69
+
70
+ if node.op_symbol in self._op_symbols:
71
+ return False
72
+
73
+ if node.dispatch_key in self._dispatch_keys:
74
+ return False
75
+
76
+ return True
77
+
78
+ def update(
79
+ self,
80
+ dsl_names: str | Iterable[str] | None,
81
+ op_symbols: str | Iterable[str] | None,
82
+ dispatch_keys: str | Iterable[str] | None,
83
+ remove_keys: bool = False,
84
+ ) -> None:
85
+ """
86
+ Update filter sets as (current | new) or (current ~ new).
87
+
88
+ Args:
89
+ dsl_names: DSL names to add/remove from filter
90
+ op_symbols: Operation symbols to add/remove from filter
91
+ dispatch_keys: Dispatch keys to add/remove from filter
92
+ remove_keys: If True, remove keys from filter; if False, add them
93
+
94
+ Note:
95
+ Uses set.discard as it doesn't raise an exception if the element
96
+ wasn't in the set to begin with.
97
+ """
98
+ if remove_keys:
99
+ self._dsl_names -= set(_resolve_iterable(dsl_names))
100
+ self._op_symbols -= set(_resolve_iterable(op_symbols))
101
+ self._dispatch_keys -= set(_resolve_iterable(dispatch_keys))
102
+ else:
103
+ self._dsl_names |= set(_resolve_iterable(dsl_names))
104
+ self._op_symbols |= set(_resolve_iterable(op_symbols))
105
+ self._dispatch_keys |= set(_resolve_iterable(dispatch_keys))
106
+
107
+ def build_disable_key_set(self) -> set[tuple[str, str]]:
108
+ """
109
+ Build a set of dictionary keys based on the current filter state.
110
+
111
+ Returns:
112
+ set[tuple[str, str]]: Set of (op_symbol, dispatch_key) tuples
113
+ """
114
+ return _build_key_set(
115
+ self._dsl_names,
116
+ self._op_symbols,
117
+ self._dispatch_keys,
118
+ )
119
+
120
+ def __str__(self) -> str:
121
+ """Return string representation of filter state."""
122
+ s = ""
123
+ s += "Filter State:\n"
124
+ s += " === DSL: ===\n"
125
+ for i, dsl in enumerate(self._dsl_names):
126
+ s += f" {i}: {dsl}\n"
127
+ s += " === OP SYMBOL: ===\n"
128
+ for i, op in enumerate(self._op_symbols):
129
+ s += f" {i}: {op}\n"
130
+ s += " === DISPATCH KEYS: ===\n"
131
+ for i, key in enumerate(self._dispatch_keys):
132
+ s += f" {i}: {key}\n"
133
+
134
+ return s
135
+
136
+
137
+ # Store the global override filtering state
138
+ _filter_state: _FilterState = _FilterState()
139
+
140
+ # Store torch.library.Library instances
141
+ _libs: dict[tuple[str, str], torch.library.Library] = {}
142
+
143
+ # Decomposition-style routers for the compile / export path, keyed by aten
144
+ # OpOverload. Built in `_register_overrides_from_graph` alongside the eager
145
+ # `Library.impl` routers.
146
+ #
147
+ # This dict is *not* written into any global compile/export decomp table (in
148
+ # particular, not into torch._inductor.decomposition.decompositions). Users
149
+ # opt into the overrides explicitly by passing `native_decomp_table()` to
150
+ # `ExportedProgram.run_decompositions(...)`, or by threading it through
151
+ # Dynamo/Inductor config for `torch.compile`. Reasons:
152
+ #
153
+ # 1. torch._inductor.decomposition.decompositions is an Inductor internal
154
+ # with no stability guarantee; writing to it couples us to Inductor's
155
+ # refactors.
156
+ # 2. Global writes would affect *every* consumer of that table (tests,
157
+ # third-party backends, etc.), with no scoping.
158
+ # 3. Import-time writes would force `import torch._native` to also pull in
159
+ # inductor → dynamo → triton, breaking
160
+ # `test_no_dsl_imports_after_import_torch`.
161
+ #
162
+ # Keeping the table registry-local means `import torch._native` stays cheap
163
+ # and consumers control exactly when and where overrides take effect.
164
+ _native_decomp_overrides: dict[object, Callable] = {}
165
+
166
+
167
+ def _has_cow_tensor(*args, **kwargs) -> bool:
168
+ def is_cow_tensor(arg) -> bool:
169
+ if isinstance(arg, torch.Tensor):
170
+ return torch._C._is_cow_tensor(arg) # pyrefly: ignore[missing-attribute]
171
+ if isinstance(arg, (list, tuple)):
172
+ return any(is_cow_tensor(item) for item in arg)
173
+ if isinstance(arg, dict):
174
+ return any(is_cow_tensor(item) for item in arg.values())
175
+ return False
176
+
177
+ return any(is_cow_tensor(arg) for arg in args) or any(
178
+ is_cow_tensor(arg) for arg in kwargs.values()
179
+ )
180
+
181
+
182
+ # store graph structures
183
+ _GraphsType = dict[tuple[str, str], list[_OverrideNode]]
184
+ _graphs: _GraphsType = {}
185
+
186
+ _MappingType = dict[str, list[tuple[str, str]]]
187
+
188
+ # map a {dsl, op, dispatch_key} to keys to all graphs that contain it
189
+ _dsl_name_to_lib_graph: _MappingType = {}
190
+ _dispatch_key_to_lib_graph: _MappingType = {}
191
+ _op_symbol_to_lib_graph: _MappingType = {}
192
+
193
+ # Monotonic counter used to mint stable, unique `_native::<id>` op names.
194
+ # Must never decrease across the process, since `_defined_native_ops`
195
+ # pins a fake kernel for each minted id.
196
+ _node_id_counter: int = 0
197
+
198
+ # Dispatch keys where installing an override would break the registry's
199
+ # assumptions. The eager router is wired at a backend key so aten's
200
+ # higher-priority Autograd/Autocast kernels handle those layers, and the
201
+ # fake kernel for `_native::<id>` redispatches to the aten op's meta -- if
202
+ # the override lived at Meta or CompositeImplicitAutograd, that
203
+ # redispatch would loop back into the router.
204
+ _DISALLOWED_DISPATCH_KEYS: frozenset[str] = frozenset(
205
+ {"Meta", "CompositeImplicitAutograd", "CompositeExplicitAutograd"}
206
+ )
207
+
208
+
209
+ def _build_key_set(
210
+ dsl_names: str | Iterable[str] | None,
211
+ op_symbols: str | Iterable[str] | None,
212
+ dispatch_keys: str | Iterable[str] | None,
213
+ ) -> set[tuple[str, str]]:
214
+ """
215
+ Build a set of dictionary keys based on filter criteria.
216
+
217
+ Args:
218
+ dsl_names: DSL names to include in key set
219
+ op_symbols: Operation symbols to include in key set
220
+ dispatch_keys: Dispatch keys to include in key set
221
+
222
+ Returns:
223
+ set[tuple[str, str]]: Set of (op_symbol, dispatch_key) tuples
224
+ """
225
+ key_set: set[tuple[str, str]] = set()
226
+
227
+ def _append_to_set(
228
+ entries: str | Iterable[str] | None, graph_lib_dict: _MappingType
229
+ ) -> None:
230
+ """Helper to add matching keys from graph_lib_dict to key_set."""
231
+ resolved_entries = _resolve_iterable(entries)
232
+
233
+ for entry in resolved_entries:
234
+ if entry in graph_lib_dict:
235
+ for key in graph_lib_dict[entry]:
236
+ key_set.add(key)
237
+
238
+ _append_to_set(dsl_names, _dsl_name_to_lib_graph)
239
+ _append_to_set(op_symbols, _op_symbol_to_lib_graph)
240
+ _append_to_set(dispatch_keys, _dispatch_key_to_lib_graph)
241
+
242
+ return key_set
243
+
244
+
245
+ def _print_override_graphs(*, print_inactive: bool = False) -> None:
246
+ """
247
+ Print all override graphs for debugging purposes.
248
+
249
+ Args:
250
+ print_inactive: Whether to print inactive nodes
251
+ """
252
+ for (op, key), node_list in _graphs.items():
253
+ print(f"{op=}, {key=}")
254
+
255
+ for i, node in enumerate(node_list):
256
+ if node.active or print_inactive:
257
+ s: str = f" {i}: {node.dsl_name=}, {node.unconditional_override=}"
258
+ if print_inactive:
259
+ s += f" {node.active=}"
260
+
261
+ print(s)
262
+
263
+
264
+ # One DEF/FRAGMENT library per namespace -- only one is allowed per process.
265
+ _def_libs: dict[str, torch.library.Library] = {}
266
+ # Ops that have already been `define`d on the _native namespace.
267
+ _defined_native_ops: set[str] = set()
268
+ # IMPL libraries on the aten namespace, keyed by (op_symbol, dispatch_key).
269
+ # One library per op/key pair so we can call `_destroy()` on it to tear down
270
+ # just that one override without affecting other ops at the same dispatch
271
+ # key. Torch's Library has no per-kernel removal API -- `_destroy` on the
272
+ # library is the only teardown mechanism.
273
+ _aten_override_libs: dict[tuple[str, str], torch.library.Library] = {}
274
+
275
+
276
+ def _get_def_library(namespace: str) -> torch.library.Library:
277
+ if namespace not in _def_libs:
278
+ _def_libs[namespace] = torch.library.Library(namespace, "FRAGMENT")
279
+ return _def_libs[namespace]
280
+
281
+
282
+ def _get_or_create_library(dispatch_key: str) -> torch.library.Library:
283
+ """
284
+ Get or create the _native IMPL library for a given dispatch key.
285
+
286
+ One library per dispatch key is shared across all overridden ops.
287
+ """
288
+ global _libs
289
+
290
+ key = ("_native", dispatch_key)
291
+ if key not in _libs:
292
+ _libs[key] = torch.library.Library("_native", "IMPL", dispatch_key)
293
+
294
+ return _libs[key]
295
+
296
+
297
+ def _install_aten_override(op_symbol: str, dispatch_key: str, kernel: Callable) -> None:
298
+ """
299
+ Install (or replace) an aten kernel at (op_symbol, dispatch_key).
300
+
301
+ Creates a fresh Library per (op, key) so we can tear down just this
302
+ one override via `_destroy_aten_override` without affecting any other
303
+ override at the same dispatch key.
304
+ """
305
+ key = (op_symbol, dispatch_key)
306
+ # Destroy any existing library so its kernel is fully removed before
307
+ # we install the new one. `_destroy` calls into the dispatcher to
308
+ # unregister all kernels on the library.
309
+ existing = _aten_override_libs.pop(key, None)
310
+ if existing is not None:
311
+ existing._destroy()
312
+
313
+ lib = torch.library.Library("aten", "IMPL", dispatch_key)
314
+ lib.impl(op_symbol, kernel, dispatch_key, with_keyset=True)
315
+ _aten_override_libs[key] = lib
316
+
317
+
318
+ def _destroy_aten_override(op_symbol: str, dispatch_key: str) -> None:
319
+ """Tear down the aten override at (op_symbol, dispatch_key), if any."""
320
+ lib = _aten_override_libs.pop((op_symbol, dispatch_key), None)
321
+ if lib is not None:
322
+ lib._destroy()
323
+
324
+
325
+ def _resolve_aten_overload(op_symbol: str) -> "torch._ops.OpOverload | None":
326
+ """
327
+ Resolve `op_symbol` to a concrete OpOverload on `torch.ops.aten`.
328
+
329
+ Accepts bare names ("bmm" → aten.bmm.default) and overload-qualified
330
+ names ("add_.Tensor" → aten.add_.Tensor). Returns None if the op is not
331
+ registered (e.g. a test-only op_symbol that never hit the C++ dispatcher).
332
+ """
333
+ name, _, overload_name = op_symbol.partition(".")
334
+ overload_name = overload_name or "default"
335
+ try:
336
+ packet = getattr(torch.ops.aten, name)
337
+ return getattr(packet, overload_name)
338
+ except AttributeError:
339
+ return None
340
+
341
+
342
+ def _aten_schema_tail(op_symbol: str) -> str:
343
+ """Return the schema of at::<op_symbol> with the `aten::<name>` prefix stripped.
344
+
345
+ Accepts bare names ("bmm" → aten.bmm.default) and overload-qualified
346
+ names ("add_.Tensor" → aten.add_.Tensor).
347
+ """
348
+ overload = _resolve_aten_overload(op_symbol)
349
+ if overload is None:
350
+ raise AttributeError(f"aten op not found for op_symbol={op_symbol!r}")
351
+ s = str(overload._schema)
352
+ # "aten::bmm(Tensor self, Tensor mat2) -> Tensor" -> "(Tensor self, Tensor mat2) -> Tensor"
353
+ _, rest = s.split("::", 1)
354
+ _, args = rest.split("(", 1)
355
+ return f"({args}"
356
+
357
+
358
+ def _define_native_op_once(name: str, op_symbol: str) -> None:
359
+ # Invariant: callers must only install the eager router at a real backend
360
+ # dispatch key (CPU, CUDA, XPU, ...). The fake kernel below redispatches
361
+ # to the aten op, and if the router were installed at Meta /
362
+ # CompositeImplicitAutograd that redispatch would re-enter the router.
363
+ # `register_op_override` enforces this via `_DISALLOWED_DISPATCH_KEYS`.
364
+ if name in _defined_native_ops:
365
+ return
366
+ _get_def_library("_native").define(f"{name}{_aten_schema_tail(op_symbol)}")
367
+ # Fake/meta kernel: required so export / dynamo / AOTAutograd can shape-infer
368
+ # through the opaque _native op. Reusing the aten op's meta is safe because
369
+ # the schema (and therefore shape rules) is cloned from it.
370
+ aten_overload = _resolve_aten_overload(op_symbol)
371
+ torch.library.register_fake(f"_native::{name}")(
372
+ lambda *args, _aten_overload=aten_overload, **kwargs: _aten_overload(
373
+ *args, **kwargs
374
+ )
375
+ )
376
+ # No autograd or autocast kernels are registered on _native::<id>. Because
377
+ # the router is registered at the backend dispatch key (e.g. CUDA), aten's
378
+ # own higher-priority kernels on aten::<op> handle both:
379
+ # - Autograd: AutogradCUDA sees aten::<op> in the autograd graph and
380
+ # uses aten's built-in derivative formula.
381
+ # - Autocast: AutocastCUDA casts inputs to the autocast dtype before
382
+ # redispatching down to our CUDA-level router.
383
+ _defined_native_ops.add(name)
384
+
385
+
386
+ def _register_node_impl(
387
+ lib: torch.library.Library, node: _OverrideNode, dispatch_key: str
388
+ ) -> None:
389
+ """
390
+ Register a single node implementation with the library.
391
+
392
+ Args:
393
+ lib: The torch.library.Library instance
394
+ node: The override node to register
395
+ dispatch_key: The dispatch key for registration
396
+ """
397
+ if not node.node_id:
398
+ raise ValueError(
399
+ f"_OverrideNode must have a non-empty node_id before registration "
400
+ f"(dsl_name={node.dsl_name!r}, op_symbol={node.op_symbol!r})"
401
+ )
402
+ _define_native_op_once(node.node_id, node.op_symbol)
403
+ lib.impl(
404
+ node.node_id,
405
+ node.impl_fn,
406
+ dispatch_key,
407
+ with_keyset=False,
408
+ allow_override=True,
409
+ )
410
+
411
+
412
+ def _resolve_iterable(iterable: str | Iterable[str] | None) -> Iterable[str]:
413
+ """
414
+ Resolve various input types to a consistent iterable of strings.
415
+
416
+ Args:
417
+ iterable: String, iterable of strings, or None
418
+
419
+ Returns:
420
+ Iterable[str]: Consistent iterable output
421
+ """
422
+ if iterable is None:
423
+ return []
424
+
425
+ if not isinstance(iterable, Iterable) or isinstance(iterable, str):
426
+ return (iterable,)
427
+
428
+ return iterable
429
+
430
+
431
+ def reenable_op_overrides(
432
+ *,
433
+ enable_dsl_names: str | list[str] | None = None,
434
+ enable_op_symbols: str | list[str] | None = None,
435
+ enable_dispatch_keys: str | list[str] | None = None,
436
+ ) -> None:
437
+ """
438
+ Re-enable overrides by removing them from filter state and reregistering.
439
+
440
+ Args:
441
+ enable_dsl_names: DSL names to re-enable
442
+ enable_op_symbols: Operation symbols to re-enable
443
+ enable_dispatch_keys: Dispatch keys to re-enable
444
+
445
+ Note:
446
+ This function uses reverse filter state management (removing from
447
+ filters to enable).
448
+ """
449
+ log.info(
450
+ "Re-registering ops by dsl: %s, op_symbol: %s, dispatch_key: %s",
451
+ enable_dsl_names,
452
+ enable_op_symbols,
453
+ enable_dispatch_keys,
454
+ )
455
+
456
+ # Update the filters - note `remove_keys=True` because
457
+ # we are removing keys from the filters (vs. adding them)
458
+ _filter_state.update(
459
+ enable_dsl_names,
460
+ enable_op_symbols,
461
+ enable_dispatch_keys,
462
+ remove_keys=True,
463
+ )
464
+
465
+ # Get the set of keys that need to be reprocessed
466
+ key_set: set[tuple[str, str]] = _build_key_set(
467
+ enable_dsl_names,
468
+ enable_op_symbols,
469
+ enable_dispatch_keys,
470
+ )
471
+
472
+ # Process each affected graph with updated filter state
473
+ for key in key_set:
474
+ op_symbol, dispatch_key = key
475
+
476
+ if key in _graphs:
477
+ # Note: We don't need to cleanup and recreate the library here
478
+ # since we're just updating the registration with new filter state
479
+ _register_overrides_from_graph(
480
+ op_symbol, dispatch_key, _graphs[key], filter_state=_filter_state
481
+ )
482
+
483
+
484
+ def deregister_op_overrides(
485
+ *,
486
+ disable_dsl_names: str | list[str] | None = None,
487
+ disable_op_symbols: str | list[str] | None = None,
488
+ disable_dispatch_keys: str | list[str] | None = None,
489
+ ) -> None:
490
+ """
491
+ De-register overrides by updating filter state and reregistering graphs.
492
+
493
+ Args:
494
+ disable_dsl_names: DSL names to disable
495
+ disable_op_symbols: Operation symbols to disable
496
+ disable_dispatch_keys: Dispatch keys to disable
497
+
498
+ Note:
499
+ This function uses filter state management to selectively disable
500
+ operations.
501
+ """
502
+ log.info(
503
+ "De-registering ops by dsl: %s, op_symbol: %s, dispatch_key: %s",
504
+ disable_dsl_names,
505
+ disable_op_symbols,
506
+ disable_dispatch_keys,
507
+ )
508
+
509
+ # Update filter state to disable specified entries
510
+ _filter_state.update(disable_dsl_names, disable_op_symbols, disable_dispatch_keys)
511
+
512
+ # Get the set of keys that need to be reprocessed
513
+ key_set: set[tuple[str, str]] = _filter_state.build_disable_key_set()
514
+
515
+ # Process each affected graph with filter state
516
+ for key in key_set:
517
+ op_symbol, dispatch_key = key
518
+
519
+ if key in _graphs:
520
+ _cleanup_and_reregister_graph(
521
+ op_symbol,
522
+ dispatch_key,
523
+ _graphs[key],
524
+ filter_state=_filter_state,
525
+ )
526
+
527
+
528
+ def get_dsl_operations(dsl_name: str) -> list[str]:
529
+ """Get list of operations registered by a specific DSL.
530
+
531
+ Args:
532
+ dsl_name: Name of the DSL to query.
533
+
534
+ Returns:
535
+ Sorted list of operation names registered by the DSL.
536
+ """
537
+ operations = set()
538
+ for (op_symbol, _), nodes in _graphs.items():
539
+ for node in nodes:
540
+ if node.dsl_name == dsl_name:
541
+ operations.add(op_symbol)
542
+ break
543
+ return sorted(operations)
544
+
545
+
546
+ def _update_registration_maps(
547
+ dsl_name: str,
548
+ op_symbol: str,
549
+ dispatch_key: str,
550
+ key: tuple[str, str],
551
+ ) -> None:
552
+ """
553
+ Update the registration mapping dictionaries.
554
+
555
+ Args:
556
+ dsl_name: The DSL name
557
+ op_symbol: The operation symbol
558
+ dispatch_key: The dispatch key
559
+ key: The dictionary key tuple
560
+ """
561
+ global _dsl_name_to_lib_graph
562
+ global _op_symbol_to_lib_graph
563
+ global _dispatch_key_to_lib_graph
564
+
565
+ def _get_new_entry_or_append(
566
+ registration: dict[str, list[tuple[str, str]]],
567
+ symbol: str,
568
+ key: tuple[str, str],
569
+ ) -> None:
570
+ """Helper to add key to registration list or create new entry."""
571
+ entry_list = registration.get(symbol)
572
+
573
+ if entry_list is None:
574
+ entry_list = [key]
575
+ registration[symbol] = entry_list
576
+ else:
577
+ entry_list.append(key)
578
+
579
+ _get_new_entry_or_append(_dsl_name_to_lib_graph, dsl_name, key)
580
+ _get_new_entry_or_append(_op_symbol_to_lib_graph, op_symbol, key)
581
+ _get_new_entry_or_append(_dispatch_key_to_lib_graph, dispatch_key, key)
582
+
583
+
584
+ def _always_true(*args: object, **kwargs: object) -> bool:
585
+ return True
586
+
587
+
588
+ def register_op_override(
589
+ backend: str,
590
+ lib_symbol: str,
591
+ op_symbol: str,
592
+ dispatch_key: str,
593
+ cond: _OpCondFn | None,
594
+ impl: _OpImplFn,
595
+ *,
596
+ allow_multiple_override: bool = False,
597
+ unconditional_override: bool = False,
598
+ ) -> None:
599
+ """
600
+ Register a passed override function to the dispatcher.
601
+
602
+ Actually a graph-building operation; real registration happens later.
603
+
604
+ Args:
605
+ backend: The backend name (DSL name)
606
+ lib_symbol: Library you're overriding symbols in (must be "aten")
607
+ op_symbol: Name of the operation you're overriding
608
+ dispatch_key: Dispatch key to override
609
+ cond: Predicate choosing whether `impl` applies to a given call. May
610
+ be None if `unconditional_override=True`.
611
+ impl: Implementation function for the override
612
+ allow_multiple_override: Allow overriding an existing override
613
+ unconditional_override: Implementation doesn't have a fallback and
614
+ doesn't require torch.DispatchKeySet as the first argument. When
615
+ True, a trivially-True predicate is supplied for the router if
616
+ `cond` is None.
617
+
618
+ Raises:
619
+ ValueError: If lib_symbol is not "aten", if dispatch_key is in
620
+ _DISALLOWED_DISPATCH_KEYS (Meta / CompositeImplicitAutograd /
621
+ CompositeExplicitAutograd), or if cond is None without
622
+ unconditional_override=True.
623
+ """
624
+ if lib_symbol != "aten":
625
+ raise ValueError(f'Unsupported lib_symbol (must be "aten", got: "{lib_symbol}"')
626
+
627
+ if dispatch_key in _DISALLOWED_DISPATCH_KEYS:
628
+ raise ValueError(
629
+ f"dispatch_key={dispatch_key!r} is not supported. Overrides must be "
630
+ f"installed at a backend key (e.g. CPU, CUDA, XPU); the router's fake "
631
+ f"kernel redispatches to aten and would recurse otherwise."
632
+ )
633
+
634
+ if cond is None:
635
+ if not unconditional_override:
636
+ raise ValueError("cond must be provided unless unconditional_override=True")
637
+ cond = _always_true
638
+
639
+ key = (op_symbol, dispatch_key)
640
+
641
+ global _graphs, _node_id_counter
642
+ op_graph = _graphs.get(key, [])
643
+
644
+ # Mint a stable id for the opaque `_native::<node_id>` op. `_sanitized`
645
+ # strips dots from overload-qualified names so the result is a valid op
646
+ # name. The monotonic counter guarantees uniqueness even if the same
647
+ # (op_symbol, dsl_name) is registered, deregistered, and re-registered.
648
+ _sanitized = op_symbol.replace(".", "_")
649
+ node_id = f"{_sanitized}_{backend}_{_node_id_counter}"
650
+ _node_id_counter += 1
651
+
652
+ op_graph.append(
653
+ _OverrideNode(
654
+ dsl_name=backend,
655
+ op_symbol=op_symbol,
656
+ dispatch_key=dispatch_key,
657
+ cond_fn=cond,
658
+ impl_fn=impl,
659
+ unconditional_override=unconditional_override,
660
+ node_id=node_id,
661
+ )
662
+ )
663
+ _graphs[key] = op_graph
664
+ # Build additional maps helpful for de-registration
665
+ _update_registration_maps(backend, op_symbol, dispatch_key, key=key)
666
+
667
+
668
+ def _should_reregister_graph(
669
+ original_graph: list[_OverrideNode],
670
+ new_graph: list[_OverrideNode],
671
+ *,
672
+ force_reregister: bool = False,
673
+ ) -> bool:
674
+ """
675
+ Determine if a graph needs reregistration based on changes.
676
+
677
+ Args:
678
+ original_graph: The original graph before modification
679
+ new_graph: The graph after modification
680
+ force_reregister: If True, always reregister regardless of changes
681
+
682
+ Returns:
683
+ bool: True if reregistration is needed
684
+ """
685
+ if force_reregister:
686
+ return True
687
+
688
+ # Check if the graph structure has changed
689
+ return original_graph != new_graph
690
+
691
+
692
+ def _cleanup_and_reregister_graph(
693
+ op_symbol: str,
694
+ dispatch_key: str,
695
+ graph: list[_OverrideNode],
696
+ *,
697
+ filter_state: _FilterState | None = None,
698
+ ) -> None:
699
+ """
700
+ Reregister a graph's routes from scratch.
701
+
702
+ Used by reorder / deregister / reenable. Libraries are intentionally
703
+ long-lived singletons; we rebuild the per-op router closure here.
704
+
705
+ Args:
706
+ op_symbol: The operation symbol
707
+ dispatch_key: The dispatch key
708
+ graph: The graph to register
709
+ filter_state: Optional filter state for conditional registration
710
+ """
711
+ _register_overrides_from_graph(
712
+ op_symbol,
713
+ dispatch_key,
714
+ graph,
715
+ filter_state=filter_state,
716
+ )
717
+
718
+
719
+ def _apply_graph_transformation(
720
+ transformation_fn: UserOrderingFn,
721
+ *,
722
+ keys_to_process: set[tuple[str, str]] | None = None,
723
+ reregister_overrides: bool = False,
724
+ filter_state: _FilterState | None = None,
725
+ ) -> None:
726
+ """
727
+ Apply a transformation function to graphs and optionally reregister.
728
+
729
+ This is the core pattern used by reorder_graphs_from_user_function and
730
+ can be reused for other graph transformation operations.
731
+
732
+ Args:
733
+ transformation_fn: Function to transform each graph
734
+ keys_to_process: Keys to process, or None for all graphs
735
+ reregister_overrides: Whether to reregister changed graphs
736
+ filter_state: Optional filter state for conditional registration
737
+
738
+ Note:
739
+ If transformation_fn raises an exception for a specific graph, that graph
740
+ will be skipped and processing will continue with remaining graphs.
741
+ """
742
+ global _graphs
743
+
744
+ # Determine which graphs to process
745
+ target_keys = (
746
+ keys_to_process if keys_to_process is not None else set(_graphs.keys())
747
+ )
748
+
749
+ # Process each graph
750
+ for op_symbol, dispatch_key in list(target_keys):
751
+ if (op_symbol, dispatch_key) not in _graphs:
752
+ continue # Skip if graph doesn't exist
753
+
754
+ original_graph = list(_graphs[(op_symbol, dispatch_key)])
755
+
756
+ # Apply the transformation with error handling
757
+ try:
758
+ new_graph = transformation_fn(op_symbol, dispatch_key, original_graph)
759
+ except (TypeError, ValueError, AttributeError, RuntimeError):
760
+ log.warning(
761
+ "Graph transformation failed for %s/%s. Preserving original graph.",
762
+ op_symbol,
763
+ dispatch_key,
764
+ exc_info=True,
765
+ )
766
+ continue
767
+ except Exception:
768
+ log.exception(
769
+ "Unexpected error in graph transformation for %s/%s. Preserving original graph.",
770
+ op_symbol,
771
+ dispatch_key,
772
+ )
773
+ continue
774
+
775
+ # Validate that the transformation returned a valid result
776
+ if not isinstance(new_graph, list):
777
+ log.warning(
778
+ "Graph transformation returned invalid type %s for %s/%s. Expected list. Preserving original graph.",
779
+ type(new_graph).__name__,
780
+ op_symbol,
781
+ dispatch_key,
782
+ )
783
+ continue
784
+
785
+ # Update the graph
786
+ _graphs[(op_symbol, dispatch_key)] = new_graph
787
+
788
+ # Reregister if needed
789
+ if reregister_overrides and _should_reregister_graph(
790
+ original_graph, new_graph, force_reregister=False
791
+ ):
792
+ _cleanup_and_reregister_graph(
793
+ op_symbol,
794
+ dispatch_key,
795
+ new_graph,
796
+ filter_state=filter_state,
797
+ )
798
+
799
+
800
+ def native_decomp_table(
801
+ overrides_only: bool = False,
802
+ ) -> dict[object, Callable]:
803
+ """
804
+ Return a decomposition table suitable for passing to
805
+ ``ExportedProgram.run_decompositions`` or to Inductor / Dynamo as a
806
+ decomposition set for ``torch.compile``.
807
+
808
+ This is the canonical way to apply native overrides outside of eager.
809
+ Callers opt in explicitly -- the registry does **not** install into any
810
+ global compile/export decomp table on its own. This preserves three
811
+ properties:
812
+
813
+ * ``import torch._native`` doesn't transitively import inductor /
814
+ dynamo / triton.
815
+ * No other consumer (ONNX, tests, third-party backends) accidentally
816
+ picks up our overrides.
817
+ * Scoping is up to the caller: pass the table only where routing is
818
+ desired.
819
+
820
+ By default, the returned table contains
821
+ ``torch.export.default_decompositions()`` with native-registered
822
+ overrides layered on top -- matching typical "run the usual
823
+ decompositions, plus my overrides" intent. The override entries win
824
+ over any same-op default, because they're merged last.
825
+
826
+ Example:
827
+
828
+ ep = torch.export.export(model, args)
829
+ ep = ep.run_decompositions(
830
+ torch._native.registry.native_decomp_table()
831
+ )
832
+
833
+ Args:
834
+ overrides_only: If True, return only the native-registered overrides
835
+ and no default aten decompositions. Useful for inspection /
836
+ debugging, or when composing tables manually.
837
+
838
+ Returns:
839
+ A dict mapping ``OpOverload`` to decomposition callable.
840
+ """
841
+ if overrides_only:
842
+ table: dict[object, Callable] = {}
843
+ else:
844
+ # Local import: keeps `import torch._native` from pulling in
845
+ # torch.export (and its transitive imports) at module load time.
846
+ from torch.export import default_decompositions
847
+
848
+ table = dict(default_decompositions())
849
+ # Merge overrides last so they win on conflicts.
850
+ table.update(_native_decomp_overrides)
851
+ return table
852
+
853
+
854
+ def _register_overrides_from_graph(
855
+ op_symbol: str,
856
+ dispatch_key: str,
857
+ graph: list[_OverrideNode],
858
+ *,
859
+ filter_state: _FilterState | None = None,
860
+ ) -> None:
861
+ """
862
+ Register all overrides in a single graph.
863
+
864
+ Args:
865
+ op_symbol: The operation symbol
866
+ dispatch_key: The dispatch key
867
+ graph: List of override nodes to register
868
+ filter_state: Optional filter state for conditional registration
869
+ """
870
+ lib = _get_or_create_library(dispatch_key)
871
+
872
+ cond_impl: list[tuple[_OpCondFn, str]] = []
873
+
874
+ # node.node_id is minted once at `register_op_override` time and is
875
+ # stable across reorder / deregister / reenable -- never regenerate it
876
+ # here, since `_defined_native_ops` pins a fake kernel against each id.
877
+ for node in graph:
878
+ enable = True
879
+ if filter_state:
880
+ enable = filter_state.check_enabled(node)
881
+
882
+ if enable:
883
+ _register_node_impl(lib, node, dispatch_key)
884
+ cond_impl.append((node.cond_fn, node.node_id))
885
+ node.active = True
886
+ else:
887
+ node.active = False
888
+
889
+ overload = _resolve_aten_overload(op_symbol)
890
+
891
+ # Tear down any existing aten override so either (a) the op cleanly
892
+ # reverts to native aten (empty cond_impl), or (b) the subsequent
893
+ # `get_kernel` call returns the native kernel rather than a stale
894
+ # previously-installed router.
895
+ _destroy_aten_override(op_symbol, dispatch_key)
896
+
897
+ # If no active conds remain for this (op, key), leave the native op
898
+ # behavior intact and drop any decomp table entry.
899
+ if not cond_impl:
900
+ if overload is not None:
901
+ _native_decomp_overrides.pop(overload, None)
902
+ return
903
+
904
+ # Capture the prior kernel at this (op, dispatch_key) *before* we install
905
+ # our override. The fallback path calls it via `call_boxed`, which
906
+ # re-enters the dispatcher with the original kernel handle -- bypassing
907
+ # our just-registered router and avoiding the recursion that would
908
+ # otherwise appear in aten's backward formulas (e.g. bmm's backward
909
+ # calls bmm, which would route back to us).
910
+ fallback_kernel = torch.library.get_kernel(f"aten::{op_symbol}", dispatch_key)
911
+
912
+ # Build the router closures. Both share a first-match-wins loop over
913
+ # `cond_impl`; they differ only in
914
+ # (a) whether cond exceptions fail loudly or silently, and
915
+ # (b) what to do when no cond matches.
916
+ #
917
+ # Eager routers run on real tensors where cond exceptions indicate a
918
+ # genuine bug; missing a match falls back to the captured native kernel.
919
+ #
920
+ # Compile/export routers run under FakeTensor where some predicates are
921
+ # undefined (e.g. _is_cow_tensor), so we swallow cond exceptions and
922
+ # treat them as non-matches. On no-match we return NotImplemented so
923
+ # Inductor reuses the default lowering rather than recursing.
924
+ _NO_MATCH = object() # sentinel; impl return values of None would be valid outputs
925
+
926
+ def _dispatch(args, kwargs, swallow_cond_exceptions: bool):
927
+ for cond, impl_name in cond_impl:
928
+ try:
929
+ matched = cond(*args, **kwargs)
930
+ except Exception:
931
+ if not swallow_cond_exceptions:
932
+ raise
933
+ continue
934
+ if matched:
935
+ return getattr(torch.ops._native, impl_name)(*args, **kwargs)
936
+ return _NO_MATCH
937
+
938
+ def eager_router(
939
+ keyset, *args, _fallback=fallback_kernel, _aten_overload=overload, **kwargs
940
+ ):
941
+ # This branch is only safe while Dynamo is actively tracing this Python
942
+ # router. The broader compile-session flag can be true when this router
943
+ # executes eagerly; redispatching to aten there would re-enter us.
944
+ #
945
+ # COW state is guarded by Dynamo's _is_cow_tensor handler but is not
946
+ # modeled in the compiled graph. If a COW input reaches this router,
947
+ # keep the existing eager path so COW-preserving fallback semantics are
948
+ # maintained instead of compiling through aten and materializing it.
949
+ if (
950
+ torch.compiler.is_dynamo_compiling()
951
+ and _aten_overload is not None
952
+ and not _has_cow_tensor(*args, **kwargs)
953
+ ):
954
+ return _aten_overload(*args, **kwargs)
955
+
956
+ result = _dispatch(args, kwargs, swallow_cond_exceptions=False)
957
+ if result is _NO_MATCH:
958
+ return _fallback.call_boxed(keyset, *args, **kwargs)
959
+ return result
960
+
961
+ def compile_router(*args, **kwargs):
962
+ result = _dispatch(args, kwargs, swallow_cond_exceptions=True)
963
+ if result is _NO_MATCH:
964
+ return NotImplemented
965
+ return result
966
+
967
+ # Eager path: install a fresh aten override for this (op, key).
968
+ _install_aten_override(op_symbol, dispatch_key, eager_router)
969
+
970
+ # Compile / export path: record the router in our own decomp table.
971
+ # Callers opt in via `native_decomp_table()` -- we deliberately do NOT
972
+ # write into torch._inductor.decomposition.decompositions (see the
973
+ # comment on `_native_decomp_overrides` for why).
974
+ if overload is not None:
975
+ _native_decomp_overrides[overload] = compile_router
976
+
977
+
978
+ def _register_all_overrides() -> None:
979
+ """
980
+ Perform all registration calls from previously-built override graphs.
981
+ """
982
+ for key, graph in _graphs.items():
983
+ op_symbol, dispatch_key = key
984
+
985
+ _register_overrides_from_graph(
986
+ op_symbol,
987
+ dispatch_key,
988
+ graph,
989
+ )
990
+
991
+
992
+ def reorder_graphs_from_user_function(
993
+ fn: UserOrderingFn,
994
+ *,
995
+ reregister_overrides: bool = False,
996
+ ) -> None:
997
+ """
998
+ Reorder override graphs using a user-provided ordering function.
999
+
1000
+ Args:
1001
+ fn: User-provided function that takes (op_symbol, dispatch_key, graph)
1002
+ and returns a reordered graph
1003
+ reregister_overrides: Whether to reregister graphs that have changed
1004
+
1005
+ Note:
1006
+ This function uses the common graph transformation pattern and can serve
1007
+ as an example for other graph manipulation operations.
1008
+ """
1009
+ _apply_graph_transformation(
1010
+ transformation_fn=fn,
1011
+ reregister_overrides=reregister_overrides,
1012
+ )
1013
+
1014
+
1015
+ def _apply_graph_filter(
1016
+ filter_fn: Callable[[str, str, _OverrideNode], bool],
1017
+ *,
1018
+ reregister_overrides: bool = False,
1019
+ ) -> None:
1020
+ """
1021
+ Apply a filter function to remove nodes from graphs.
1022
+
1023
+ This is a convenience function that uses the graph transformation pattern
1024
+ to filter out unwanted nodes.
1025
+
1026
+ Args:
1027
+ filter_fn: Function that takes (op_symbol, dispatch_key, node) and
1028
+ returns True to keep the node, False to remove it
1029
+ reregister_overrides: Whether to reregister modified graphs
1030
+
1031
+ Example:
1032
+ # Remove all nodes with "deprecated" in the DSL name
1033
+ _apply_graph_filter(
1034
+ lambda op, dk, node: "deprecated" not in node.dsl_name,
1035
+ reregister_overrides=True
1036
+ )
1037
+
1038
+ Note:
1039
+ If filter_fn raises an exception for a specific graph, the original
1040
+ graph will be preserved and processing will continue.
1041
+ """
1042
+
1043
+ def filtering_transformation(
1044
+ op_symbol: str, dispatch_key: str, graph: list[_OverrideNode]
1045
+ ) -> list[_OverrideNode]:
1046
+ """Apply filter_fn to graph with error handling."""
1047
+ try:
1048
+ return [node for node in graph if filter_fn(op_symbol, dispatch_key, node)]
1049
+ except (TypeError, ValueError, AttributeError, RuntimeError):
1050
+ log.warning(
1051
+ "Graph transformation failed for %s/%s. Preserving original graph.",
1052
+ op_symbol,
1053
+ dispatch_key,
1054
+ exc_info=True,
1055
+ )
1056
+ return graph
1057
+ except Exception:
1058
+ log.exception(
1059
+ "Unexpected error in graph transformation for %s/%s. Preserving original graph.",
1060
+ op_symbol,
1061
+ dispatch_key,
1062
+ )
1063
+ return graph
1064
+
1065
+ _apply_graph_transformation(
1066
+ transformation_fn=filtering_transformation,
1067
+ reregister_overrides=reregister_overrides,
1068
+ )
1069
+
1070
+
1071
+ def _apply_selective_reordering(
1072
+ condition_fn: Callable[[str, str], bool],
1073
+ ordering_fn: UserOrderingFn,
1074
+ *,
1075
+ reregister_overrides: bool = False,
1076
+ ) -> None:
1077
+ """
1078
+ Apply reordering only to graphs that match a condition.
1079
+
1080
+ This allows for more targeted reordering operations.
1081
+
1082
+ Args:
1083
+ condition_fn: Function that takes (op_symbol, dispatch_key) and
1084
+ returns True if the graph should be reordered
1085
+ ordering_fn: Ordering function to apply to matching graphs
1086
+ reregister_overrides: Whether to reregister modified graphs
1087
+
1088
+ Example:
1089
+ # Only reorder CUDA operations
1090
+ _apply_selective_reordering(
1091
+ condition_fn=lambda op, dk: dk == "CUDA",
1092
+ ordering_fn=lambda op, dk, g: sorted(g, key=lambda n: n.dsl_name),
1093
+ reregister_overrides=True
1094
+ )
1095
+
1096
+ Note:
1097
+ If condition_fn or ordering_fn raises an exception for a specific graph,
1098
+ the original graph will be preserved and processing will continue.
1099
+ """
1100
+
1101
+ def conditional_transformation(
1102
+ op_symbol: str, dispatch_key: str, graph: list[_OverrideNode]
1103
+ ) -> list[_OverrideNode]:
1104
+ """Apply ordering_fn conditionally based on condition_fn result."""
1105
+ try:
1106
+ should_reorder = condition_fn(op_symbol, dispatch_key)
1107
+ except (TypeError, ValueError, AttributeError, RuntimeError):
1108
+ log.warning(
1109
+ "Graph transformation failed for %s/%s. Preserving original graph.",
1110
+ op_symbol,
1111
+ dispatch_key,
1112
+ exc_info=True,
1113
+ )
1114
+ return graph
1115
+ except Exception:
1116
+ log.exception(
1117
+ "Unexpected error in graph transformation for %s/%s. Preserving original graph.",
1118
+ op_symbol,
1119
+ dispatch_key,
1120
+ )
1121
+ return graph
1122
+
1123
+ if should_reorder:
1124
+ try:
1125
+ return ordering_fn(op_symbol, dispatch_key, graph)
1126
+ except (TypeError, ValueError, AttributeError, RuntimeError):
1127
+ log.warning(
1128
+ "Graph transformation failed for %s/%s. Preserving original graph.",
1129
+ op_symbol,
1130
+ dispatch_key,
1131
+ exc_info=True,
1132
+ )
1133
+ return graph
1134
+ except Exception:
1135
+ log.exception(
1136
+ "Unexpected error in graph transformation for %s/%s. Preserving original graph.",
1137
+ op_symbol,
1138
+ dispatch_key,
1139
+ )
1140
+ return graph
1141
+
1142
+ return graph # Return unchanged if condition doesn't match
1143
+
1144
+ _apply_graph_transformation(
1145
+ transformation_fn=conditional_transformation,
1146
+ reregister_overrides=reregister_overrides,
1147
+ )
.venv/lib/python3.12/site-packages/torch/_native/triton/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .const_tensor_wrapper import ConstTensorWrapper
2
+
3
+
4
+ __all__ = ["ConstTensorWrapper"]
.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (291 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/const_tensor_wrapper.cpython-312.pyc ADDED
Binary file (4.83 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_native/triton/const_tensor_wrapper.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ class ConstTensorWrapper:
5
+ """Read-only, zero-copy view of a tensor for Triton kernel arguments.
6
+
7
+ Triton extracts a kernel pointer argument by duck typing: any object with a
8
+ ``data_ptr()`` method and a ``dtype`` is treated as a pointer (see Triton's
9
+ ``jit.py``). ``ConstTensorWrapper`` overrides ``data_ptr()`` to return
10
+ ``const_data_ptr()``, so passing a copy-on-write tensor to an argument the
11
+ kernel only reads does not materialize it. The remaining attributes Triton
12
+ inspects during specialization and launch are forwarded to the wrapped
13
+ tensor.
14
+
15
+ Only wrap arguments the kernel treats as read-only (loads, never stores).
16
+ Triton does not enforce this; wrapping a written argument is a bug.
17
+
18
+ Accessors run under DisableTorchFunctionSubclass so the wrapper never
19
+ re-enters __torch_function__: const_data_ptr() and friends are dispatched
20
+ methods, and re-entering while an override is mid-redispatch trips the
21
+ "cannot skip two levels of __torch_function__" guard.
22
+ """
23
+
24
+ def __init__(self, tensor: torch.Tensor) -> None:
25
+ self._tensor = tensor
26
+
27
+ def data_ptr(self) -> int:
28
+ with torch._C.DisableTorchFunctionSubclass():
29
+ # const_data_ptr() exists at runtime but is absent from the stubs.
30
+ return self._tensor.const_data_ptr() # type: ignore[attr-defined]
31
+
32
+ @property
33
+ def dtype(self) -> torch.dtype:
34
+ return self._tensor.dtype
35
+
36
+ @property
37
+ def device(self) -> torch.device:
38
+ return self._tensor.device
39
+
40
+ @property
41
+ def shape(self) -> torch.Size:
42
+ return self._tensor.shape
43
+
44
+ @property
45
+ def ndim(self) -> int:
46
+ return self._tensor.ndim
47
+
48
+ def dim(self) -> int:
49
+ with torch._C.DisableTorchFunctionSubclass():
50
+ return self._tensor.dim()
51
+
52
+ def size(self, dim: int | None = None) -> torch.Size | int:
53
+ with torch._C.DisableTorchFunctionSubclass():
54
+ return self._tensor.size() if dim is None else self._tensor.size(dim)
55
+
56
+ def stride(self, dim: int | None = None) -> tuple[int, ...] | int:
57
+ with torch._C.DisableTorchFunctionSubclass():
58
+ return self._tensor.stride() if dim is None else self._tensor.stride(dim)
59
+
60
+ def element_size(self) -> int:
61
+ with torch._C.DisableTorchFunctionSubclass():
62
+ return self._tensor.element_size()
.venv/lib/python3.12/site-packages/torch/_native/triton_utils.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+ import sys
4
+ from typing import cast
5
+
6
+ from torch._vendor.packaging.version import Version
7
+
8
+ from ..backends import cuda as _cuda
9
+ from .common_utils import (
10
+ _available_version,
11
+ _unavailable_reason,
12
+ check_native_jit_disabled,
13
+ check_native_version_skip,
14
+ )
15
+ from .dsl_registry import dsl_registry, DSLModuleProtocol
16
+ from .registry import (
17
+ _OpCondFn,
18
+ _OpImplFn,
19
+ deregister_op_overrides as _deregister_op_overrides_impl,
20
+ register_op_override as _register_op_override_impl,
21
+ )
22
+
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+
27
+ _TRITON_DSL_NAME = "triton"
28
+ _TRITON_REQUIRED_VERSION_MAJOR = 3
29
+ _TRITON_MINIMUM_VERSION_MINOR = 6
30
+
31
+
32
+ @functools.cache
33
+ def _check_runtime_available() -> tuple[bool, Version | None]:
34
+ """
35
+ Check if triton is available
36
+
37
+ NOTE: must not import at this point
38
+ """
39
+ # Skip all checks if running on CPU-only binary
40
+ if not _cuda.is_built():
41
+ return (False, None)
42
+
43
+ deps = [
44
+ ("triton", "triton"),
45
+ ]
46
+ reason = _unavailable_reason(deps)
47
+ if reason is None:
48
+ available = True
49
+ version = _available_version("triton")
50
+ else:
51
+ # info, not warning: see cutedsl_utils._check_runtime_available for
52
+ # rationale (missing optional deps is the common case; surface via
53
+ # TORCH_LOGS=+native_dsl when needed).
54
+ log.info("triton native DSL ops require: `triton` %s", reason)
55
+ available = False
56
+ version = None
57
+ return available, version
58
+
59
+
60
+ def runtime_available() -> bool:
61
+ available, _ = _check_runtime_available()
62
+ return available
63
+
64
+
65
+ def runtime_version() -> None | Version:
66
+ _, version = _check_runtime_available()
67
+ return version
68
+
69
+
70
+ @functools.cache
71
+ def _version_is_sufficient() -> bool:
72
+ _, version = _check_runtime_available()
73
+
74
+ if version is None:
75
+ return False
76
+
77
+ # Either exact version, or same major
78
+ major_ok = version.major == _TRITON_REQUIRED_VERSION_MAJOR
79
+ minor_ok = version.minor >= _TRITON_MINIMUM_VERSION_MINOR
80
+
81
+ if (major_ok and minor_ok) or check_native_version_skip():
82
+ return True
83
+
84
+ log.info(
85
+ "triton version %s is not sufficient (>= (%s.%s.*)); "
86
+ "set TORCH_NATIVE_SKIP_VERSION_CHECK=1 to override",
87
+ version,
88
+ _TRITON_REQUIRED_VERSION_MAJOR,
89
+ _TRITON_MINIMUM_VERSION_MINOR,
90
+ )
91
+ return False
92
+
93
+
94
+ def deregister_op_overrides() -> None:
95
+ """
96
+ Deregister all ops through triton
97
+ """
98
+ _deregister_op_overrides_impl(disable_dsl_names=_TRITON_DSL_NAME)
99
+
100
+
101
+ def register_op_override(
102
+ lib_symbol: str,
103
+ op_symbol: str,
104
+ dispatch_key: str,
105
+ cond: _OpCondFn | None,
106
+ impl: _OpImplFn,
107
+ *,
108
+ allow_multiple_override: bool = False,
109
+ unconditional_override: bool = False,
110
+ ) -> None:
111
+ """
112
+ See torch/_native/registry.py for the underlying implementation
113
+ and arguments. This is a thin, DSL-checking wrapper over
114
+ _register_op_override_impl
115
+ """
116
+ available, version = _check_runtime_available()
117
+ if (not available) or check_native_jit_disabled():
118
+ return
119
+
120
+ if not _version_is_sufficient():
121
+ return
122
+
123
+ _register_op_override_impl(
124
+ _TRITON_DSL_NAME,
125
+ lib_symbol,
126
+ op_symbol,
127
+ dispatch_key,
128
+ cond,
129
+ impl,
130
+ allow_multiple_override=allow_multiple_override,
131
+ unconditional_override=unconditional_override,
132
+ )
133
+
134
+
135
+ # Register this DSL module with the registry
136
+ # Note: Import-time registration ensures DSL is available when module is loaded
137
+ dsl_registry.register_dsl("triton", cast(DSLModuleProtocol, sys.modules[__name__]))
.venv/lib/python3.12/site-packages/torch/_numpy/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ from . import fft, linalg, random
4
+ from ._dtypes import * # noqa: F403
5
+ from ._funcs import * # noqa: F403
6
+ from ._getlimits import finfo, iinfo
7
+ from ._ndarray import (
8
+ array,
9
+ asarray,
10
+ ascontiguousarray,
11
+ can_cast,
12
+ from_dlpack,
13
+ ndarray,
14
+ newaxis,
15
+ result_type,
16
+ )
17
+ from ._ufuncs import * # noqa: F403
18
+ from ._util import AxisError, UFuncTypeError
19
+
20
+
21
+ from math import pi, e # usort: skip
22
+
23
+
24
+ all = all # noqa: PLW0127
25
+ alltrue = all
26
+
27
+ any = any # noqa: PLW0127
28
+ sometrue = any
29
+
30
+ inf = float("inf")
31
+ nan = float("nan")
32
+
33
+ False_ = False
34
+ True_ = True
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (877 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_binary_ufuncs_impl.cpython-312.pyc ADDED
Binary file (2.43 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_casting_dicts.cpython-312.pyc ADDED
Binary file (47.4 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes.cpython-312.pyc ADDED
Binary file (15.8 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes_impl.cpython-312.pyc ADDED
Binary file (8.41 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs.cpython-312.pyc ADDED
Binary file (2.23 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs_impl.cpython-312.pyc ADDED
Binary file (76.1 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_getlimits.cpython-312.pyc ADDED
Binary file (748 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ndarray.cpython-312.pyc ADDED
Binary file (32.3 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_normalizations.cpython-312.pyc ADDED
Binary file (12.9 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_reductions_impl.cpython-312.pyc ADDED
Binary file (16.4 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ufuncs.cpython-312.pyc ADDED
Binary file (9.41 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_unary_ufuncs_impl.cpython-312.pyc ADDED
Binary file (1.76 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_util.cpython-312.pyc ADDED
Binary file (12.1 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/fft.cpython-312.pyc ADDED
Binary file (7.33 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/linalg.cpython-312.pyc ADDED
Binary file (11.6 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/random.cpython-312.pyc ADDED
Binary file (6.91 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/_binary_ufuncs_impl.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """Export torch work functions for binary ufuncs, rename/tweak to match numpy.
4
+ This listing is further exported to public symbols in the `torch._numpy/_ufuncs.py` module.
5
+ """
6
+
7
+ import torch
8
+ from torch import ( # noqa: F401
9
+ add,
10
+ arctan2,
11
+ bitwise_and,
12
+ bitwise_left_shift as left_shift,
13
+ bitwise_or,
14
+ bitwise_right_shift as right_shift,
15
+ bitwise_xor,
16
+ copysign,
17
+ divide,
18
+ eq as equal,
19
+ float_power,
20
+ floor_divide,
21
+ fmax,
22
+ fmin,
23
+ fmod,
24
+ gcd,
25
+ greater,
26
+ greater_equal,
27
+ heaviside,
28
+ hypot,
29
+ lcm,
30
+ ldexp,
31
+ less,
32
+ less_equal,
33
+ logaddexp,
34
+ logaddexp2,
35
+ logical_and,
36
+ logical_or,
37
+ logical_xor,
38
+ maximum,
39
+ minimum,
40
+ multiply,
41
+ nextafter,
42
+ not_equal,
43
+ pow as power,
44
+ remainder,
45
+ remainder as mod,
46
+ subtract,
47
+ true_divide,
48
+ )
49
+
50
+ from . import _dtypes_impl, _util
51
+
52
+
53
+ # work around torch limitations w.r.t. numpy
54
+ def matmul(x, y):
55
+ # work around:
56
+ # - RuntimeError: expected scalar type Int but found Double
57
+ # - RuntimeError: "addmm_impl_cpu_" not implemented for 'Bool'
58
+ # - RuntimeError: "addmm_impl_cpu_" not implemented for 'Half'
59
+ dtype = _dtypes_impl.result_type_impl(x, y)
60
+ is_bool = dtype == torch.bool
61
+ is_half = (x.dtype == torch.float16 or y.dtype == torch.float16) and (
62
+ x.is_cpu or y.is_cpu
63
+ )
64
+
65
+ work_dtype = dtype
66
+ if is_bool:
67
+ work_dtype = torch.uint8
68
+ if is_half:
69
+ work_dtype = torch.float32
70
+
71
+ x = _util.cast_if_needed(x, work_dtype)
72
+ y = _util.cast_if_needed(y, work_dtype)
73
+
74
+ result = torch.matmul(x, y)
75
+
76
+ if work_dtype != dtype:
77
+ result = result.to(dtype)
78
+
79
+ return result
80
+
81
+
82
+ # a stub implementation of divmod, should be improved after
83
+ # https://github.com/pytorch/pytorch/issues/90820 is fixed in pytorch
84
+ def divmod(x, y):
85
+ return x // y, x % y
.venv/lib/python3.12/site-packages/torch/_numpy/_casting_dicts.py ADDED
@@ -0,0 +1,1368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import torch
4
+
5
+
6
+ # These two dicts are autogenerated with autogen/gen_dtypes.py,
7
+ # using numpy version 1.24.3.
8
+
9
+ _can_cast_dict = {
10
+ "no": {
11
+ torch.float16: {
12
+ torch.float16: True,
13
+ torch.float32: False,
14
+ torch.float64: False,
15
+ torch.complex64: False,
16
+ torch.complex128: False,
17
+ torch.uint8: False,
18
+ torch.uint16: False,
19
+ torch.uint32: False,
20
+ torch.uint64: False,
21
+ torch.int8: False,
22
+ torch.int16: False,
23
+ torch.int32: False,
24
+ torch.int64: False,
25
+ torch.bool: False,
26
+ },
27
+ torch.float32: {
28
+ torch.float16: False,
29
+ torch.float32: True,
30
+ torch.float64: False,
31
+ torch.complex64: False,
32
+ torch.complex128: False,
33
+ torch.uint8: False,
34
+ torch.uint16: False,
35
+ torch.uint32: False,
36
+ torch.uint64: False,
37
+ torch.int8: False,
38
+ torch.int16: False,
39
+ torch.int32: False,
40
+ torch.int64: False,
41
+ torch.bool: False,
42
+ },
43
+ torch.float64: {
44
+ torch.float16: False,
45
+ torch.float32: False,
46
+ torch.float64: True,
47
+ torch.complex64: False,
48
+ torch.complex128: False,
49
+ torch.uint8: False,
50
+ torch.uint16: False,
51
+ torch.uint32: False,
52
+ torch.uint64: False,
53
+ torch.int8: False,
54
+ torch.int16: False,
55
+ torch.int32: False,
56
+ torch.int64: False,
57
+ torch.bool: False,
58
+ },
59
+ torch.complex64: {
60
+ torch.float16: False,
61
+ torch.float32: False,
62
+ torch.float64: False,
63
+ torch.complex64: True,
64
+ torch.complex128: False,
65
+ torch.uint8: False,
66
+ torch.uint16: False,
67
+ torch.uint32: False,
68
+ torch.uint64: False,
69
+ torch.int8: False,
70
+ torch.int16: False,
71
+ torch.int32: False,
72
+ torch.int64: False,
73
+ torch.bool: False,
74
+ },
75
+ torch.complex128: {
76
+ torch.float16: False,
77
+ torch.float32: False,
78
+ torch.float64: False,
79
+ torch.complex64: False,
80
+ torch.complex128: True,
81
+ torch.uint8: False,
82
+ torch.uint16: False,
83
+ torch.uint32: False,
84
+ torch.uint64: False,
85
+ torch.int8: False,
86
+ torch.int16: False,
87
+ torch.int32: False,
88
+ torch.int64: False,
89
+ torch.bool: False,
90
+ },
91
+ torch.uint8: {
92
+ torch.float16: False,
93
+ torch.float32: False,
94
+ torch.float64: False,
95
+ torch.complex64: False,
96
+ torch.complex128: False,
97
+ torch.uint8: True,
98
+ torch.uint16: False,
99
+ torch.uint32: False,
100
+ torch.uint64: False,
101
+ torch.int8: False,
102
+ torch.int16: False,
103
+ torch.int32: False,
104
+ torch.int64: False,
105
+ torch.bool: False,
106
+ },
107
+ torch.uint16: {
108
+ torch.float16: False,
109
+ torch.float32: False,
110
+ torch.float64: False,
111
+ torch.complex64: False,
112
+ torch.complex128: False,
113
+ torch.uint8: False,
114
+ torch.uint16: True,
115
+ torch.uint32: False,
116
+ torch.uint64: False,
117
+ torch.int8: False,
118
+ torch.int16: False,
119
+ torch.int32: False,
120
+ torch.int64: False,
121
+ torch.bool: False,
122
+ },
123
+ torch.uint32: {
124
+ torch.float16: False,
125
+ torch.float32: False,
126
+ torch.float64: False,
127
+ torch.complex64: False,
128
+ torch.complex128: False,
129
+ torch.uint8: False,
130
+ torch.uint16: False,
131
+ torch.uint32: True,
132
+ torch.uint64: False,
133
+ torch.int8: False,
134
+ torch.int16: False,
135
+ torch.int32: False,
136
+ torch.int64: False,
137
+ torch.bool: False,
138
+ },
139
+ torch.uint64: {
140
+ torch.float16: False,
141
+ torch.float32: False,
142
+ torch.float64: False,
143
+ torch.complex64: False,
144
+ torch.complex128: False,
145
+ torch.uint8: False,
146
+ torch.uint16: False,
147
+ torch.uint32: False,
148
+ torch.uint64: True,
149
+ torch.int8: False,
150
+ torch.int16: False,
151
+ torch.int32: False,
152
+ torch.int64: False,
153
+ torch.bool: False,
154
+ },
155
+ torch.int8: {
156
+ torch.float16: False,
157
+ torch.float32: False,
158
+ torch.float64: False,
159
+ torch.complex64: False,
160
+ torch.complex128: False,
161
+ torch.uint8: False,
162
+ torch.uint16: False,
163
+ torch.uint32: False,
164
+ torch.uint64: False,
165
+ torch.int8: True,
166
+ torch.int16: False,
167
+ torch.int32: False,
168
+ torch.int64: False,
169
+ torch.bool: False,
170
+ },
171
+ torch.int16: {
172
+ torch.float16: False,
173
+ torch.float32: False,
174
+ torch.float64: False,
175
+ torch.complex64: False,
176
+ torch.complex128: False,
177
+ torch.uint8: False,
178
+ torch.uint16: False,
179
+ torch.uint32: False,
180
+ torch.uint64: False,
181
+ torch.int8: False,
182
+ torch.int16: True,
183
+ torch.int32: False,
184
+ torch.int64: False,
185
+ torch.bool: False,
186
+ },
187
+ torch.int32: {
188
+ torch.float16: False,
189
+ torch.float32: False,
190
+ torch.float64: False,
191
+ torch.complex64: False,
192
+ torch.complex128: False,
193
+ torch.uint8: False,
194
+ torch.uint16: False,
195
+ torch.uint32: False,
196
+ torch.uint64: False,
197
+ torch.int8: False,
198
+ torch.int16: False,
199
+ torch.int32: True,
200
+ torch.int64: False,
201
+ torch.bool: False,
202
+ },
203
+ torch.int64: {
204
+ torch.float16: False,
205
+ torch.float32: False,
206
+ torch.float64: False,
207
+ torch.complex64: False,
208
+ torch.complex128: False,
209
+ torch.uint8: False,
210
+ torch.uint16: False,
211
+ torch.uint32: False,
212
+ torch.uint64: False,
213
+ torch.int8: False,
214
+ torch.int16: False,
215
+ torch.int32: False,
216
+ torch.int64: True,
217
+ torch.bool: False,
218
+ },
219
+ torch.bool: {
220
+ torch.float16: False,
221
+ torch.float32: False,
222
+ torch.float64: False,
223
+ torch.complex64: False,
224
+ torch.complex128: False,
225
+ torch.uint8: False,
226
+ torch.uint16: False,
227
+ torch.uint32: False,
228
+ torch.uint64: False,
229
+ torch.int8: False,
230
+ torch.int16: False,
231
+ torch.int32: False,
232
+ torch.int64: False,
233
+ torch.bool: True,
234
+ },
235
+ },
236
+ "equiv": {
237
+ torch.float16: {
238
+ torch.float16: True,
239
+ torch.float32: False,
240
+ torch.float64: False,
241
+ torch.complex64: False,
242
+ torch.complex128: False,
243
+ torch.uint8: False,
244
+ torch.uint16: False,
245
+ torch.uint32: False,
246
+ torch.uint64: False,
247
+ torch.int8: False,
248
+ torch.int16: False,
249
+ torch.int32: False,
250
+ torch.int64: False,
251
+ torch.bool: False,
252
+ },
253
+ torch.float32: {
254
+ torch.float16: False,
255
+ torch.float32: True,
256
+ torch.float64: False,
257
+ torch.complex64: False,
258
+ torch.complex128: False,
259
+ torch.uint8: False,
260
+ torch.uint16: False,
261
+ torch.uint32: False,
262
+ torch.uint64: False,
263
+ torch.int8: False,
264
+ torch.int16: False,
265
+ torch.int32: False,
266
+ torch.int64: False,
267
+ torch.bool: False,
268
+ },
269
+ torch.float64: {
270
+ torch.float16: False,
271
+ torch.float32: False,
272
+ torch.float64: True,
273
+ torch.complex64: False,
274
+ torch.complex128: False,
275
+ torch.uint8: False,
276
+ torch.uint16: False,
277
+ torch.uint32: False,
278
+ torch.uint64: False,
279
+ torch.int8: False,
280
+ torch.int16: False,
281
+ torch.int32: False,
282
+ torch.int64: False,
283
+ torch.bool: False,
284
+ },
285
+ torch.complex64: {
286
+ torch.float16: False,
287
+ torch.float32: False,
288
+ torch.float64: False,
289
+ torch.complex64: True,
290
+ torch.complex128: False,
291
+ torch.uint8: False,
292
+ torch.uint16: False,
293
+ torch.uint32: False,
294
+ torch.uint64: False,
295
+ torch.int8: False,
296
+ torch.int16: False,
297
+ torch.int32: False,
298
+ torch.int64: False,
299
+ torch.bool: False,
300
+ },
301
+ torch.complex128: {
302
+ torch.float16: False,
303
+ torch.float32: False,
304
+ torch.float64: False,
305
+ torch.complex64: False,
306
+ torch.complex128: True,
307
+ torch.uint8: False,
308
+ torch.uint16: False,
309
+ torch.uint32: False,
310
+ torch.uint64: False,
311
+ torch.int8: False,
312
+ torch.int16: False,
313
+ torch.int32: False,
314
+ torch.int64: False,
315
+ torch.bool: False,
316
+ },
317
+ torch.uint8: {
318
+ torch.float16: False,
319
+ torch.float32: False,
320
+ torch.float64: False,
321
+ torch.complex64: False,
322
+ torch.complex128: False,
323
+ torch.uint8: True,
324
+ torch.uint16: False,
325
+ torch.uint32: False,
326
+ torch.uint64: False,
327
+ torch.int8: False,
328
+ torch.int16: False,
329
+ torch.int32: False,
330
+ torch.int64: False,
331
+ torch.bool: False,
332
+ },
333
+ torch.uint16: {
334
+ torch.float16: False,
335
+ torch.float32: False,
336
+ torch.float64: False,
337
+ torch.complex64: False,
338
+ torch.complex128: False,
339
+ torch.uint8: False,
340
+ torch.uint16: True,
341
+ torch.uint32: False,
342
+ torch.uint64: False,
343
+ torch.int8: False,
344
+ torch.int16: False,
345
+ torch.int32: False,
346
+ torch.int64: False,
347
+ torch.bool: False,
348
+ },
349
+ torch.uint32: {
350
+ torch.float16: False,
351
+ torch.float32: False,
352
+ torch.float64: False,
353
+ torch.complex64: False,
354
+ torch.complex128: False,
355
+ torch.uint8: False,
356
+ torch.uint16: False,
357
+ torch.uint32: True,
358
+ torch.uint64: False,
359
+ torch.int8: False,
360
+ torch.int16: False,
361
+ torch.int32: False,
362
+ torch.int64: False,
363
+ torch.bool: False,
364
+ },
365
+ torch.uint64: {
366
+ torch.float16: False,
367
+ torch.float32: False,
368
+ torch.float64: False,
369
+ torch.complex64: False,
370
+ torch.complex128: False,
371
+ torch.uint8: False,
372
+ torch.uint16: False,
373
+ torch.uint32: False,
374
+ torch.uint64: True,
375
+ torch.int8: False,
376
+ torch.int16: False,
377
+ torch.int32: False,
378
+ torch.int64: False,
379
+ torch.bool: False,
380
+ },
381
+ torch.int8: {
382
+ torch.float16: False,
383
+ torch.float32: False,
384
+ torch.float64: False,
385
+ torch.complex64: False,
386
+ torch.complex128: False,
387
+ torch.uint8: False,
388
+ torch.uint16: False,
389
+ torch.uint32: False,
390
+ torch.uint64: False,
391
+ torch.int8: True,
392
+ torch.int16: False,
393
+ torch.int32: False,
394
+ torch.int64: False,
395
+ torch.bool: False,
396
+ },
397
+ torch.int16: {
398
+ torch.float16: False,
399
+ torch.float32: False,
400
+ torch.float64: False,
401
+ torch.complex64: False,
402
+ torch.complex128: False,
403
+ torch.uint8: False,
404
+ torch.uint16: False,
405
+ torch.uint32: False,
406
+ torch.uint64: False,
407
+ torch.int8: False,
408
+ torch.int16: True,
409
+ torch.int32: False,
410
+ torch.int64: False,
411
+ torch.bool: False,
412
+ },
413
+ torch.int32: {
414
+ torch.float16: False,
415
+ torch.float32: False,
416
+ torch.float64: False,
417
+ torch.complex64: False,
418
+ torch.complex128: False,
419
+ torch.uint8: False,
420
+ torch.uint16: False,
421
+ torch.uint32: False,
422
+ torch.uint64: False,
423
+ torch.int8: False,
424
+ torch.int16: False,
425
+ torch.int32: True,
426
+ torch.int64: False,
427
+ torch.bool: False,
428
+ },
429
+ torch.int64: {
430
+ torch.float16: False,
431
+ torch.float32: False,
432
+ torch.float64: False,
433
+ torch.complex64: False,
434
+ torch.complex128: False,
435
+ torch.uint8: False,
436
+ torch.uint16: False,
437
+ torch.uint32: False,
438
+ torch.uint64: False,
439
+ torch.int8: False,
440
+ torch.int16: False,
441
+ torch.int32: False,
442
+ torch.int64: True,
443
+ torch.bool: False,
444
+ },
445
+ torch.bool: {
446
+ torch.float16: False,
447
+ torch.float32: False,
448
+ torch.float64: False,
449
+ torch.complex64: False,
450
+ torch.complex128: False,
451
+ torch.uint8: False,
452
+ torch.uint16: False,
453
+ torch.uint32: False,
454
+ torch.uint64: False,
455
+ torch.int8: False,
456
+ torch.int16: False,
457
+ torch.int32: False,
458
+ torch.int64: False,
459
+ torch.bool: True,
460
+ },
461
+ },
462
+ "safe": {
463
+ torch.float16: {
464
+ torch.float16: True,
465
+ torch.float32: True,
466
+ torch.float64: True,
467
+ torch.complex64: True,
468
+ torch.complex128: True,
469
+ torch.uint8: False,
470
+ torch.uint16: False,
471
+ torch.uint32: False,
472
+ torch.uint64: False,
473
+ torch.int8: False,
474
+ torch.int16: False,
475
+ torch.int32: False,
476
+ torch.int64: False,
477
+ torch.bool: False,
478
+ },
479
+ torch.float32: {
480
+ torch.float16: False,
481
+ torch.float32: True,
482
+ torch.float64: True,
483
+ torch.complex64: True,
484
+ torch.complex128: True,
485
+ torch.uint8: False,
486
+ torch.uint16: False,
487
+ torch.uint32: False,
488
+ torch.uint64: False,
489
+ torch.int8: False,
490
+ torch.int16: False,
491
+ torch.int32: False,
492
+ torch.int64: False,
493
+ torch.bool: False,
494
+ },
495
+ torch.float64: {
496
+ torch.float16: False,
497
+ torch.float32: False,
498
+ torch.float64: True,
499
+ torch.complex64: False,
500
+ torch.complex128: True,
501
+ torch.uint8: False,
502
+ torch.uint16: False,
503
+ torch.uint32: False,
504
+ torch.uint64: False,
505
+ torch.int8: False,
506
+ torch.int16: False,
507
+ torch.int32: False,
508
+ torch.int64: False,
509
+ torch.bool: False,
510
+ },
511
+ torch.complex64: {
512
+ torch.float16: False,
513
+ torch.float32: False,
514
+ torch.float64: False,
515
+ torch.complex64: True,
516
+ torch.complex128: True,
517
+ torch.uint8: False,
518
+ torch.uint16: False,
519
+ torch.uint32: False,
520
+ torch.uint64: False,
521
+ torch.int8: False,
522
+ torch.int16: False,
523
+ torch.int32: False,
524
+ torch.int64: False,
525
+ torch.bool: False,
526
+ },
527
+ torch.complex128: {
528
+ torch.float16: False,
529
+ torch.float32: False,
530
+ torch.float64: False,
531
+ torch.complex64: False,
532
+ torch.complex128: True,
533
+ torch.uint8: False,
534
+ torch.uint16: False,
535
+ torch.uint32: False,
536
+ torch.uint64: False,
537
+ torch.int8: False,
538
+ torch.int16: False,
539
+ torch.int32: False,
540
+ torch.int64: False,
541
+ torch.bool: False,
542
+ },
543
+ torch.uint8: {
544
+ torch.float16: True,
545
+ torch.float32: True,
546
+ torch.float64: True,
547
+ torch.complex64: True,
548
+ torch.complex128: True,
549
+ torch.uint8: True,
550
+ torch.uint16: True,
551
+ torch.uint32: True,
552
+ torch.uint64: True,
553
+ torch.int8: False,
554
+ torch.int16: True,
555
+ torch.int32: True,
556
+ torch.int64: True,
557
+ torch.bool: False,
558
+ },
559
+ torch.uint16: {
560
+ torch.float16: False,
561
+ torch.float32: True,
562
+ torch.float64: True,
563
+ torch.complex64: True,
564
+ torch.complex128: True,
565
+ torch.uint8: False,
566
+ torch.uint16: True,
567
+ torch.uint32: True,
568
+ torch.uint64: True,
569
+ torch.int8: False,
570
+ torch.int16: False,
571
+ torch.int32: True,
572
+ torch.int64: True,
573
+ torch.bool: False,
574
+ },
575
+ torch.uint32: {
576
+ torch.float16: False,
577
+ torch.float32: False,
578
+ torch.float64: True,
579
+ torch.complex64: False,
580
+ torch.complex128: True,
581
+ torch.uint8: False,
582
+ torch.uint16: False,
583
+ torch.uint32: True,
584
+ torch.uint64: True,
585
+ torch.int8: False,
586
+ torch.int16: False,
587
+ torch.int32: False,
588
+ torch.int64: True,
589
+ torch.bool: False,
590
+ },
591
+ torch.uint64: {
592
+ torch.float16: False,
593
+ torch.float32: False,
594
+ torch.float64: True,
595
+ torch.complex64: False,
596
+ torch.complex128: True,
597
+ torch.uint8: False,
598
+ torch.uint16: False,
599
+ torch.uint32: False,
600
+ torch.uint64: True,
601
+ torch.int8: False,
602
+ torch.int16: False,
603
+ torch.int32: False,
604
+ torch.int64: False,
605
+ torch.bool: False,
606
+ },
607
+ torch.int8: {
608
+ torch.float16: True,
609
+ torch.float32: True,
610
+ torch.float64: True,
611
+ torch.complex64: True,
612
+ torch.complex128: True,
613
+ torch.uint8: False,
614
+ torch.uint16: False,
615
+ torch.uint32: False,
616
+ torch.uint64: False,
617
+ torch.int8: True,
618
+ torch.int16: True,
619
+ torch.int32: True,
620
+ torch.int64: True,
621
+ torch.bool: False,
622
+ },
623
+ torch.int16: {
624
+ torch.float16: False,
625
+ torch.float32: True,
626
+ torch.float64: True,
627
+ torch.complex64: True,
628
+ torch.complex128: True,
629
+ torch.uint8: False,
630
+ torch.uint16: False,
631
+ torch.uint32: False,
632
+ torch.uint64: False,
633
+ torch.int8: False,
634
+ torch.int16: True,
635
+ torch.int32: True,
636
+ torch.int64: True,
637
+ torch.bool: False,
638
+ },
639
+ torch.int32: {
640
+ torch.float16: False,
641
+ torch.float32: False,
642
+ torch.float64: True,
643
+ torch.complex64: False,
644
+ torch.complex128: True,
645
+ torch.uint8: False,
646
+ torch.uint16: False,
647
+ torch.uint32: False,
648
+ torch.uint64: False,
649
+ torch.int8: False,
650
+ torch.int16: False,
651
+ torch.int32: True,
652
+ torch.int64: True,
653
+ torch.bool: False,
654
+ },
655
+ torch.int64: {
656
+ torch.float16: False,
657
+ torch.float32: False,
658
+ torch.float64: True,
659
+ torch.complex64: False,
660
+ torch.complex128: True,
661
+ torch.uint8: False,
662
+ torch.uint16: False,
663
+ torch.uint32: False,
664
+ torch.uint64: False,
665
+ torch.int8: False,
666
+ torch.int16: False,
667
+ torch.int32: False,
668
+ torch.int64: True,
669
+ torch.bool: False,
670
+ },
671
+ torch.bool: {
672
+ torch.float16: True,
673
+ torch.float32: True,
674
+ torch.float64: True,
675
+ torch.complex64: True,
676
+ torch.complex128: True,
677
+ torch.uint8: True,
678
+ torch.uint16: True,
679
+ torch.uint32: True,
680
+ torch.uint64: True,
681
+ torch.int8: True,
682
+ torch.int16: True,
683
+ torch.int32: True,
684
+ torch.int64: True,
685
+ torch.bool: True,
686
+ },
687
+ },
688
+ "same_kind": {
689
+ torch.float16: {
690
+ torch.float16: True,
691
+ torch.float32: True,
692
+ torch.float64: True,
693
+ torch.complex64: True,
694
+ torch.complex128: True,
695
+ torch.uint8: False,
696
+ torch.uint16: False,
697
+ torch.uint32: False,
698
+ torch.uint64: False,
699
+ torch.int8: False,
700
+ torch.int16: False,
701
+ torch.int32: False,
702
+ torch.int64: False,
703
+ torch.bool: False,
704
+ },
705
+ torch.float32: {
706
+ torch.float16: True,
707
+ torch.float32: True,
708
+ torch.float64: True,
709
+ torch.complex64: True,
710
+ torch.complex128: True,
711
+ torch.uint8: False,
712
+ torch.uint16: False,
713
+ torch.uint32: False,
714
+ torch.uint64: False,
715
+ torch.int8: False,
716
+ torch.int16: False,
717
+ torch.int32: False,
718
+ torch.int64: False,
719
+ torch.bool: False,
720
+ },
721
+ torch.float64: {
722
+ torch.float16: True,
723
+ torch.float32: True,
724
+ torch.float64: True,
725
+ torch.complex64: True,
726
+ torch.complex128: True,
727
+ torch.uint8: False,
728
+ torch.uint16: False,
729
+ torch.uint32: False,
730
+ torch.uint64: False,
731
+ torch.int8: False,
732
+ torch.int16: False,
733
+ torch.int32: False,
734
+ torch.int64: False,
735
+ torch.bool: False,
736
+ },
737
+ torch.complex64: {
738
+ torch.float16: False,
739
+ torch.float32: False,
740
+ torch.float64: False,
741
+ torch.complex64: True,
742
+ torch.complex128: True,
743
+ torch.uint8: False,
744
+ torch.uint16: False,
745
+ torch.uint32: False,
746
+ torch.uint64: False,
747
+ torch.int8: False,
748
+ torch.int16: False,
749
+ torch.int32: False,
750
+ torch.int64: False,
751
+ torch.bool: False,
752
+ },
753
+ torch.complex128: {
754
+ torch.float16: False,
755
+ torch.float32: False,
756
+ torch.float64: False,
757
+ torch.complex64: True,
758
+ torch.complex128: True,
759
+ torch.uint8: False,
760
+ torch.uint16: False,
761
+ torch.uint32: False,
762
+ torch.uint64: False,
763
+ torch.int8: False,
764
+ torch.int16: False,
765
+ torch.int32: False,
766
+ torch.int64: False,
767
+ torch.bool: False,
768
+ },
769
+ torch.uint8: {
770
+ torch.float16: True,
771
+ torch.float32: True,
772
+ torch.float64: True,
773
+ torch.complex64: True,
774
+ torch.complex128: True,
775
+ torch.uint8: True,
776
+ torch.uint16: True,
777
+ torch.uint32: True,
778
+ torch.uint64: True,
779
+ torch.int8: True,
780
+ torch.int16: True,
781
+ torch.int32: True,
782
+ torch.int64: True,
783
+ torch.bool: False,
784
+ },
785
+ torch.uint16: {
786
+ torch.float16: True,
787
+ torch.float32: True,
788
+ torch.float64: True,
789
+ torch.complex64: True,
790
+ torch.complex128: True,
791
+ torch.uint8: True,
792
+ torch.uint16: True,
793
+ torch.uint32: True,
794
+ torch.uint64: True,
795
+ torch.int8: True,
796
+ torch.int16: True,
797
+ torch.int32: True,
798
+ torch.int64: True,
799
+ torch.bool: False,
800
+ },
801
+ torch.uint32: {
802
+ torch.float16: True,
803
+ torch.float32: True,
804
+ torch.float64: True,
805
+ torch.complex64: True,
806
+ torch.complex128: True,
807
+ torch.uint8: True,
808
+ torch.uint16: True,
809
+ torch.uint32: True,
810
+ torch.uint64: True,
811
+ torch.int8: True,
812
+ torch.int16: True,
813
+ torch.int32: True,
814
+ torch.int64: True,
815
+ torch.bool: False,
816
+ },
817
+ torch.uint64: {
818
+ torch.float16: True,
819
+ torch.float32: True,
820
+ torch.float64: True,
821
+ torch.complex64: True,
822
+ torch.complex128: True,
823
+ torch.uint8: True,
824
+ torch.uint16: True,
825
+ torch.uint32: True,
826
+ torch.uint64: True,
827
+ torch.int8: True,
828
+ torch.int16: True,
829
+ torch.int32: True,
830
+ torch.int64: True,
831
+ torch.bool: False,
832
+ },
833
+ torch.int8: {
834
+ torch.float16: True,
835
+ torch.float32: True,
836
+ torch.float64: True,
837
+ torch.complex64: True,
838
+ torch.complex128: True,
839
+ torch.uint8: False,
840
+ torch.uint16: False,
841
+ torch.uint32: False,
842
+ torch.uint64: False,
843
+ torch.int8: True,
844
+ torch.int16: True,
845
+ torch.int32: True,
846
+ torch.int64: True,
847
+ torch.bool: False,
848
+ },
849
+ torch.int16: {
850
+ torch.float16: True,
851
+ torch.float32: True,
852
+ torch.float64: True,
853
+ torch.complex64: True,
854
+ torch.complex128: True,
855
+ torch.uint8: False,
856
+ torch.uint16: False,
857
+ torch.uint32: False,
858
+ torch.uint64: False,
859
+ torch.int8: True,
860
+ torch.int16: True,
861
+ torch.int32: True,
862
+ torch.int64: True,
863
+ torch.bool: False,
864
+ },
865
+ torch.int32: {
866
+ torch.float16: True,
867
+ torch.float32: True,
868
+ torch.float64: True,
869
+ torch.complex64: True,
870
+ torch.complex128: True,
871
+ torch.uint8: False,
872
+ torch.uint16: False,
873
+ torch.uint32: False,
874
+ torch.uint64: False,
875
+ torch.int8: True,
876
+ torch.int16: True,
877
+ torch.int32: True,
878
+ torch.int64: True,
879
+ torch.bool: False,
880
+ },
881
+ torch.int64: {
882
+ torch.float16: True,
883
+ torch.float32: True,
884
+ torch.float64: True,
885
+ torch.complex64: True,
886
+ torch.complex128: True,
887
+ torch.uint8: False,
888
+ torch.uint16: False,
889
+ torch.uint32: False,
890
+ torch.uint64: False,
891
+ torch.int8: True,
892
+ torch.int16: True,
893
+ torch.int32: True,
894
+ torch.int64: True,
895
+ torch.bool: False,
896
+ },
897
+ torch.bool: {
898
+ torch.float16: True,
899
+ torch.float32: True,
900
+ torch.float64: True,
901
+ torch.complex64: True,
902
+ torch.complex128: True,
903
+ torch.uint8: True,
904
+ torch.uint16: True,
905
+ torch.uint32: True,
906
+ torch.uint64: True,
907
+ torch.int8: True,
908
+ torch.int16: True,
909
+ torch.int32: True,
910
+ torch.int64: True,
911
+ torch.bool: True,
912
+ },
913
+ },
914
+ "unsafe": {
915
+ torch.float16: {
916
+ torch.float16: True,
917
+ torch.float32: True,
918
+ torch.float64: True,
919
+ torch.complex64: True,
920
+ torch.complex128: True,
921
+ torch.uint8: True,
922
+ torch.uint16: True,
923
+ torch.uint32: True,
924
+ torch.uint64: True,
925
+ torch.int8: True,
926
+ torch.int16: True,
927
+ torch.int32: True,
928
+ torch.int64: True,
929
+ torch.bool: True,
930
+ },
931
+ torch.float32: {
932
+ torch.float16: True,
933
+ torch.float32: True,
934
+ torch.float64: True,
935
+ torch.complex64: True,
936
+ torch.complex128: True,
937
+ torch.uint8: True,
938
+ torch.uint16: True,
939
+ torch.uint32: True,
940
+ torch.uint64: True,
941
+ torch.int8: True,
942
+ torch.int16: True,
943
+ torch.int32: True,
944
+ torch.int64: True,
945
+ torch.bool: True,
946
+ },
947
+ torch.float64: {
948
+ torch.float16: True,
949
+ torch.float32: True,
950
+ torch.float64: True,
951
+ torch.complex64: True,
952
+ torch.complex128: True,
953
+ torch.uint8: True,
954
+ torch.uint16: True,
955
+ torch.uint32: True,
956
+ torch.uint64: True,
957
+ torch.int8: True,
958
+ torch.int16: True,
959
+ torch.int32: True,
960
+ torch.int64: True,
961
+ torch.bool: True,
962
+ },
963
+ torch.complex64: {
964
+ torch.float16: True,
965
+ torch.float32: True,
966
+ torch.float64: True,
967
+ torch.complex64: True,
968
+ torch.complex128: True,
969
+ torch.uint8: True,
970
+ torch.uint16: True,
971
+ torch.uint32: True,
972
+ torch.uint64: True,
973
+ torch.int8: True,
974
+ torch.int16: True,
975
+ torch.int32: True,
976
+ torch.int64: True,
977
+ torch.bool: True,
978
+ },
979
+ torch.complex128: {
980
+ torch.float16: True,
981
+ torch.float32: True,
982
+ torch.float64: True,
983
+ torch.complex64: True,
984
+ torch.complex128: True,
985
+ torch.uint8: True,
986
+ torch.uint16: True,
987
+ torch.uint32: True,
988
+ torch.uint64: True,
989
+ torch.int8: True,
990
+ torch.int16: True,
991
+ torch.int32: True,
992
+ torch.int64: True,
993
+ torch.bool: True,
994
+ },
995
+ torch.uint8: {
996
+ torch.float16: True,
997
+ torch.float32: True,
998
+ torch.float64: True,
999
+ torch.complex64: True,
1000
+ torch.complex128: True,
1001
+ torch.uint8: True,
1002
+ torch.uint16: True,
1003
+ torch.uint32: True,
1004
+ torch.uint64: True,
1005
+ torch.int8: True,
1006
+ torch.int16: True,
1007
+ torch.int32: True,
1008
+ torch.int64: True,
1009
+ torch.bool: True,
1010
+ },
1011
+ torch.uint16: {
1012
+ torch.float16: True,
1013
+ torch.float32: True,
1014
+ torch.float64: True,
1015
+ torch.complex64: True,
1016
+ torch.complex128: True,
1017
+ torch.uint8: True,
1018
+ torch.uint16: True,
1019
+ torch.uint32: True,
1020
+ torch.uint64: True,
1021
+ torch.int8: True,
1022
+ torch.int16: True,
1023
+ torch.int32: True,
1024
+ torch.int64: True,
1025
+ torch.bool: True,
1026
+ },
1027
+ torch.uint32: {
1028
+ torch.float16: True,
1029
+ torch.float32: True,
1030
+ torch.float64: True,
1031
+ torch.complex64: True,
1032
+ torch.complex128: True,
1033
+ torch.uint8: True,
1034
+ torch.uint16: True,
1035
+ torch.uint32: True,
1036
+ torch.uint64: True,
1037
+ torch.int8: True,
1038
+ torch.int16: True,
1039
+ torch.int32: True,
1040
+ torch.int64: True,
1041
+ torch.bool: True,
1042
+ },
1043
+ torch.uint64: {
1044
+ torch.float16: True,
1045
+ torch.float32: True,
1046
+ torch.float64: True,
1047
+ torch.complex64: True,
1048
+ torch.complex128: True,
1049
+ torch.uint8: True,
1050
+ torch.uint16: True,
1051
+ torch.uint32: True,
1052
+ torch.uint64: True,
1053
+ torch.int8: True,
1054
+ torch.int16: True,
1055
+ torch.int32: True,
1056
+ torch.int64: True,
1057
+ torch.bool: True,
1058
+ },
1059
+ torch.int8: {
1060
+ torch.float16: True,
1061
+ torch.float32: True,
1062
+ torch.float64: True,
1063
+ torch.complex64: True,
1064
+ torch.complex128: True,
1065
+ torch.uint8: True,
1066
+ torch.uint16: True,
1067
+ torch.uint32: True,
1068
+ torch.uint64: True,
1069
+ torch.int8: True,
1070
+ torch.int16: True,
1071
+ torch.int32: True,
1072
+ torch.int64: True,
1073
+ torch.bool: True,
1074
+ },
1075
+ torch.int16: {
1076
+ torch.float16: True,
1077
+ torch.float32: True,
1078
+ torch.float64: True,
1079
+ torch.complex64: True,
1080
+ torch.complex128: True,
1081
+ torch.uint8: True,
1082
+ torch.uint16: True,
1083
+ torch.uint32: True,
1084
+ torch.uint64: True,
1085
+ torch.int8: True,
1086
+ torch.int16: True,
1087
+ torch.int32: True,
1088
+ torch.int64: True,
1089
+ torch.bool: True,
1090
+ },
1091
+ torch.int32: {
1092
+ torch.float16: True,
1093
+ torch.float32: True,
1094
+ torch.float64: True,
1095
+ torch.complex64: True,
1096
+ torch.complex128: True,
1097
+ torch.uint8: True,
1098
+ torch.uint16: True,
1099
+ torch.uint32: True,
1100
+ torch.uint64: True,
1101
+ torch.int8: True,
1102
+ torch.int16: True,
1103
+ torch.int32: True,
1104
+ torch.int64: True,
1105
+ torch.bool: True,
1106
+ },
1107
+ torch.int64: {
1108
+ torch.float16: True,
1109
+ torch.float32: True,
1110
+ torch.float64: True,
1111
+ torch.complex64: True,
1112
+ torch.complex128: True,
1113
+ torch.uint8: True,
1114
+ torch.uint16: True,
1115
+ torch.uint32: True,
1116
+ torch.uint64: True,
1117
+ torch.int8: True,
1118
+ torch.int16: True,
1119
+ torch.int32: True,
1120
+ torch.int64: True,
1121
+ torch.bool: True,
1122
+ },
1123
+ torch.bool: {
1124
+ torch.float16: True,
1125
+ torch.float32: True,
1126
+ torch.float64: True,
1127
+ torch.complex64: True,
1128
+ torch.complex128: True,
1129
+ torch.uint8: True,
1130
+ torch.uint16: True,
1131
+ torch.uint32: True,
1132
+ torch.uint64: True,
1133
+ torch.int8: True,
1134
+ torch.int16: True,
1135
+ torch.int32: True,
1136
+ torch.int64: True,
1137
+ torch.bool: True,
1138
+ },
1139
+ },
1140
+ }
1141
+
1142
+
1143
+ _result_type_dict = {
1144
+ torch.float16: {
1145
+ torch.float16: torch.float16,
1146
+ torch.float32: torch.float32,
1147
+ torch.float64: torch.float64,
1148
+ torch.complex64: torch.complex64,
1149
+ torch.complex128: torch.complex128,
1150
+ torch.uint8: torch.float16,
1151
+ torch.uint16: torch.float32,
1152
+ torch.uint32: torch.float64,
1153
+ torch.uint64: torch.float64,
1154
+ torch.int8: torch.float16,
1155
+ torch.int16: torch.float32,
1156
+ torch.int32: torch.float64,
1157
+ torch.int64: torch.float64,
1158
+ torch.bool: torch.float16,
1159
+ },
1160
+ torch.float32: {
1161
+ torch.float16: torch.float32,
1162
+ torch.float32: torch.float32,
1163
+ torch.float64: torch.float64,
1164
+ torch.complex64: torch.complex64,
1165
+ torch.complex128: torch.complex128,
1166
+ torch.uint8: torch.float32,
1167
+ torch.uint16: torch.float32,
1168
+ torch.uint32: torch.float64,
1169
+ torch.uint64: torch.float64,
1170
+ torch.int8: torch.float32,
1171
+ torch.int16: torch.float32,
1172
+ torch.int32: torch.float64,
1173
+ torch.int64: torch.float64,
1174
+ torch.bool: torch.float32,
1175
+ },
1176
+ torch.float64: {
1177
+ torch.float16: torch.float64,
1178
+ torch.float32: torch.float64,
1179
+ torch.float64: torch.float64,
1180
+ torch.complex64: torch.complex128,
1181
+ torch.complex128: torch.complex128,
1182
+ torch.uint8: torch.float64,
1183
+ torch.uint16: torch.float64,
1184
+ torch.uint32: torch.float64,
1185
+ torch.uint64: torch.float64,
1186
+ torch.int8: torch.float64,
1187
+ torch.int16: torch.float64,
1188
+ torch.int32: torch.float64,
1189
+ torch.int64: torch.float64,
1190
+ torch.bool: torch.float64,
1191
+ },
1192
+ torch.complex64: {
1193
+ torch.float16: torch.complex64,
1194
+ torch.float32: torch.complex64,
1195
+ torch.float64: torch.complex128,
1196
+ torch.complex64: torch.complex64,
1197
+ torch.complex128: torch.complex128,
1198
+ torch.uint8: torch.complex64,
1199
+ torch.uint16: torch.complex64,
1200
+ torch.uint32: torch.complex128,
1201
+ torch.uint64: torch.complex128,
1202
+ torch.int8: torch.complex64,
1203
+ torch.int16: torch.complex64,
1204
+ torch.int32: torch.complex128,
1205
+ torch.int64: torch.complex128,
1206
+ torch.bool: torch.complex64,
1207
+ },
1208
+ torch.complex128: {
1209
+ torch.float16: torch.complex128,
1210
+ torch.float32: torch.complex128,
1211
+ torch.float64: torch.complex128,
1212
+ torch.complex64: torch.complex128,
1213
+ torch.complex128: torch.complex128,
1214
+ torch.uint8: torch.complex128,
1215
+ torch.uint16: torch.complex128,
1216
+ torch.uint32: torch.complex128,
1217
+ torch.uint64: torch.complex128,
1218
+ torch.int8: torch.complex128,
1219
+ torch.int16: torch.complex128,
1220
+ torch.int32: torch.complex128,
1221
+ torch.int64: torch.complex128,
1222
+ torch.bool: torch.complex128,
1223
+ },
1224
+ torch.uint8: {
1225
+ torch.float16: torch.float16,
1226
+ torch.float32: torch.float32,
1227
+ torch.float64: torch.float64,
1228
+ torch.complex64: torch.complex64,
1229
+ torch.complex128: torch.complex128,
1230
+ torch.uint8: torch.uint8,
1231
+ torch.uint16: torch.uint16,
1232
+ torch.uint32: torch.uint32,
1233
+ torch.uint64: torch.uint64,
1234
+ torch.int8: torch.int16,
1235
+ torch.int16: torch.int16,
1236
+ torch.int32: torch.int32,
1237
+ torch.int64: torch.int64,
1238
+ torch.bool: torch.uint8,
1239
+ },
1240
+ torch.uint16: {
1241
+ torch.float16: torch.float32,
1242
+ torch.float32: torch.float32,
1243
+ torch.float64: torch.float64,
1244
+ torch.complex64: torch.complex64,
1245
+ torch.complex128: torch.complex128,
1246
+ torch.uint8: torch.uint16,
1247
+ torch.uint16: torch.uint16,
1248
+ torch.uint32: torch.uint32,
1249
+ torch.uint64: torch.uint64,
1250
+ torch.int8: torch.int32,
1251
+ torch.int16: torch.int32,
1252
+ torch.int32: torch.int32,
1253
+ torch.int64: torch.int64,
1254
+ torch.bool: torch.uint16,
1255
+ },
1256
+ torch.uint32: {
1257
+ torch.float16: torch.float64,
1258
+ torch.float32: torch.float64,
1259
+ torch.float64: torch.float64,
1260
+ torch.complex64: torch.complex128,
1261
+ torch.complex128: torch.complex128,
1262
+ torch.uint8: torch.uint32,
1263
+ torch.uint16: torch.uint32,
1264
+ torch.uint32: torch.uint32,
1265
+ torch.uint64: torch.uint64,
1266
+ torch.int8: torch.int64,
1267
+ torch.int16: torch.int64,
1268
+ torch.int32: torch.int64,
1269
+ torch.int64: torch.int64,
1270
+ torch.bool: torch.uint32,
1271
+ },
1272
+ torch.uint64: {
1273
+ torch.float16: torch.float64,
1274
+ torch.float32: torch.float64,
1275
+ torch.float64: torch.float64,
1276
+ torch.complex64: torch.complex128,
1277
+ torch.complex128: torch.complex128,
1278
+ torch.uint8: torch.uint64,
1279
+ torch.uint16: torch.uint64,
1280
+ torch.uint32: torch.uint64,
1281
+ torch.uint64: torch.uint64,
1282
+ torch.int8: torch.float64,
1283
+ torch.int16: torch.float64,
1284
+ torch.int32: torch.float64,
1285
+ torch.int64: torch.float64,
1286
+ torch.bool: torch.uint64,
1287
+ },
1288
+ torch.int8: {
1289
+ torch.float16: torch.float16,
1290
+ torch.float32: torch.float32,
1291
+ torch.float64: torch.float64,
1292
+ torch.complex64: torch.complex64,
1293
+ torch.complex128: torch.complex128,
1294
+ torch.uint8: torch.int16,
1295
+ torch.uint16: torch.int32,
1296
+ torch.uint32: torch.int64,
1297
+ torch.uint64: torch.float64,
1298
+ torch.int8: torch.int8,
1299
+ torch.int16: torch.int16,
1300
+ torch.int32: torch.int32,
1301
+ torch.int64: torch.int64,
1302
+ torch.bool: torch.int8,
1303
+ },
1304
+ torch.int16: {
1305
+ torch.float16: torch.float32,
1306
+ torch.float32: torch.float32,
1307
+ torch.float64: torch.float64,
1308
+ torch.complex64: torch.complex64,
1309
+ torch.complex128: torch.complex128,
1310
+ torch.uint8: torch.int16,
1311
+ torch.uint16: torch.int32,
1312
+ torch.uint32: torch.int64,
1313
+ torch.uint64: torch.float64,
1314
+ torch.int8: torch.int16,
1315
+ torch.int16: torch.int16,
1316
+ torch.int32: torch.int32,
1317
+ torch.int64: torch.int64,
1318
+ torch.bool: torch.int16,
1319
+ },
1320
+ torch.int32: {
1321
+ torch.float16: torch.float64,
1322
+ torch.float32: torch.float64,
1323
+ torch.float64: torch.float64,
1324
+ torch.complex64: torch.complex128,
1325
+ torch.complex128: torch.complex128,
1326
+ torch.uint8: torch.int32,
1327
+ torch.uint16: torch.int32,
1328
+ torch.uint32: torch.int64,
1329
+ torch.uint64: torch.float64,
1330
+ torch.int8: torch.int32,
1331
+ torch.int16: torch.int32,
1332
+ torch.int32: torch.int32,
1333
+ torch.int64: torch.int64,
1334
+ torch.bool: torch.int32,
1335
+ },
1336
+ torch.int64: {
1337
+ torch.float16: torch.float64,
1338
+ torch.float32: torch.float64,
1339
+ torch.float64: torch.float64,
1340
+ torch.complex64: torch.complex128,
1341
+ torch.complex128: torch.complex128,
1342
+ torch.uint8: torch.int64,
1343
+ torch.uint16: torch.int64,
1344
+ torch.uint32: torch.int64,
1345
+ torch.uint64: torch.float64,
1346
+ torch.int8: torch.int64,
1347
+ torch.int16: torch.int64,
1348
+ torch.int32: torch.int64,
1349
+ torch.int64: torch.int64,
1350
+ torch.bool: torch.int64,
1351
+ },
1352
+ torch.bool: {
1353
+ torch.float16: torch.float16,
1354
+ torch.float32: torch.float32,
1355
+ torch.float64: torch.float64,
1356
+ torch.complex64: torch.complex64,
1357
+ torch.complex128: torch.complex128,
1358
+ torch.uint8: torch.uint8,
1359
+ torch.uint16: torch.uint16,
1360
+ torch.uint32: torch.uint32,
1361
+ torch.uint64: torch.uint64,
1362
+ torch.int8: torch.int8,
1363
+ torch.int16: torch.int16,
1364
+ torch.int32: torch.int32,
1365
+ torch.int64: torch.int64,
1366
+ torch.bool: torch.bool,
1367
+ },
1368
+ }
.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Define analogs of numpy dtypes supported by pytorch.
2
+ Define the scalar types and supported dtypes and numpy <--> torch dtype mappings.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import builtins
8
+ from typing import TYPE_CHECKING, TypeGuard, TypeVar
9
+
10
+ import torch
11
+
12
+ from . import _dtypes_impl
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Callable
17
+
18
+ from ._ndarray import ndarray
19
+
20
+
21
+ _T = TypeVar("_T")
22
+
23
+
24
+ # ### Scalar types ###
25
+
26
+
27
+ class generic:
28
+ name = "generic"
29
+ # Concrete scalar types below set these; declared here so the dtype machinery
30
+ # can read them off any scalar type.
31
+ typecode: str
32
+ torch_dtype: torch.dtype
33
+
34
+ def __new__(cls, value: object) -> ndarray:
35
+ # NumPy scalars are modelled as 0-D arrays
36
+ # so a call to np.float32(4) produces a 0-D array.
37
+
38
+ from ._ndarray import asarray, ndarray
39
+
40
+ if isinstance(value, str) and value in ["inf", "nan"]:
41
+ value = {"inf": torch.inf, "nan": torch.nan}[value]
42
+
43
+ if isinstance(value, ndarray):
44
+ return value.astype(cls)
45
+ else:
46
+ return asarray(value, dtype=cls)
47
+
48
+
49
+ ##################
50
+ # abstract types #
51
+ ##################
52
+
53
+
54
+ class number(generic):
55
+ name = "number"
56
+
57
+
58
+ class integer(number):
59
+ name = "integer"
60
+
61
+
62
+ class inexact(number):
63
+ name = "inexact"
64
+
65
+
66
+ class signedinteger(integer):
67
+ name = "signedinteger"
68
+
69
+
70
+ class unsignedinteger(integer):
71
+ name = "unsignedinteger"
72
+
73
+
74
+ class floating(inexact):
75
+ name = "floating"
76
+
77
+
78
+ class complexfloating(inexact):
79
+ name = "complexfloating"
80
+
81
+
82
+ _abstract_dtypes = [
83
+ "generic",
84
+ "number",
85
+ "integer",
86
+ "signedinteger",
87
+ "unsignedinteger",
88
+ "inexact",
89
+ "floating",
90
+ "complexfloating",
91
+ ]
92
+
93
+ # ##### concrete types
94
+
95
+ # signed integers
96
+
97
+
98
+ class int8(signedinteger):
99
+ name = "int8"
100
+ typecode = "b"
101
+ torch_dtype = torch.int8
102
+
103
+
104
+ class int16(signedinteger):
105
+ name = "int16"
106
+ typecode = "h"
107
+ torch_dtype = torch.int16
108
+
109
+
110
+ class int32(signedinteger):
111
+ name = "int32"
112
+ typecode = "i"
113
+ torch_dtype = torch.int32
114
+
115
+
116
+ class int64(signedinteger):
117
+ name = "int64"
118
+ typecode = "l"
119
+ torch_dtype = torch.int64
120
+
121
+
122
+ # unsigned integers
123
+
124
+
125
+ class uint8(unsignedinteger):
126
+ name = "uint8"
127
+ typecode = "B"
128
+ torch_dtype = torch.uint8
129
+
130
+
131
+ class uint16(unsignedinteger):
132
+ name = "uint16"
133
+ typecode = "H"
134
+ torch_dtype = torch.uint16
135
+
136
+
137
+ class uint32(signedinteger):
138
+ name = "uint32"
139
+ typecode = "I"
140
+ torch_dtype = torch.uint32
141
+
142
+
143
+ class uint64(signedinteger):
144
+ name = "uint64"
145
+ typecode = "L"
146
+ torch_dtype = torch.uint64
147
+
148
+
149
+ # floating point
150
+
151
+
152
+ class float16(floating):
153
+ name = "float16"
154
+ typecode = "e"
155
+ torch_dtype = torch.float16
156
+
157
+
158
+ class float32(floating):
159
+ name = "float32"
160
+ typecode = "f"
161
+ torch_dtype = torch.float32
162
+
163
+
164
+ class float64(floating):
165
+ name = "float64"
166
+ typecode = "d"
167
+ torch_dtype = torch.float64
168
+
169
+
170
+ class complex64(complexfloating):
171
+ name = "complex64"
172
+ typecode = "F"
173
+ torch_dtype = torch.complex64
174
+
175
+
176
+ class complex128(complexfloating):
177
+ name = "complex128"
178
+ typecode = "D"
179
+ torch_dtype = torch.complex128
180
+
181
+
182
+ class bool_(generic):
183
+ name = "bool_"
184
+ typecode = "?"
185
+ torch_dtype = torch.bool
186
+
187
+
188
+ # name aliases
189
+ _name_aliases = {
190
+ "intp": int64,
191
+ "int_": int64,
192
+ "intc": int32,
193
+ "byte": int8,
194
+ "short": int16,
195
+ "longlong": int64, # XXX: is this correct?
196
+ "ulonglong": uint64,
197
+ "ubyte": uint8,
198
+ "half": float16,
199
+ "single": float32,
200
+ "double": float64,
201
+ "float_": float64,
202
+ "csingle": complex64,
203
+ "singlecomplex": complex64,
204
+ "cdouble": complex128,
205
+ "cfloat": complex128,
206
+ "complex_": complex128,
207
+ }
208
+ # We register float_ = float32 and so on
209
+ for name, obj in _name_aliases.items():
210
+ vars()[name] = obj
211
+
212
+
213
+ # Replicate this NumPy-defined way of grouping scalar types,
214
+ # cf tests/core/test_scalar_methods.py
215
+ sctypes = {
216
+ "int": [int8, int16, int32, int64],
217
+ "uint": [uint8, uint16, uint32, uint64],
218
+ "float": [float16, float32, float64],
219
+ "complex": [complex64, complex128],
220
+ "others": [bool_],
221
+ }
222
+
223
+
224
+ # Support mappings/functions
225
+
226
+ _names = {st.name: st for cat in sctypes for st in sctypes[cat]}
227
+ _typecodes = {st.typecode: st for cat in sctypes for st in sctypes[cat]}
228
+ _torch_dtypes = {st.torch_dtype: st for cat in sctypes for st in sctypes[cat]}
229
+
230
+
231
+ _aliases = {
232
+ "u1": uint8,
233
+ "i1": int8,
234
+ "i2": int16,
235
+ "i4": int32,
236
+ "i8": int64,
237
+ "b": int8, # XXX: srsly?
238
+ "f2": float16,
239
+ "f4": float32,
240
+ "f8": float64,
241
+ "c8": complex64,
242
+ "c16": complex128,
243
+ # numpy-specific trailing underscore
244
+ "bool_": bool_,
245
+ }
246
+
247
+
248
+ _python_types = {
249
+ int: int64,
250
+ float: float64,
251
+ complex: complex128,
252
+ builtins.bool: bool_,
253
+ # also allow stringified names of python types
254
+ int.__name__: int64,
255
+ float.__name__: float64,
256
+ complex.__name__: complex128,
257
+ builtins.bool.__name__: bool_,
258
+ }
259
+
260
+
261
+ def sctype_from_string(s: object) -> type[generic]:
262
+ """Normalize a string value: a type 'name' or a typecode or a width alias."""
263
+ if s in _names:
264
+ return _names[s]
265
+ if s in _name_aliases:
266
+ return _name_aliases[s]
267
+ if s in _typecodes:
268
+ return _typecodes[s]
269
+ if s in _aliases:
270
+ return _aliases[s]
271
+ if s in _python_types:
272
+ return _python_types[s]
273
+ raise TypeError(f"data type {s!r} not understood")
274
+
275
+
276
+ def sctype_from_torch_dtype(torch_dtype: torch.dtype) -> type[generic]:
277
+ return _torch_dtypes[torch_dtype]
278
+
279
+
280
+ # ### DTypes. ###
281
+
282
+
283
+ def dtype(arg: object) -> DType:
284
+ if arg is None:
285
+ arg = _dtypes_impl.default_dtypes().float_dtype
286
+ return DType(arg)
287
+
288
+
289
+ class DType:
290
+ _scalar_type: type[generic]
291
+
292
+ def __init__(self, arg: object) -> None:
293
+ # a pytorch object?
294
+ if isinstance(arg, torch.dtype):
295
+ sctype = _torch_dtypes[arg]
296
+ elif isinstance(arg, torch.Tensor):
297
+ sctype = _torch_dtypes[arg.dtype]
298
+ # a scalar type?
299
+ elif issubclass_(arg, generic):
300
+ sctype = arg
301
+ # a dtype already?
302
+ elif isinstance(arg, DType):
303
+ sctype = arg._scalar_type
304
+ # a has a right attribute?
305
+ elif hasattr(arg, "dtype"):
306
+ sctype = arg.dtype._scalar_type
307
+ else:
308
+ sctype = sctype_from_string(arg)
309
+ self._scalar_type = sctype
310
+
311
+ @property
312
+ def name(self) -> str:
313
+ return self._scalar_type.name
314
+
315
+ @property
316
+ def type(self) -> type[generic]:
317
+ return self._scalar_type
318
+
319
+ @property
320
+ def kind(self) -> str:
321
+ # https://numpy.org/doc/stable/reference/generated/numpy.dtype.kind.html
322
+ return _torch_dtypes[self.torch_dtype].name[0]
323
+
324
+ @property
325
+ def typecode(self) -> str:
326
+ return self._scalar_type.typecode
327
+
328
+ def __eq__(self, other: object) -> bool:
329
+ if isinstance(other, DType):
330
+ return self._scalar_type == other._scalar_type
331
+ try:
332
+ other_instance = DType(other)
333
+ except TypeError:
334
+ return False
335
+ return self._scalar_type == other_instance._scalar_type
336
+
337
+ @property
338
+ def torch_dtype(self) -> torch.dtype:
339
+ return self._scalar_type.torch_dtype
340
+
341
+ def __hash__(self) -> int:
342
+ return hash(self._scalar_type.name)
343
+
344
+ def __repr__(self) -> str:
345
+ return f'dtype("{self.name}")'
346
+
347
+ __str__ = __repr__
348
+
349
+ @property
350
+ def itemsize(self) -> int:
351
+ elem = self.type(1)
352
+ return elem.tensor.element_size()
353
+
354
+ def __getstate__(self) -> builtins.type[generic]:
355
+ return self._scalar_type
356
+
357
+ def __setstate__(self, value: builtins.type[generic]) -> None:
358
+ self._scalar_type = value
359
+
360
+
361
+ typecodes = {
362
+ "All": "efdFDBbhil?",
363
+ "AllFloat": "efdFD",
364
+ "AllInteger": "Bbhil",
365
+ "Integer": "bhil",
366
+ "UnsignedInteger": "B",
367
+ "Float": "efd",
368
+ "Complex": "FD",
369
+ }
370
+
371
+
372
+ # ### Defaults and dtype discovery
373
+
374
+
375
+ def set_default_dtype(
376
+ fp_dtype: object = "numpy", int_dtype: object = "numpy"
377
+ ) -> Callable[[], _dtypes_impl.DefaultDTypes]:
378
+ """Set the (global) defaults for fp, complex, and int dtypes.
379
+
380
+ The complex dtype is inferred from the float (fp) dtype. It has
381
+ a width at least twice the width of the float dtype,
382
+ i.e., it's complex128 for float64 and complex64 for float32.
383
+
384
+ Parameters
385
+ ----------
386
+ fp_dtype
387
+ Allowed values are "numpy", "pytorch" or dtype_like things which
388
+ can be converted into a DType instance.
389
+ Default is "numpy" (i.e. float64).
390
+ int_dtype
391
+ Allowed values are "numpy", "pytorch" or dtype_like things which
392
+ can be converted into a DType instance.
393
+ Default is "numpy" (i.e. int64).
394
+
395
+ Returns
396
+ -------
397
+ The old default dtype state: a namedtuple with attributes ``float_dtype``,
398
+ ``complex_dtypes`` and ``int_dtype``. These attributes store *pytorch*
399
+ dtypes.
400
+
401
+ Notes
402
+ ------------
403
+ This function has a side effect: it sets the global state with the provided dtypes.
404
+
405
+ The complex dtype has bit width of at least twice the width of the float
406
+ dtype, i.e. it's complex128 for float64 and complex64 for float32.
407
+
408
+ """
409
+ if fp_dtype not in ["numpy", "pytorch"]:
410
+ fp_dtype = dtype(fp_dtype).torch_dtype
411
+ if int_dtype not in ["numpy", "pytorch"]:
412
+ int_dtype = dtype(int_dtype).torch_dtype
413
+
414
+ if fp_dtype == "numpy":
415
+ float_dtype = torch.float64
416
+ elif fp_dtype == "pytorch":
417
+ float_dtype = torch.float32
418
+ else:
419
+ float_dtype = fp_dtype
420
+
421
+ complex_dtype = {
422
+ torch.float64: torch.complex128,
423
+ torch.float32: torch.complex64,
424
+ torch.float16: torch.complex64,
425
+ }[float_dtype]
426
+
427
+ if int_dtype in ["numpy", "pytorch"]:
428
+ int_dtype = torch.int64
429
+
430
+ new_defaults = _dtypes_impl.DefaultDTypes(
431
+ float_dtype=float_dtype, complex_dtype=complex_dtype, int_dtype=int_dtype
432
+ )
433
+
434
+ # set the new global state and return the old state
435
+ old_defaults = _dtypes_impl.default_dtypes
436
+ # pyrefly: ignore[bad-assignment] # TODO
437
+ _dtypes_impl._default_dtypes = new_defaults
438
+ return old_defaults
439
+
440
+
441
+ def issubclass_(arg: object, klass: type[_T]) -> TypeGuard[type[_T]]:
442
+ # issubclass() raises TypeError if arg is not a class; guard explicitly so a
443
+ # non-class arg returns False (and narrows arg to type[_T] on success).
444
+ return isinstance(arg, type) and issubclass(arg, klass)
445
+
446
+
447
+ def issubdtype(arg1: object, arg2: object) -> bool:
448
+ # cf https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numerictypes.py#L356-L420
449
+
450
+ # We also accept strings even if NumPy doesn't as dtypes are serialized as their
451
+ # string representation in dynamo's graph
452
+ def str_to_abstract(t: object) -> object:
453
+ if isinstance(t, str) and t in _abstract_dtypes:
454
+ return globals()[t]
455
+ return t
456
+
457
+ arg1 = str_to_abstract(arg1)
458
+ arg2 = str_to_abstract(arg2)
459
+
460
+ if not issubclass_(arg1, generic):
461
+ arg1 = dtype(arg1).type
462
+ if not issubclass_(arg2, generic):
463
+ arg2 = dtype(arg2).type
464
+ return issubclass(arg1, arg2)
465
+
466
+
467
+ __all__ = ["dtype", "DType", "typecodes", "issubdtype", "set_default_dtype", "sctypes"]
468
+ __all__ += list(_names.keys())
469
+ __all__ += list(_name_aliases.keys())
470
+ __all__ += _abstract_dtypes # noqa: PLE0605
.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes_impl.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """Dtypes/scalar type implementations with torch dtypes.
4
+
5
+ Here `dtype` is always a torch.dtype, this module knows nothing about
6
+ scalar types, wrapper dtypes or anything like that. PyTorch only.
7
+ """
8
+
9
+ from collections import namedtuple
10
+
11
+ import torch
12
+
13
+
14
+ # defaults : mimic NumPy, allow user control
15
+ DefaultDTypes = namedtuple(
16
+ "DefaultDTypes", ["float_dtype", "complex_dtype", "int_dtype"]
17
+ )
18
+
19
+ # a global state
20
+ # We set it the first time we call default_dtypes() to avoid importing
21
+ # torch._dynamo.config and create a circular reference
22
+ _default_dtypes = None
23
+
24
+
25
+ def default_dtypes():
26
+ global _default_dtypes
27
+ if _default_dtypes is None:
28
+ import torch._dynamo.config as config
29
+
30
+ _default_dtypes = DefaultDTypes(
31
+ float_dtype=getattr(torch, config.numpy_default_float),
32
+ complex_dtype=getattr(torch, config.numpy_default_complex),
33
+ int_dtype=getattr(torch, config.numpy_default_int),
34
+ )
35
+ if not isinstance(_default_dtypes.float_dtype, torch.dtype):
36
+ raise AssertionError(
37
+ f"float_dtype must be a torch.dtype, got {type(_default_dtypes.float_dtype)}"
38
+ )
39
+ if not isinstance(_default_dtypes.complex_dtype, torch.dtype):
40
+ raise AssertionError(
41
+ f"complex_dtype must be a torch.dtype, got {type(_default_dtypes.complex_dtype)}"
42
+ )
43
+ if not isinstance(_default_dtypes.int_dtype, torch.dtype):
44
+ raise AssertionError(
45
+ f"int_dtype must be a torch.dtype, got {type(_default_dtypes.int_dtype)}"
46
+ )
47
+ return _default_dtypes
48
+
49
+
50
+ def get_default_dtype_for(dtype):
51
+ """Default scalar type given sctype category."""
52
+ if dtype == torch.bool:
53
+ return dtype
54
+ if dtype.is_complex:
55
+ return default_dtypes().complex_dtype
56
+ if dtype.is_floating_point:
57
+ return default_dtypes().float_dtype
58
+ # else, it must be (some) integer
59
+ return default_dtypes().int_dtype
60
+
61
+
62
+ from . import _casting_dicts as _cd
63
+
64
+
65
+ def can_cast_impl(from_torch_dtype, to_torch_dtype, casting):
66
+ return _cd._can_cast_dict[casting][from_torch_dtype][to_torch_dtype]
67
+
68
+
69
+ def result_type_impl(*tensors):
70
+ # NB: torch dtypes here
71
+ dtyp = tensors[0].dtype
72
+ if len(tensors) == 1:
73
+ return dtyp
74
+
75
+ for curr in tensors[1:]:
76
+ dtyp = _cd._result_type_dict[dtyp][curr.dtype]
77
+
78
+ return dtyp
79
+
80
+
81
+ def python_type_for_torch(dtyp):
82
+ """Get a python scalar type a torch dtype"""
83
+ if dtyp.is_floating_point:
84
+ typ = float
85
+ elif dtyp.is_complex:
86
+ typ = complex
87
+ elif dtyp == torch.bool:
88
+ typ = bool
89
+ else:
90
+ typ = int
91
+ return typ
92
+
93
+
94
+ # ### NEP 50 helpers ###
95
+
96
+ _SCALAR_TYPES = (int, bool, float, complex)
97
+
98
+ _SCALAR_AND_SYMBOLIC_TYPES = (
99
+ *_SCALAR_TYPES,
100
+ torch.SymInt,
101
+ torch.SymFloat,
102
+ torch.SymBool,
103
+ )
104
+
105
+ _NEP50_FUNCS_TENSOR_ONLY = (
106
+ "minimum",
107
+ "maximum",
108
+ "logaddexp",
109
+ "logaddexp2",
110
+ "lcm",
111
+ "gcd",
112
+ "hypot",
113
+ "heaviside",
114
+ "fmod",
115
+ "fmin",
116
+ "fmax",
117
+ "copysign",
118
+ "arctan2",
119
+ )
120
+
121
+
122
+ def is_scalar(x):
123
+ return isinstance(x, _SCALAR_TYPES)
124
+
125
+
126
+ def is_scalar_or_symbolic(x):
127
+ return isinstance(x, _SCALAR_AND_SYMBOLIC_TYPES)
128
+
129
+
130
+ def _dtype_for_scalar(py_type):
131
+ return {
132
+ bool: torch.bool,
133
+ torch.SymBool: torch.bool,
134
+ int: torch.int64,
135
+ torch.SymInt: torch.int64,
136
+ float: torch.float64,
137
+ torch.SymFloat: torch.float64,
138
+ complex: torch.complex128,
139
+ }[py_type]
140
+
141
+
142
+ def _dtype_for_scalar_or_tensor(x):
143
+ return x.dtype if isinstance(x, torch.Tensor) else _dtype_for_scalar(type(x))
144
+
145
+
146
+ def is_float_or_fp_tensor(x):
147
+ return _dtype_for_scalar_or_tensor(x).is_floating_point
148
+
149
+
150
+ def is_complex_or_complex_tensor(x):
151
+ return _dtype_for_scalar_or_tensor(x).is_complex
152
+
153
+
154
+ def _category(dtype):
155
+ return {
156
+ torch.bool: 0,
157
+ torch.SymBool: 0,
158
+ # int
159
+ torch.uint8: 1,
160
+ torch.int8: 1,
161
+ torch.int16: 1,
162
+ torch.int32: 1,
163
+ torch.int64: 1,
164
+ torch.SymInt: 1,
165
+ # float
166
+ torch.float16: 2,
167
+ torch.float32: 2,
168
+ torch.float64: 2,
169
+ torch.SymFloat: 2,
170
+ # complex
171
+ torch.complex64: 3,
172
+ torch.complex128: 3,
173
+ }[dtype]
174
+
175
+
176
+ def nep50_to_tensors(x1, x2, handle_weaks, function_name):
177
+ """If either of inputs is a python scalar, type-promote with NEP 50."""
178
+
179
+ def to_tensor(scalar, dtype=None):
180
+ if dtype is None:
181
+ dtype = _dtype_for_scalar(type(scalar))
182
+ dtype = get_default_dtype_for(dtype)
183
+ return torch.as_tensor(scalar, dtype=dtype)
184
+
185
+ x1_is_weak = not isinstance(x1, torch.Tensor)
186
+ x2_is_weak = not isinstance(x2, torch.Tensor)
187
+ if not handle_weaks or (x1_is_weak and x2_is_weak):
188
+ x1 = to_tensor(x1) if x1_is_weak else x1
189
+ x2 = to_tensor(x2) if x2_is_weak else x2
190
+ return x1, x2
191
+
192
+ # scalar <op> tensor: NEP 50
193
+ if x1_is_weak == x2_is_weak:
194
+ raise AssertionError(
195
+ f"Expected exactly one weak type, got x1_is_weak={x1_is_weak}, x2_is_weak={x2_is_weak}"
196
+ )
197
+
198
+ weak, not_weak = (x1, x2) if x1_is_weak else (x2, x1)
199
+
200
+ # find the dtype for the weak's type
201
+ weak_dtype = _dtype_for_scalar(type(weak))
202
+
203
+ cat_weak = _category(weak_dtype)
204
+ cat_not_weak = _category(not_weak.dtype)
205
+
206
+ dt = not_weak.dtype if cat_weak <= cat_not_weak else None
207
+
208
+ # special-case complex + float32
209
+ if weak_dtype.is_complex and not_weak.dtype == torch.float32:
210
+ dt = torch.complex64
211
+
212
+ # detect overflows: in PyTorch, uint8(-1) wraps around to 255,
213
+ # while NEP50 mandates an exception.
214
+ #
215
+ # Note that we only check if each element of the binop overflows,
216
+ # not the result. Consider, e.g. `uint8(100) + 200`. Operands are OK
217
+ # in uint8, but the result overflows and wrap around 255.
218
+ # Numpy emits a RuntimeWarning, PyTorch does not, and we do not either.
219
+ if cat_weak == 1 and cat_not_weak == 1:
220
+ # integers
221
+ iinfo = torch.iinfo(not_weak.dtype)
222
+ if not (iinfo.min <= weak <= iinfo.max):
223
+ raise OverflowError(
224
+ f"Python integer {weak} out of bounds for {not_weak.dtype}"
225
+ )
226
+ if weak_dtype != dt or function_name in _NEP50_FUNCS_TENSOR_ONLY:
227
+ # finally, can make `weak` into a 0D tensor, if both parameters are required to be tensor.
228
+ weak = to_tensor(weak, dt)
229
+
230
+ return (weak, not_weak) if x1_is_weak else (not_weak, weak)
.venv/lib/python3.12/site-packages/torch/_numpy/_funcs.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import inspect
4
+ import itertools
5
+
6
+ from . import _funcs_impl, _reductions_impl
7
+ from ._normalizations import normalizer
8
+
9
+
10
+ # _funcs_impl.py contains functions which mimic NumPy's eponymous equivalents,
11
+ # and consume/return PyTorch tensors/dtypes.
12
+ # They are also type annotated.
13
+ # Pull these functions from _funcs_impl and decorate them with @normalizer, which
14
+ # - Converts any input `np.ndarray`, `torch._numpy.ndarray`, list of lists, Python scalars, etc into a `torch.Tensor`.
15
+ # - Maps NumPy dtypes to PyTorch dtypes
16
+ # - If the input to the `axis` kwarg is an ndarray, it maps it into a tuple
17
+ # - Implements the semantics for the `out=` arg
18
+ # - Wraps back the outputs into `torch._numpy.ndarrays`
19
+
20
+
21
+ def _public_functions(mod):
22
+ def is_public_function(f):
23
+ return inspect.isfunction(f) and not f.__name__.startswith("_")
24
+
25
+ return inspect.getmembers(mod, is_public_function)
26
+
27
+
28
+ # We fill in __all__ in the loop below
29
+ __all__ = []
30
+
31
+ # decorate implementer functions with argument normalizers and export to the top namespace
32
+ for name, func in itertools.chain(
33
+ _public_functions(_funcs_impl), _public_functions(_reductions_impl)
34
+ ):
35
+ if name in ["percentile", "quantile", "median"]:
36
+ decorated = normalizer(func, promote_scalar_result=True)
37
+ elif name == "einsum":
38
+ # normalized manually
39
+ decorated = func
40
+ else:
41
+ decorated = normalizer(func)
42
+
43
+ decorated.__qualname__ = name
44
+ decorated.__name__ = name
45
+ vars()[name] = decorated
46
+ __all__.append(name)
47
+
48
+
49
+ """
50
+ Vendored objects from numpy.lib.index_tricks
51
+ """
52
+
53
+
54
+ class IndexExpression:
55
+ """
56
+ Written by Konrad Hinsen <hinsen@cnrs-orleans.fr>
57
+ last revision: 1999-7-23
58
+
59
+ Cosmetic changes by T. Oliphant 2001
60
+ """
61
+
62
+ def __init__(self, maketuple):
63
+ self.maketuple = maketuple
64
+
65
+ def __getitem__(self, item):
66
+ if self.maketuple and not isinstance(item, tuple):
67
+ return (item,)
68
+ else:
69
+ return item
70
+
71
+
72
+ index_exp = IndexExpression(maketuple=True)
73
+ s_ = IndexExpression(maketuple=False)
74
+
75
+
76
+ __all__ += ["index_exp", "s_"]
.venv/lib/python3.12/site-packages/torch/_numpy/_funcs_impl.py ADDED
@@ -0,0 +1,2064 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """A thin pytorch / numpy compat layer.
4
+
5
+ Things imported from here have numpy-compatible signatures but operate on
6
+ pytorch tensors.
7
+ """
8
+
9
+ # Contents of this module ends up in the main namespace via _funcs.py
10
+ # where type annotations are used in conjunction with the @normalizer decorator.
11
+ from __future__ import annotations
12
+
13
+ import builtins
14
+ import itertools
15
+ import operator
16
+ from typing import TYPE_CHECKING
17
+
18
+ import torch
19
+
20
+ from . import _dtypes_impl, _util
21
+
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Sequence
25
+
26
+ from ._normalizations import (
27
+ ArrayLike,
28
+ ArrayLikeOrScalar,
29
+ CastingModes,
30
+ DTypeLike,
31
+ NDArray,
32
+ NotImplementedType,
33
+ OutArray,
34
+ )
35
+
36
+
37
+ def copy(
38
+ a: ArrayLike, order: NotImplementedType = "K", subok: NotImplementedType = False
39
+ ):
40
+ return a.clone()
41
+
42
+
43
+ def copyto(
44
+ dst: NDArray,
45
+ src: ArrayLike,
46
+ casting: CastingModes | None = "same_kind",
47
+ where: NotImplementedType = None,
48
+ ):
49
+ (src,) = _util.typecast_tensors((src,), dst.dtype, casting=casting)
50
+ dst.copy_(src)
51
+
52
+
53
+ def atleast_1d(*arys: ArrayLike):
54
+ res = torch.atleast_1d(*arys)
55
+ if isinstance(res, tuple):
56
+ return list(res)
57
+ else:
58
+ return res
59
+
60
+
61
+ def atleast_2d(*arys: ArrayLike):
62
+ res = torch.atleast_2d(*arys)
63
+ if isinstance(res, tuple):
64
+ return list(res)
65
+ else:
66
+ return res
67
+
68
+
69
+ def atleast_3d(*arys: ArrayLike):
70
+ res = torch.atleast_3d(*arys)
71
+ if isinstance(res, tuple):
72
+ return list(res)
73
+ else:
74
+ return res
75
+
76
+
77
+ def _concat_check(tup, dtype, out):
78
+ if tup == ():
79
+ raise ValueError("need at least one array to concatenate")
80
+
81
+ """Check inputs in concatenate et al."""
82
+ if out is not None and dtype is not None:
83
+ # mimic numpy
84
+ raise TypeError(
85
+ "concatenate() only takes `out` or `dtype` as an "
86
+ "argument, but both were provided."
87
+ )
88
+
89
+
90
+ def _concat_cast_helper(tensors, out=None, dtype=None, casting="same_kind"):
91
+ """Figure out dtypes, cast if necessary."""
92
+
93
+ if out is not None or dtype is not None:
94
+ # figure out the type of the inputs and outputs
95
+ out_dtype = out.dtype.torch_dtype if dtype is None else dtype
96
+ else:
97
+ out_dtype = _dtypes_impl.result_type_impl(*tensors)
98
+
99
+ # cast input arrays if necessary; do not broadcast them against `out`
100
+ tensors = _util.typecast_tensors(tensors, out_dtype, casting)
101
+
102
+ return tensors
103
+
104
+
105
+ def _concatenate(
106
+ tensors, axis=0, out=None, dtype=None, casting: CastingModes | None = "same_kind"
107
+ ):
108
+ # pure torch implementation, used below and in cov/corrcoef below
109
+ tensors, axis = _util.axis_none_flatten(*tensors, axis=axis)
110
+ tensors = _concat_cast_helper(tensors, out, dtype, casting)
111
+ return torch.cat(tensors, axis)
112
+
113
+
114
+ def concatenate(
115
+ ar_tuple: Sequence[ArrayLike],
116
+ axis=0,
117
+ out: OutArray | None = None,
118
+ dtype: DTypeLike | None = None,
119
+ casting: CastingModes | None = "same_kind",
120
+ ):
121
+ _concat_check(ar_tuple, dtype, out=out)
122
+ result = _concatenate(ar_tuple, axis=axis, out=out, dtype=dtype, casting=casting)
123
+ return result
124
+
125
+
126
+ def vstack(
127
+ tup: Sequence[ArrayLike],
128
+ *,
129
+ dtype: DTypeLike | None = None,
130
+ casting: CastingModes | None = "same_kind",
131
+ ):
132
+ _concat_check(tup, dtype, out=None)
133
+ tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
134
+ return torch.vstack(tensors)
135
+
136
+
137
+ row_stack = vstack
138
+
139
+
140
+ def hstack(
141
+ tup: Sequence[ArrayLike],
142
+ *,
143
+ dtype: DTypeLike | None = None,
144
+ casting: CastingModes | None = "same_kind",
145
+ ):
146
+ _concat_check(tup, dtype, out=None)
147
+ tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
148
+ return torch.hstack(tensors)
149
+
150
+
151
+ def dstack(
152
+ tup: Sequence[ArrayLike],
153
+ *,
154
+ dtype: DTypeLike | None = None,
155
+ casting: CastingModes | None = "same_kind",
156
+ ):
157
+ # XXX: in numpy 1.24 dstack does not have dtype and casting keywords
158
+ # but {h,v}stack do. Hence add them here for consistency.
159
+ _concat_check(tup, dtype, out=None)
160
+ tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
161
+ return torch.dstack(tensors)
162
+
163
+
164
+ def column_stack(
165
+ tup: Sequence[ArrayLike],
166
+ *,
167
+ dtype: DTypeLike | None = None,
168
+ casting: CastingModes | None = "same_kind",
169
+ ):
170
+ # XXX: in numpy 1.24 column_stack does not have dtype and casting keywords
171
+ # but row_stack does. (because row_stack is an alias for vstack, really).
172
+ # Hence add these keywords here for consistency.
173
+ _concat_check(tup, dtype, out=None)
174
+ tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
175
+ return torch.column_stack(tensors)
176
+
177
+
178
+ def stack(
179
+ arrays: Sequence[ArrayLike],
180
+ axis=0,
181
+ out: OutArray | None = None,
182
+ *,
183
+ dtype: DTypeLike | None = None,
184
+ casting: CastingModes | None = "same_kind",
185
+ ):
186
+ _concat_check(arrays, dtype, out=out)
187
+
188
+ tensors = _concat_cast_helper(arrays, dtype=dtype, casting=casting)
189
+ result_ndim = tensors[0].ndim + 1
190
+ axis = _util.normalize_axis_index(axis, result_ndim)
191
+ return torch.stack(tensors, axis=axis)
192
+
193
+
194
+ def append(arr: ArrayLike, values: ArrayLike, axis=None):
195
+ if axis is None:
196
+ if arr.ndim != 1:
197
+ arr = arr.flatten()
198
+ values = values.flatten()
199
+ axis = arr.ndim - 1
200
+ return _concatenate((arr, values), axis=axis)
201
+
202
+
203
+ # ### split ###
204
+
205
+
206
+ def _split_helper(tensor, indices_or_sections, axis, strict=False):
207
+ if isinstance(indices_or_sections, int):
208
+ return _split_helper_int(tensor, indices_or_sections, axis, strict)
209
+ elif isinstance(indices_or_sections, (list, tuple)):
210
+ # NB: drop split=..., it only applies to split_helper_int
211
+ return _split_helper_list(tensor, list(indices_or_sections), axis)
212
+ else:
213
+ raise TypeError(f"split_helper: {type(indices_or_sections)}")
214
+
215
+
216
+ def _split_helper_int(tensor, indices_or_sections, axis, strict=False):
217
+ if not isinstance(indices_or_sections, int):
218
+ raise NotImplementedError("split: indices_or_sections")
219
+
220
+ axis = _util.normalize_axis_index(axis, tensor.ndim)
221
+
222
+ # numpy: l%n chunks of size (l//n + 1), the rest are sized l//n
223
+ l, n = tensor.shape[axis], indices_or_sections
224
+
225
+ if n <= 0:
226
+ raise ValueError
227
+
228
+ if l % n == 0:
229
+ num, sz = n, l // n
230
+ lst = [sz] * num
231
+ else:
232
+ if strict:
233
+ raise ValueError("array split does not result in an equal division")
234
+
235
+ num, sz = l % n, l // n + 1
236
+ lst = [sz] * num
237
+
238
+ lst += [sz - 1] * (n - num)
239
+
240
+ return torch.split(tensor, lst, axis)
241
+
242
+
243
+ def _split_helper_list(tensor, indices_or_sections, axis):
244
+ if not isinstance(indices_or_sections, list):
245
+ raise NotImplementedError("split: indices_or_sections: list")
246
+ # numpy expects indices, while torch expects lengths of sections
247
+ # also, numpy appends zero-size arrays for indices above the shape[axis]
248
+ lst = [x for x in indices_or_sections if x <= tensor.shape[axis]]
249
+ num_extra = len(indices_or_sections) - len(lst)
250
+
251
+ lst.append(tensor.shape[axis])
252
+ lst = [
253
+ lst[0],
254
+ ] + [a - b for a, b in zip(lst[1:], lst[:-1])]
255
+ lst += [0] * num_extra
256
+
257
+ return torch.split(tensor, lst, axis)
258
+
259
+
260
+ def array_split(ary: ArrayLike, indices_or_sections, axis=0):
261
+ return _split_helper(ary, indices_or_sections, axis)
262
+
263
+
264
+ def split(ary: ArrayLike, indices_or_sections, axis=0):
265
+ return _split_helper(ary, indices_or_sections, axis, strict=True)
266
+
267
+
268
+ def hsplit(ary: ArrayLike, indices_or_sections):
269
+ if ary.ndim == 0:
270
+ raise ValueError("hsplit only works on arrays of 1 or more dimensions")
271
+ axis = 1 if ary.ndim > 1 else 0
272
+ return _split_helper(ary, indices_or_sections, axis, strict=True)
273
+
274
+
275
+ def vsplit(ary: ArrayLike, indices_or_sections):
276
+ if ary.ndim < 2:
277
+ raise ValueError("vsplit only works on arrays of 2 or more dimensions")
278
+ return _split_helper(ary, indices_or_sections, 0, strict=True)
279
+
280
+
281
+ def dsplit(ary: ArrayLike, indices_or_sections):
282
+ if ary.ndim < 3:
283
+ raise ValueError("dsplit only works on arrays of 3 or more dimensions")
284
+ return _split_helper(ary, indices_or_sections, 2, strict=True)
285
+
286
+
287
+ def kron(a: ArrayLike, b: ArrayLike):
288
+ return torch.kron(a, b)
289
+
290
+
291
+ def vander(x: ArrayLike, N=None, increasing=False):
292
+ return torch.vander(x, N, increasing)
293
+
294
+
295
+ # ### linspace, geomspace, logspace and arange ###
296
+
297
+
298
+ def linspace(
299
+ start: ArrayLike,
300
+ stop: ArrayLike,
301
+ num=50,
302
+ endpoint=True,
303
+ retstep=False,
304
+ dtype: DTypeLike | None = None,
305
+ axis=0,
306
+ ):
307
+ if axis != 0 or retstep or not endpoint:
308
+ raise NotImplementedError
309
+ if dtype is None:
310
+ dtype = _dtypes_impl.default_dtypes().float_dtype
311
+ # XXX: raises TypeError if start or stop are not scalars
312
+ return torch.linspace(start, stop, num, dtype=dtype)
313
+
314
+
315
+ def geomspace(
316
+ start: ArrayLike,
317
+ stop: ArrayLike,
318
+ num=50,
319
+ endpoint=True,
320
+ dtype: DTypeLike | None = None,
321
+ axis=0,
322
+ ):
323
+ if axis != 0 or not endpoint:
324
+ raise NotImplementedError
325
+ base = torch.pow(stop / start, 1.0 / (num - 1))
326
+ logbase = torch.log(base)
327
+ return torch.logspace(
328
+ torch.log(start) / logbase,
329
+ torch.log(stop) / logbase,
330
+ num,
331
+ base=base,
332
+ )
333
+
334
+
335
+ def logspace(
336
+ start,
337
+ stop,
338
+ num=50,
339
+ endpoint=True,
340
+ base=10.0,
341
+ dtype: DTypeLike | None = None,
342
+ axis=0,
343
+ ):
344
+ if axis != 0 or not endpoint:
345
+ raise NotImplementedError
346
+ return torch.logspace(start, stop, num, base=base, dtype=dtype)
347
+
348
+
349
+ def arange(
350
+ start: ArrayLikeOrScalar | None = None,
351
+ stop: ArrayLikeOrScalar | None = None,
352
+ step: ArrayLikeOrScalar | None = 1,
353
+ dtype: DTypeLike | None = None,
354
+ *,
355
+ like: NotImplementedType = None,
356
+ ):
357
+ if step == 0:
358
+ raise ZeroDivisionError
359
+ if stop is None and start is None:
360
+ raise TypeError
361
+ if stop is None:
362
+ # XXX: this breaks if start is passed as a kwarg:
363
+ # arange(start=4) should raise (no stop) but doesn't
364
+ start, stop = 0, start
365
+ if start is None:
366
+ start = 0
367
+
368
+ # the dtype of the result
369
+ if dtype is None:
370
+ dtype = (
371
+ _dtypes_impl.default_dtypes().float_dtype
372
+ if any(_dtypes_impl.is_float_or_fp_tensor(x) for x in (start, stop, step))
373
+ else _dtypes_impl.default_dtypes().int_dtype
374
+ )
375
+ work_dtype = torch.float64 if dtype.is_complex else dtype
376
+
377
+ # RuntimeError: "lt_cpu" not implemented for 'ComplexFloat'. Fall back to eager.
378
+ if any(_dtypes_impl.is_complex_or_complex_tensor(x) for x in (start, stop, step)):
379
+ raise NotImplementedError
380
+
381
+ if (step > 0 and start > stop) or (step < 0 and start < stop):
382
+ # empty range
383
+ return torch.empty(0, dtype=dtype)
384
+
385
+ result = torch.arange(start, stop, step, dtype=work_dtype)
386
+ result = _util.cast_if_needed(result, dtype)
387
+ return result
388
+
389
+
390
+ # ### zeros/ones/empty/full ###
391
+
392
+
393
+ def empty(
394
+ shape,
395
+ dtype: DTypeLike | None = None,
396
+ order: NotImplementedType = "C",
397
+ *,
398
+ like: NotImplementedType = None,
399
+ ):
400
+ if dtype is None:
401
+ dtype = _dtypes_impl.default_dtypes().float_dtype
402
+ return torch.empty(shape, dtype=dtype)
403
+
404
+
405
+ # NB: *_like functions deliberately deviate from numpy: it has subok=True
406
+ # as the default; we set subok=False and raise on anything else.
407
+
408
+
409
+ def empty_like(
410
+ prototype: ArrayLike,
411
+ dtype: DTypeLike | None = None,
412
+ order: NotImplementedType = "K",
413
+ subok: NotImplementedType = False,
414
+ shape=None,
415
+ ):
416
+ result = torch.empty_like(prototype, dtype=dtype)
417
+ if shape is not None:
418
+ result = result.reshape(shape)
419
+ return result
420
+
421
+
422
+ def full(
423
+ shape,
424
+ fill_value: ArrayLike,
425
+ dtype: DTypeLike | None = None,
426
+ order: NotImplementedType = "C",
427
+ *,
428
+ like: NotImplementedType = None,
429
+ ):
430
+ if isinstance(shape, int):
431
+ shape = (shape,)
432
+ if dtype is None:
433
+ dtype = fill_value.dtype
434
+ if not isinstance(shape, (tuple, list)):
435
+ shape = (shape,)
436
+ return torch.full(shape, fill_value, dtype=dtype)
437
+
438
+
439
+ def full_like(
440
+ a: ArrayLike,
441
+ fill_value,
442
+ dtype: DTypeLike | None = None,
443
+ order: NotImplementedType = "K",
444
+ subok: NotImplementedType = False,
445
+ shape=None,
446
+ ):
447
+ # XXX: fill_value broadcasts
448
+ result = torch.full_like(a, fill_value, dtype=dtype)
449
+ if shape is not None:
450
+ result = result.reshape(shape)
451
+ return result
452
+
453
+
454
+ def ones(
455
+ shape,
456
+ dtype: DTypeLike | None = None,
457
+ order: NotImplementedType = "C",
458
+ *,
459
+ like: NotImplementedType = None,
460
+ ):
461
+ if dtype is None:
462
+ dtype = _dtypes_impl.default_dtypes().float_dtype
463
+ return torch.ones(shape, dtype=dtype)
464
+
465
+
466
+ def ones_like(
467
+ a: ArrayLike,
468
+ dtype: DTypeLike | None = None,
469
+ order: NotImplementedType = "K",
470
+ subok: NotImplementedType = False,
471
+ shape=None,
472
+ ):
473
+ result = torch.ones_like(a, dtype=dtype)
474
+ if shape is not None:
475
+ result = result.reshape(shape)
476
+ return result
477
+
478
+
479
+ def zeros(
480
+ shape,
481
+ dtype: DTypeLike | None = None,
482
+ order: NotImplementedType = "C",
483
+ *,
484
+ like: NotImplementedType = None,
485
+ ):
486
+ if dtype is None:
487
+ dtype = _dtypes_impl.default_dtypes().float_dtype
488
+ return torch.zeros(shape, dtype=dtype)
489
+
490
+
491
+ def zeros_like(
492
+ a: ArrayLike,
493
+ dtype: DTypeLike | None = None,
494
+ order: NotImplementedType = "K",
495
+ subok: NotImplementedType = False,
496
+ shape=None,
497
+ ):
498
+ result = torch.zeros_like(a, dtype=dtype)
499
+ if shape is not None:
500
+ result = result.reshape(shape)
501
+ return result
502
+
503
+
504
+ # ### cov & corrcoef ###
505
+
506
+
507
+ def _xy_helper_corrcoef(x_tensor, y_tensor=None, rowvar=True):
508
+ """Prepare inputs for cov and corrcoef."""
509
+
510
+ # https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/function_base.py#L2636
511
+ if y_tensor is not None:
512
+ # make sure x and y are at least 2D
513
+ ndim_extra = 2 - x_tensor.ndim
514
+ if ndim_extra > 0:
515
+ x_tensor = x_tensor.view((1,) * ndim_extra + x_tensor.shape)
516
+ if not rowvar and x_tensor.shape[0] != 1:
517
+ x_tensor = x_tensor.mT
518
+ x_tensor = x_tensor.clone()
519
+
520
+ ndim_extra = 2 - y_tensor.ndim
521
+ if ndim_extra > 0:
522
+ y_tensor = y_tensor.view((1,) * ndim_extra + y_tensor.shape)
523
+ if not rowvar and y_tensor.shape[0] != 1:
524
+ y_tensor = y_tensor.mT
525
+ y_tensor = y_tensor.clone()
526
+
527
+ x_tensor = _concatenate((x_tensor, y_tensor), axis=0)
528
+
529
+ return x_tensor
530
+
531
+
532
+ def corrcoef(
533
+ x: ArrayLike,
534
+ y: ArrayLike | None = None,
535
+ rowvar=True,
536
+ bias=None,
537
+ ddof=None,
538
+ *,
539
+ dtype: DTypeLike | None = None,
540
+ ):
541
+ if bias is not None or ddof is not None:
542
+ # deprecated in NumPy
543
+ raise NotImplementedError
544
+ xy_tensor = _xy_helper_corrcoef(x, y, rowvar)
545
+
546
+ is_half = (xy_tensor.dtype == torch.float16) and xy_tensor.is_cpu
547
+ if is_half:
548
+ # work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
549
+ dtype = torch.float32
550
+
551
+ xy_tensor = _util.cast_if_needed(xy_tensor, dtype)
552
+ result = torch.corrcoef(xy_tensor)
553
+
554
+ if is_half:
555
+ result = result.to(torch.float16)
556
+
557
+ return result
558
+
559
+
560
+ def cov(
561
+ m: ArrayLike,
562
+ y: ArrayLike | None = None,
563
+ rowvar=True,
564
+ bias=False,
565
+ ddof=None,
566
+ fweights: ArrayLike | None = None,
567
+ aweights: ArrayLike | None = None,
568
+ *,
569
+ dtype: DTypeLike | None = None,
570
+ ):
571
+ m = _xy_helper_corrcoef(m, y, rowvar)
572
+
573
+ if ddof is None:
574
+ ddof = 1 if bias == 0 else 0
575
+
576
+ is_half = (m.dtype == torch.float16) and m.is_cpu
577
+ if is_half:
578
+ # work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
579
+ dtype = torch.float32
580
+
581
+ m = _util.cast_if_needed(m, dtype)
582
+ result = torch.cov(m, correction=ddof, aweights=aweights, fweights=fweights)
583
+
584
+ if is_half:
585
+ result = result.to(torch.float16)
586
+
587
+ return result
588
+
589
+
590
+ def _conv_corr_impl(a, v, mode):
591
+ dt = _dtypes_impl.result_type_impl(a, v)
592
+ a = _util.cast_if_needed(a, dt)
593
+ v = _util.cast_if_needed(v, dt)
594
+
595
+ padding = v.shape[0] - 1 if mode == "full" else mode
596
+
597
+ if padding == "same" and v.shape[0] % 2 == 0:
598
+ # UserWarning: Using padding='same' with even kernel lengths and odd
599
+ # dilation may require a zero-padded copy of the input be created
600
+ # (Triggered internally at pytorch/aten/src/ATen/native/Convolution.cpp:1010.)
601
+ raise NotImplementedError("mode='same' and even-length weights")
602
+
603
+ # NumPy only accepts 1D arrays; PyTorch requires 2D inputs and 3D weights
604
+ aa = a[None, :]
605
+ vv = v[None, None, :]
606
+
607
+ result = torch.nn.functional.conv1d(aa, vv, padding=padding)
608
+
609
+ # torch returns a 2D result, numpy returns a 1D array
610
+ return result[0, :]
611
+
612
+
613
+ def convolve(a: ArrayLike, v: ArrayLike, mode="full"):
614
+ # NumPy: if v is longer than a, the arrays are swapped before computation
615
+ if a.shape[0] < v.shape[0]:
616
+ a, v = v, a
617
+
618
+ # flip the weights since numpy does and torch does not
619
+ v = torch.flip(v, (0,))
620
+
621
+ return _conv_corr_impl(a, v, mode)
622
+
623
+
624
+ def correlate(a: ArrayLike, v: ArrayLike, mode="valid"):
625
+ v = torch.conj_physical(v)
626
+ return _conv_corr_impl(a, v, mode)
627
+
628
+
629
+ # ### logic & element selection ###
630
+
631
+
632
+ def bincount(x: ArrayLike, /, weights: ArrayLike | None = None, minlength=0):
633
+ if x.numel() == 0:
634
+ # edge case allowed by numpy
635
+ x = x.new_empty(0, dtype=int)
636
+
637
+ int_dtype = _dtypes_impl.default_dtypes().int_dtype
638
+ (x,) = _util.typecast_tensors((x,), int_dtype, casting="safe")
639
+
640
+ return torch.bincount(x, weights, minlength)
641
+
642
+
643
+ def where(
644
+ condition: ArrayLike,
645
+ x: ArrayLikeOrScalar | None = None,
646
+ y: ArrayLikeOrScalar | None = None,
647
+ /,
648
+ ):
649
+ if (x is None) != (y is None):
650
+ raise ValueError("either both or neither of x and y should be given")
651
+
652
+ if condition.dtype != torch.bool:
653
+ condition = condition.to(torch.bool)
654
+
655
+ if x is None and y is None:
656
+ result = torch.where(condition)
657
+ else:
658
+ result = torch.where(condition, x, y)
659
+ return result
660
+
661
+
662
+ # ###### module-level queries of object properties
663
+
664
+
665
+ def ndim(a: ArrayLike):
666
+ return a.ndim
667
+
668
+
669
+ def shape(a: ArrayLike):
670
+ return tuple(a.shape)
671
+
672
+
673
+ def size(a: ArrayLike, axis=None):
674
+ if axis is None:
675
+ return a.numel()
676
+ else:
677
+ return a.shape[axis]
678
+
679
+
680
+ # ###### shape manipulations and indexing
681
+
682
+
683
+ def expand_dims(a: ArrayLike, axis):
684
+ shape = _util.expand_shape(a.shape, axis)
685
+ return a.view(shape) # never copies
686
+
687
+
688
+ def flip(m: ArrayLike, axis=None):
689
+ # XXX: semantic difference: np.flip returns a view, torch.flip copies
690
+ if axis is None:
691
+ axis = tuple(range(m.ndim))
692
+ else:
693
+ axis = _util.normalize_axis_tuple(axis, m.ndim)
694
+ return torch.flip(m, axis)
695
+
696
+
697
+ def flipud(m: ArrayLike):
698
+ return torch.flipud(m)
699
+
700
+
701
+ def fliplr(m: ArrayLike):
702
+ return torch.fliplr(m)
703
+
704
+
705
+ def rot90(m: ArrayLike, k=1, axes=(0, 1)):
706
+ axes = _util.normalize_axis_tuple(axes, m.ndim)
707
+ return torch.rot90(m, k, axes)
708
+
709
+
710
+ # ### broadcasting and indices ###
711
+
712
+
713
+ def broadcast_to(array: ArrayLike, shape, subok: NotImplementedType = False):
714
+ return torch.broadcast_to(array, size=shape)
715
+
716
+
717
+ # This is a function from tuples to tuples, so we just reuse it. However,
718
+ # dynamo expects its __module__ to be torch._numpy
719
+ def broadcast_shapes(*args):
720
+ return torch.broadcast_shapes(*args)
721
+
722
+
723
+ def broadcast_arrays(*args: ArrayLike, subok: NotImplementedType = False):
724
+ return torch.broadcast_tensors(*args)
725
+
726
+
727
+ def meshgrid(*xi: ArrayLike, copy=True, sparse=False, indexing="xy"):
728
+ ndim = len(xi)
729
+
730
+ if indexing not in ["xy", "ij"]:
731
+ raise ValueError("Valid values for `indexing` are 'xy' and 'ij'.")
732
+
733
+ s0 = (1,) * ndim
734
+ output = [x.reshape(s0[:i] + (-1,) + s0[i + 1 :]) for i, x in enumerate(xi)]
735
+
736
+ if indexing == "xy" and ndim > 1:
737
+ # switch first and second axis
738
+ output[0] = output[0].reshape((1, -1) + s0[2:])
739
+ output[1] = output[1].reshape((-1, 1) + s0[2:])
740
+
741
+ if not sparse:
742
+ # Return the full N-D matrix (not only the 1-D vector)
743
+ output = torch.broadcast_tensors(*output)
744
+
745
+ if copy:
746
+ output = [x.clone() for x in output]
747
+
748
+ return list(output) # match numpy, return a list
749
+
750
+
751
+ def indices(dimensions, dtype: DTypeLike | None = int, sparse=False):
752
+ # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1691-L1791
753
+ dimensions = tuple(dimensions)
754
+ N = len(dimensions)
755
+ shape = (1,) * N
756
+ if sparse:
757
+ res = ()
758
+ else:
759
+ res = torch.empty((N,) + dimensions, dtype=dtype)
760
+ for i, dim in enumerate(dimensions):
761
+ idx = torch.arange(dim, dtype=dtype).reshape(
762
+ shape[:i] + (dim,) + shape[i + 1 :]
763
+ )
764
+ if sparse:
765
+ res = res + (idx,)
766
+ else:
767
+ res[i] = idx
768
+ return res
769
+
770
+
771
+ # ### tri*-something ###
772
+
773
+
774
+ def tril(m: ArrayLike, k=0):
775
+ return torch.tril(m, k)
776
+
777
+
778
+ def triu(m: ArrayLike, k=0):
779
+ return torch.triu(m, k)
780
+
781
+
782
+ def tril_indices(n, k=0, m=None):
783
+ if m is None:
784
+ m = n
785
+ return torch.tril_indices(n, m, offset=k)
786
+
787
+
788
+ def triu_indices(n, k=0, m=None):
789
+ if m is None:
790
+ m = n
791
+ return torch.triu_indices(n, m, offset=k)
792
+
793
+
794
+ def tril_indices_from(arr: ArrayLike, k=0):
795
+ if arr.ndim != 2:
796
+ raise ValueError("input array must be 2-d")
797
+ # Return a tensor rather than a tuple to avoid a graphbreak
798
+ return torch.tril_indices(arr.shape[0], arr.shape[1], offset=k)
799
+
800
+
801
+ def triu_indices_from(arr: ArrayLike, k=0):
802
+ if arr.ndim != 2:
803
+ raise ValueError("input array must be 2-d")
804
+ # Return a tensor rather than a tuple to avoid a graphbreak
805
+ return torch.triu_indices(arr.shape[0], arr.shape[1], offset=k)
806
+
807
+
808
+ def tri(
809
+ N,
810
+ M=None,
811
+ k=0,
812
+ dtype: DTypeLike | None = None,
813
+ *,
814
+ like: NotImplementedType = None,
815
+ ):
816
+ if M is None:
817
+ M = N
818
+ tensor = torch.ones((N, M), dtype=dtype)
819
+ return torch.tril(tensor, diagonal=k)
820
+
821
+
822
+ # ### equality, equivalence, allclose ###
823
+
824
+
825
+ def isclose(a: ArrayLike, b: ArrayLike, rtol=1.0e-5, atol=1.0e-8, equal_nan=False):
826
+ dtype = _dtypes_impl.result_type_impl(a, b)
827
+ a = _util.cast_if_needed(a, dtype)
828
+ b = _util.cast_if_needed(b, dtype)
829
+ return torch.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
830
+
831
+
832
+ def allclose(a: ArrayLike, b: ArrayLike, rtol=1e-05, atol=1e-08, equal_nan=False):
833
+ dtype = _dtypes_impl.result_type_impl(a, b)
834
+ a = _util.cast_if_needed(a, dtype)
835
+ b = _util.cast_if_needed(b, dtype)
836
+ return torch.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
837
+
838
+
839
+ def _tensor_equal(a1, a2, equal_nan=False):
840
+ # Implementation of array_equal/array_equiv.
841
+ if a1.shape != a2.shape:
842
+ return False
843
+ cond = a1 == a2
844
+ if equal_nan:
845
+ cond = cond | (torch.isnan(a1) & torch.isnan(a2))
846
+ return cond.all().item()
847
+
848
+
849
+ def array_equal(a1: ArrayLike, a2: ArrayLike, equal_nan=False):
850
+ return _tensor_equal(a1, a2, equal_nan=equal_nan)
851
+
852
+
853
+ def array_equiv(a1: ArrayLike, a2: ArrayLike):
854
+ # *almost* the same as array_equal: _equiv tries to broadcast, _equal does not
855
+ try:
856
+ a1_t, a2_t = torch.broadcast_tensors(a1, a2)
857
+ except RuntimeError:
858
+ # failed to broadcast => not equivalent
859
+ return False
860
+ return _tensor_equal(a1_t, a2_t)
861
+
862
+
863
+ def nan_to_num(
864
+ x: ArrayLike, copy: NotImplementedType = True, nan=0.0, posinf=None, neginf=None
865
+ ):
866
+ # work around RuntimeError: "nan_to_num" not implemented for 'ComplexDouble'
867
+ if x.is_complex():
868
+ re = torch.nan_to_num(x.real, nan=nan, posinf=posinf, neginf=neginf)
869
+ im = torch.nan_to_num(x.imag, nan=nan, posinf=posinf, neginf=neginf)
870
+ return re + 1j * im
871
+ else:
872
+ return torch.nan_to_num(x, nan=nan, posinf=posinf, neginf=neginf)
873
+
874
+
875
+ # ### put/take_along_axis ###
876
+
877
+
878
+ def take(
879
+ a: ArrayLike,
880
+ indices: ArrayLike,
881
+ axis=None,
882
+ out: OutArray | None = None,
883
+ mode: NotImplementedType = "raise",
884
+ ):
885
+ (a,), axis = _util.axis_none_flatten(a, axis=axis)
886
+ axis = _util.normalize_axis_index(axis, a.ndim)
887
+ idx = (slice(None),) * axis + (indices, ...)
888
+ result = a[idx]
889
+ return result
890
+
891
+
892
+ def take_along_axis(arr: ArrayLike, indices: ArrayLike, axis):
893
+ (arr,), axis = _util.axis_none_flatten(arr, axis=axis)
894
+ axis = _util.normalize_axis_index(axis, arr.ndim)
895
+ return torch.take_along_dim(arr, indices, axis)
896
+
897
+
898
+ def put(
899
+ a: NDArray,
900
+ indices: ArrayLike,
901
+ values: ArrayLike,
902
+ mode: NotImplementedType = "raise",
903
+ ):
904
+ v = values.type(a.dtype)
905
+ # If indices is larger than v, expand v to at least the size of indices. Any
906
+ # unnecessary trailing elements are then trimmed.
907
+ if indices.numel() > v.numel():
908
+ ratio = (indices.numel() + v.numel() - 1) // v.numel()
909
+ v = v.unsqueeze(0).expand((ratio,) + v.shape)
910
+ # Trim unnecessary elements, regardless if v was expanded or not. Note
911
+ # np.put() trims v to match indices by default too.
912
+ if indices.numel() < v.numel():
913
+ v = v.flatten()
914
+ v = v[: indices.numel()]
915
+ a.put_(indices, v)
916
+ return None
917
+
918
+
919
+ def put_along_axis(arr: ArrayLike, indices: ArrayLike, values: ArrayLike, axis):
920
+ (arr,), axis = _util.axis_none_flatten(arr, axis=axis)
921
+ axis = _util.normalize_axis_index(axis, arr.ndim)
922
+
923
+ indices, values = torch.broadcast_tensors(indices, values)
924
+ values = _util.cast_if_needed(values, arr.dtype)
925
+ result = torch.scatter(arr, axis, indices, values)
926
+ arr.copy_(result.reshape(arr.shape))
927
+ return None
928
+
929
+
930
+ def choose(
931
+ a: ArrayLike,
932
+ choices: Sequence[ArrayLike],
933
+ out: OutArray | None = None,
934
+ mode: NotImplementedType = "raise",
935
+ ):
936
+ # First, broadcast elements of `choices`
937
+ choices = torch.stack(torch.broadcast_tensors(*choices))
938
+
939
+ # Use an analog of `gather(choices, 0, a)` which broadcasts `choices` vs `a`:
940
+ # (taken from https://github.com/pytorch/pytorch/issues/9407#issuecomment-1427907939)
941
+ idx_list = [
942
+ torch.arange(dim).view((1,) * i + (dim,) + (1,) * (choices.ndim - i - 1))
943
+ for i, dim in enumerate(choices.shape)
944
+ ]
945
+
946
+ idx_list[0] = a
947
+ return choices[tuple(idx_list)].squeeze(0)
948
+
949
+
950
+ # ### unique et al. ###
951
+
952
+
953
+ def unique(
954
+ ar: ArrayLike,
955
+ return_index: NotImplementedType = False,
956
+ return_inverse=False,
957
+ return_counts=False,
958
+ axis=None,
959
+ *,
960
+ equal_nan: NotImplementedType = True,
961
+ ):
962
+ (ar,), axis = _util.axis_none_flatten(ar, axis=axis)
963
+ axis = _util.normalize_axis_index(axis, ar.ndim)
964
+
965
+ result = torch.unique(
966
+ ar, return_inverse=return_inverse, return_counts=return_counts, dim=axis
967
+ )
968
+
969
+ return result
970
+
971
+
972
+ def nonzero(a: ArrayLike):
973
+ return torch.nonzero(a, as_tuple=True)
974
+
975
+
976
+ def argwhere(a: ArrayLike):
977
+ return torch.argwhere(a)
978
+
979
+
980
+ def flatnonzero(a: ArrayLike):
981
+ return torch.flatten(a).nonzero(as_tuple=True)[0]
982
+
983
+
984
+ def clip(
985
+ a: ArrayLike,
986
+ min: ArrayLike | None = None,
987
+ max: ArrayLike | None = None,
988
+ out: OutArray | None = None,
989
+ ):
990
+ return torch.clamp(a, min, max)
991
+
992
+
993
+ def repeat(a: ArrayLike, repeats: ArrayLikeOrScalar, axis=None):
994
+ return torch.repeat_interleave(a, repeats, axis)
995
+
996
+
997
+ def tile(A: ArrayLike, reps):
998
+ if isinstance(reps, int):
999
+ reps = (reps,)
1000
+ return torch.tile(A, reps)
1001
+
1002
+
1003
+ def resize(a: ArrayLike, new_shape=None):
1004
+ # implementation vendored from
1005
+ # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/fromnumeric.py#L1420-L1497
1006
+ if new_shape is None:
1007
+ return a
1008
+
1009
+ if isinstance(new_shape, int):
1010
+ new_shape = (new_shape,)
1011
+
1012
+ a = a.flatten()
1013
+
1014
+ new_size = 1
1015
+ for dim_length in new_shape:
1016
+ new_size *= dim_length
1017
+ if dim_length < 0:
1018
+ raise ValueError("all elements of `new_shape` must be non-negative")
1019
+
1020
+ if a.numel() == 0 or new_size == 0:
1021
+ # First case must zero fill. The second would have repeats == 0.
1022
+ return torch.zeros(new_shape, dtype=a.dtype)
1023
+
1024
+ repeats = -(-new_size // a.numel()) # ceil division
1025
+ a = concatenate((a,) * repeats)[:new_size]
1026
+
1027
+ return reshape(a, new_shape)
1028
+
1029
+
1030
+ # ### diag et al. ###
1031
+
1032
+
1033
+ def diagonal(a: ArrayLike, offset=0, axis1=0, axis2=1):
1034
+ axis1 = _util.normalize_axis_index(axis1, a.ndim)
1035
+ axis2 = _util.normalize_axis_index(axis2, a.ndim)
1036
+ return torch.diagonal(a, offset, axis1, axis2)
1037
+
1038
+
1039
+ def trace(
1040
+ a: ArrayLike,
1041
+ offset=0,
1042
+ axis1=0,
1043
+ axis2=1,
1044
+ dtype: DTypeLike | None = None,
1045
+ out: OutArray | None = None,
1046
+ ):
1047
+ result = torch.diagonal(a, offset, dim1=axis1, dim2=axis2).sum(-1, dtype=dtype)
1048
+ return result
1049
+
1050
+
1051
+ def eye(
1052
+ N,
1053
+ M=None,
1054
+ k=0,
1055
+ dtype: DTypeLike | None = None,
1056
+ order: NotImplementedType = "C",
1057
+ *,
1058
+ like: NotImplementedType = None,
1059
+ ):
1060
+ if dtype is None:
1061
+ dtype = _dtypes_impl.default_dtypes().float_dtype
1062
+ if M is None:
1063
+ M = N
1064
+ z = torch.zeros(N, M, dtype=dtype)
1065
+ z.diagonal(k).fill_(1)
1066
+ return z
1067
+
1068
+
1069
+ def identity(n, dtype: DTypeLike | None = None, *, like: NotImplementedType = None):
1070
+ return torch.eye(n, dtype=dtype)
1071
+
1072
+
1073
+ def diag(v: ArrayLike, k=0):
1074
+ return torch.diag(v, k)
1075
+
1076
+
1077
+ def diagflat(v: ArrayLike, k=0):
1078
+ return torch.diagflat(v, k)
1079
+
1080
+
1081
+ def diag_indices(n, ndim=2):
1082
+ idx = torch.arange(n)
1083
+ return (idx,) * ndim
1084
+
1085
+
1086
+ def diag_indices_from(arr: ArrayLike):
1087
+ if not arr.ndim >= 2:
1088
+ raise ValueError("input array must be at least 2-d")
1089
+ # For more than d=2, the strided formula is only valid for arrays with
1090
+ # all dimensions equal, so we check first.
1091
+ s = arr.shape
1092
+ if s[1:] != s[:-1]:
1093
+ raise ValueError("All dimensions of input must be of equal length")
1094
+ return diag_indices(s[0], arr.ndim)
1095
+
1096
+
1097
+ def fill_diagonal(a: ArrayLike, val: ArrayLike, wrap=False):
1098
+ if a.ndim < 2:
1099
+ raise ValueError("array must be at least 2-d")
1100
+ if val.numel() == 0 and not wrap:
1101
+ a.fill_diagonal_(val)
1102
+ return a
1103
+
1104
+ if val.ndim == 0:
1105
+ val = val.unsqueeze(0)
1106
+
1107
+ # torch.Tensor.fill_diagonal_ only accepts scalars
1108
+ # If the size of val is too large, then val is trimmed
1109
+ if a.ndim == 2:
1110
+ tall = a.shape[0] > a.shape[1]
1111
+ # wrap does nothing for wide matrices...
1112
+ if not wrap or not tall:
1113
+ # Never wraps
1114
+ diag = a.diagonal()
1115
+ diag.copy_(val[: diag.numel()])
1116
+ else:
1117
+ # wraps and tall... leaving one empty line between diagonals?!
1118
+ max_, min_ = a.shape
1119
+ idx = torch.arange(max_ - max_ // (min_ + 1))
1120
+ mod = idx % min_
1121
+ div = idx // min_
1122
+ a[(div * (min_ + 1) + mod, mod)] = val[: idx.numel()]
1123
+ else:
1124
+ idx = diag_indices_from(a)
1125
+ # a.shape = (n, n, ..., n)
1126
+ a[idx] = val[: a.shape[0]]
1127
+
1128
+ return a
1129
+
1130
+
1131
+ def vdot(a: ArrayLike, b: ArrayLike, /):
1132
+ # 1. torch only accepts 1D arrays, numpy flattens
1133
+ # 2. torch requires matching dtype, while numpy casts (?)
1134
+ t_a, t_b = torch.atleast_1d(a, b)
1135
+ if t_a.ndim > 1:
1136
+ t_a = t_a.flatten()
1137
+ if t_b.ndim > 1:
1138
+ t_b = t_b.flatten()
1139
+
1140
+ dtype = _dtypes_impl.result_type_impl(t_a, t_b)
1141
+ is_half = dtype == torch.float16 and (t_a.is_cpu or t_b.is_cpu)
1142
+ is_bool = dtype == torch.bool
1143
+
1144
+ # work around torch's "dot" not implemented for 'Half', 'Bool'
1145
+ if is_half:
1146
+ dtype = torch.float32
1147
+ elif is_bool:
1148
+ dtype = torch.uint8
1149
+
1150
+ t_a = _util.cast_if_needed(t_a, dtype)
1151
+ t_b = _util.cast_if_needed(t_b, dtype)
1152
+
1153
+ result = torch.vdot(t_a, t_b)
1154
+
1155
+ if is_half:
1156
+ result = result.to(torch.float16)
1157
+ elif is_bool:
1158
+ result = result.to(torch.bool)
1159
+
1160
+ return result
1161
+
1162
+
1163
+ def tensordot(a: ArrayLike, b: ArrayLike, axes=2):
1164
+ if isinstance(axes, (list, tuple)):
1165
+ axes = [[ax] if isinstance(ax, int) else ax for ax in axes]
1166
+
1167
+ target_dtype = _dtypes_impl.result_type_impl(a, b)
1168
+ a = _util.cast_if_needed(a, target_dtype)
1169
+ b = _util.cast_if_needed(b, target_dtype)
1170
+
1171
+ return torch.tensordot(a, b, dims=axes)
1172
+
1173
+
1174
+ def dot(a: ArrayLike, b: ArrayLike, out: OutArray | None = None):
1175
+ dtype = _dtypes_impl.result_type_impl(a, b)
1176
+ is_bool = dtype == torch.bool
1177
+ if is_bool:
1178
+ dtype = torch.uint8
1179
+
1180
+ a = _util.cast_if_needed(a, dtype)
1181
+ b = _util.cast_if_needed(b, dtype)
1182
+
1183
+ if a.ndim == 0 or b.ndim == 0:
1184
+ result = a * b
1185
+ else:
1186
+ result = torch.matmul(a, b)
1187
+
1188
+ if is_bool:
1189
+ result = result.to(torch.bool)
1190
+
1191
+ return result
1192
+
1193
+
1194
+ def inner(a: ArrayLike, b: ArrayLike, /):
1195
+ dtype = _dtypes_impl.result_type_impl(a, b)
1196
+ is_half = dtype == torch.float16 and (a.is_cpu or b.is_cpu)
1197
+ is_bool = dtype == torch.bool
1198
+
1199
+ if is_half:
1200
+ # work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
1201
+ dtype = torch.float32
1202
+ elif is_bool:
1203
+ dtype = torch.uint8
1204
+
1205
+ a = _util.cast_if_needed(a, dtype)
1206
+ b = _util.cast_if_needed(b, dtype)
1207
+
1208
+ result = torch.inner(a, b)
1209
+
1210
+ if is_half:
1211
+ result = result.to(torch.float16)
1212
+ elif is_bool:
1213
+ result = result.to(torch.bool)
1214
+ return result
1215
+
1216
+
1217
+ def outer(a: ArrayLike, b: ArrayLike, out: OutArray | None = None):
1218
+ return torch.outer(a, b)
1219
+
1220
+
1221
+ def cross(a: ArrayLike, b: ArrayLike, axisa=-1, axisb=-1, axisc=-1, axis=None):
1222
+ # implementation vendored from
1223
+ # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1486-L1685
1224
+ if axis is not None:
1225
+ axisa, axisb, axisc = (axis,) * 3
1226
+
1227
+ # Check axisa and axisb are within bounds
1228
+ axisa = _util.normalize_axis_index(axisa, a.ndim)
1229
+ axisb = _util.normalize_axis_index(axisb, b.ndim)
1230
+
1231
+ # Move working axis to the end of the shape
1232
+ a = torch.moveaxis(a, axisa, -1)
1233
+ b = torch.moveaxis(b, axisb, -1)
1234
+ msg = "incompatible dimensions for cross product\n(dimension must be 2 or 3)"
1235
+ if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
1236
+ raise ValueError(msg)
1237
+
1238
+ # Create the output array
1239
+ shape = broadcast_shapes(a[..., 0].shape, b[..., 0].shape)
1240
+ if a.shape[-1] == 3 or b.shape[-1] == 3:
1241
+ shape += (3,)
1242
+ # Check axisc is within bounds
1243
+ axisc = _util.normalize_axis_index(axisc, len(shape))
1244
+ dtype = _dtypes_impl.result_type_impl(a, b)
1245
+ cp = torch.empty(shape, dtype=dtype)
1246
+
1247
+ # recast arrays as dtype
1248
+ a = _util.cast_if_needed(a, dtype)
1249
+ b = _util.cast_if_needed(b, dtype)
1250
+
1251
+ # create local aliases for readability
1252
+ a0 = a[..., 0]
1253
+ a1 = a[..., 1]
1254
+ if a.shape[-1] == 3:
1255
+ a2 = a[..., 2]
1256
+ b0 = b[..., 0]
1257
+ b1 = b[..., 1]
1258
+ if b.shape[-1] == 3:
1259
+ b2 = b[..., 2]
1260
+ if cp.ndim != 0 and cp.shape[-1] == 3:
1261
+ cp0 = cp[..., 0]
1262
+ cp1 = cp[..., 1]
1263
+ cp2 = cp[..., 2]
1264
+
1265
+ if a.shape[-1] == 2:
1266
+ if b.shape[-1] == 2:
1267
+ # a0 * b1 - a1 * b0
1268
+ cp[...] = a0 * b1 - a1 * b0
1269
+ return cp
1270
+ else:
1271
+ if b.shape[-1] != 3:
1272
+ raise AssertionError(f"b.shape[-1] must be 3, got {b.shape[-1]}")
1273
+ # cp0 = a1 * b2 - 0 (a2 = 0)
1274
+ # cp1 = 0 - a0 * b2 (a2 = 0)
1275
+ # cp2 = a0 * b1 - a1 * b0
1276
+ cp0[...] = a1 * b2
1277
+ cp1[...] = -a0 * b2
1278
+ cp2[...] = a0 * b1 - a1 * b0
1279
+ else:
1280
+ if a.shape[-1] != 3:
1281
+ raise AssertionError(f"a.shape[-1] must be 3, got {a.shape[-1]}")
1282
+ if b.shape[-1] == 3:
1283
+ cp0[...] = a1 * b2 - a2 * b1
1284
+ cp1[...] = a2 * b0 - a0 * b2
1285
+ cp2[...] = a0 * b1 - a1 * b0
1286
+ else:
1287
+ if b.shape[-1] != 2:
1288
+ raise AssertionError(f"b.shape[-1] must be 2, got {b.shape[-1]}")
1289
+ cp0[...] = -a2 * b1
1290
+ cp1[...] = a2 * b0
1291
+ cp2[...] = a0 * b1 - a1 * b0
1292
+
1293
+ return torch.moveaxis(cp, -1, axisc)
1294
+
1295
+
1296
+ def einsum(*operands, out=None, dtype=None, order="K", casting="safe", optimize=False):
1297
+ # Have to manually normalize *operands and **kwargs, following the NumPy signature
1298
+ # We have a local import to avoid polluting the global space, as it will be then
1299
+ # exported in funcs.py
1300
+ from ._ndarray import ndarray
1301
+ from ._normalizations import (
1302
+ maybe_copy_to,
1303
+ normalize_array_like,
1304
+ normalize_casting,
1305
+ normalize_dtype,
1306
+ wrap_tensors,
1307
+ )
1308
+
1309
+ dtype = normalize_dtype(dtype)
1310
+ casting = normalize_casting(casting)
1311
+ if out is not None and not isinstance(out, ndarray):
1312
+ raise TypeError("'out' must be an array")
1313
+ if order != "K":
1314
+ raise NotImplementedError("'order' parameter is not supported.")
1315
+
1316
+ # parse arrays and normalize them
1317
+ sublist_format = not isinstance(operands[0], str)
1318
+ if sublist_format:
1319
+ # op, str, op, str ... [sublistout] format: normalize every other argument
1320
+
1321
+ # - if sublistout is not given, the length of operands is even, and we pick
1322
+ # odd-numbered elements, which are arrays.
1323
+ # - if sublistout is given, the length of operands is odd, we peel off
1324
+ # the last one, and pick odd-numbered elements, which are arrays.
1325
+ # Without [:-1], we would have picked sublistout, too.
1326
+ array_operands = operands[:-1][::2]
1327
+ else:
1328
+ # ("ij->", arrays) format
1329
+ subscripts, array_operands = operands[0], operands[1:]
1330
+
1331
+ tensors = [normalize_array_like(op) for op in array_operands]
1332
+ target_dtype = _dtypes_impl.result_type_impl(*tensors) if dtype is None else dtype
1333
+
1334
+ # work around 'bmm' not implemented for 'Half' etc
1335
+ is_half = target_dtype == torch.float16 and all(t.is_cpu for t in tensors)
1336
+ if is_half:
1337
+ target_dtype = torch.float32
1338
+
1339
+ is_short_int = target_dtype in [torch.uint8, torch.int8, torch.int16, torch.int32]
1340
+ if is_short_int:
1341
+ target_dtype = torch.int64
1342
+
1343
+ tensors = _util.typecast_tensors(tensors, target_dtype, casting)
1344
+
1345
+ from torch.backends import opt_einsum
1346
+
1347
+ try:
1348
+ # set the global state to handle the optimize=... argument, restore on exit
1349
+ if opt_einsum.is_available():
1350
+ old_strategy = torch.backends.opt_einsum.strategy
1351
+ old_enabled = torch.backends.opt_einsum.enabled
1352
+
1353
+ # torch.einsum calls opt_einsum.contract_path, which runs into
1354
+ # https://github.com/dgasmith/opt_einsum/issues/219
1355
+ # for strategy={True, False}
1356
+ if optimize is True:
1357
+ optimize = "auto"
1358
+ elif optimize is False:
1359
+ torch.backends.opt_einsum.enabled = False
1360
+
1361
+ torch.backends.opt_einsum.strategy = optimize
1362
+
1363
+ if sublist_format:
1364
+ # recombine operands
1365
+ sublists = operands[1::2]
1366
+ has_sublistout = len(operands) % 2 == 1
1367
+ if has_sublistout:
1368
+ sublistout = operands[-1]
1369
+ operands = list(itertools.chain.from_iterable(zip(tensors, sublists)))
1370
+ if has_sublistout:
1371
+ operands.append(sublistout)
1372
+
1373
+ result = torch.einsum(*operands)
1374
+ else:
1375
+ result = torch.einsum(subscripts, *tensors)
1376
+
1377
+ finally:
1378
+ if opt_einsum.is_available():
1379
+ torch.backends.opt_einsum.strategy = old_strategy
1380
+ torch.backends.opt_einsum.enabled = old_enabled
1381
+
1382
+ result = maybe_copy_to(out, result)
1383
+ return wrap_tensors(result)
1384
+
1385
+
1386
+ # ### sort and partition ###
1387
+
1388
+
1389
+ def _sort_helper(tensor, axis, kind, order):
1390
+ if tensor.dtype.is_complex:
1391
+ raise NotImplementedError(f"sorting {tensor.dtype} is not supported")
1392
+ (tensor,), axis = _util.axis_none_flatten(tensor, axis=axis)
1393
+ axis = _util.normalize_axis_index(axis, tensor.ndim)
1394
+
1395
+ stable = kind == "stable"
1396
+
1397
+ return tensor, axis, stable
1398
+
1399
+
1400
+ def sort(a: ArrayLike, axis=-1, kind=None, order: NotImplementedType = None):
1401
+ # `order` keyword arg is only relevant for structured dtypes; so not supported here.
1402
+ a, axis, stable = _sort_helper(a, axis, kind, order)
1403
+ result = torch.sort(a, dim=axis, stable=stable)
1404
+ return result.values
1405
+
1406
+
1407
+ def argsort(a: ArrayLike, axis=-1, kind=None, order: NotImplementedType = None):
1408
+ a, axis, stable = _sort_helper(a, axis, kind, order)
1409
+ return torch.argsort(a, dim=axis, stable=stable)
1410
+
1411
+
1412
+ def searchsorted(
1413
+ a: ArrayLike, v: ArrayLike, side="left", sorter: ArrayLike | None = None
1414
+ ):
1415
+ if a.dtype.is_complex:
1416
+ raise NotImplementedError(f"searchsorted with dtype={a.dtype}")
1417
+
1418
+ return torch.searchsorted(a, v, side=side, sorter=sorter)
1419
+
1420
+
1421
+ # ### swap/move/roll axis ###
1422
+
1423
+
1424
+ def moveaxis(a: ArrayLike, source, destination):
1425
+ source = _util.normalize_axis_tuple(source, a.ndim, "source")
1426
+ destination = _util.normalize_axis_tuple(destination, a.ndim, "destination")
1427
+ return torch.moveaxis(a, source, destination)
1428
+
1429
+
1430
+ def swapaxes(a: ArrayLike, axis1, axis2):
1431
+ axis1 = _util.normalize_axis_index(axis1, a.ndim)
1432
+ axis2 = _util.normalize_axis_index(axis2, a.ndim)
1433
+ return torch.swapaxes(a, axis1, axis2)
1434
+
1435
+
1436
+ def rollaxis(a: ArrayLike, axis, start=0):
1437
+ # Straight vendor from:
1438
+ # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1259
1439
+ #
1440
+ # Also note this function in NumPy is mostly retained for backwards compat
1441
+ # (https://stackoverflow.com/questions/29891583/reason-why-numpy-rollaxis-is-so-confusing)
1442
+ # so let's not touch it unless hard pressed.
1443
+ n = a.ndim
1444
+ axis = _util.normalize_axis_index(axis, n)
1445
+ if start < 0:
1446
+ start += n
1447
+ msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
1448
+ if not (0 <= start < n + 1):
1449
+ raise _util.AxisError(msg % ("start", -n, "start", n + 1, start))
1450
+ if axis < start:
1451
+ # it's been removed
1452
+ start -= 1
1453
+ if axis == start:
1454
+ # numpy returns a view, here we try returning the tensor itself
1455
+ # return tensor[...]
1456
+ return a
1457
+ axes = list(range(n))
1458
+ axes.remove(axis)
1459
+ axes.insert(start, axis)
1460
+ return a.view(axes)
1461
+
1462
+
1463
+ def roll(a: ArrayLike, shift, axis=None):
1464
+ if axis is not None:
1465
+ axis = _util.normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
1466
+ if not isinstance(shift, tuple):
1467
+ shift = (shift,) * len(axis)
1468
+ return torch.roll(a, shift, axis)
1469
+
1470
+
1471
+ # ### shape manipulations ###
1472
+
1473
+
1474
+ def squeeze(a: ArrayLike, axis=None):
1475
+ if axis == ():
1476
+ result = a
1477
+ elif axis is None:
1478
+ result = a.squeeze()
1479
+ else:
1480
+ if isinstance(axis, tuple):
1481
+ result = a
1482
+ for ax in axis:
1483
+ result = a.squeeze(ax)
1484
+ else:
1485
+ result = a.squeeze(axis)
1486
+ return result
1487
+
1488
+
1489
+ def reshape(a: ArrayLike, newshape, order: NotImplementedType = "C"):
1490
+ # if sh = (1, 2, 3), numpy allows both .reshape(sh) and .reshape(*sh)
1491
+ newshape = newshape[0] if len(newshape) == 1 else newshape
1492
+ return a.reshape(newshape)
1493
+
1494
+
1495
+ # NB: cannot use torch.reshape(a, newshape) above, because of
1496
+ # (Pdb) torch.reshape(torch.as_tensor([1]), 1)
1497
+ # *** TypeError: reshape(): argument 'shape' (position 2) must be tuple of SymInts, not int
1498
+
1499
+
1500
+ def transpose(a: ArrayLike, axes=None):
1501
+ # numpy allows both .transpose(sh) and .transpose(*sh)
1502
+ # also older code uses axes being a list
1503
+ if axes in [(), None, (None,)]:
1504
+ axes = tuple(reversed(range(a.ndim)))
1505
+ elif len(axes) == 1:
1506
+ axes = axes[0]
1507
+ return a.permute(axes)
1508
+
1509
+
1510
+ def ravel(a: ArrayLike, order: NotImplementedType = "C"):
1511
+ return torch.flatten(a)
1512
+
1513
+
1514
+ def diff(
1515
+ a: ArrayLike,
1516
+ n=1,
1517
+ axis=-1,
1518
+ prepend: ArrayLike | None = None,
1519
+ append: ArrayLike | None = None,
1520
+ ):
1521
+ axis = _util.normalize_axis_index(axis, a.ndim)
1522
+
1523
+ if n < 0:
1524
+ raise ValueError(f"order must be non-negative but got {n}")
1525
+
1526
+ if n == 0:
1527
+ # match numpy and return the input immediately
1528
+ return a
1529
+
1530
+ if prepend is not None:
1531
+ shape = list(a.shape)
1532
+ shape[axis] = prepend.shape[axis] if prepend.ndim > 0 else 1
1533
+ prepend = torch.broadcast_to(prepend, shape)
1534
+
1535
+ if append is not None:
1536
+ shape = list(a.shape)
1537
+ shape[axis] = append.shape[axis] if append.ndim > 0 else 1
1538
+ append = torch.broadcast_to(append, shape)
1539
+
1540
+ return torch.diff(a, n, axis=axis, prepend=prepend, append=append)
1541
+
1542
+
1543
+ # ### math functions ###
1544
+
1545
+
1546
+ def angle(z: ArrayLike, deg=False):
1547
+ result = torch.angle(z)
1548
+ if deg:
1549
+ result = result * (180 / torch.pi)
1550
+ return result
1551
+
1552
+
1553
+ def sinc(x: ArrayLike):
1554
+ return torch.sinc(x)
1555
+
1556
+
1557
+ # NB: have to normalize *varargs manually
1558
+ def gradient(f: ArrayLike, *varargs, axis=None, edge_order=1):
1559
+ N = f.ndim # number of dimensions
1560
+
1561
+ varargs = _util.ndarrays_to_tensors(varargs)
1562
+
1563
+ if axis is None:
1564
+ axes = tuple(range(N))
1565
+ else:
1566
+ axes = _util.normalize_axis_tuple(axis, N)
1567
+
1568
+ len_axes = len(axes)
1569
+ n = len(varargs)
1570
+ if n == 0:
1571
+ # no spacing argument - use 1 in all axes
1572
+ dx = [1.0] * len_axes
1573
+ elif n == 1 and (_dtypes_impl.is_scalar(varargs[0]) or varargs[0].ndim == 0):
1574
+ # single scalar or 0D tensor for all axes (np.ndim(varargs[0]) == 0)
1575
+ dx = varargs * len_axes
1576
+ elif n == len_axes:
1577
+ # scalar or 1d array for each axis
1578
+ dx = list(varargs)
1579
+ for i, distances in enumerate(dx):
1580
+ distances = torch.as_tensor(distances)
1581
+ if distances.ndim == 0:
1582
+ continue
1583
+ elif distances.ndim != 1:
1584
+ raise ValueError("distances must be either scalars or 1d")
1585
+ if len(distances) != f.shape[axes[i]]:
1586
+ raise ValueError(
1587
+ "when 1d, distances must match "
1588
+ "the length of the corresponding dimension"
1589
+ )
1590
+ if not (distances.dtype.is_floating_point or distances.dtype.is_complex):
1591
+ distances = distances.double()
1592
+
1593
+ diffx = torch.diff(distances)
1594
+ # if distances are constant reduce to the scalar case
1595
+ # since it brings a consistent speedup
1596
+ if (diffx == diffx[0]).all():
1597
+ diffx = diffx[0]
1598
+ dx[i] = diffx
1599
+ else:
1600
+ raise TypeError("invalid number of arguments")
1601
+
1602
+ if edge_order > 2:
1603
+ raise ValueError("'edge_order' greater than 2 not supported")
1604
+
1605
+ # use central differences on interior and one-sided differences on the
1606
+ # endpoints. This preserves second order-accuracy over the full domain.
1607
+
1608
+ outvals = []
1609
+
1610
+ # create slice objects --- initially all are [:, :, ..., :]
1611
+ slice1 = [slice(None)] * N
1612
+ slice2 = [slice(None)] * N
1613
+ slice3 = [slice(None)] * N
1614
+ slice4 = [slice(None)] * N
1615
+
1616
+ otype = f.dtype
1617
+ if _dtypes_impl.python_type_for_torch(otype) in (int, bool):
1618
+ # Convert to floating point.
1619
+ # First check if f is a numpy integer type; if so, convert f to float64
1620
+ # to avoid modular arithmetic when computing the changes in f.
1621
+ f = f.double()
1622
+ otype = torch.float64
1623
+
1624
+ for axis, ax_dx in zip(axes, dx):
1625
+ if f.shape[axis] < edge_order + 1:
1626
+ raise ValueError(
1627
+ "Shape of array too small to calculate a numerical gradient, "
1628
+ "at least (edge_order + 1) elements are required."
1629
+ )
1630
+ # result allocation
1631
+ out = torch.empty_like(f, dtype=otype)
1632
+
1633
+ # spacing for the current axis (NB: np.ndim(ax_dx) == 0)
1634
+ uniform_spacing = _dtypes_impl.is_scalar(ax_dx) or ax_dx.ndim == 0
1635
+
1636
+ # Numerical differentiation: 2nd order interior
1637
+ slice1[axis] = slice(1, -1)
1638
+ slice2[axis] = slice(None, -2)
1639
+ slice3[axis] = slice(1, -1)
1640
+ slice4[axis] = slice(2, None)
1641
+
1642
+ if uniform_spacing:
1643
+ out[tuple(slice1)] = (f[tuple(slice4)] - f[tuple(slice2)]) / (2.0 * ax_dx)
1644
+ else:
1645
+ dx1 = ax_dx[0:-1]
1646
+ dx2 = ax_dx[1:]
1647
+ a = -(dx2) / (dx1 * (dx1 + dx2))
1648
+ b = (dx2 - dx1) / (dx1 * dx2)
1649
+ c = dx1 / (dx2 * (dx1 + dx2))
1650
+ # fix the shape for broadcasting
1651
+ shape = [1] * N
1652
+ shape[axis] = -1
1653
+ a = a.reshape(shape)
1654
+ b = b.reshape(shape)
1655
+ c = c.reshape(shape)
1656
+ # 1D equivalent -- out[1:-1] = a * f[:-2] + b * f[1:-1] + c * f[2:]
1657
+ out[tuple(slice1)] = (
1658
+ a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
1659
+ )
1660
+
1661
+ # Numerical differentiation: 1st order edges
1662
+ if edge_order == 1:
1663
+ slice1[axis] = 0
1664
+ slice2[axis] = 1
1665
+ slice3[axis] = 0
1666
+ dx_0 = ax_dx if uniform_spacing else ax_dx[0]
1667
+ # 1D equivalent -- out[0] = (f[1] - f[0]) / (x[1] - x[0])
1668
+ out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_0
1669
+
1670
+ slice1[axis] = -1
1671
+ slice2[axis] = -1
1672
+ slice3[axis] = -2
1673
+ dx_n = ax_dx if uniform_spacing else ax_dx[-1]
1674
+ # 1D equivalent -- out[-1] = (f[-1] - f[-2]) / (x[-1] - x[-2])
1675
+ out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_n
1676
+
1677
+ # Numerical differentiation: 2nd order edges
1678
+ else:
1679
+ slice1[axis] = 0
1680
+ slice2[axis] = 0
1681
+ slice3[axis] = 1
1682
+ slice4[axis] = 2
1683
+ if uniform_spacing:
1684
+ a = -1.5 / ax_dx
1685
+ b = 2.0 / ax_dx
1686
+ c = -0.5 / ax_dx
1687
+ else:
1688
+ dx1 = ax_dx[0]
1689
+ dx2 = ax_dx[1]
1690
+ a = -(2.0 * dx1 + dx2) / (dx1 * (dx1 + dx2))
1691
+ b = (dx1 + dx2) / (dx1 * dx2)
1692
+ c = -dx1 / (dx2 * (dx1 + dx2))
1693
+ # 1D equivalent -- out[0] = a * f[0] + b * f[1] + c * f[2]
1694
+ out[tuple(slice1)] = (
1695
+ a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
1696
+ )
1697
+
1698
+ slice1[axis] = -1
1699
+ slice2[axis] = -3
1700
+ slice3[axis] = -2
1701
+ slice4[axis] = -1
1702
+ if uniform_spacing:
1703
+ a = 0.5 / ax_dx
1704
+ b = -2.0 / ax_dx
1705
+ c = 1.5 / ax_dx
1706
+ else:
1707
+ dx1 = ax_dx[-2]
1708
+ dx2 = ax_dx[-1]
1709
+ a = (dx2) / (dx1 * (dx1 + dx2))
1710
+ b = -(dx2 + dx1) / (dx1 * dx2)
1711
+ c = (2.0 * dx2 + dx1) / (dx2 * (dx1 + dx2))
1712
+ # 1D equivalent -- out[-1] = a * f[-3] + b * f[-2] + c * f[-1]
1713
+ out[tuple(slice1)] = (
1714
+ a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
1715
+ )
1716
+
1717
+ outvals.append(out)
1718
+
1719
+ # reset the slice object in this dimension to ":"
1720
+ slice1[axis] = slice(None)
1721
+ slice2[axis] = slice(None)
1722
+ slice3[axis] = slice(None)
1723
+ slice4[axis] = slice(None)
1724
+
1725
+ if len_axes == 1:
1726
+ return outvals[0]
1727
+ else:
1728
+ return outvals
1729
+
1730
+
1731
+ # ### Type/shape etc queries ###
1732
+
1733
+
1734
+ def round(a: ArrayLike, decimals=0, out: OutArray | None = None):
1735
+ if a.is_floating_point():
1736
+ result = torch.round(a, decimals=decimals)
1737
+ elif a.is_complex():
1738
+ # RuntimeError: "round_cpu" not implemented for 'ComplexFloat'
1739
+ result = torch.complex(
1740
+ torch.round(a.real, decimals=decimals),
1741
+ torch.round(a.imag, decimals=decimals),
1742
+ )
1743
+ else:
1744
+ # RuntimeError: "round_cpu" not implemented for 'int'
1745
+ result = a
1746
+ return result
1747
+
1748
+
1749
+ around = round
1750
+ round_ = round
1751
+
1752
+
1753
+ def real_if_close(a: ArrayLike, tol=100):
1754
+ if not torch.is_complex(a):
1755
+ return a
1756
+ if tol > 1:
1757
+ # Undocumented in numpy: if tol < 1, it's an absolute tolerance!
1758
+ # Otherwise, tol > 1 is relative tolerance, in units of the dtype epsilon
1759
+ # https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/type_check.py#L577
1760
+ tol = tol * torch.finfo(a.dtype).eps
1761
+
1762
+ mask = torch.abs(a.imag) < tol
1763
+ return a.real if mask.all() else a
1764
+
1765
+
1766
+ def real(a: ArrayLike):
1767
+ return torch.real(a)
1768
+
1769
+
1770
+ def imag(a: ArrayLike):
1771
+ if a.is_complex():
1772
+ return a.imag
1773
+ return torch.zeros_like(a)
1774
+
1775
+
1776
+ def iscomplex(x: ArrayLike):
1777
+ if torch.is_complex(x):
1778
+ return x.imag != 0
1779
+ return torch.zeros_like(x, dtype=torch.bool)
1780
+
1781
+
1782
+ def isreal(x: ArrayLike):
1783
+ if torch.is_complex(x):
1784
+ return x.imag == 0
1785
+ return torch.ones_like(x, dtype=torch.bool)
1786
+
1787
+
1788
+ def iscomplexobj(x: ArrayLike):
1789
+ return torch.is_complex(x)
1790
+
1791
+
1792
+ def isrealobj(x: ArrayLike):
1793
+ return not torch.is_complex(x)
1794
+
1795
+
1796
+ def isneginf(x: ArrayLike, out: OutArray | None = None):
1797
+ return torch.isneginf(x)
1798
+
1799
+
1800
+ def isposinf(x: ArrayLike, out: OutArray | None = None):
1801
+ return torch.isposinf(x)
1802
+
1803
+
1804
+ def i0(x: ArrayLike):
1805
+ return torch.special.i0(x)
1806
+
1807
+
1808
+ def isscalar(a):
1809
+ # We need to use normalize_array_like, but we don't want to export it in funcs.py
1810
+ from ._normalizations import normalize_array_like
1811
+
1812
+ try:
1813
+ t = normalize_array_like(a)
1814
+ return t.numel() == 1
1815
+ except Exception:
1816
+ return False
1817
+
1818
+
1819
+ # ### Filter windows ###
1820
+
1821
+
1822
+ def hamming(M):
1823
+ dtype = _dtypes_impl.default_dtypes().float_dtype
1824
+ return torch.hamming_window(M, periodic=False, dtype=dtype)
1825
+
1826
+
1827
+ def hanning(M):
1828
+ dtype = _dtypes_impl.default_dtypes().float_dtype
1829
+ return torch.hann_window(M, periodic=False, dtype=dtype)
1830
+
1831
+
1832
+ def kaiser(M, beta):
1833
+ dtype = _dtypes_impl.default_dtypes().float_dtype
1834
+ return torch.kaiser_window(M, beta=beta, periodic=False, dtype=dtype)
1835
+
1836
+
1837
+ def blackman(M):
1838
+ dtype = _dtypes_impl.default_dtypes().float_dtype
1839
+ return torch.blackman_window(M, periodic=False, dtype=dtype)
1840
+
1841
+
1842
+ def bartlett(M):
1843
+ dtype = _dtypes_impl.default_dtypes().float_dtype
1844
+ return torch.bartlett_window(M, periodic=False, dtype=dtype)
1845
+
1846
+
1847
+ # ### Dtype routines ###
1848
+
1849
+ # vendored from https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/type_check.py#L666
1850
+
1851
+
1852
+ array_type = [
1853
+ [torch.float16, torch.float32, torch.float64],
1854
+ [None, torch.complex64, torch.complex128],
1855
+ ]
1856
+ array_precision = {
1857
+ torch.float16: 0,
1858
+ torch.float32: 1,
1859
+ torch.float64: 2,
1860
+ torch.complex64: 1,
1861
+ torch.complex128: 2,
1862
+ }
1863
+
1864
+
1865
+ def common_type(*tensors: ArrayLike):
1866
+ is_complex = False
1867
+ precision = 0
1868
+ for a in tensors:
1869
+ t = a.dtype
1870
+ if iscomplexobj(a):
1871
+ is_complex = True
1872
+ if not (t.is_floating_point or t.is_complex):
1873
+ p = 2 # array_precision[_nx.double]
1874
+ else:
1875
+ p = array_precision.get(t)
1876
+ if p is None:
1877
+ raise TypeError("can't get common type for non-numeric array")
1878
+ precision = builtins.max(precision, p)
1879
+ if is_complex:
1880
+ return array_type[1][precision]
1881
+ else:
1882
+ return array_type[0][precision]
1883
+
1884
+
1885
+ # ### histograms ###
1886
+
1887
+
1888
+ def histogram(
1889
+ a: ArrayLike,
1890
+ bins: ArrayLike = 10,
1891
+ range=None,
1892
+ normed=None,
1893
+ weights: ArrayLike | None = None,
1894
+ density=None,
1895
+ ):
1896
+ if normed is not None:
1897
+ raise ValueError("normed argument is deprecated, use density= instead")
1898
+
1899
+ if weights is not None and weights.dtype.is_complex:
1900
+ raise NotImplementedError("complex weights histogram.")
1901
+
1902
+ is_a_int = not (a.dtype.is_floating_point or a.dtype.is_complex)
1903
+ is_w_int = weights is None or not weights.dtype.is_floating_point
1904
+ if is_a_int:
1905
+ a = a.double()
1906
+
1907
+ if weights is not None:
1908
+ weights = _util.cast_if_needed(weights, a.dtype)
1909
+
1910
+ if isinstance(bins, torch.Tensor):
1911
+ if bins.ndim == 0:
1912
+ # bins was a single int
1913
+ bins = operator.index(bins)
1914
+ else:
1915
+ bins = _util.cast_if_needed(bins, a.dtype)
1916
+
1917
+ if range is None:
1918
+ h, b = torch.histogram(a, bins, weight=weights, density=bool(density))
1919
+ else:
1920
+ h, b = torch.histogram(
1921
+ a, bins, range=range, weight=weights, density=bool(density)
1922
+ )
1923
+
1924
+ if not density and is_w_int:
1925
+ h = h.long()
1926
+ if is_a_int:
1927
+ b = b.long()
1928
+
1929
+ return h, b
1930
+
1931
+
1932
+ def histogram2d(
1933
+ x,
1934
+ y,
1935
+ bins=10,
1936
+ range: ArrayLike | None = None,
1937
+ normed=None,
1938
+ weights: ArrayLike | None = None,
1939
+ density=None,
1940
+ ):
1941
+ # vendored from https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/twodim_base.py#L655-L821
1942
+ if len(x) != len(y):
1943
+ raise ValueError("x and y must have the same length.")
1944
+
1945
+ try:
1946
+ N = len(bins)
1947
+ except TypeError:
1948
+ N = 1
1949
+
1950
+ if N != 1 and N != 2:
1951
+ bins = [bins, bins]
1952
+
1953
+ h, e = histogramdd((x, y), bins, range, normed, weights, density)
1954
+
1955
+ return h, e[0], e[1]
1956
+
1957
+
1958
+ def histogramdd(
1959
+ sample,
1960
+ bins=10,
1961
+ range: ArrayLike | None = None,
1962
+ normed=None,
1963
+ weights: ArrayLike | None = None,
1964
+ density=None,
1965
+ ):
1966
+ # have to normalize manually because `sample` interpretation differs
1967
+ # for a list of lists and a 2D array
1968
+ if normed is not None:
1969
+ raise ValueError("normed argument is deprecated, use density= instead")
1970
+
1971
+ from ._normalizations import normalize_array_like, normalize_seq_array_like
1972
+
1973
+ if isinstance(sample, (list, tuple)):
1974
+ sample = normalize_array_like(sample).T
1975
+ else:
1976
+ sample = normalize_array_like(sample)
1977
+
1978
+ sample = torch.atleast_2d(sample)
1979
+
1980
+ if not (sample.dtype.is_floating_point or sample.dtype.is_complex):
1981
+ sample = sample.double()
1982
+
1983
+ # bins is either an int, or a sequence of ints or a sequence of arrays
1984
+ bins_is_array = not (
1985
+ isinstance(bins, int) or builtins.all(isinstance(b, int) for b in bins)
1986
+ )
1987
+ if bins_is_array:
1988
+ bins = normalize_seq_array_like(bins)
1989
+ bins_dtypes = [b.dtype for b in bins]
1990
+ bins = [_util.cast_if_needed(b, sample.dtype) for b in bins]
1991
+
1992
+ if range is not None:
1993
+ range = range.flatten().tolist()
1994
+
1995
+ if weights is not None:
1996
+ # range=... is required : interleave min and max values per dimension
1997
+ mm = sample.aminmax(dim=0)
1998
+ range = torch.cat(mm).reshape(2, -1).T.flatten()
1999
+ range = tuple(range.tolist())
2000
+ weights = _util.cast_if_needed(weights, sample.dtype)
2001
+ w_kwd = {"weight": weights}
2002
+ else:
2003
+ w_kwd = {}
2004
+
2005
+ h, b = torch.histogramdd(sample, bins, range, density=bool(density), **w_kwd)
2006
+
2007
+ if bins_is_array:
2008
+ b = [_util.cast_if_needed(bb, dtyp) for bb, dtyp in zip(b, bins_dtypes)]
2009
+
2010
+ return h, b
2011
+
2012
+
2013
+ # ### odds and ends
2014
+
2015
+
2016
+ def min_scalar_type(a: ArrayLike, /):
2017
+ # https://github.com/numpy/numpy/blob/maintenance/1.24.x/numpy/core/src/multiarray/convert_datatype.c#L1288
2018
+
2019
+ from ._dtypes import DType
2020
+
2021
+ if a.numel() > 1:
2022
+ # numpy docs: "For non-scalar array a, returns the vector's dtype unmodified."
2023
+ return DType(a.dtype)
2024
+
2025
+ if a.dtype == torch.bool:
2026
+ dtype = torch.bool
2027
+
2028
+ elif a.dtype.is_complex:
2029
+ fi = torch.finfo(torch.float32)
2030
+ fits_in_single = a.dtype == torch.complex64 or (
2031
+ fi.min <= a.real <= fi.max and fi.min <= a.imag <= fi.max
2032
+ )
2033
+ dtype = torch.complex64 if fits_in_single else torch.complex128
2034
+
2035
+ elif a.dtype.is_floating_point:
2036
+ for dt in [torch.float16, torch.float32, torch.float64]:
2037
+ fi = torch.finfo(dt)
2038
+ if fi.min <= a <= fi.max:
2039
+ dtype = dt
2040
+ break
2041
+ else:
2042
+ # must be integer
2043
+ for dt in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]:
2044
+ # Prefer unsigned int where possible, as numpy does.
2045
+ ii = torch.iinfo(dt)
2046
+ if ii.min <= a <= ii.max:
2047
+ dtype = dt
2048
+ break
2049
+
2050
+ return DType(dtype)
2051
+
2052
+
2053
+ def pad(array: ArrayLike, pad_width: ArrayLike, mode="constant", **kwargs):
2054
+ if mode != "constant":
2055
+ raise NotImplementedError
2056
+ value = kwargs.get("constant_values", 0)
2057
+ # `value` must be a python scalar for torch.nn.functional.pad
2058
+ typ = _dtypes_impl.python_type_for_torch(array.dtype)
2059
+ value = typ(value)
2060
+
2061
+ pad_width = torch.broadcast_to(pad_width, (array.ndim, 2))
2062
+ pad_width = torch.flip(pad_width, (0,)).flatten()
2063
+
2064
+ return torch.nn.functional.pad(array, tuple(pad_width), value=value)
.venv/lib/python3.12/site-packages/torch/_numpy/_getlimits.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import torch
4
+
5
+ from . import _dtypes
6
+
7
+
8
+ def finfo(dtyp):
9
+ torch_dtype = _dtypes.dtype(dtyp).torch_dtype
10
+ return torch.finfo(torch_dtype)
11
+
12
+
13
+ def iinfo(dtyp):
14
+ torch_dtype = _dtypes.dtype(dtyp).torch_dtype
15
+ return torch.iinfo(torch_dtype)
.venv/lib/python3.12/site-packages/torch/_numpy/_ndarray.py ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ from __future__ import annotations
4
+
5
+ import builtins
6
+ import math
7
+ import operator
8
+ from collections.abc import Sequence
9
+
10
+ import torch
11
+
12
+ from . import _dtypes, _dtypes_impl, _funcs, _ufuncs, _util
13
+ from ._normalizations import (
14
+ ArrayLike,
15
+ normalize_array_like,
16
+ normalizer,
17
+ NotImplementedType,
18
+ )
19
+
20
+
21
+ newaxis = None
22
+
23
+ FLAGS = [
24
+ "C_CONTIGUOUS",
25
+ "F_CONTIGUOUS",
26
+ "OWNDATA",
27
+ "WRITEABLE",
28
+ "ALIGNED",
29
+ "WRITEBACKIFCOPY",
30
+ "FNC",
31
+ "FORC",
32
+ "BEHAVED",
33
+ "CARRAY",
34
+ "FARRAY",
35
+ ]
36
+
37
+ SHORTHAND_TO_FLAGS = {
38
+ "C": "C_CONTIGUOUS",
39
+ "F": "F_CONTIGUOUS",
40
+ "O": "OWNDATA",
41
+ "W": "WRITEABLE",
42
+ "A": "ALIGNED",
43
+ "X": "WRITEBACKIFCOPY",
44
+ "B": "BEHAVED",
45
+ "CA": "CARRAY",
46
+ "FA": "FARRAY",
47
+ }
48
+
49
+
50
+ class Flags:
51
+ def __init__(self, flag_to_value: dict):
52
+ invalid_keys = [k for k in flag_to_value if k not in FLAGS]
53
+ if invalid_keys:
54
+ raise AssertionError(f"Invalid flag keys: {invalid_keys}")
55
+ self._flag_to_value = flag_to_value
56
+
57
+ def __getattr__(self, attr: str):
58
+ if attr.islower() and attr.upper() in FLAGS:
59
+ return self[attr.upper()]
60
+ else:
61
+ raise AttributeError(f"No flag attribute '{attr}'")
62
+
63
+ def __getitem__(self, key):
64
+ if key in SHORTHAND_TO_FLAGS:
65
+ key = SHORTHAND_TO_FLAGS[key]
66
+ if key in FLAGS:
67
+ try:
68
+ return self._flag_to_value[key]
69
+ except KeyError as e:
70
+ raise NotImplementedError(f"{key=}") from e
71
+ else:
72
+ raise KeyError(f"No flag key '{key}'")
73
+
74
+ def __setattr__(self, attr, value):
75
+ if attr.islower() and attr.upper() in FLAGS:
76
+ self[attr.upper()] = value
77
+ else:
78
+ super().__setattr__(attr, value)
79
+
80
+ def __setitem__(self, key, value):
81
+ if key in FLAGS or key in SHORTHAND_TO_FLAGS:
82
+ raise NotImplementedError("Modifying flags is not implemented")
83
+ else:
84
+ raise KeyError(f"No flag key '{key}'")
85
+
86
+
87
+ def create_method(fn, name=None):
88
+ name = name or fn.__name__
89
+
90
+ def f(*args, **kwargs):
91
+ return fn(*args, **kwargs)
92
+
93
+ f.__name__ = name
94
+ f.__qualname__ = f"ndarray.{name}"
95
+ return f
96
+
97
+
98
+ # Map ndarray.name_method -> np.name_func
99
+ # If name_func == None, it means that name_method == name_func
100
+ methods = {
101
+ "clip": None,
102
+ "nonzero": None,
103
+ "repeat": None,
104
+ "round": None,
105
+ "squeeze": None,
106
+ "swapaxes": None,
107
+ "ravel": None,
108
+ # linalg
109
+ "diagonal": None,
110
+ "dot": None,
111
+ "trace": None,
112
+ # sorting
113
+ "argsort": None,
114
+ "searchsorted": None,
115
+ # reductions
116
+ "argmax": None,
117
+ "argmin": None,
118
+ "any": None,
119
+ "all": None,
120
+ "max": None,
121
+ "min": None,
122
+ "ptp": None,
123
+ "sum": None,
124
+ "prod": None,
125
+ "mean": None,
126
+ "var": None,
127
+ "std": None,
128
+ # scans
129
+ "cumsum": None,
130
+ "cumprod": None,
131
+ # advanced indexing
132
+ "take": None,
133
+ "choose": None,
134
+ }
135
+
136
+ dunder = {
137
+ "abs": "absolute",
138
+ "invert": None,
139
+ "pos": "positive",
140
+ "neg": "negative",
141
+ "gt": "greater",
142
+ "lt": "less",
143
+ "ge": "greater_equal",
144
+ "le": "less_equal",
145
+ }
146
+
147
+ # dunder methods with right-looking and in-place variants
148
+ ri_dunder = {
149
+ "add": None,
150
+ "sub": "subtract",
151
+ "mul": "multiply",
152
+ "truediv": "divide",
153
+ "floordiv": "floor_divide",
154
+ "pow": "power",
155
+ "mod": "remainder",
156
+ "and": "bitwise_and",
157
+ "or": "bitwise_or",
158
+ "xor": "bitwise_xor",
159
+ "lshift": "left_shift",
160
+ "rshift": "right_shift",
161
+ "matmul": None,
162
+ }
163
+
164
+
165
+ def _upcast_int_indices(index):
166
+ if isinstance(index, torch.Tensor):
167
+ if index.dtype in (torch.int8, torch.int16, torch.int32, torch.uint8):
168
+ return index.to(torch.int64)
169
+ elif isinstance(index, tuple):
170
+ return tuple(_upcast_int_indices(i) for i in index)
171
+ return index
172
+
173
+
174
+ def _has_advanced_indexing(index):
175
+ """Check if there's any advanced indexing"""
176
+ return any(
177
+ isinstance(idx, (Sequence, bool))
178
+ or (isinstance(idx, torch.Tensor) and (idx.dtype == torch.bool or idx.ndim > 0))
179
+ for idx in index
180
+ )
181
+
182
+
183
+ def _numpy_compatible_indexing(index):
184
+ """Convert scalar indices to lists when advanced indexing is present for NumPy compatibility."""
185
+ if not isinstance(index, tuple):
186
+ index = (index,)
187
+
188
+ # Check if there's any advanced indexing (sequences, booleans, or tensors)
189
+ has_advanced = _has_advanced_indexing(index)
190
+
191
+ if not has_advanced:
192
+ return index
193
+
194
+ # Convert integer scalar indices to single-element lists when advanced indexing is present
195
+ # Note: Do NOT convert boolean scalars (True/False) as they have special meaning in NumPy
196
+ converted = []
197
+ for idx in index:
198
+ if isinstance(idx, int) and not isinstance(idx, bool):
199
+ # Integer scalars should be converted to lists
200
+ converted.append([idx])
201
+ elif (
202
+ isinstance(idx, torch.Tensor)
203
+ and idx.ndim == 0
204
+ and not torch.is_floating_point(idx)
205
+ and idx.dtype != torch.bool
206
+ ):
207
+ # Zero-dimensional tensors holding integers should be treated the same as integer scalars
208
+ converted.append([idx])
209
+ else:
210
+ # Everything else (booleans, lists, slices, etc.) stays as is
211
+ converted.append(idx)
212
+
213
+ return tuple(converted)
214
+
215
+
216
+ def _get_bool_depth(s):
217
+ """Returns the depth of a boolean sequence/tensor"""
218
+ if isinstance(s, bool):
219
+ return True, 0
220
+ if isinstance(s, torch.Tensor) and s.dtype == torch.bool:
221
+ return True, s.ndim
222
+ if not (isinstance(s, Sequence) and s and s[0] != s):
223
+ return False, 0
224
+ is_bool, depth = _get_bool_depth(s[0])
225
+ return is_bool, depth + 1
226
+
227
+
228
+ def _numpy_empty_ellipsis_patch(index, tensor_ndim):
229
+ """
230
+ Patch for NumPy-compatible ellipsis behavior when ellipsis doesn't match any dimensions.
231
+
232
+ In NumPy, when an ellipsis (...) doesn't actually match any dimensions of the input array,
233
+ it still acts as a separator between advanced indices. PyTorch doesn't have this behavior.
234
+
235
+ This function detects when we have:
236
+ 1. Advanced indexing on both sides of an ellipsis
237
+ 2. The ellipsis doesn't actually match any dimensions
238
+ """
239
+ if not isinstance(index, tuple):
240
+ index = (index,)
241
+
242
+ # Find ellipsis position
243
+ ellipsis_pos = None
244
+ for i, idx in enumerate(index):
245
+ if idx is Ellipsis:
246
+ ellipsis_pos = i
247
+ break
248
+
249
+ # If no ellipsis, no patch needed
250
+ if ellipsis_pos is None:
251
+ return index, lambda x: x, lambda x: x
252
+
253
+ # Count non-ellipsis dimensions consumed by the index
254
+ consumed_dims = 0
255
+ for idx in index:
256
+ is_bool, depth = _get_bool_depth(idx)
257
+ if is_bool:
258
+ consumed_dims += depth
259
+ elif idx is Ellipsis or idx is None:
260
+ continue
261
+ else:
262
+ consumed_dims += 1
263
+
264
+ # Calculate how many dimensions the ellipsis should match
265
+ ellipsis_dims = tensor_ndim - consumed_dims
266
+
267
+ # Check if ellipsis doesn't match any dimensions
268
+ if ellipsis_dims == 0:
269
+ # Check if we have advanced indexing on both sides of ellipsis
270
+ left_advanced = _has_advanced_indexing(index[:ellipsis_pos])
271
+ right_advanced = _has_advanced_indexing(index[ellipsis_pos + 1 :])
272
+
273
+ if left_advanced and right_advanced:
274
+ # This is the case where NumPy and PyTorch differ
275
+ # We need to ensure the advanced indices are treated as separated
276
+ new_index = index[:ellipsis_pos] + (None,) + index[ellipsis_pos + 1 :]
277
+ end_ndims = 1 + sum(
278
+ 1 for idx in index[ellipsis_pos + 1 :] if isinstance(idx, slice)
279
+ )
280
+
281
+ def squeeze_fn(x):
282
+ return x.squeeze(-end_ndims)
283
+
284
+ def unsqueeze_fn(x):
285
+ if isinstance(x, torch.Tensor) and x.ndim >= end_ndims:
286
+ return x.unsqueeze(-end_ndims)
287
+ return x
288
+
289
+ return new_index, squeeze_fn, unsqueeze_fn
290
+
291
+ return index, lambda x: x, lambda x: x
292
+
293
+
294
+ # Used to indicate that a parameter is unspecified (as opposed to explicitly
295
+ # `None`)
296
+ class _Unspecified:
297
+ pass
298
+
299
+
300
+ _Unspecified.unspecified = _Unspecified()
301
+
302
+ ###############################################################
303
+ # ndarray class #
304
+ ###############################################################
305
+
306
+
307
+ class ndarray:
308
+ def __init__(self, t=None):
309
+ if t is None:
310
+ self.tensor = torch.Tensor()
311
+ elif isinstance(t, torch.Tensor):
312
+ self.tensor = t
313
+ else:
314
+ raise ValueError(
315
+ "ndarray constructor is not recommended; prefer"
316
+ "either array(...) or zeros/empty(...)"
317
+ )
318
+
319
+ # Register NumPy functions as methods
320
+ for method, name in methods.items():
321
+ fn = getattr(_funcs, name or method)
322
+ vars()[method] = create_method(fn, method)
323
+
324
+ # Regular methods but coming from ufuncs
325
+ conj = create_method(_ufuncs.conjugate, "conj")
326
+ conjugate = create_method(_ufuncs.conjugate)
327
+
328
+ for method, name in dunder.items():
329
+ fn = getattr(_ufuncs, name or method)
330
+ method = f"__{method}__"
331
+ vars()[method] = create_method(fn, method)
332
+
333
+ for method, name in ri_dunder.items():
334
+ fn = getattr(_ufuncs, name or method)
335
+ plain = f"__{method}__"
336
+ vars()[plain] = create_method(fn, plain)
337
+ rvar = f"__r{method}__"
338
+ vars()[rvar] = create_method(lambda self, other, fn=fn: fn(other, self), rvar)
339
+ ivar = f"__i{method}__"
340
+ vars()[ivar] = create_method(
341
+ lambda self, other, fn=fn: fn(self, other, out=self), ivar
342
+ )
343
+
344
+ # There's no __idivmod__
345
+ __divmod__ = create_method(_ufuncs.divmod, "__divmod__")
346
+ __rdivmod__ = create_method(
347
+ lambda self, other: _ufuncs.divmod(other, self), "__rdivmod__"
348
+ )
349
+
350
+ # prevent loop variables leaking into the ndarray class namespace
351
+ del ivar, rvar, name, plain, fn, method
352
+
353
+ @property
354
+ def shape(self):
355
+ return tuple(self.tensor.shape)
356
+
357
+ @property
358
+ def size(self):
359
+ return self.tensor.numel()
360
+
361
+ @property
362
+ def ndim(self):
363
+ return self.tensor.ndim
364
+
365
+ @property
366
+ def dtype(self):
367
+ return _dtypes.dtype(self.tensor.dtype)
368
+
369
+ @property
370
+ def strides(self):
371
+ elsize = self.tensor.element_size()
372
+ return tuple(stride * elsize for stride in self.tensor.stride())
373
+
374
+ @property
375
+ def itemsize(self):
376
+ return self.tensor.element_size()
377
+
378
+ @property
379
+ def flags(self):
380
+ # Note contiguous in torch is assumed C-style
381
+ return Flags(
382
+ {
383
+ "C_CONTIGUOUS": self.tensor.is_contiguous(),
384
+ "F_CONTIGUOUS": self.T.tensor.is_contiguous(),
385
+ "OWNDATA": self.tensor._base is None,
386
+ "WRITEABLE": True, # pytorch does not have readonly tensors
387
+ }
388
+ )
389
+
390
+ @property
391
+ def data(self):
392
+ return self.tensor.data_ptr()
393
+
394
+ @property
395
+ def nbytes(self):
396
+ return self.tensor.storage().nbytes()
397
+
398
+ @property
399
+ def T(self):
400
+ return self.transpose()
401
+
402
+ @property
403
+ def real(self):
404
+ return _funcs.real(self)
405
+
406
+ @real.setter
407
+ def real(self, value):
408
+ self.tensor.real = asarray(value).tensor
409
+
410
+ @property
411
+ def imag(self):
412
+ return _funcs.imag(self)
413
+
414
+ @imag.setter
415
+ def imag(self, value):
416
+ self.tensor.imag = asarray(value).tensor
417
+
418
+ @property
419
+ def flat(self):
420
+ return self.ravel()
421
+
422
+ # ctors
423
+ def astype(self, dtype, order="K", casting="unsafe", subok=True, copy=True):
424
+ if order != "K":
425
+ raise NotImplementedError(f"astype(..., order={order} is not implemented.")
426
+ if casting != "unsafe":
427
+ raise NotImplementedError(
428
+ f"astype(..., casting={casting} is not implemented."
429
+ )
430
+ if not subok:
431
+ raise NotImplementedError(f"astype(..., subok={subok} is not implemented.")
432
+ if not copy:
433
+ raise NotImplementedError(f"astype(..., copy={copy} is not implemented.")
434
+ torch_dtype = _dtypes.dtype(dtype).torch_dtype
435
+ t = self.tensor.to(torch_dtype)
436
+ return ndarray(t)
437
+
438
+ @normalizer
439
+ def copy(self: ArrayLike, order: NotImplementedType = "C"):
440
+ return self.clone()
441
+
442
+ @normalizer
443
+ def flatten(self: ArrayLike, order: NotImplementedType = "C"):
444
+ return torch.flatten(self)
445
+
446
+ def resize(self, *new_shape, refcheck=False):
447
+ # NB: differs from np.resize: fills with zeros instead of making repeated copies of input.
448
+ if refcheck:
449
+ raise NotImplementedError(
450
+ f"resize(..., refcheck={refcheck} is not implemented."
451
+ )
452
+ if new_shape in [(), (None,)]:
453
+ return
454
+
455
+ # support both x.resize((2, 2)) and x.resize(2, 2)
456
+ if len(new_shape) == 1:
457
+ new_shape = new_shape[0]
458
+ if isinstance(new_shape, int):
459
+ new_shape = (new_shape,)
460
+
461
+ if builtins.any(x < 0 for x in new_shape):
462
+ raise ValueError("all elements of `new_shape` must be non-negative")
463
+
464
+ new_numel, old_numel = math.prod(new_shape), self.tensor.numel()
465
+
466
+ self.tensor.resize_(new_shape)
467
+
468
+ if new_numel >= old_numel:
469
+ # zero-fill new elements
470
+ if not self.tensor.is_contiguous():
471
+ raise AssertionError("tensor must be contiguous for resize with growth")
472
+ b = self.tensor.flatten() # does not copy
473
+ b[old_numel:].zero_()
474
+
475
+ def view(self, dtype=_Unspecified.unspecified, type=_Unspecified.unspecified):
476
+ if dtype is _Unspecified.unspecified:
477
+ dtype = self.dtype
478
+ if type is not _Unspecified.unspecified:
479
+ raise NotImplementedError(f"view(..., type={type} is not implemented.")
480
+ torch_dtype = _dtypes.dtype(dtype).torch_dtype
481
+ tview = self.tensor.view(torch_dtype)
482
+ return ndarray(tview)
483
+
484
+ @normalizer
485
+ def fill(self, value: ArrayLike):
486
+ # Both Pytorch and NumPy accept 0D arrays/tensors and scalars, and
487
+ # error out on D > 0 arrays
488
+ self.tensor.fill_(value)
489
+
490
+ def tolist(self):
491
+ return self.tensor.tolist()
492
+
493
+ def __iter__(self):
494
+ return (ndarray(x) for x in self.tensor.__iter__())
495
+
496
+ def __str__(self):
497
+ return (
498
+ str(self.tensor)
499
+ .replace("tensor", "torch.ndarray")
500
+ .replace("dtype=torch.", "dtype=")
501
+ )
502
+
503
+ __repr__ = create_method(__str__)
504
+
505
+ def __eq__(self, other):
506
+ try:
507
+ return _ufuncs.equal(self, other)
508
+ except (RuntimeError, TypeError):
509
+ # Failed to convert other to array: definitely not equal.
510
+ falsy = torch.full(self.shape, fill_value=False, dtype=bool)
511
+ return asarray(falsy)
512
+
513
+ def __ne__(self, other):
514
+ return ~(self == other)
515
+
516
+ def __index__(self):
517
+ try:
518
+ return operator.index(self.tensor.item())
519
+ except Exception as exc:
520
+ raise TypeError(
521
+ "only integer scalar arrays can be converted to a scalar index"
522
+ ) from exc
523
+
524
+ def __bool__(self):
525
+ return bool(self.tensor)
526
+
527
+ def __int__(self):
528
+ return int(self.tensor)
529
+
530
+ def __float__(self):
531
+ return float(self.tensor)
532
+
533
+ def __complex__(self):
534
+ return complex(self.tensor)
535
+
536
+ def is_integer(self):
537
+ try:
538
+ v = self.tensor.item()
539
+ result = int(v) == v
540
+ except Exception:
541
+ result = False
542
+ return result
543
+
544
+ def __len__(self):
545
+ return self.tensor.shape[0]
546
+
547
+ def __contains__(self, x):
548
+ return self.tensor.__contains__(x)
549
+
550
+ def transpose(self, *axes):
551
+ # np.transpose(arr, axis=None) but arr.transpose(*axes)
552
+ return _funcs.transpose(self, axes)
553
+
554
+ def reshape(self, *shape, order="C"):
555
+ # arr.reshape(shape) and arr.reshape(*shape)
556
+ return _funcs.reshape(self, shape, order=order)
557
+
558
+ def sort(self, axis=-1, kind=None, order=None):
559
+ # ndarray.sort works in-place
560
+ _funcs.copyto(self, _funcs.sort(self, axis, kind, order))
561
+
562
+ def item(self, *args):
563
+ # Mimic NumPy's implementation with three special cases (no arguments,
564
+ # a flat index and a multi-index):
565
+ # https://github.com/numpy/numpy/blob/main/numpy/_core/src/multiarray/methods.c#L702
566
+ if args == ():
567
+ return self.tensor.item()
568
+ elif len(args) == 1:
569
+ # int argument
570
+ return self.ravel()[args[0]]
571
+ else:
572
+ return self.__getitem__(args)
573
+
574
+ def __getitem__(self, index):
575
+ tensor = self.tensor
576
+
577
+ def neg_step(i, s):
578
+ if not (isinstance(s, slice) and s.step is not None and s.step < 0):
579
+ return s
580
+
581
+ nonlocal tensor
582
+ tensor = torch.flip(tensor, (i,))
583
+
584
+ # Account for the fact that a slice includes the start but not the end
585
+ if not (isinstance(s.start, int) or s.start is None):
586
+ raise AssertionError(
587
+ f"slice start must be int or None, got {type(s.start).__name__}"
588
+ )
589
+ if not (isinstance(s.stop, int) or s.stop is None):
590
+ raise AssertionError(
591
+ f"slice stop must be int or None, got {type(s.stop).__name__}"
592
+ )
593
+ start = s.stop + 1 if s.stop else None
594
+ stop = s.start + 1 if s.start else None
595
+
596
+ return slice(start, stop, -s.step)
597
+
598
+ if isinstance(index, Sequence):
599
+ index = type(index)(neg_step(i, s) for i, s in enumerate(index))
600
+ else:
601
+ index = neg_step(0, index)
602
+ index = _util.ndarrays_to_tensors(index)
603
+ index = _upcast_int_indices(index)
604
+ # Apply NumPy-compatible indexing conversion
605
+ index = _numpy_compatible_indexing(index)
606
+ # Apply NumPy-compatible empty ellipsis behavior
607
+ index, maybe_squeeze, _ = _numpy_empty_ellipsis_patch(index, tensor.ndim)
608
+ return maybe_squeeze(ndarray(tensor.__getitem__(index)))
609
+
610
+ def __setitem__(self, index, value):
611
+ index = _util.ndarrays_to_tensors(index)
612
+ index = _upcast_int_indices(index)
613
+ # Apply NumPy-compatible indexing conversion
614
+ index = _numpy_compatible_indexing(index)
615
+ # Apply NumPy-compatible empty ellipsis behavior
616
+ index, _, maybe_unsqueeze = _numpy_empty_ellipsis_patch(index, self.tensor.ndim)
617
+
618
+ if not _dtypes_impl.is_scalar(value):
619
+ value = normalize_array_like(value)
620
+ value = _util.cast_if_needed(value, self.tensor.dtype)
621
+
622
+ return self.tensor.__setitem__(index, maybe_unsqueeze(value))
623
+
624
+ take = _funcs.take
625
+ put = _funcs.put
626
+
627
+ def __dlpack__(self, *, stream=None):
628
+ return self.tensor.__dlpack__(stream=stream)
629
+
630
+ def __dlpack_device__(self):
631
+ return self.tensor.__dlpack_device__()
632
+
633
+
634
+ def _tolist(obj):
635
+ """Recursively convert tensors into lists."""
636
+ a1 = []
637
+ for elem in obj:
638
+ if isinstance(elem, (list, tuple)):
639
+ elem = _tolist(elem)
640
+ if isinstance(elem, ndarray):
641
+ a1.append(elem.tensor.tolist())
642
+ else:
643
+ a1.append(elem)
644
+ return a1
645
+
646
+
647
+ # This is the ideally the only place which talks to ndarray directly.
648
+ # The rest goes through asarray (preferred) or array.
649
+
650
+
651
+ def array(obj, dtype=None, *, copy=True, order="K", subok=False, ndmin=0, like=None):
652
+ if subok is not False:
653
+ raise NotImplementedError("'subok' parameter is not supported.")
654
+ if like is not None:
655
+ raise NotImplementedError("'like' parameter is not supported.")
656
+ if order != "K":
657
+ raise NotImplementedError
658
+
659
+ # a happy path
660
+ if (
661
+ isinstance(obj, ndarray)
662
+ and copy is False
663
+ and dtype is None
664
+ and ndmin <= obj.ndim
665
+ ):
666
+ return obj
667
+
668
+ if isinstance(obj, (list, tuple)):
669
+ # FIXME and they have the same dtype, device, etc
670
+ if obj and all(isinstance(x, torch.Tensor) for x in obj):
671
+ # list of arrays: *under torch.Dynamo* these are FakeTensors
672
+ obj = torch.stack(obj)
673
+ else:
674
+ # XXX: remove tolist
675
+ # lists of ndarrays: [1, [2, 3], ndarray(4)] convert to lists of lists
676
+ obj = _tolist(obj)
677
+
678
+ # is obj an ndarray already?
679
+ if isinstance(obj, ndarray):
680
+ obj = obj.tensor
681
+
682
+ # is a specific dtype requested?
683
+ torch_dtype = None
684
+ if dtype is not None:
685
+ torch_dtype = _dtypes.dtype(dtype).torch_dtype
686
+
687
+ tensor = _util._coerce_to_tensor(obj, torch_dtype, copy, ndmin)
688
+ return ndarray(tensor)
689
+
690
+
691
+ def asarray(a, dtype=None, order="K", *, like=None):
692
+ return array(a, dtype=dtype, order=order, like=like, copy=False, ndmin=0)
693
+
694
+
695
+ def ascontiguousarray(a, dtype=None, *, like=None):
696
+ arr = asarray(a, dtype=dtype, like=like)
697
+ if not arr.tensor.is_contiguous():
698
+ arr.tensor = arr.tensor.contiguous()
699
+ return arr
700
+
701
+
702
+ def from_dlpack(x, /):
703
+ t = torch.from_dlpack(x)
704
+ return ndarray(t)
705
+
706
+
707
+ def _extract_dtype(entry):
708
+ try:
709
+ dty = _dtypes.dtype(entry)
710
+ except Exception:
711
+ dty = asarray(entry).dtype
712
+ return dty
713
+
714
+
715
+ def can_cast(from_, to, casting="safe"):
716
+ from_ = _extract_dtype(from_)
717
+ to_ = _extract_dtype(to)
718
+
719
+ return _dtypes_impl.can_cast_impl(from_.torch_dtype, to_.torch_dtype, casting)
720
+
721
+
722
+ def result_type(*arrays_and_dtypes):
723
+ tensors = []
724
+ for entry in arrays_and_dtypes:
725
+ try:
726
+ t = asarray(entry).tensor
727
+ except (RuntimeError, ValueError, TypeError):
728
+ dty = _dtypes.dtype(entry)
729
+ t = torch.empty(1, dtype=dty.torch_dtype)
730
+ tensors.append(t)
731
+
732
+ torch_dtype = _dtypes_impl.result_type_impl(*tensors)
733
+ return _dtypes.dtype(torch_dtype)
.venv/lib/python3.12/site-packages/torch/_numpy/_normalizations.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ "Normalize" arguments: convert array_likes to tensors, dtypes to torch dtypes and so on."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import inspect
7
+ import operator
8
+ import typing
9
+ from typing import TYPE_CHECKING
10
+
11
+ import torch
12
+
13
+ from . import _dtypes, _dtypes_impl, _util
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Callable
18
+
19
+ from ._ndarray import ndarray
20
+
21
+
22
+ # These names are used both as static type annotations and as runtime markers:
23
+ # the `normalizer` decorator dispatches on the *string* form of each parameter's
24
+ # annotation (e.g. "ArrayLike", "OutArray | None"). Because `from __future__
25
+ # import annotations` is active everywhere these are used, the annotations are
26
+ # never evaluated, so the static type below is what each parameter resolves to
27
+ # *after* normalization runs (e.g. an ArrayLike argument is a torch.Tensor by the
28
+ # time the implementer body sees it).
29
+ ArrayLike: typing.TypeAlias = torch.Tensor
30
+ Scalar = int | float | complex | bool
31
+ ArrayLikeOrScalar = ArrayLike | Scalar
32
+
33
+ # DTypeLike normalizes to a torch.dtype (or None when no dtype is given).
34
+ DTypeLike: typing.TypeAlias = "torch.dtype | None"
35
+ # AxisLike is an axis specification: a single axis, a tuple of axes, or None.
36
+ AxisLike: typing.TypeAlias = "int | tuple[int, ...] | None"
37
+ # NDArray normalizes to the wrapped tensor.
38
+ NDArray: typing.TypeAlias = torch.Tensor
39
+ # CastingModes is one of the numpy casting strings.
40
+ CastingModes: typing.TypeAlias = str
41
+ # KeepDims is the keepdims flag; handled entirely by the normalizer.
42
+ KeepDims: typing.TypeAlias = bool
43
+
44
+ # OutArray is to annotate the out= array argument.
45
+ #
46
+ # This one is special is several respects:
47
+ # First, It needs to be an NDArray, and we need to preserve the `result is out`
48
+ # semantics. Therefore, we cannot just extract the Tensor from the out array.
49
+ # So we never pass the out array to implementer functions and handle it in the
50
+ # `normalizer` below.
51
+ # Second, the out= argument can be either keyword or positional argument, and
52
+ # as a positional arg, it can be anywhere in the signature.
53
+ # To handle all this, we define a special `OutArray` annotation and dispatch on it.
54
+ #
55
+ OutArray: typing.TypeAlias = "ndarray"
56
+
57
+ # NotImplementedType marks unsupported parameters; the normalizer raises unless
58
+ # the argument equals the (always None) default, so the value is never used.
59
+ NotImplementedType: typing.TypeAlias = None
60
+
61
+
62
+ def normalize_array_like(
63
+ x: object,
64
+ parm: inspect.Parameter | None = None, # codespell:ignore
65
+ ) -> torch.Tensor:
66
+ from ._ndarray import asarray
67
+
68
+ return asarray(x).tensor
69
+
70
+
71
+ def normalize_array_like_or_scalar(
72
+ x: object,
73
+ parm: inspect.Parameter | None = None, # codespell:ignore
74
+ ) -> torch.Tensor | Scalar:
75
+ if _dtypes_impl.is_scalar_or_symbolic(x):
76
+ return x # pyrefly: ignore[bad-return]
77
+ return normalize_array_like(x, parm) # codespell:ignore
78
+
79
+
80
+ def normalize_optional_array_like_or_scalar(
81
+ x: object,
82
+ parm: inspect.Parameter | None = None, # codespell:ignore
83
+ ) -> torch.Tensor | Scalar | None:
84
+ if x is None:
85
+ return None
86
+ return normalize_array_like_or_scalar(x, parm) # codespell:ignore
87
+
88
+
89
+ def normalize_optional_array_like(
90
+ x: object,
91
+ parm: inspect.Parameter | None = None, # codespell:ignore
92
+ ) -> torch.Tensor | None:
93
+ # This explicit normalizer is needed because otherwise normalize_array_like
94
+ # does not run for a parameter annotated as Optional[ArrayLike]
95
+ return None if x is None else normalize_array_like(x, parm) # codespell:ignore
96
+
97
+
98
+ def normalize_seq_array_like(
99
+ x: typing.Iterable[object],
100
+ parm: inspect.Parameter | None = None, # codespell:ignore
101
+ ) -> tuple[torch.Tensor, ...]:
102
+ return tuple(normalize_array_like(value) for value in x)
103
+
104
+
105
+ def normalize_dtype(
106
+ dtype: object,
107
+ parm: inspect.Parameter | None = None, # codespell:ignore
108
+ ) -> torch.dtype | None:
109
+ # cf _decorators.dtype_to_torch
110
+ torch_dtype = None
111
+ if dtype is not None:
112
+ torch_dtype = _dtypes.dtype(dtype).torch_dtype
113
+ return torch_dtype
114
+
115
+
116
+ def normalize_not_implemented(
117
+ arg: object,
118
+ parm: inspect.Parameter, # codespell:ignore
119
+ ) -> None:
120
+ if arg != parm.default: # codespell:ignore
121
+ raise NotImplementedError(
122
+ f"'{parm.name}' parameter is not supported." # codespell:ignore
123
+ )
124
+
125
+
126
+ def normalize_axis_like(
127
+ arg: AxisLike | ndarray,
128
+ parm: inspect.Parameter | None = None, # codespell:ignore
129
+ ) -> AxisLike:
130
+ from ._ndarray import ndarray
131
+
132
+ if isinstance(arg, ndarray):
133
+ return operator.index(arg)
134
+ return arg
135
+
136
+
137
+ def normalize_ndarray(
138
+ arg: object,
139
+ parm: inspect.Parameter | None = None, # codespell:ignore
140
+ ) -> torch.Tensor | None:
141
+ # check the arg is an ndarray, extract its tensor attribute
142
+ if arg is None:
143
+ return arg
144
+
145
+ from ._ndarray import ndarray
146
+
147
+ if not isinstance(arg, ndarray):
148
+ name = parm.name if parm is not None else "argument" # codespell:ignore
149
+ raise TypeError(f"'{name}' must be an array")
150
+ return arg.tensor
151
+
152
+
153
+ def normalize_outarray(
154
+ arg: object,
155
+ parm: inspect.Parameter | None = None, # codespell:ignore
156
+ ) -> ndarray | None:
157
+ # almost normalize_ndarray, only return the array, not its tensor
158
+ if arg is None:
159
+ return arg
160
+ from ._ndarray import ndarray
161
+
162
+ # Dynamo can pass torch tensors as out arguments,
163
+ # wrap it in an ndarray before processing
164
+ if isinstance(arg, torch.Tensor):
165
+ arg = ndarray(arg)
166
+
167
+ if not isinstance(arg, ndarray):
168
+ name = parm.name if parm is not None else "argument" # codespell:ignore
169
+ raise TypeError(f"'{name}' must be an array")
170
+ return arg
171
+
172
+
173
+ def normalize_casting(
174
+ arg: object,
175
+ parm: inspect.Parameter | None = None, # codespell:ignore
176
+ ) -> CastingModes:
177
+ valid = ("no", "equiv", "safe", "same_kind", "unsafe")
178
+ if not isinstance(arg, str) or arg not in valid:
179
+ raise ValueError(
180
+ f"casting must be one of 'no', 'equiv', 'safe', 'same_kind', or 'unsafe' (got '{arg}')"
181
+ )
182
+ return arg
183
+
184
+
185
+ # The registered normalizers have intentionally heterogeneous signatures
186
+ # (e.g. normalize_seq_array_like takes an iterable), so the common callable
187
+ # type erases the parameter list.
188
+ normalizers: dict[str, Callable[..., object]] = {
189
+ "ArrayLike": normalize_array_like,
190
+ "ArrayLikeOrScalar": normalize_array_like_or_scalar,
191
+ "Optional[ArrayLike]": normalize_optional_array_like,
192
+ "ArrayLike | None": normalize_optional_array_like,
193
+ "Sequence[ArrayLike]": normalize_seq_array_like,
194
+ "Optional[ArrayLikeOrScalar]": normalize_optional_array_like_or_scalar,
195
+ "ArrayLikeOrScalar | None": normalize_optional_array_like_or_scalar,
196
+ "Optional[NDArray]": normalize_ndarray,
197
+ "NDArray | None": normalize_ndarray,
198
+ "Optional[OutArray]": normalize_outarray,
199
+ "OutArray | None": normalize_outarray,
200
+ "NDArray": normalize_ndarray,
201
+ "Optional[DTypeLike]": normalize_dtype,
202
+ "DTypeLike | None": normalize_dtype,
203
+ "AxisLike": normalize_axis_like,
204
+ "NotImplementedType": normalize_not_implemented,
205
+ "Optional[CastingModes]": normalize_casting,
206
+ "CastingModes | None": normalize_casting,
207
+ }
208
+
209
+
210
+ def maybe_normalize(arg: object, parm: inspect.Parameter) -> object: # codespell:ignore
211
+ """Normalize arg if a normalizer is registered."""
212
+ normalizer = normalizers.get(parm.annotation) # codespell:ignore
213
+ return normalizer(arg, parm) if normalizer else arg # codespell:ignore
214
+
215
+
216
+ # ### Return value helpers ###
217
+
218
+
219
+ def maybe_copy_to(
220
+ out: ndarray | None, result: object, promote_scalar_result: bool = False
221
+ ) -> object:
222
+ # NB: here out is either an ndarray or None
223
+ if out is None:
224
+ return result
225
+ elif isinstance(result, torch.Tensor):
226
+ if result.shape != out.shape:
227
+ can_fit = result.numel() == 1 and out.ndim == 0
228
+ if promote_scalar_result and can_fit:
229
+ result = result.squeeze()
230
+ else:
231
+ raise ValueError(
232
+ f"Bad size of the out array: out.shape = {out.shape}"
233
+ f" while result.shape = {result.shape}."
234
+ )
235
+ out.tensor.copy_(result)
236
+ return out
237
+ elif isinstance(result, (tuple, list)):
238
+ return type(result)(
239
+ maybe_copy_to(o, r, promote_scalar_result) for o, r in zip(out, result)
240
+ )
241
+ else:
242
+ raise AssertionError # We should never hit this path
243
+
244
+
245
+ def wrap_tensors(result: object) -> object:
246
+ from ._ndarray import ndarray
247
+
248
+ if isinstance(result, torch.Tensor):
249
+ return ndarray(result)
250
+ elif isinstance(result, (tuple, list)):
251
+ result = type(result)(wrap_tensors(x) for x in result)
252
+ return result
253
+
254
+
255
+ def array_or_scalar(
256
+ values: torch.Tensor,
257
+ py_type: type[int | float | complex | bool] = float,
258
+ return_scalar: bool = False,
259
+ ) -> int | float | complex | bool | ndarray:
260
+ if return_scalar:
261
+ return py_type(values.item())
262
+ else:
263
+ from ._ndarray import ndarray
264
+
265
+ return ndarray(values)
266
+
267
+
268
+ # ### The main decorator to normalize arguments / postprocess the output ###
269
+
270
+ _P = typing.ParamSpec("_P")
271
+ _R = typing.TypeVar("_R")
272
+
273
+
274
+ @typing.overload
275
+ def normalizer(_func: Callable[_P, _R]) -> Callable[_P, _R]: ...
276
+
277
+
278
+ @typing.overload
279
+ def normalizer(
280
+ _func: None = None, *, promote_scalar_result: bool = False
281
+ ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
282
+
283
+
284
+ def normalizer(
285
+ _func: Callable[_P, _R] | None = None, *, promote_scalar_result: bool = False
286
+ ) -> Callable[_P, _R] | Callable[[Callable[_P, _R]], Callable[_P, _R]]:
287
+ def normalizer_inner(func: Callable[_P, _R]) -> Callable[_P, _R]:
288
+ @functools.wraps(func)
289
+ def wrapped(*args: _P.args, **kwds: _P.kwargs) -> _R:
290
+ sig = inspect.signature(func)
291
+ params = sig.parameters
292
+ first_param = next(iter(params.values()))
293
+
294
+ # NumPy's API does not have positional args before variadic positional args
295
+ norm_args: tuple[object, ...]
296
+ if first_param.kind == inspect.Parameter.VAR_POSITIONAL:
297
+ norm_args = tuple(maybe_normalize(arg, first_param) for arg in args)
298
+ else:
299
+ # NB: extra unknown arguments: pass through, will raise in func(*args) below
300
+ norm_args = (
301
+ tuple(
302
+ maybe_normalize(arg, parm) # codespell:ignore
303
+ for arg, parm in zip(args, params.values()) # codespell:ignore
304
+ )
305
+ + args[len(params.values()) :]
306
+ )
307
+
308
+ norm_kwds = {
309
+ name: maybe_normalize(arg, params[name]) if name in params else arg
310
+ for name, arg in kwds.items()
311
+ }
312
+
313
+ # The normalizer rebuilds args/kwds, so they are no longer the
314
+ # ParamSpec-tracked *args/**kwargs; the call is correct at runtime.
315
+ # pyrefly: ignore[invalid-param-spec]
316
+ result: object = func(*norm_args, **norm_kwds)
317
+
318
+ # keepdims
319
+ bound_args = None
320
+ if "keepdims" in params and params["keepdims"].annotation == "KeepDims":
321
+ # keepdims can be in any position so we need sig.bind
322
+ bound_args = sig.bind(*norm_args, **norm_kwds).arguments
323
+ if bound_args.get("keepdims", False):
324
+ # In this case the first arg is the initial tensor and
325
+ # the second arg is (optionally) the axis
326
+ tensor = norm_args[0]
327
+ axis = bound_args.get("axis")
328
+ if not isinstance(tensor, torch.Tensor):
329
+ raise AssertionError("keepdims requires a tensor first arg")
330
+ # pyrefly: ignore[bad-argument-type]
331
+ result = _util.apply_keepdims(result, axis, tensor.ndim)
332
+
333
+ # out
334
+ if "out" in params:
335
+ # out can be in any position so we need sig.bind
336
+ if bound_args is None:
337
+ bound_args = sig.bind(*norm_args, **norm_kwds).arguments
338
+ out = bound_args.get("out")
339
+ result = maybe_copy_to(out, result, promote_scalar_result)
340
+ result = wrap_tensors(result)
341
+
342
+ return result # pyrefly: ignore[bad-return]
343
+
344
+ return wrapped
345
+
346
+ if _func is None:
347
+ return normalizer_inner
348
+ else:
349
+ return normalizer_inner(_func)
.venv/lib/python3.12/site-packages/torch/_numpy/_reductions_impl.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of reduction operations, to be wrapped into arrays, dtypes etc
2
+ in the 'public' layer.
3
+
4
+ Anything here only deals with torch objects, e.g. "dtype" is a torch.dtype instance etc
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ from typing import Concatenate, ParamSpec, TYPE_CHECKING, TypeVar
11
+
12
+ import torch
13
+
14
+ from . import _dtypes_impl, _util
15
+
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Callable
19
+
20
+ from ._normalizations import (
21
+ ArrayLike,
22
+ AxisLike,
23
+ DTypeLike,
24
+ KeepDims,
25
+ NotImplementedType,
26
+ OutArray,
27
+ )
28
+
29
+
30
+ _P = ParamSpec("_P")
31
+ _R = TypeVar("_R")
32
+
33
+
34
+ def _deco_axis_expand(
35
+ func: Callable[Concatenate[torch.Tensor, AxisLike, _P], _R],
36
+ ) -> Callable[Concatenate[torch.Tensor, AxisLike, _P], _R]:
37
+ """
38
+ Generically handle axis arguments in reductions.
39
+ axis is *always* the 2nd arg in the function so no need to have a look at its signature
40
+ """
41
+
42
+ @functools.wraps(func)
43
+ def wrapped(
44
+ a: torch.Tensor, axis: AxisLike = None, *args: _P.args, **kwds: _P.kwargs
45
+ ) -> _R:
46
+ if axis is not None:
47
+ axis = _util.normalize_axis_tuple(axis, a.ndim)
48
+
49
+ if axis == ():
50
+ # So we insert a length-one axis and run the reduction along it.
51
+ # We cannot return a.clone() as this would sidestep the checks inside the function
52
+ newshape = _util.expand_shape(a.shape, axis=0)
53
+ a = a.reshape(newshape)
54
+ axis = (0,)
55
+
56
+ return func(a, axis, *args, **kwds)
57
+
58
+ return wrapped
59
+
60
+
61
+ def _atleast_float(dtype: torch.dtype | None, other_dtype: torch.dtype) -> torch.dtype:
62
+ """Return a dtype that is real or complex floating-point.
63
+
64
+ For inputs that are boolean or integer dtypes, this returns the default
65
+ float dtype; inputs that are complex get converted to the default complex
66
+ dtype; real floating-point dtypes (`float*`) get passed through unchanged
67
+ """
68
+ if dtype is None:
69
+ dtype = other_dtype
70
+ if not (dtype.is_floating_point or dtype.is_complex):
71
+ return _dtypes_impl.default_dtypes().float_dtype
72
+ return dtype
73
+
74
+
75
+ @_deco_axis_expand
76
+ def count_nonzero(
77
+ a: ArrayLike, axis: AxisLike = None, *, keepdims: KeepDims = False
78
+ ) -> torch.Tensor:
79
+ return a.count_nonzero(axis)
80
+
81
+
82
+ @_deco_axis_expand
83
+ def argmax(
84
+ a: ArrayLike,
85
+ axis: AxisLike = None,
86
+ out: OutArray | None = None,
87
+ *,
88
+ keepdims: KeepDims = False,
89
+ ) -> torch.Tensor:
90
+ if a.is_complex():
91
+ raise NotImplementedError(f"argmax with dtype={a.dtype}.")
92
+
93
+ axis = _util.allow_only_single_axis(axis)
94
+
95
+ if a.dtype == torch.bool:
96
+ # RuntimeError: "argmax_cpu" not implemented for 'Bool'
97
+ a = a.to(torch.uint8)
98
+
99
+ return torch.argmax(a, axis)
100
+
101
+
102
+ @_deco_axis_expand
103
+ def argmin(
104
+ a: ArrayLike,
105
+ axis: AxisLike = None,
106
+ out: OutArray | None = None,
107
+ *,
108
+ keepdims: KeepDims = False,
109
+ ) -> torch.Tensor:
110
+ if a.is_complex():
111
+ raise NotImplementedError(f"argmin with dtype={a.dtype}.")
112
+
113
+ axis = _util.allow_only_single_axis(axis)
114
+
115
+ if a.dtype == torch.bool:
116
+ # RuntimeError: "argmin_cpu" not implemented for 'Bool'
117
+ a = a.to(torch.uint8)
118
+
119
+ return torch.argmin(a, axis)
120
+
121
+
122
+ @_deco_axis_expand
123
+ def any(
124
+ a: ArrayLike,
125
+ axis: AxisLike = None,
126
+ out: OutArray | None = None,
127
+ keepdims: KeepDims = False,
128
+ *,
129
+ where: NotImplementedType = None,
130
+ ) -> torch.Tensor:
131
+ axis = _util.allow_only_single_axis(axis)
132
+ return torch.any(a) if axis is None else torch.any(a, dim=axis)
133
+
134
+
135
+ @_deco_axis_expand
136
+ def all(
137
+ a: ArrayLike,
138
+ axis: AxisLike = None,
139
+ out: OutArray | None = None,
140
+ keepdims: KeepDims = False,
141
+ *,
142
+ where: NotImplementedType = None,
143
+ ) -> torch.Tensor:
144
+ axis = _util.allow_only_single_axis(axis)
145
+ return torch.all(a) if axis is None else torch.all(a, dim=axis)
146
+
147
+
148
+ @_deco_axis_expand
149
+ def amax(
150
+ a: ArrayLike,
151
+ axis: AxisLike = None,
152
+ out: OutArray | None = None,
153
+ keepdims: KeepDims = False,
154
+ initial: NotImplementedType = None,
155
+ where: NotImplementedType = None,
156
+ ) -> torch.Tensor:
157
+ if a.is_complex():
158
+ raise NotImplementedError(f"amax with dtype={a.dtype}")
159
+
160
+ return a.amax() if axis is None else a.amax(axis)
161
+
162
+
163
+ max = amax
164
+
165
+
166
+ @_deco_axis_expand
167
+ def amin(
168
+ a: ArrayLike,
169
+ axis: AxisLike = None,
170
+ out: OutArray | None = None,
171
+ keepdims: KeepDims = False,
172
+ initial: NotImplementedType = None,
173
+ where: NotImplementedType = None,
174
+ ) -> torch.Tensor:
175
+ if a.is_complex():
176
+ raise NotImplementedError(f"amin with dtype={a.dtype}")
177
+
178
+ return a.amin() if axis is None else a.amin(axis)
179
+
180
+
181
+ min = amin
182
+
183
+
184
+ @_deco_axis_expand
185
+ def ptp(
186
+ a: ArrayLike,
187
+ axis: AxisLike = None,
188
+ out: OutArray | None = None,
189
+ keepdims: KeepDims = False,
190
+ ) -> torch.Tensor:
191
+ amax = a.amax() if axis is None else a.amax(axis)
192
+ amin = a.amin() if axis is None else a.amin(axis)
193
+ return amax - amin
194
+
195
+
196
+ @_deco_axis_expand
197
+ def sum(
198
+ a: ArrayLike,
199
+ axis: AxisLike = None,
200
+ dtype: DTypeLike | None = None,
201
+ out: OutArray | None = None,
202
+ keepdims: KeepDims = False,
203
+ initial: NotImplementedType = None,
204
+ where: NotImplementedType = None,
205
+ ) -> torch.Tensor:
206
+ if dtype is not None and not isinstance(dtype, torch.dtype):
207
+ raise AssertionError(
208
+ f"dtype must be None or a torch.dtype, got {type(dtype).__name__}"
209
+ )
210
+
211
+ if dtype == torch.bool:
212
+ dtype = _dtypes_impl.default_dtypes().int_dtype
213
+
214
+ if axis is None:
215
+ return a.sum(dtype=dtype)
216
+ return a.sum(dim=axis, dtype=dtype)
217
+
218
+
219
+ @_deco_axis_expand
220
+ def prod(
221
+ a: ArrayLike,
222
+ axis: AxisLike = None,
223
+ dtype: DTypeLike | None = None,
224
+ out: OutArray | None = None,
225
+ keepdims: KeepDims = False,
226
+ initial: NotImplementedType = None,
227
+ where: NotImplementedType = None,
228
+ ) -> torch.Tensor:
229
+ axis = _util.allow_only_single_axis(axis)
230
+
231
+ if dtype == torch.bool:
232
+ dtype = _dtypes_impl.default_dtypes().int_dtype
233
+
234
+ if axis is None:
235
+ return a.prod(dtype=dtype)
236
+ return a.prod(dim=axis, dtype=dtype)
237
+
238
+
239
+ product = prod
240
+
241
+
242
+ @_deco_axis_expand
243
+ def mean(
244
+ a: ArrayLike,
245
+ axis: AxisLike = None,
246
+ dtype: DTypeLike | None = None,
247
+ out: OutArray | None = None,
248
+ keepdims: KeepDims = False,
249
+ *,
250
+ where: NotImplementedType = None,
251
+ ) -> torch.Tensor:
252
+ dtype = _atleast_float(dtype, a.dtype)
253
+
254
+ if axis is None:
255
+ return a.mean(dtype=dtype)
256
+ return a.mean(dim=axis, dtype=dtype)
257
+
258
+
259
+ @_deco_axis_expand
260
+ def std(
261
+ a: ArrayLike,
262
+ axis: AxisLike = None,
263
+ dtype: DTypeLike | None = None,
264
+ out: OutArray | None = None,
265
+ ddof: float = 0,
266
+ keepdims: KeepDims = False,
267
+ *,
268
+ where: NotImplementedType = None,
269
+ ) -> torch.Tensor:
270
+ in_dtype = dtype
271
+ dtype = _atleast_float(dtype, a.dtype)
272
+ tensor = _util.cast_if_needed(a, dtype)
273
+ result = tensor.std(dim=axis, correction=ddof)
274
+ return _util.cast_if_needed(result, in_dtype)
275
+
276
+
277
+ @_deco_axis_expand
278
+ def var(
279
+ a: ArrayLike,
280
+ axis: AxisLike = None,
281
+ dtype: DTypeLike | None = None,
282
+ out: OutArray | None = None,
283
+ ddof: float = 0,
284
+ keepdims: KeepDims = False,
285
+ *,
286
+ where: NotImplementedType = None,
287
+ ) -> torch.Tensor:
288
+ in_dtype = dtype
289
+ dtype = _atleast_float(dtype, a.dtype)
290
+ tensor = _util.cast_if_needed(a, dtype)
291
+ result = tensor.var(dim=axis, correction=ddof)
292
+ return _util.cast_if_needed(result, in_dtype)
293
+
294
+
295
+ # cumsum / cumprod are almost reductions:
296
+ # 1. no keepdims
297
+ # 2. axis=None flattens
298
+
299
+
300
+ def cumsum(
301
+ a: ArrayLike,
302
+ axis: AxisLike = None,
303
+ dtype: DTypeLike | None = None,
304
+ out: OutArray | None = None,
305
+ ) -> torch.Tensor:
306
+ if dtype == torch.bool:
307
+ dtype = _dtypes_impl.default_dtypes().int_dtype
308
+ if dtype is None:
309
+ dtype = a.dtype
310
+
311
+ # pyrefly: ignore[bad-argument-type]
312
+ (a,), axis = _util.axis_none_flatten(a, axis=axis)
313
+ axis = _util.normalize_axis_index(axis, a.ndim)
314
+
315
+ # torch accepts the numpy-compat `axis=` alias, but its stub only lists `dim`.
316
+ # pyrefly: ignore[missing-argument, unexpected-keyword]
317
+ return a.cumsum(axis=axis, dtype=dtype)
318
+
319
+
320
+ def cumprod(
321
+ a: ArrayLike,
322
+ axis: AxisLike = None,
323
+ dtype: DTypeLike | None = None,
324
+ out: OutArray | None = None,
325
+ ) -> torch.Tensor:
326
+ if dtype == torch.bool:
327
+ dtype = _dtypes_impl.default_dtypes().int_dtype
328
+ if dtype is None:
329
+ dtype = a.dtype
330
+
331
+ # pyrefly: ignore[bad-argument-type]
332
+ (a,), axis = _util.axis_none_flatten(a, axis=axis)
333
+ axis = _util.normalize_axis_index(axis, a.ndim)
334
+
335
+ # torch accepts the numpy-compat `axis=` alias, but its stub only lists `dim`.
336
+ # pyrefly: ignore[missing-argument, unexpected-keyword]
337
+ return a.cumprod(axis=axis, dtype=dtype)
338
+
339
+
340
+ cumproduct = cumprod
341
+
342
+
343
+ def average(
344
+ a: ArrayLike,
345
+ axis: int | None = None,
346
+ weights: ArrayLike | None = None,
347
+ returned: bool = False,
348
+ *,
349
+ keepdims: bool = False,
350
+ ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
351
+ if weights is None:
352
+ result = mean(a, axis)
353
+ wsum = torch.as_tensor(a.numel() / result.numel(), dtype=result.dtype)
354
+ else:
355
+ if not a.dtype.is_floating_point:
356
+ a = a.double()
357
+
358
+ # axis & weights
359
+ if a.shape != weights.shape:
360
+ if axis is None:
361
+ raise TypeError(
362
+ "Axis must be specified when shapes of a and weights differ."
363
+ )
364
+ if weights.ndim != 1:
365
+ raise TypeError(
366
+ "1D weights expected when shapes of a and weights differ."
367
+ )
368
+ if weights.shape[0] != a.shape[axis]:
369
+ raise ValueError(
370
+ "Length of weights not compatible with specified axis."
371
+ )
372
+
373
+ # setup weight to broadcast along axis
374
+ weights = torch.broadcast_to(weights, (a.ndim - 1) * (1,) + weights.shape)
375
+ weights = weights.swapaxes(-1, axis)
376
+
377
+ # do the work
378
+ result_dtype = _dtypes_impl.result_type_impl(a, weights)
379
+ numerator = sum(a * weights, axis, dtype=result_dtype)
380
+ wsum = sum(weights, axis, dtype=result_dtype)
381
+ result = numerator / wsum
382
+
383
+ # We process keepdims manually because the decorator does not deal with variadic returns
384
+ if keepdims:
385
+ result = _util.apply_keepdims(result, axis, a.ndim)
386
+
387
+ if returned:
388
+ if wsum.shape != result.shape:
389
+ wsum = torch.broadcast_to(wsum, result.shape).clone()
390
+ return result, wsum
391
+ else:
392
+ return result
393
+
394
+
395
+ # Not using deco_axis_expand as it assumes that axis is the second arg
396
+ def quantile(
397
+ a: ArrayLike,
398
+ q: ArrayLike,
399
+ axis: AxisLike = None,
400
+ out: OutArray | None = None,
401
+ overwrite_input: bool = False,
402
+ method: str = "linear",
403
+ keepdims: KeepDims = False,
404
+ *,
405
+ interpolation: NotImplementedType = None,
406
+ ) -> torch.Tensor:
407
+ if overwrite_input:
408
+ # raise NotImplementedError("overwrite_input in quantile not implemented.")
409
+ # NumPy documents that `overwrite_input` MAY modify inputs:
410
+ # https://numpy.org/doc/stable/reference/generated/numpy.percentile.html#numpy-percentile
411
+ # Here we choose to work out-of-place because why not.
412
+ pass
413
+
414
+ if not a.dtype.is_floating_point:
415
+ dtype = _dtypes_impl.default_dtypes().float_dtype
416
+ a = a.to(dtype)
417
+
418
+ # edge case: torch.quantile only supports float32 and float64
419
+ if a.dtype == torch.float16:
420
+ a = a.to(torch.float32)
421
+
422
+ if axis is None:
423
+ a = a.flatten()
424
+ q = q.flatten()
425
+ axis = (0,)
426
+ else:
427
+ axis = _util.normalize_axis_tuple(axis, a.ndim)
428
+
429
+ # FIXME(Mario) Doesn't np.quantile accept a tuple?
430
+ # torch.quantile does accept a number. If we don't want to implement the tuple behaviour
431
+ # (it's deffo low prio) change `normalize_axis_tuple` into a normalize_axis index above.
432
+ axis = _util.allow_only_single_axis(axis)
433
+
434
+ q = _util.cast_if_needed(q, a.dtype)
435
+
436
+ return torch.quantile(a, q, axis, interpolation=method)
437
+
438
+
439
+ def percentile(
440
+ a: ArrayLike,
441
+ q: ArrayLike,
442
+ axis: AxisLike = None,
443
+ out: OutArray | None = None,
444
+ overwrite_input: bool = False,
445
+ method: str = "linear",
446
+ keepdims: KeepDims = False,
447
+ *,
448
+ interpolation: NotImplementedType = None,
449
+ ) -> torch.Tensor:
450
+ # np.percentile(float_tensor, 30) : q.dtype is int64 => q / 100.0 is float32
451
+ if _dtypes_impl.python_type_for_torch(q.dtype) is int:
452
+ q = q.to(_dtypes_impl.default_dtypes().float_dtype)
453
+ qq = q / 100.0
454
+
455
+ return quantile(
456
+ a,
457
+ qq,
458
+ axis=axis,
459
+ overwrite_input=overwrite_input,
460
+ method=method,
461
+ keepdims=keepdims,
462
+ interpolation=interpolation,
463
+ )
464
+
465
+
466
+ def median(
467
+ a: ArrayLike,
468
+ axis: int | None = None,
469
+ out: OutArray | None = None,
470
+ overwrite_input: bool = False,
471
+ keepdims: KeepDims = False,
472
+ ) -> torch.Tensor:
473
+ return quantile(
474
+ a,
475
+ torch.as_tensor(0.5),
476
+ axis=axis,
477
+ overwrite_input=overwrite_input,
478
+ out=out,
479
+ keepdims=keepdims,
480
+ )
.venv/lib/python3.12/site-packages/torch/_numpy/_ufuncs.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+
7
+ from . import _binary_ufuncs_impl, _dtypes_impl, _unary_ufuncs_impl, _util
8
+ from ._normalizations import (
9
+ ArrayLike,
10
+ ArrayLikeOrScalar,
11
+ CastingModes,
12
+ DTypeLike,
13
+ normalizer,
14
+ NotImplementedType,
15
+ OutArray,
16
+ )
17
+
18
+
19
+ def _ufunc_postprocess(result, out, casting):
20
+ if out is not None:
21
+ result = _util.typecast_tensor(result, out.dtype.torch_dtype, casting)
22
+ result = torch.broadcast_to(result, out.shape)
23
+ return result
24
+
25
+
26
+ # ############# Binary ufuncs ######################
27
+
28
+ _binary = [
29
+ name
30
+ for name in dir(_binary_ufuncs_impl)
31
+ if not name.startswith("_") and name not in ["torch", "matmul", "divmod", "ldexp"]
32
+ ]
33
+
34
+
35
+ NEP50_FUNCS = (
36
+ "add",
37
+ "subtract",
38
+ "multiply",
39
+ "floor_divide",
40
+ "true_divide",
41
+ "divide",
42
+ "remainder",
43
+ "bitwise_and",
44
+ "bitwise_or",
45
+ "bitwise_xor",
46
+ "bitwise_left_shift",
47
+ "bitwise_right_shift",
48
+ "hypot",
49
+ "arctan2",
50
+ "logaddexp",
51
+ "logaddexp2",
52
+ "heaviside",
53
+ "copysign",
54
+ "fmax",
55
+ "minimum",
56
+ "fmin",
57
+ "maximum",
58
+ "fmod",
59
+ "gcd",
60
+ "lcm",
61
+ "pow",
62
+ )
63
+
64
+
65
+ def deco_binary_ufunc(torch_func):
66
+ """Common infra for binary ufuncs.
67
+
68
+ Normalize arguments, sort out type casting, broadcasting and delegate to
69
+ the pytorch functions for the actual work.
70
+ """
71
+
72
+ @normalizer
73
+ def wrapped(
74
+ x1: ArrayLikeOrScalar,
75
+ x2: ArrayLikeOrScalar,
76
+ /,
77
+ out: OutArray | None = None,
78
+ *,
79
+ where: NotImplementedType = True,
80
+ casting: CastingModes | None = "same_kind",
81
+ order: NotImplementedType = "K",
82
+ dtype: DTypeLike | None = None,
83
+ subok: NotImplementedType = False,
84
+ signature: NotImplementedType = None,
85
+ extobj: NotImplementedType = None,
86
+ ):
87
+ if dtype is not None:
88
+
89
+ def cast(x, dtype):
90
+ if isinstance(x, torch.Tensor):
91
+ return _util.typecast_tensor(x, dtype, casting)
92
+ else:
93
+ return torch.as_tensor(x, dtype=dtype)
94
+
95
+ x1 = cast(x1, dtype)
96
+ x2 = cast(x2, dtype)
97
+ elif isinstance(x1, torch.Tensor) and isinstance(x2, torch.Tensor):
98
+ dtype = _dtypes_impl.result_type_impl(x1, x2)
99
+ x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting)
100
+ else:
101
+ x1, x2 = _dtypes_impl.nep50_to_tensors(
102
+ x1, x2, torch_func.__name__ in NEP50_FUNCS, torch_func.__name__
103
+ )
104
+
105
+ result = torch_func(x1, x2)
106
+
107
+ return _ufunc_postprocess(result, out, casting)
108
+
109
+ wrapped.__qualname__ = torch_func.__name__
110
+ wrapped.__name__ = torch_func.__name__
111
+
112
+ return wrapped
113
+
114
+
115
+ # matmul's signature is _slightly_ different from other ufuncs:
116
+ # - no where=...
117
+ # - additional axis=..., axes=...
118
+ # - no NEP50 scalars in or out
119
+ @normalizer
120
+ def matmul(
121
+ x1: ArrayLike,
122
+ x2: ArrayLike,
123
+ /,
124
+ out: OutArray | None = None,
125
+ *,
126
+ casting: CastingModes | None = "same_kind",
127
+ order: NotImplementedType = "K",
128
+ dtype: DTypeLike | None = None,
129
+ subok: NotImplementedType = False,
130
+ signature: NotImplementedType = None,
131
+ extobj: NotImplementedType = None,
132
+ axes: NotImplementedType = None,
133
+ axis: NotImplementedType = None,
134
+ ):
135
+ if dtype is None:
136
+ dtype = _dtypes_impl.result_type_impl(x1, x2)
137
+ x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting)
138
+
139
+ result = _binary_ufuncs_impl.matmul(x1, x2)
140
+
141
+ result = _ufunc_postprocess(result, out, casting)
142
+ return result
143
+
144
+
145
+ # ldexp casting is special : the dtype of the result == dtype of the 1st arg
146
+ @normalizer
147
+ def ldexp(
148
+ x1: ArrayLikeOrScalar,
149
+ x2: ArrayLikeOrScalar,
150
+ /,
151
+ out: OutArray | None = None,
152
+ *,
153
+ where: NotImplementedType = True,
154
+ casting: CastingModes | None = "same_kind",
155
+ order: NotImplementedType = "K",
156
+ dtype: DTypeLike | None = None,
157
+ subok: NotImplementedType = False,
158
+ signature: NotImplementedType = None,
159
+ extobj: NotImplementedType = None,
160
+ ):
161
+ if dtype is not None:
162
+ if isinstance(x1, torch.Tensor):
163
+ x1 = _util.typecast_tensor(x1, dtype, casting)
164
+ else:
165
+ x1 = torch.as_tensor(x1, dtype=dtype)
166
+ else:
167
+ if not isinstance(x1, torch.Tensor):
168
+ x1 = torch.as_tensor(x1)
169
+ x1 = _util.cast_int_to_float(x1)
170
+
171
+ x2 = torch.as_tensor(x2)
172
+ # the second arg must be integer
173
+ if _dtypes_impl._category(x2.dtype) != 1:
174
+ raise ValueError("ldexp 2nd arg must be integer")
175
+
176
+ result = _binary_ufuncs_impl.ldexp(x1, x2)
177
+
178
+ if x1.dtype == torch.float16:
179
+ # torch.ldexp(f16, int) -> f32, undo it
180
+ result = result.to(torch.float16)
181
+
182
+ return _ufunc_postprocess(result, out, casting)
183
+
184
+
185
+ # nin=2, nout=2
186
+ @normalizer
187
+ def divmod(
188
+ x1: ArrayLike,
189
+ x2: ArrayLike,
190
+ out1: OutArray | None = None,
191
+ out2: OutArray | None = None,
192
+ /,
193
+ out: tuple[OutArray | None, OutArray | None] = (None, None),
194
+ *,
195
+ where: NotImplementedType = True,
196
+ casting: CastingModes | None = "same_kind",
197
+ order: NotImplementedType = "K",
198
+ dtype: DTypeLike | None = None,
199
+ subok: NotImplementedType = False,
200
+ signature: NotImplementedType = None,
201
+ extobj: NotImplementedType = None,
202
+ ):
203
+ # make sure we either have no out arrays at all, or there is either
204
+ # out1, out2, or out=tuple, but not both
205
+ num_outs = sum(x is not None for x in [out1, out2])
206
+ if num_outs == 1:
207
+ raise ValueError("both out1 and out2 need to be provided")
208
+ elif num_outs == 2:
209
+ o1, o2 = out
210
+ if o1 is not None or o2 is not None:
211
+ raise TypeError(
212
+ "cannot specify 'out' as both a positional and keyword argument"
213
+ )
214
+ else:
215
+ out1, out2 = out
216
+
217
+ if dtype is None:
218
+ dtype = _dtypes_impl.result_type_impl(x1, x2)
219
+ x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting)
220
+
221
+ quot, rem = _binary_ufuncs_impl.divmod(x1, x2)
222
+
223
+ quot = _ufunc_postprocess(quot, out1, casting)
224
+ rem = _ufunc_postprocess(rem, out2, casting)
225
+ return quot, rem
226
+
227
+
228
+ #
229
+ # Attach ufuncs to this module, for a further export to the public namespace in __init__.py
230
+ #
231
+ for name in _binary:
232
+ ufunc = getattr(_binary_ufuncs_impl, name)
233
+ vars()[name] = deco_binary_ufunc(ufunc)
234
+
235
+
236
+ def modf(x, /, *args, **kwds):
237
+ quot, rem = divmod(x, 1, *args, **kwds)
238
+ return rem, quot
239
+
240
+
241
+ _binary = _binary + ["divmod", "modf", "matmul", "ldexp"]
242
+
243
+
244
+ # ############# Unary ufuncs ######################
245
+
246
+
247
+ _unary = [
248
+ name
249
+ for name in dir(_unary_ufuncs_impl)
250
+ if not name.startswith("_") and name != "torch"
251
+ ]
252
+
253
+
254
+ # these are ufunc(int) -> float
255
+ _fp_unary = [
256
+ "arccos",
257
+ "arccosh",
258
+ "arcsin",
259
+ "arcsinh",
260
+ "arctan",
261
+ "arctanh",
262
+ "cbrt",
263
+ "cos",
264
+ "cosh",
265
+ "deg2rad",
266
+ "degrees",
267
+ "exp",
268
+ "exp2",
269
+ "expm1",
270
+ "log",
271
+ "log10",
272
+ "log1p",
273
+ "log2",
274
+ "rad2deg",
275
+ "radians",
276
+ "reciprocal",
277
+ "sin",
278
+ "sinh",
279
+ "sqrt",
280
+ "square",
281
+ "tan",
282
+ "tanh",
283
+ "trunc",
284
+ ]
285
+
286
+
287
+ def deco_unary_ufunc(torch_func):
288
+ """Common infra for unary ufuncs.
289
+
290
+ Normalize arguments, sort out type casting, broadcasting and delegate to
291
+ the pytorch functions for the actual work.
292
+ """
293
+
294
+ @normalizer
295
+ def wrapped(
296
+ x: ArrayLike,
297
+ /,
298
+ out: OutArray | None = None,
299
+ *,
300
+ where=True,
301
+ casting: CastingModes | None = "same_kind",
302
+ order="K",
303
+ dtype: DTypeLike | None = None,
304
+ subok: NotImplementedType = False,
305
+ signature=None,
306
+ extobj=None,
307
+ ):
308
+ if dtype is not None:
309
+ x = _util.typecast_tensor(x, dtype, casting)
310
+
311
+ if torch_func.__name__ in _fp_unary:
312
+ x = _util.cast_int_to_float(x)
313
+
314
+ result = torch_func(x)
315
+ result = _ufunc_postprocess(result, out, casting)
316
+ return result
317
+
318
+ wrapped.__qualname__ = torch_func.__name__
319
+ wrapped.__name__ = torch_func.__name__
320
+
321
+ return wrapped
322
+
323
+
324
+ #
325
+ # Attach ufuncs to this module, for a further export to the public namespace in __init__.py
326
+ #
327
+ for name in _unary:
328
+ ufunc = getattr(_unary_ufuncs_impl, name)
329
+ vars()[name] = deco_unary_ufunc(ufunc)
330
+
331
+
332
+ __all__ = _binary + _unary # noqa: PLE0605
.venv/lib/python3.12/site-packages/torch/_numpy/_unary_ufuncs_impl.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """Export torch work functions for unary ufuncs, rename/tweak to match numpy.
4
+ This listing is further exported to public symbols in the `_numpy/_ufuncs.py` module.
5
+ """
6
+
7
+ import torch
8
+ from torch import ( # noqa: F401
9
+ absolute as fabs,
10
+ arccos,
11
+ arccosh,
12
+ arcsin,
13
+ arcsinh,
14
+ arctan,
15
+ arctanh,
16
+ bitwise_not,
17
+ bitwise_not as invert,
18
+ ceil,
19
+ conj_physical as conjugate,
20
+ cos,
21
+ cosh,
22
+ deg2rad,
23
+ deg2rad as radians,
24
+ exp,
25
+ exp2,
26
+ expm1,
27
+ floor,
28
+ isfinite,
29
+ isinf,
30
+ isnan,
31
+ log,
32
+ log10,
33
+ log1p,
34
+ log2,
35
+ logical_not,
36
+ negative,
37
+ rad2deg,
38
+ rad2deg as degrees,
39
+ reciprocal,
40
+ round as fix,
41
+ round as rint,
42
+ sign,
43
+ signbit,
44
+ sin,
45
+ sinh,
46
+ sqrt,
47
+ square,
48
+ tan,
49
+ tanh,
50
+ trunc,
51
+ )
52
+
53
+
54
+ # special cases: torch does not export these names
55
+ def cbrt(x):
56
+ return torch.pow(x, 1 / 3)
57
+
58
+
59
+ def positive(x):
60
+ return +x
61
+
62
+
63
+ def absolute(x):
64
+ # work around torch.absolute not impl for bools
65
+ if x.dtype == torch.bool:
66
+ return x
67
+ return torch.absolute(x)
68
+
69
+
70
+ # TODO set __name__ and __qualname__
71
+ abs = absolute
72
+ conj = conjugate
.venv/lib/python3.12/site-packages/torch/_numpy/_util.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assorted utilities, which do not need anything other than torch and stdlib."""
2
+
3
+ import operator
4
+ from collections.abc import Iterable, Sequence, Sized
5
+ from typing import TypeGuard
6
+
7
+ import torch
8
+
9
+ from . import _dtypes_impl
10
+
11
+
12
+ # https://github.com/numpy/numpy/blob/v1.23.0/numpy/distutils/misc_util.py#L497-L504
13
+ def is_sequence(seq: object) -> TypeGuard[Sized]:
14
+ if isinstance(seq, str):
15
+ return False
16
+ if not isinstance(seq, Sized):
17
+ return False
18
+ try:
19
+ len(seq)
20
+ except Exception:
21
+ return False
22
+ return True
23
+
24
+
25
+ class AxisError(ValueError, IndexError):
26
+ pass
27
+
28
+
29
+ class UFuncTypeError(TypeError, RuntimeError):
30
+ pass
31
+
32
+
33
+ def cast_if_needed(tensor: torch.Tensor, dtype: torch.dtype | None) -> torch.Tensor:
34
+ # NB: no casting if dtype=None
35
+ if dtype is not None and tensor.dtype != dtype:
36
+ tensor = tensor.to(dtype)
37
+ return tensor
38
+
39
+
40
+ def cast_int_to_float(x: torch.Tensor) -> torch.Tensor:
41
+ # cast integers and bools to the default float dtype
42
+ if _dtypes_impl._category(x.dtype) < 2:
43
+ x = x.to(_dtypes_impl.default_dtypes().float_dtype)
44
+ return x
45
+
46
+
47
+ # a replica of the version in ./numpy/numpy/core/src/multiarray/common.h
48
+ def normalize_axis_index(ax: int, ndim: int, argname: str | None = None) -> int:
49
+ if not (-ndim <= ax < ndim):
50
+ raise AxisError(f"axis {ax} is out of bounds for array of dimension {ndim}")
51
+ if ax < 0:
52
+ ax += ndim
53
+ return ax
54
+
55
+
56
+ # from https://github.com/numpy/numpy/blob/main/numpy/core/numeric.py#L1378
57
+ def normalize_axis_tuple(
58
+ axis: int | Iterable[int],
59
+ ndim: int,
60
+ argname: str | None = None,
61
+ allow_duplicate: bool = False,
62
+ ) -> tuple[int, ...]:
63
+ """
64
+ Normalizes an axis argument into a tuple of non-negative integer axes.
65
+
66
+ This handles shorthands such as ``1`` and converts them to ``(1,)``,
67
+ as well as performing the handling of negative indices covered by
68
+ `normalize_axis_index`.
69
+
70
+ By default, this forbids axes from being specified multiple times.
71
+ Used internally by multi-axis-checking logic.
72
+
73
+ Parameters
74
+ ----------
75
+ axis : int, iterable of int
76
+ The un-normalized index or indices of the axis.
77
+ ndim : int
78
+ The number of dimensions of the array that `axis` should be normalized
79
+ against.
80
+ argname : str, optional
81
+ A prefix to put before the error message, typically the name of the
82
+ argument.
83
+ allow_duplicate : bool, optional
84
+ If False, the default, disallow an axis from being specified twice.
85
+
86
+ Returns
87
+ -------
88
+ normalized_axes : tuple of int
89
+ The normalized axis index, such that `0 <= normalized_axis < ndim`
90
+ """
91
+ # Optimization to speed-up the most common cases.
92
+ axes: Iterable[int]
93
+ if isinstance(axis, (tuple, list)):
94
+ axes = axis
95
+ else:
96
+ # operator.index handles the scalar shorthand (int and __index__-like
97
+ # objects); a TypeError means axis is already an iterable of ints.
98
+ try:
99
+ axes = [operator.index(axis)] # pyrefly: ignore[bad-argument-type]
100
+ except TypeError:
101
+ axes = axis # pyrefly: ignore[bad-assignment]
102
+ # Going via an iterator directly is slower than via list comprehension.
103
+ result = tuple(normalize_axis_index(ax, ndim, argname) for ax in axes)
104
+ if not allow_duplicate and len(set(map(int, result))) != len(result):
105
+ if argname:
106
+ raise ValueError(f"repeated axis in `{argname}` argument")
107
+ else:
108
+ raise ValueError("repeated axis")
109
+ return result
110
+
111
+
112
+ def allow_only_single_axis(axis: int | tuple[int, ...] | None) -> int | None:
113
+ if axis is None:
114
+ return axis
115
+ if isinstance(axis, int):
116
+ return axis
117
+ if len(axis) != 1:
118
+ raise NotImplementedError("does not handle tuple axis")
119
+ return axis[0]
120
+
121
+
122
+ def expand_shape(
123
+ arr_shape: Sequence[int], axis: int | tuple[int, ...] | list[int]
124
+ ) -> list[int]:
125
+ # taken from numpy 1.23.x, expand_dims function
126
+ axis_seq = axis if isinstance(axis, (list, tuple)) else (axis,)
127
+ out_ndim = len(axis_seq) + len(arr_shape)
128
+ normalized = normalize_axis_tuple(axis_seq, out_ndim)
129
+ shape_it = iter(arr_shape)
130
+ shape = [1 if ax in normalized else next(shape_it) for ax in range(out_ndim)]
131
+ return shape
132
+
133
+
134
+ def apply_keepdims(
135
+ tensor: torch.Tensor, axis: int | tuple[int, ...] | None, ndim: int
136
+ ) -> torch.Tensor:
137
+ if axis is None:
138
+ # tensor was a scalar
139
+ shape = (1,) * ndim
140
+ tensor = tensor.expand(shape).contiguous()
141
+ else:
142
+ shape = expand_shape(tensor.shape, axis)
143
+ tensor = tensor.reshape(shape)
144
+ return tensor
145
+
146
+
147
+ def axis_none_flatten(
148
+ *tensors: torch.Tensor, axis: int | None = None
149
+ ) -> tuple[tuple[torch.Tensor, ...], int]:
150
+ """Flatten the arrays if axis is None."""
151
+ if axis is None:
152
+ tensors = tuple(ar.flatten() for ar in tensors)
153
+ return tensors, 0
154
+ else:
155
+ return tensors, axis
156
+
157
+
158
+ def typecast_tensor(
159
+ t: torch.Tensor, target_dtype: torch.dtype, casting: str
160
+ ) -> torch.Tensor:
161
+ """Dtype-cast tensor to target_dtype.
162
+
163
+ Parameters
164
+ ----------
165
+ t : torch.Tensor
166
+ The tensor to cast
167
+ target_dtype : torch dtype object
168
+ The array dtype to cast all tensors to
169
+ casting : str
170
+ The casting mode, see `np.can_cast`
171
+
172
+ Returns
173
+ -------
174
+ `torch.Tensor` of the `target_dtype` dtype
175
+
176
+ Raises
177
+ ------
178
+ ValueError
179
+ if the argument cannot be cast according to the `casting` rule
180
+
181
+ """
182
+ can_cast = _dtypes_impl.can_cast_impl
183
+
184
+ if not can_cast(t.dtype, target_dtype, casting=casting):
185
+ raise TypeError(
186
+ f"Cannot cast array data from {t.dtype} to"
187
+ f" {target_dtype} according to the rule '{casting}'"
188
+ )
189
+ return cast_if_needed(t, target_dtype)
190
+
191
+
192
+ def typecast_tensors(
193
+ tensors: Sequence[torch.Tensor], target_dtype: torch.dtype, casting: str
194
+ ) -> tuple[torch.Tensor, ...]:
195
+ return tuple(typecast_tensor(t, target_dtype, casting) for t in tensors)
196
+
197
+
198
+ def _try_convert_to_tensor(obj: object) -> torch.Tensor:
199
+ try:
200
+ tensor = torch.as_tensor(obj)
201
+ except Exception as e:
202
+ mesg = f"failed to convert {obj} to ndarray. \nInternal error is: {str(e)}."
203
+ raise NotImplementedError(mesg) # noqa: B904
204
+ return tensor
205
+
206
+
207
+ def _coerce_to_tensor(
208
+ obj: object,
209
+ dtype: torch.dtype | None = None,
210
+ copy: bool = False,
211
+ ndmin: int = 0,
212
+ ) -> torch.Tensor:
213
+ """The core logic of the array(...) function.
214
+
215
+ Parameters
216
+ ----------
217
+ obj : tensor_like
218
+ The thing to coerce
219
+ dtype : torch.dtype object or None
220
+ Coerce to this torch dtype
221
+ copy : bool
222
+ Copy or not
223
+ ndmin : int
224
+ The results as least this many dimensions
225
+ is_weak : bool
226
+ Whether obj is a weakly typed python scalar.
227
+
228
+ Returns
229
+ -------
230
+ tensor : torch.Tensor
231
+ a tensor object with requested dtype, ndim and copy semantics.
232
+
233
+ Notes
234
+ -----
235
+ This is almost a "tensor_like" coercive function. Does not handle wrapper
236
+ ndarrays (those should be handled in the ndarray-aware layer prior to
237
+ invoking this function).
238
+ """
239
+ if isinstance(obj, torch.Tensor):
240
+ tensor = obj
241
+ else:
242
+ # tensor.dtype is the pytorch default, typically float32. If obj's elements
243
+ # are not exactly representable in float32, we've lost precision:
244
+ # >>> torch.as_tensor(1e12).item() - 1e12
245
+ # -4096.0
246
+ default_dtype = torch.get_default_dtype()
247
+ torch.set_default_dtype(_dtypes_impl.get_default_dtype_for(torch.float32))
248
+ try:
249
+ tensor = _try_convert_to_tensor(obj)
250
+ finally:
251
+ torch.set_default_dtype(default_dtype)
252
+
253
+ # type cast if requested
254
+ tensor = cast_if_needed(tensor, dtype)
255
+
256
+ # adjust ndim if needed
257
+ ndim_extra = ndmin - tensor.ndim
258
+ if ndim_extra > 0:
259
+ tensor = tensor.view((1,) * ndim_extra + tensor.shape)
260
+
261
+ # special handling for np._CopyMode
262
+ try:
263
+ copy = bool(copy)
264
+ except ValueError:
265
+ # TODO handle _CopyMode.IF_NEEDED correctly
266
+ copy = False
267
+ # copy if requested
268
+ if copy:
269
+ tensor = tensor.clone()
270
+
271
+ return tensor
272
+
273
+
274
+ def ndarrays_to_tensors(*inputs: object) -> object:
275
+ """Convert all ndarrays from `inputs` to tensors. (other things are intact)"""
276
+ from ._ndarray import ndarray
277
+
278
+ if len(inputs) == 0:
279
+ return ValueError()
280
+ elif len(inputs) == 1:
281
+ input_ = inputs[0]
282
+ if isinstance(input_, ndarray):
283
+ return input_.tensor
284
+ elif isinstance(input_, tuple):
285
+ result = []
286
+ for sub_input in input_:
287
+ sub_result = ndarrays_to_tensors(sub_input)
288
+ result.append(sub_result)
289
+ return tuple(result)
290
+ else:
291
+ return input_
292
+ else:
293
+ if not isinstance(inputs, tuple):
294
+ raise AssertionError(
295
+ f"Expected inputs to be a tuple, got {type(inputs).__name__}"
296
+ )
297
+ return ndarrays_to_tensors(inputs)
.venv/lib/python3.12/site-packages/torch/_numpy/fft.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ from typing import Concatenate, ParamSpec, TYPE_CHECKING, TypeVar
5
+
6
+ import torch
7
+
8
+ from . import _dtypes_impl, _util
9
+ from ._normalizations import ArrayLike, normalizer
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Callable, Sequence
14
+
15
+
16
+ _P = ParamSpec("_P")
17
+ _R = TypeVar("_R")
18
+
19
+
20
+ def upcast(
21
+ func: Callable[Concatenate[torch.Tensor, _P], _R],
22
+ ) -> Callable[Concatenate[torch.Tensor, _P], _R]:
23
+ """NumPy fft casts inputs to 64 bit and *returns 64-bit results*."""
24
+
25
+ @functools.wraps(func)
26
+ def wrapped(tensor: torch.Tensor, *args: _P.args, **kwds: _P.kwargs) -> _R:
27
+ target_dtype = (
28
+ _dtypes_impl.default_dtypes().complex_dtype
29
+ if tensor.is_complex()
30
+ else _dtypes_impl.default_dtypes().float_dtype
31
+ )
32
+ tensor = _util.cast_if_needed(tensor, target_dtype)
33
+ return func(tensor, *args, **kwds)
34
+
35
+ return wrapped
36
+
37
+
38
+ @normalizer
39
+ @upcast
40
+ def fft(
41
+ a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None
42
+ ) -> torch.Tensor:
43
+ return torch.fft.fft(a, n, dim=axis, norm=norm)
44
+
45
+
46
+ @normalizer
47
+ @upcast
48
+ def ifft(
49
+ a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None
50
+ ) -> torch.Tensor:
51
+ return torch.fft.ifft(a, n, dim=axis, norm=norm)
52
+
53
+
54
+ @normalizer
55
+ @upcast
56
+ def rfft(
57
+ a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None
58
+ ) -> torch.Tensor:
59
+ return torch.fft.rfft(a, n, dim=axis, norm=norm)
60
+
61
+
62
+ @normalizer
63
+ @upcast
64
+ def irfft(
65
+ a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None
66
+ ) -> torch.Tensor:
67
+ return torch.fft.irfft(a, n, dim=axis, norm=norm)
68
+
69
+
70
+ @normalizer
71
+ @upcast
72
+ def fftn(
73
+ a: ArrayLike,
74
+ s: Sequence[int] | None = None,
75
+ axes: Sequence[int] | None = None,
76
+ norm: str | None = None,
77
+ ) -> torch.Tensor:
78
+ return torch.fft.fftn(a, s, dim=axes, norm=norm)
79
+
80
+
81
+ @normalizer
82
+ @upcast
83
+ def ifftn(
84
+ a: ArrayLike,
85
+ s: Sequence[int] | None = None,
86
+ axes: Sequence[int] | None = None,
87
+ norm: str | None = None,
88
+ ) -> torch.Tensor:
89
+ return torch.fft.ifftn(a, s, dim=axes, norm=norm)
90
+
91
+
92
+ @normalizer
93
+ @upcast
94
+ def rfftn(
95
+ a: ArrayLike,
96
+ s: Sequence[int] | None = None,
97
+ axes: Sequence[int] | None = None,
98
+ norm: str | None = None,
99
+ ) -> torch.Tensor:
100
+ return torch.fft.rfftn(a, s, dim=axes, norm=norm)
101
+
102
+
103
+ @normalizer
104
+ @upcast
105
+ def irfftn(
106
+ a: ArrayLike,
107
+ s: Sequence[int] | None = None,
108
+ axes: Sequence[int] | None = None,
109
+ norm: str | None = None,
110
+ ) -> torch.Tensor:
111
+ return torch.fft.irfftn(a, s, dim=axes, norm=norm)
112
+
113
+
114
+ @normalizer
115
+ @upcast
116
+ def fft2(
117
+ a: ArrayLike,
118
+ s: Sequence[int] | None = None,
119
+ axes: Sequence[int] = (-2, -1),
120
+ norm: str | None = None,
121
+ ) -> torch.Tensor:
122
+ return torch.fft.fft2(a, s, dim=axes, norm=norm)
123
+
124
+
125
+ @normalizer
126
+ @upcast
127
+ def ifft2(
128
+ a: ArrayLike,
129
+ s: Sequence[int] | None = None,
130
+ axes: Sequence[int] = (-2, -1),
131
+ norm: str | None = None,
132
+ ) -> torch.Tensor:
133
+ return torch.fft.ifft2(a, s, dim=axes, norm=norm)
134
+
135
+
136
+ @normalizer
137
+ @upcast
138
+ def rfft2(
139
+ a: ArrayLike,
140
+ s: Sequence[int] | None = None,
141
+ axes: Sequence[int] = (-2, -1),
142
+ norm: str | None = None,
143
+ ) -> torch.Tensor:
144
+ return torch.fft.rfft2(a, s, dim=axes, norm=norm)
145
+
146
+
147
+ @normalizer
148
+ @upcast
149
+ def irfft2(
150
+ a: ArrayLike,
151
+ s: Sequence[int] | None = None,
152
+ axes: Sequence[int] = (-2, -1),
153
+ norm: str | None = None,
154
+ ) -> torch.Tensor:
155
+ return torch.fft.irfft2(a, s, dim=axes, norm=norm)
156
+
157
+
158
+ @normalizer
159
+ @upcast
160
+ def hfft(
161
+ a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None
162
+ ) -> torch.Tensor:
163
+ return torch.fft.hfft(a, n, dim=axis, norm=norm)
164
+
165
+
166
+ @normalizer
167
+ @upcast
168
+ def ihfft(
169
+ a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None
170
+ ) -> torch.Tensor:
171
+ return torch.fft.ihfft(a, n, dim=axis, norm=norm)
172
+
173
+
174
+ @normalizer
175
+ def fftfreq(n: int, d: float = 1.0) -> torch.Tensor:
176
+ return torch.fft.fftfreq(n, d)
177
+
178
+
179
+ @normalizer
180
+ def rfftfreq(n: int, d: float = 1.0) -> torch.Tensor:
181
+ return torch.fft.rfftfreq(n, d)
182
+
183
+
184
+ @normalizer
185
+ def fftshift(x: ArrayLike, axes: int | Sequence[int] | None = None) -> torch.Tensor:
186
+ return torch.fft.fftshift(x, axes)
187
+
188
+
189
+ @normalizer
190
+ def ifftshift(x: ArrayLike, axes: int | Sequence[int] | None = None) -> torch.Tensor:
191
+ return torch.fft.ifftshift(x, axes)
.venv/lib/python3.12/site-packages/torch/_numpy/linalg.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import math
5
+ from typing import ParamSpec, TYPE_CHECKING, TypeVar
6
+
7
+ import torch
8
+
9
+ from . import _dtypes_impl, _util
10
+ from ._normalizations import ArrayLike, KeepDims, normalizer, OutArray
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Callable, Sequence
15
+
16
+
17
+ _P = ParamSpec("_P")
18
+ _R = TypeVar("_R")
19
+
20
+
21
+ class LinAlgError(Exception):
22
+ pass
23
+
24
+
25
+ def _atleast_float_1(a: torch.Tensor) -> torch.Tensor:
26
+ if not (a.dtype.is_floating_point or a.dtype.is_complex):
27
+ a = a.to(_dtypes_impl.default_dtypes().float_dtype)
28
+ return a
29
+
30
+
31
+ def _atleast_float_2(
32
+ a: torch.Tensor, b: torch.Tensor
33
+ ) -> tuple[torch.Tensor, torch.Tensor]:
34
+ dtyp = _dtypes_impl.result_type_impl(a, b)
35
+ if not (dtyp.is_floating_point or dtyp.is_complex):
36
+ dtyp = _dtypes_impl.default_dtypes().float_dtype
37
+
38
+ a = _util.cast_if_needed(a, dtyp)
39
+ b = _util.cast_if_needed(b, dtyp)
40
+ return a, b
41
+
42
+
43
+ def linalg_errors(func: Callable[_P, _R]) -> Callable[_P, _R]:
44
+ @functools.wraps(func)
45
+ def wrapped(*args: _P.args, **kwds: _P.kwargs) -> _R:
46
+ try:
47
+ return func(*args, **kwds)
48
+ except torch._C._LinAlgError as e: # pyrefly: ignore[missing-attribute] # TODO
49
+ raise LinAlgError(*e.args) # noqa: B904
50
+
51
+ return wrapped
52
+
53
+
54
+ # ### Matrix and vector products ###
55
+
56
+
57
+ @normalizer
58
+ @linalg_errors
59
+ def matrix_power(a: ArrayLike, n: int) -> torch.Tensor:
60
+ a = _atleast_float_1(a)
61
+ return torch.linalg.matrix_power(a, n)
62
+
63
+
64
+ @normalizer
65
+ @linalg_errors
66
+ def multi_dot(
67
+ inputs: Sequence[ArrayLike], *, out: OutArray | None = None
68
+ ) -> torch.Tensor:
69
+ return torch.linalg.multi_dot(inputs)
70
+
71
+
72
+ # ### Solving equations and inverting matrices ###
73
+
74
+
75
+ @normalizer
76
+ @linalg_errors
77
+ def solve(a: ArrayLike, b: ArrayLike) -> torch.Tensor:
78
+ a, b = _atleast_float_2(a, b)
79
+ return torch.linalg.solve(a, b)
80
+
81
+
82
+ @normalizer
83
+ @linalg_errors
84
+ def lstsq(
85
+ a: ArrayLike, b: ArrayLike, rcond: float | None = None
86
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
87
+ a, b = _atleast_float_2(a, b)
88
+ # NumPy is using gelsd: https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/umath_linalg.cpp#L3991
89
+ # on CUDA, only `gels` is available though, so use it instead
90
+ driver = "gels" if a.is_cuda or b.is_cuda else "gelsd"
91
+ return torch.linalg.lstsq(a, b, rcond=rcond, driver=driver)
92
+
93
+
94
+ @normalizer
95
+ @linalg_errors
96
+ def inv(a: ArrayLike) -> torch.Tensor:
97
+ a = _atleast_float_1(a)
98
+ result = torch.linalg.inv(a)
99
+ return result
100
+
101
+
102
+ @normalizer
103
+ @linalg_errors
104
+ def pinv(a: ArrayLike, rcond: float = 1e-15, hermitian: bool = False) -> torch.Tensor:
105
+ a = _atleast_float_1(a)
106
+ return torch.linalg.pinv(a, rtol=rcond, hermitian=hermitian)
107
+
108
+
109
+ @normalizer
110
+ @linalg_errors
111
+ def tensorsolve(
112
+ a: ArrayLike, b: ArrayLike, axes: Sequence[int] | None = None
113
+ ) -> torch.Tensor:
114
+ a, b = _atleast_float_2(a, b)
115
+ return torch.linalg.tensorsolve(a, b, dims=axes)
116
+
117
+
118
+ @normalizer
119
+ @linalg_errors
120
+ def tensorinv(a: ArrayLike, ind: int = 2) -> torch.Tensor:
121
+ a = _atleast_float_1(a)
122
+ return torch.linalg.tensorinv(a, ind=ind)
123
+
124
+
125
+ # ### Norms and other numbers ###
126
+
127
+
128
+ @normalizer
129
+ @linalg_errors
130
+ def det(a: ArrayLike) -> torch.Tensor:
131
+ a = _atleast_float_1(a)
132
+ return torch.linalg.det(a)
133
+
134
+
135
+ @normalizer
136
+ @linalg_errors
137
+ def slogdet(a: ArrayLike) -> tuple[torch.Tensor, torch.Tensor]:
138
+ a = _atleast_float_1(a)
139
+ return torch.linalg.slogdet(a)
140
+
141
+
142
+ @normalizer
143
+ @linalg_errors
144
+ def cond(x: ArrayLike, p: int | str | None = None) -> torch.Tensor:
145
+ x = _atleast_float_1(x)
146
+
147
+ # check if empty
148
+ # cf: https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/linalg.py#L1744
149
+ if x.numel() == 0 and math.prod(x.shape[-2:]) == 0:
150
+ raise LinAlgError("cond is not defined on empty arrays")
151
+
152
+ result = torch.linalg.cond(x, p=p)
153
+
154
+ # Convert nans to infs (numpy does it in a data-dependent way, depending on
155
+ # whether the input array has nans or not)
156
+ # XXX: NumPy does this: https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/linalg.py#L1744
157
+ return torch.where(torch.isnan(result), float("inf"), result)
158
+
159
+
160
+ @normalizer
161
+ @linalg_errors
162
+ def matrix_rank(
163
+ a: ArrayLike, tol: float | None = None, hermitian: bool = False
164
+ ) -> torch.Tensor | int:
165
+ a = _atleast_float_1(a)
166
+
167
+ if a.ndim < 2:
168
+ return int((a != 0).any())
169
+
170
+ if tol is None:
171
+ # follow https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/linalg.py#L1885
172
+ atol = 0
173
+ rtol = max(a.shape[-2:]) * torch.finfo(a.dtype).eps
174
+ else:
175
+ atol, rtol = tol, 0
176
+ return torch.linalg.matrix_rank(a, atol=atol, rtol=rtol, hermitian=hermitian)
177
+
178
+
179
+ @normalizer
180
+ @linalg_errors
181
+ def norm(
182
+ x: ArrayLike,
183
+ ord: int | float | str | None = None,
184
+ axis: int | tuple[int, ...] | None = None,
185
+ keepdims: KeepDims = False,
186
+ ) -> torch.Tensor:
187
+ x = _atleast_float_1(x)
188
+ return torch.linalg.norm(x, ord=ord, dim=axis)
189
+
190
+
191
+ # ### Decompositions ###
192
+
193
+
194
+ @normalizer
195
+ @linalg_errors
196
+ def cholesky(a: ArrayLike) -> torch.Tensor:
197
+ a = _atleast_float_1(a)
198
+ return torch.linalg.cholesky(a)
199
+
200
+
201
+ @normalizer
202
+ @linalg_errors
203
+ def qr(
204
+ a: ArrayLike, mode: str = "reduced"
205
+ ) -> tuple[torch.Tensor, torch.Tensor] | torch.Tensor:
206
+ a = _atleast_float_1(a)
207
+ result = torch.linalg.qr(a, mode=mode)
208
+ if mode == "r":
209
+ # match NumPy
210
+ return result.R
211
+ return result
212
+
213
+
214
+ @normalizer
215
+ @linalg_errors
216
+ def svd(
217
+ a: ArrayLike,
218
+ full_matrices: bool = True,
219
+ compute_uv: bool = True,
220
+ hermitian: bool = False,
221
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor] | torch.Tensor:
222
+ a = _atleast_float_1(a)
223
+ if not compute_uv:
224
+ return torch.linalg.svdvals(a)
225
+
226
+ # NB: ignore the hermitian= argument (no pytorch equivalent)
227
+ result = torch.linalg.svd(a, full_matrices=full_matrices)
228
+ return result
229
+
230
+
231
+ # ### Eigenvalues and eigenvectors ###
232
+
233
+
234
+ @normalizer
235
+ @linalg_errors
236
+ def eig(a: ArrayLike) -> tuple[torch.Tensor, torch.Tensor]:
237
+ a = _atleast_float_1(a)
238
+ w, vt = torch.linalg.eig(a)
239
+
240
+ if not a.is_complex() and w.is_complex() and (w.imag == 0).all():
241
+ w = w.real
242
+ vt = vt.real
243
+ return w, vt
244
+
245
+
246
+ @normalizer
247
+ @linalg_errors
248
+ def eigh(a: ArrayLike, UPLO: str = "L") -> tuple[torch.Tensor, torch.Tensor]:
249
+ a = _atleast_float_1(a)
250
+ return torch.linalg.eigh(a, UPLO=UPLO)
251
+
252
+
253
+ @normalizer
254
+ @linalg_errors
255
+ def eigvals(a: ArrayLike) -> torch.Tensor:
256
+ a = _atleast_float_1(a)
257
+ result = torch.linalg.eigvals(a)
258
+ if not a.is_complex() and result.is_complex() and (result.imag == 0).all():
259
+ result = result.real
260
+ return result
261
+
262
+
263
+ @normalizer
264
+ @linalg_errors
265
+ def eigvalsh(a: ArrayLike, UPLO: str = "L") -> torch.Tensor:
266
+ a = _atleast_float_1(a)
267
+ return torch.linalg.eigvalsh(a, UPLO=UPLO)
.venv/lib/python3.12/site-packages/torch/_numpy/random.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """Wrapper to mimic (parts of) np.random API surface.
4
+
5
+ NumPy has strict guarantees on reproducibility etc; here we don't give any.
6
+
7
+ Q: default dtype is float64 in numpy
8
+
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import functools
14
+ from math import sqrt
15
+
16
+ import torch
17
+
18
+ from . import _dtypes_impl, _util
19
+ from ._normalizations import array_or_scalar, ArrayLike, normalizer
20
+
21
+
22
+ __all__ = [
23
+ "seed",
24
+ "random_sample",
25
+ "sample",
26
+ "random",
27
+ "rand",
28
+ "randn",
29
+ "normal",
30
+ "choice",
31
+ "randint",
32
+ "shuffle",
33
+ "uniform",
34
+ ]
35
+
36
+
37
+ def use_numpy_random():
38
+ # local import to avoid ref cycles
39
+ import torch._dynamo.config as config
40
+
41
+ return config.use_numpy_random_stream
42
+
43
+
44
+ def deco_stream(func):
45
+ @functools.wraps(func)
46
+ def inner(*args, **kwds):
47
+ if not use_numpy_random():
48
+ return func(*args, **kwds)
49
+ else:
50
+ import numpy
51
+
52
+ from ._ndarray import ndarray
53
+
54
+ f = getattr(numpy.random, func.__name__)
55
+
56
+ # numpy funcs accept numpy ndarrays, unwrap
57
+ args = tuple(
58
+ arg.tensor.numpy() if isinstance(arg, ndarray) else arg for arg in args
59
+ )
60
+ kwds = {
61
+ key: val.tensor.numpy() if isinstance(val, ndarray) else val
62
+ for key, val in kwds.items()
63
+ }
64
+
65
+ value = f(*args, **kwds)
66
+
67
+ # `value` can be either numpy.ndarray or python scalar (or None)
68
+ if isinstance(value, numpy.ndarray):
69
+ value = ndarray(torch.as_tensor(value))
70
+
71
+ return value
72
+
73
+ return inner
74
+
75
+
76
+ @deco_stream
77
+ def seed(seed=None):
78
+ if seed is not None:
79
+ torch.random.manual_seed(seed)
80
+
81
+
82
+ @deco_stream
83
+ def random_sample(size=None):
84
+ if size is None:
85
+ size = ()
86
+ dtype = _dtypes_impl.default_dtypes().float_dtype
87
+ values = torch.empty(size, dtype=dtype).uniform_()
88
+ return array_or_scalar(values, return_scalar=size == ())
89
+
90
+
91
+ def rand(*size):
92
+ if size == ():
93
+ size = None
94
+ return random_sample(size)
95
+
96
+
97
+ sample = random_sample
98
+ random = random_sample
99
+
100
+
101
+ @deco_stream
102
+ def uniform(low=0.0, high=1.0, size=None):
103
+ if size is None:
104
+ size = ()
105
+ dtype = _dtypes_impl.default_dtypes().float_dtype
106
+ values = torch.empty(size, dtype=dtype).uniform_(low, high)
107
+ return array_or_scalar(values, return_scalar=size == ())
108
+
109
+
110
+ @deco_stream
111
+ def randn(*size):
112
+ dtype = _dtypes_impl.default_dtypes().float_dtype
113
+ values = torch.randn(size, dtype=dtype)
114
+ return array_or_scalar(values, return_scalar=size == ())
115
+
116
+
117
+ @deco_stream
118
+ def normal(loc=0.0, scale=1.0, size=None):
119
+ if size is None:
120
+ size = ()
121
+ dtype = _dtypes_impl.default_dtypes().float_dtype
122
+ values = torch.empty(size, dtype=dtype).normal_(loc, scale)
123
+ return array_or_scalar(values, return_scalar=size == ())
124
+
125
+
126
+ @deco_stream
127
+ def shuffle(x):
128
+ # no @normalizer because we do not cast e.g. lists to tensors
129
+ from ._ndarray import ndarray
130
+
131
+ if isinstance(x, torch.Tensor):
132
+ tensor = x
133
+ elif isinstance(x, ndarray):
134
+ tensor = x.tensor
135
+ else:
136
+ raise NotImplementedError("We do not random.shuffle lists in-place")
137
+
138
+ perm = torch.randperm(tensor.shape[0])
139
+ xp = tensor[perm]
140
+ tensor.copy_(xp)
141
+
142
+
143
+ @deco_stream
144
+ def randint(low, high=None, size=None):
145
+ if size is None:
146
+ size = ()
147
+ if not isinstance(size, (tuple, list)):
148
+ size = (size,)
149
+ if high is None:
150
+ low, high = 0, low
151
+ values = torch.randint(low, high, size=size)
152
+ return array_or_scalar(values, int, return_scalar=size == ())
153
+
154
+
155
+ @deco_stream
156
+ @normalizer
157
+ def choice(a: ArrayLike, size=None, replace=True, p: ArrayLike | None = None):
158
+ # https://stackoverflow.com/questions/59461811/random-choice-with-pytorch
159
+ if a.numel() == 1:
160
+ a = torch.arange(a)
161
+
162
+ # TODO: check a.dtype is integer -- cf np.random.choice(3.4) which raises
163
+
164
+ # number of draws
165
+ if size is None:
166
+ num_el = 1
167
+ elif _util.is_sequence(size):
168
+ num_el = 1
169
+ for el in size:
170
+ num_el *= el
171
+ else:
172
+ num_el = size
173
+
174
+ # prepare the probabilities
175
+ if p is None:
176
+ p = torch.ones_like(a) / a.shape[0]
177
+
178
+ # cf https://github.com/numpy/numpy/blob/main/numpy/random/mtrand.pyx#L973
179
+ atol = sqrt(torch.finfo(p.dtype).eps)
180
+ if abs(p.sum() - 1.0) > atol:
181
+ raise ValueError("probabilities do not sum to 1.")
182
+
183
+ # actually sample
184
+ indices = torch.multinomial(p, num_el, replacement=replace)
185
+
186
+ if _util.is_sequence(size):
187
+ indices = indices.reshape(size)
188
+
189
+ samples = a[indices]
190
+
191
+ return samples
.venv/lib/python3.12/site-packages/torch/_numpy/testing/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ from .utils import (
4
+ _gen_alignment_data,
5
+ assert_,
6
+ assert_allclose,
7
+ assert_almost_equal,
8
+ assert_array_almost_equal,
9
+ assert_array_equal,
10
+ assert_array_less,
11
+ assert_equal,
12
+ assert_raises_regex,
13
+ assert_warns,
14
+ HAS_REFCOUNT,
15
+ IS_WASM,
16
+ suppress_warnings,
17
+ )
18
+
19
+
20
+ # from .testing import assert_allclose # FIXME
.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (576 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/utils.cpython-312.pyc ADDED
Binary file (85.2 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_numpy/testing/utils.py ADDED
@@ -0,0 +1,2453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """
4
+ Utility function to facilitate testing.
5
+
6
+ """
7
+
8
+ import contextlib
9
+ import gc
10
+ import operator
11
+ import os
12
+ import platform
13
+ import pprint
14
+ import re
15
+ import shutil
16
+ import sys
17
+ import warnings
18
+ from functools import wraps
19
+ from io import StringIO
20
+ from tempfile import mkdtemp, mkstemp
21
+ from warnings import WarningMessage
22
+
23
+ import torch._numpy as np
24
+ from torch._numpy import arange, asarray as asanyarray, empty, float32, intp, ndarray
25
+
26
+
27
+ __all__ = [
28
+ "assert_equal",
29
+ "assert_almost_equal",
30
+ "assert_approx_equal",
31
+ "assert_array_equal",
32
+ "assert_array_less",
33
+ "assert_string_equal",
34
+ "assert_",
35
+ "assert_array_almost_equal",
36
+ "build_err_msg",
37
+ "decorate_methods",
38
+ "print_assert_equal",
39
+ "verbose",
40
+ "assert_",
41
+ "assert_array_almost_equal_nulp",
42
+ "assert_raises_regex",
43
+ "assert_array_max_ulp",
44
+ "assert_warns",
45
+ "assert_no_warnings",
46
+ "assert_allclose",
47
+ "IgnoreException",
48
+ "clear_and_catch_warnings",
49
+ "temppath",
50
+ "tempdir",
51
+ "IS_PYPY",
52
+ "HAS_REFCOUNT",
53
+ "IS_WASM",
54
+ "suppress_warnings",
55
+ "assert_array_compare",
56
+ "assert_no_gc_cycles",
57
+ "break_cycles",
58
+ "IS_PYSTON",
59
+ ]
60
+
61
+
62
+ verbose = 0
63
+
64
+ IS_WASM = platform.machine() in ["wasm32", "wasm64"]
65
+ IS_PYPY = sys.implementation.name == "pypy"
66
+ IS_PYSTON = hasattr(sys, "pyston_version_info")
67
+ HAS_REFCOUNT = getattr(sys, "getrefcount", None) is not None and not IS_PYSTON
68
+
69
+
70
+ def assert_(val, msg=""):
71
+ """
72
+ Assert that works in release mode.
73
+ Accepts callable msg to allow deferring evaluation until failure.
74
+
75
+ The Python built-in ``assert`` does not work when executing code in
76
+ optimized mode (the ``-O`` flag) - no byte-code is generated for it.
77
+
78
+ For documentation on usage, refer to the Python documentation.
79
+
80
+ """
81
+ __tracebackhide__ = True # Hide traceback for py.test
82
+ if not val:
83
+ try:
84
+ smsg = msg()
85
+ except TypeError:
86
+ smsg = msg
87
+ raise AssertionError(smsg)
88
+
89
+
90
+ def gisnan(x):
91
+ return np.isnan(x)
92
+
93
+
94
+ def gisfinite(x):
95
+ return np.isfinite(x)
96
+
97
+
98
+ def gisinf(x):
99
+ return np.isinf(x)
100
+
101
+
102
+ def build_err_msg(
103
+ arrays,
104
+ err_msg,
105
+ header="Items are not equal:",
106
+ verbose=True,
107
+ names=("ACTUAL", "DESIRED"),
108
+ precision=8,
109
+ ):
110
+ msg = ["\n" + header]
111
+ if err_msg:
112
+ if err_msg.find("\n") == -1 and len(err_msg) < 79 - len(header):
113
+ msg = [msg[0] + " " + err_msg]
114
+ else:
115
+ msg.append(err_msg)
116
+ if verbose:
117
+ for i, a in enumerate(arrays):
118
+ if isinstance(a, ndarray):
119
+ # precision argument is only needed if the objects are ndarrays
120
+ # r_func = partial(array_repr, precision=precision)
121
+ r_func = ndarray.__repr__
122
+ else:
123
+ r_func = repr
124
+
125
+ try:
126
+ r = r_func(a)
127
+ except Exception as exc:
128
+ r = f"[repr failed for <{type(a).__name__}>: {exc}]"
129
+ if r.count("\n") > 3:
130
+ r = "\n".join(r.splitlines()[:3])
131
+ r += "..."
132
+ msg.append(f" {names[i]}: {r}")
133
+ return "\n".join(msg)
134
+
135
+
136
+ def assert_equal(actual, desired, err_msg="", verbose=True):
137
+ """
138
+ Raises an AssertionError if two objects are not equal.
139
+
140
+ Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
141
+ check that all elements of these objects are equal. An exception is raised
142
+ at the first conflicting values.
143
+
144
+ When one of `actual` and `desired` is a scalar and the other is array_like,
145
+ the function checks that each element of the array_like object is equal to
146
+ the scalar.
147
+
148
+ This function handles NaN comparisons as if NaN was a "normal" number.
149
+ That is, AssertionError is not raised if both objects have NaNs in the same
150
+ positions. This is in contrast to the IEEE standard on NaNs, which says
151
+ that NaN compared to anything must return False.
152
+
153
+ Parameters
154
+ ----------
155
+ actual : array_like
156
+ The object to check.
157
+ desired : array_like
158
+ The expected object.
159
+ err_msg : str, optional
160
+ The error message to be printed in case of failure.
161
+ verbose : bool, optional
162
+ If True, the conflicting values are appended to the error message.
163
+
164
+ Raises
165
+ ------
166
+ AssertionError
167
+ If actual and desired are not equal.
168
+
169
+ Examples
170
+ --------
171
+ >>> np.testing.assert_equal([4, 5], [4, 6])
172
+ Traceback (most recent call last):
173
+ ...
174
+ AssertionError:
175
+ Items are not equal:
176
+ item=1
177
+ ACTUAL: 5
178
+ DESIRED: 6
179
+
180
+ The following comparison does not raise an exception. There are NaNs
181
+ in the inputs, but they are in the same positions.
182
+
183
+ >>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
184
+
185
+ """
186
+ __tracebackhide__ = True # Hide traceback for py.test
187
+
188
+ num_nones = sum([actual is None, desired is None])
189
+ if num_nones == 1:
190
+ raise AssertionError(f"Not equal: {actual} != {desired}")
191
+ elif num_nones == 2:
192
+ return True
193
+ # else, carry on
194
+
195
+ if isinstance(actual, np.DType) or isinstance(desired, np.DType):
196
+ result = actual == desired
197
+ if not result:
198
+ raise AssertionError(f"Not equal: {actual} != {desired}")
199
+ else:
200
+ return True
201
+
202
+ if isinstance(desired, str) and isinstance(actual, str):
203
+ if actual != desired:
204
+ raise AssertionError(f"Strings not equal: {actual!r} != {desired!r}")
205
+ return
206
+
207
+ if isinstance(desired, dict):
208
+ if not isinstance(actual, dict):
209
+ raise AssertionError(repr(type(actual)))
210
+ assert_equal(len(actual), len(desired), err_msg, verbose)
211
+ for k in desired:
212
+ if k not in actual:
213
+ raise AssertionError(repr(k))
214
+ assert_equal(actual[k], desired[k], f"key={k!r}\n{err_msg}", verbose)
215
+ return
216
+ if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
217
+ assert_equal(len(actual), len(desired), err_msg, verbose)
218
+ for k in range(len(desired)):
219
+ assert_equal(actual[k], desired[k], f"item={k!r}\n{err_msg}", verbose)
220
+ return
221
+
222
+ from torch._numpy import imag, iscomplexobj, isscalar, ndarray, real, signbit
223
+
224
+ if isinstance(actual, ndarray) or isinstance(desired, ndarray):
225
+ return assert_array_equal(actual, desired, err_msg, verbose)
226
+ msg = build_err_msg([actual, desired], err_msg, verbose=verbose)
227
+
228
+ # Handle complex numbers: separate into real/imag to handle
229
+ # nan/inf/negative zero correctly
230
+ # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
231
+ try:
232
+ usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
233
+ except (ValueError, TypeError):
234
+ usecomplex = False
235
+
236
+ if usecomplex:
237
+ if iscomplexobj(actual):
238
+ actualr = real(actual)
239
+ actuali = imag(actual)
240
+ else:
241
+ actualr = actual
242
+ actuali = 0
243
+ if iscomplexobj(desired):
244
+ desiredr = real(desired)
245
+ desiredi = imag(desired)
246
+ else:
247
+ desiredr = desired
248
+ desiredi = 0
249
+ try:
250
+ assert_equal(actualr, desiredr)
251
+ assert_equal(actuali, desiredi)
252
+ except AssertionError:
253
+ raise AssertionError(msg) # noqa: B904
254
+
255
+ # isscalar test to check cases such as [np.nan] != np.nan
256
+ if isscalar(desired) != isscalar(actual):
257
+ raise AssertionError(msg)
258
+
259
+ # Inf/nan/negative zero handling
260
+ try:
261
+ isdesnan = gisnan(desired)
262
+ isactnan = gisnan(actual)
263
+ if isdesnan and isactnan:
264
+ return # both nan, so equal
265
+
266
+ if desired == 0 and actual == 0:
267
+ if not signbit(desired) == signbit(actual):
268
+ raise AssertionError(msg)
269
+
270
+ except (TypeError, ValueError, NotImplementedError):
271
+ pass
272
+
273
+ try:
274
+ # Explicitly use __eq__ for comparison, gh-2552
275
+ if not (desired == actual):
276
+ raise AssertionError(msg)
277
+
278
+ except (DeprecationWarning, FutureWarning) as e:
279
+ # this handles the case when the two types are not even comparable
280
+ if "elementwise == comparison" in e.args[0]:
281
+ raise AssertionError(msg) # noqa: B904
282
+ else:
283
+ raise
284
+
285
+
286
+ def print_assert_equal(test_string, actual, desired):
287
+ """
288
+ Test if two objects are equal, and print an error message if test fails.
289
+
290
+ The test is performed with ``actual == desired``.
291
+
292
+ Parameters
293
+ ----------
294
+ test_string : str
295
+ The message supplied to AssertionError.
296
+ actual : object
297
+ The object to test for equality against `desired`.
298
+ desired : object
299
+ The expected result.
300
+
301
+ Examples
302
+ --------
303
+ >>> np.testing.print_assert_equal(
304
+ ... "Test XYZ of func xyz", [0, 1], [0, 1]
305
+ ... ) # doctest: +SKIP
306
+ >>> np.testing.print_assert_equal(
307
+ ... "Test XYZ of func xyz", [0, 1], [0, 2]
308
+ ... ) # doctest: +SKIP
309
+ Traceback (most recent call last):
310
+ ...
311
+ AssertionError: Test XYZ of func xyz failed
312
+ ACTUAL:
313
+ [0, 1]
314
+ DESIRED:
315
+ [0, 2]
316
+
317
+ """
318
+ __tracebackhide__ = True # Hide traceback for py.test
319
+ import pprint
320
+
321
+ if actual != desired:
322
+ msg = StringIO()
323
+ msg.write(test_string)
324
+ msg.write(" failed\nACTUAL: \n")
325
+ pprint.pprint(actual, msg)
326
+ msg.write("DESIRED: \n")
327
+ pprint.pprint(desired, msg)
328
+ raise AssertionError(msg.getvalue())
329
+
330
+
331
+ def assert_almost_equal(actual, desired, decimal=7, err_msg="", verbose=True):
332
+ """
333
+ Raises an AssertionError if two items are not equal up to desired
334
+ precision.
335
+
336
+ .. note:: It is recommended to use one of `assert_allclose`,
337
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
338
+ instead of this function for more consistent floating point
339
+ comparisons.
340
+
341
+ The test verifies that the elements of `actual` and `desired` satisfy.
342
+
343
+ ``abs(desired-actual) < float64(1.5 * 10**(-decimal))``
344
+
345
+ That is a looser test than originally documented, but agrees with what the
346
+ actual implementation in `assert_array_almost_equal` did up to rounding
347
+ vagaries. An exception is raised at conflicting values. For ndarrays this
348
+ delegates to assert_array_almost_equal
349
+
350
+ Parameters
351
+ ----------
352
+ actual : array_like
353
+ The object to check.
354
+ desired : array_like
355
+ The expected object.
356
+ decimal : int, optional
357
+ Desired precision, default is 7.
358
+ err_msg : str, optional
359
+ The error message to be printed in case of failure.
360
+ verbose : bool, optional
361
+ If True, the conflicting values are appended to the error message.
362
+
363
+ Raises
364
+ ------
365
+ AssertionError
366
+ If actual and desired are not equal up to specified precision.
367
+
368
+ See Also
369
+ --------
370
+ assert_allclose: Compare two array_like objects for equality with desired
371
+ relative and/or absolute precision.
372
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
373
+
374
+ Examples
375
+ --------
376
+ >>> from torch._numpy.testing import assert_almost_equal
377
+ >>> assert_almost_equal(2.3333333333333, 2.33333334)
378
+ >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
379
+ Traceback (most recent call last):
380
+ ...
381
+ AssertionError:
382
+ Arrays are not almost equal to 10 decimals
383
+ ACTUAL: 2.3333333333333
384
+ DESIRED: 2.33333334
385
+
386
+ >>> assert_almost_equal(
387
+ ... np.array([1.0, 2.3333333333333]), np.array([1.0, 2.33333334]), decimal=9
388
+ ... )
389
+ Traceback (most recent call last):
390
+ ...
391
+ AssertionError:
392
+ Arrays are not almost equal to 9 decimals
393
+ <BLANKLINE>
394
+ Mismatched elements: 1 / 2 (50%)
395
+ Max absolute difference: 6.666699636781459e-09
396
+ Max relative difference: 2.8571569790287484e-09
397
+ x: torch.ndarray([1.0000, 2.3333], dtype=float64)
398
+ y: torch.ndarray([1.0000, 2.3333], dtype=float64)
399
+
400
+ """
401
+ __tracebackhide__ = True # Hide traceback for py.test
402
+ from torch._numpy import imag, iscomplexobj, ndarray, real
403
+
404
+ # Handle complex numbers: separate into real/imag to handle
405
+ # nan/inf/negative zero correctly
406
+ # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
407
+ try:
408
+ usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
409
+ except ValueError:
410
+ usecomplex = False
411
+
412
+ def _build_err_msg():
413
+ header = f"Arrays are not almost equal to {decimal:d} decimals"
414
+ return build_err_msg([actual, desired], err_msg, verbose=verbose, header=header)
415
+
416
+ if usecomplex:
417
+ if iscomplexobj(actual):
418
+ actualr = real(actual)
419
+ actuali = imag(actual)
420
+ else:
421
+ actualr = actual
422
+ actuali = 0
423
+ if iscomplexobj(desired):
424
+ desiredr = real(desired)
425
+ desiredi = imag(desired)
426
+ else:
427
+ desiredr = desired
428
+ desiredi = 0
429
+ try:
430
+ assert_almost_equal(actualr, desiredr, decimal=decimal)
431
+ assert_almost_equal(actuali, desiredi, decimal=decimal)
432
+ except AssertionError:
433
+ raise AssertionError(_build_err_msg()) # noqa: B904
434
+
435
+ if isinstance(actual, (ndarray, tuple, list)) or isinstance(
436
+ desired, (ndarray, tuple, list)
437
+ ):
438
+ return assert_array_almost_equal(actual, desired, decimal, err_msg)
439
+ try:
440
+ # If one of desired/actual is not finite, handle it specially here:
441
+ # check that both are nan if any is a nan, and test for equality
442
+ # otherwise
443
+ if not (gisfinite(desired) and gisfinite(actual)):
444
+ if gisnan(desired) or gisnan(actual):
445
+ if not (gisnan(desired) and gisnan(actual)):
446
+ raise AssertionError(_build_err_msg())
447
+ else:
448
+ if not desired == actual:
449
+ raise AssertionError(_build_err_msg())
450
+ return
451
+ except (NotImplementedError, TypeError):
452
+ pass
453
+ if abs(desired - actual) >= np.float64(1.5 * 10.0 ** (-decimal)):
454
+ raise AssertionError(_build_err_msg())
455
+
456
+
457
+ def assert_approx_equal(actual, desired, significant=7, err_msg="", verbose=True):
458
+ """
459
+ Raises an AssertionError if two items are not equal up to significant
460
+ digits.
461
+
462
+ .. note:: It is recommended to use one of `assert_allclose`,
463
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
464
+ instead of this function for more consistent floating point
465
+ comparisons.
466
+
467
+ Given two numbers, check that they are approximately equal.
468
+ Approximately equal is defined as the number of significant digits
469
+ that agree.
470
+
471
+ Parameters
472
+ ----------
473
+ actual : scalar
474
+ The object to check.
475
+ desired : scalar
476
+ The expected object.
477
+ significant : int, optional
478
+ Desired precision, default is 7.
479
+ err_msg : str, optional
480
+ The error message to be printed in case of failure.
481
+ verbose : bool, optional
482
+ If True, the conflicting values are appended to the error message.
483
+
484
+ Raises
485
+ ------
486
+ AssertionError
487
+ If actual and desired are not equal up to specified precision.
488
+
489
+ See Also
490
+ --------
491
+ assert_allclose: Compare two array_like objects for equality with desired
492
+ relative and/or absolute precision.
493
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
494
+
495
+ Examples
496
+ --------
497
+ >>> np.testing.assert_approx_equal(
498
+ ... 0.12345677777777e-20, 0.1234567e-20
499
+ ... ) # doctest: +SKIP
500
+ >>> np.testing.assert_approx_equal(
501
+ ... 0.12345670e-20,
502
+ ... 0.12345671e-20, # doctest: +SKIP
503
+ ... significant=8,
504
+ ... )
505
+ >>> np.testing.assert_approx_equal(
506
+ ... 0.12345670e-20,
507
+ ... 0.12345672e-20, # doctest: +SKIP
508
+ ... significant=8,
509
+ ... )
510
+ Traceback (most recent call last):
511
+ ...
512
+ AssertionError:
513
+ Items are not equal to 8 significant digits:
514
+ ACTUAL: 1.234567e-21
515
+ DESIRED: 1.2345672e-21
516
+
517
+ the evaluated condition that raises the exception is
518
+
519
+ >>> abs(0.12345670e-20 / 1e-21 - 0.12345672e-20 / 1e-21) >= 10 ** -(8 - 1)
520
+ True
521
+
522
+ """
523
+ __tracebackhide__ = True # Hide traceback for py.test
524
+ import numpy as np
525
+
526
+ (actual, desired) = map(float, (actual, desired))
527
+ if desired == actual:
528
+ return
529
+ # Normalized the numbers to be in range (-10.0,10.0)
530
+ # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
531
+ scale = 0.5 * (np.abs(desired) + np.abs(actual))
532
+ scale = np.power(10, np.floor(np.log10(scale)))
533
+ try:
534
+ sc_desired = desired / scale
535
+ except ZeroDivisionError:
536
+ sc_desired = 0.0
537
+ try:
538
+ sc_actual = actual / scale
539
+ except ZeroDivisionError:
540
+ sc_actual = 0.0
541
+ msg = build_err_msg(
542
+ [actual, desired],
543
+ err_msg,
544
+ header=f"Items are not equal to {significant:d} significant digits:",
545
+ verbose=verbose,
546
+ )
547
+ try:
548
+ # If one of desired/actual is not finite, handle it specially here:
549
+ # check that both are nan if any is a nan, and test for equality
550
+ # otherwise
551
+ if not (gisfinite(desired) and gisfinite(actual)):
552
+ if gisnan(desired) or gisnan(actual):
553
+ if not (gisnan(desired) and gisnan(actual)):
554
+ raise AssertionError(msg)
555
+ else:
556
+ if not desired == actual:
557
+ raise AssertionError(msg)
558
+ return
559
+ except (TypeError, NotImplementedError):
560
+ pass
561
+ if np.abs(sc_desired - sc_actual) >= np.power(10.0, -(significant - 1)):
562
+ raise AssertionError(msg)
563
+
564
+
565
+ def assert_array_compare(
566
+ comparison,
567
+ x,
568
+ y,
569
+ err_msg="",
570
+ verbose=True,
571
+ header="",
572
+ precision=6,
573
+ equal_nan=True,
574
+ equal_inf=True,
575
+ *,
576
+ strict=False,
577
+ ):
578
+ __tracebackhide__ = True # Hide traceback for py.test
579
+ from torch._numpy import all, array, asarray, bool_, inf, isnan, max
580
+
581
+ x = asarray(x)
582
+ y = asarray(y)
583
+
584
+ def array2string(a):
585
+ return str(a)
586
+
587
+ # original array for output formatting
588
+ ox, oy = x, y
589
+
590
+ def func_assert_same_pos(x, y, func=isnan, hasval="nan"):
591
+ """Handling nan/inf.
592
+
593
+ Combine results of running func on x and y, checking that they are True
594
+ at the same locations.
595
+
596
+ """
597
+ __tracebackhide__ = True # Hide traceback for py.test
598
+ x_id = func(x)
599
+ y_id = func(y)
600
+ # We include work-arounds here to handle three types of slightly
601
+ # pathological ndarray subclasses:
602
+ # (1) all() on `masked` array scalars can return masked arrays, so we
603
+ # use != True
604
+ # (2) __eq__ on some ndarray subclasses returns Python booleans
605
+ # instead of element-wise comparisons, so we cast to bool_() and
606
+ # use isinstance(..., bool) checks
607
+ # (3) subclasses with bare-bones __array_function__ implementations may
608
+ # not implement np.all(), so favor using the .all() method
609
+ # We are not committed to supporting such subclasses, but it's nice to
610
+ # support them if possible.
611
+ if (x_id == y_id).all().item() is not True:
612
+ msg = build_err_msg(
613
+ [x, y],
614
+ err_msg + f"\nx and y {hasval} location mismatch:",
615
+ verbose=verbose,
616
+ header=header,
617
+ names=("x", "y"),
618
+ precision=precision,
619
+ )
620
+ raise AssertionError(msg)
621
+ # If there is a scalar, then here we know the array has the same
622
+ # flag as it everywhere, so we should return the scalar flag.
623
+ if isinstance(x_id, bool) or x_id.ndim == 0:
624
+ return bool_(x_id)
625
+ elif isinstance(y_id, bool) or y_id.ndim == 0:
626
+ return bool_(y_id)
627
+ else:
628
+ return y_id
629
+
630
+ try:
631
+ if strict:
632
+ cond = x.shape == y.shape and x.dtype == y.dtype
633
+ else:
634
+ cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
635
+ if not cond:
636
+ if x.shape != y.shape:
637
+ reason = f"\n(shapes {x.shape}, {y.shape} mismatch)"
638
+ else:
639
+ reason = f"\n(dtypes {x.dtype}, {y.dtype} mismatch)"
640
+ msg = build_err_msg(
641
+ [x, y],
642
+ err_msg + reason,
643
+ verbose=verbose,
644
+ header=header,
645
+ names=("x", "y"),
646
+ precision=precision,
647
+ )
648
+ raise AssertionError(msg)
649
+
650
+ flagged = bool_(False)
651
+
652
+ if equal_nan:
653
+ flagged = func_assert_same_pos(x, y, func=isnan, hasval="nan")
654
+
655
+ if equal_inf:
656
+ flagged |= func_assert_same_pos(
657
+ x, y, func=lambda xy: xy == +inf, hasval="+inf"
658
+ )
659
+ flagged |= func_assert_same_pos(
660
+ x, y, func=lambda xy: xy == -inf, hasval="-inf"
661
+ )
662
+
663
+ if flagged.ndim > 0:
664
+ x, y = x[~flagged], y[~flagged]
665
+ # Only do the comparison if actual values are left
666
+ if x.size == 0:
667
+ return
668
+ elif flagged:
669
+ # no sense doing comparison if everything is flagged.
670
+ return
671
+
672
+ val = comparison(x, y)
673
+
674
+ if isinstance(val, bool):
675
+ cond = val
676
+ reduced = array([val])
677
+ else:
678
+ reduced = val.ravel()
679
+ cond = reduced.all()
680
+
681
+ # The below comparison is a hack to ensure that fully masked
682
+ # results, for which val.ravel().all() returns np.ma.masked,
683
+ # do not trigger a failure (np.ma.masked != True evaluates as
684
+ # np.ma.masked, which is falsy).
685
+ if not cond:
686
+ n_mismatch = reduced.size - int(reduced.sum(dtype=intp))
687
+ n_elements = flagged.size if flagged.ndim != 0 else reduced.size
688
+ percent_mismatch = 100 * n_mismatch / n_elements
689
+ remarks = [
690
+ f"Mismatched elements: {n_mismatch} / {n_elements} ({percent_mismatch:.3g}%)"
691
+ ]
692
+
693
+ # with errstate(all='ignore'):
694
+ # ignore errors for non-numeric types
695
+ with contextlib.suppress(TypeError, RuntimeError):
696
+ error = abs(x - y)
697
+ if np.issubdtype(x.dtype, np.unsignedinteger):
698
+ error2 = abs(y - x)
699
+ np.minimum(error, error2, out=error)
700
+ max_abs_error = max(error)
701
+ remarks.append(
702
+ "Max absolute difference: " + array2string(max_abs_error.item())
703
+ )
704
+
705
+ # note: this definition of relative error matches that one
706
+ # used by assert_allclose (found in np.isclose)
707
+ # Filter values where the divisor would be zero
708
+ nonzero = bool_(y != 0)
709
+ if all(~nonzero):
710
+ max_rel_error = array(inf)
711
+ else:
712
+ max_rel_error = max(error[nonzero] / abs(y[nonzero]))
713
+ remarks.append(
714
+ "Max relative difference: " + array2string(max_rel_error.item())
715
+ )
716
+
717
+ err_msg += "\n" + "\n".join(remarks)
718
+ msg = build_err_msg(
719
+ [ox, oy],
720
+ err_msg,
721
+ verbose=verbose,
722
+ header=header,
723
+ names=("x", "y"),
724
+ precision=precision,
725
+ )
726
+ raise AssertionError(msg)
727
+ except ValueError:
728
+ import traceback
729
+
730
+ efmt = traceback.format_exc()
731
+ header = f"error during assertion:\n\n{efmt}\n\n{header}"
732
+
733
+ msg = build_err_msg(
734
+ [x, y],
735
+ err_msg,
736
+ verbose=verbose,
737
+ header=header,
738
+ names=("x", "y"),
739
+ precision=precision,
740
+ )
741
+ raise ValueError(msg) # noqa: B904
742
+
743
+
744
+ def assert_array_equal(x, y, err_msg="", verbose=True, *, strict=False):
745
+ """
746
+ Raises an AssertionError if two array_like objects are not equal.
747
+
748
+ Given two array_like objects, check that the shape is equal and all
749
+ elements of these objects are equal (but see the Notes for the special
750
+ handling of a scalar). An exception is raised at shape mismatch or
751
+ conflicting values. In contrast to the standard usage in numpy, NaNs
752
+ are compared like numbers, no assertion is raised if both objects have
753
+ NaNs in the same positions.
754
+
755
+ The usual caution for verifying equality with floating point numbers is
756
+ advised.
757
+
758
+ Parameters
759
+ ----------
760
+ x : array_like
761
+ The actual object to check.
762
+ y : array_like
763
+ The desired, expected object.
764
+ err_msg : str, optional
765
+ The error message to be printed in case of failure.
766
+ verbose : bool, optional
767
+ If True, the conflicting values are appended to the error message.
768
+ strict : bool, optional
769
+ If True, raise an AssertionError when either the shape or the data
770
+ type of the array_like objects does not match. The special
771
+ handling for scalars mentioned in the Notes section is disabled.
772
+
773
+ Raises
774
+ ------
775
+ AssertionError
776
+ If actual and desired objects are not equal.
777
+
778
+ See Also
779
+ --------
780
+ assert_allclose: Compare two array_like objects for equality with desired
781
+ relative and/or absolute precision.
782
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
783
+
784
+ Notes
785
+ -----
786
+ When one of `x` and `y` is a scalar and the other is array_like, the
787
+ function checks that each element of the array_like object is equal to
788
+ the scalar. This behaviour can be disabled with the `strict` parameter.
789
+
790
+ Examples
791
+ --------
792
+ The first assert does not raise an exception:
793
+
794
+ >>> np.testing.assert_array_equal(
795
+ ... [1.0, 2.33333, np.nan], [np.exp(0), 2.33333, np.nan]
796
+ ... )
797
+
798
+ Use `assert_allclose` or one of the nulp (number of floating point values)
799
+ functions for these cases instead:
800
+
801
+ >>> np.testing.assert_allclose(
802
+ ... [1.0, np.pi, np.nan], [1, np.sqrt(np.pi) ** 2, np.nan], rtol=1e-10, atol=0
803
+ ... )
804
+
805
+ As mentioned in the Notes section, `assert_array_equal` has special
806
+ handling for scalars. Here the test checks that each value in `x` is 3:
807
+
808
+ >>> x = np.full((2, 5), fill_value=3)
809
+ >>> np.testing.assert_array_equal(x, 3)
810
+
811
+ Use `strict` to raise an AssertionError when comparing a scalar with an
812
+ array:
813
+
814
+ >>> np.testing.assert_array_equal(x, 3, strict=True)
815
+ Traceback (most recent call last):
816
+ ...
817
+ AssertionError:
818
+ Arrays are not equal
819
+ <BLANKLINE>
820
+ (shapes (2, 5), () mismatch)
821
+ x: torch.ndarray([[3, 3, 3, 3, 3],
822
+ [3, 3, 3, 3, 3]])
823
+ y: torch.ndarray(3)
824
+
825
+ The `strict` parameter also ensures that the array data types match:
826
+
827
+ >>> x = np.array([2, 2, 2])
828
+ >>> y = np.array([2.0, 2.0, 2.0], dtype=np.float32)
829
+ >>> np.testing.assert_array_equal(x, y, strict=True)
830
+ Traceback (most recent call last):
831
+ ...
832
+ AssertionError:
833
+ Arrays are not equal
834
+ <BLANKLINE>
835
+ (dtypes dtype("int64"), dtype("float32") mismatch)
836
+ x: torch.ndarray([2, 2, 2])
837
+ y: torch.ndarray([2., 2., 2.])
838
+ """
839
+ __tracebackhide__ = True # Hide traceback for py.test
840
+ assert_array_compare(
841
+ operator.__eq__,
842
+ x,
843
+ y,
844
+ err_msg=err_msg,
845
+ verbose=verbose,
846
+ header="Arrays are not equal",
847
+ strict=strict,
848
+ )
849
+
850
+
851
+ def assert_array_almost_equal(x, y, decimal=6, err_msg="", verbose=True):
852
+ """
853
+ Raises an AssertionError if two objects are not equal up to desired
854
+ precision.
855
+
856
+ .. note:: It is recommended to use one of `assert_allclose`,
857
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
858
+ instead of this function for more consistent floating point
859
+ comparisons.
860
+
861
+ The test verifies identical shapes and that the elements of ``actual`` and
862
+ ``desired`` satisfy.
863
+
864
+ ``abs(desired-actual) < 1.5 * 10**(-decimal)``
865
+
866
+ That is a looser test than originally documented, but agrees with what the
867
+ actual implementation did up to rounding vagaries. An exception is raised
868
+ at shape mismatch or conflicting values. In contrast to the standard usage
869
+ in numpy, NaNs are compared like numbers, no assertion is raised if both
870
+ objects have NaNs in the same positions.
871
+
872
+ Parameters
873
+ ----------
874
+ x : array_like
875
+ The actual object to check.
876
+ y : array_like
877
+ The desired, expected object.
878
+ decimal : int, optional
879
+ Desired precision, default is 6.
880
+ err_msg : str, optional
881
+ The error message to be printed in case of failure.
882
+ verbose : bool, optional
883
+ If True, the conflicting values are appended to the error message.
884
+
885
+ Raises
886
+ ------
887
+ AssertionError
888
+ If actual and desired are not equal up to specified precision.
889
+
890
+ See Also
891
+ --------
892
+ assert_allclose: Compare two array_like objects for equality with desired
893
+ relative and/or absolute precision.
894
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
895
+
896
+ Examples
897
+ --------
898
+ the first assert does not raise an exception
899
+
900
+ >>> np.testing.assert_array_almost_equal([1.0, 2.333, np.nan], [1.0, 2.333, np.nan])
901
+
902
+ >>> np.testing.assert_array_almost_equal(
903
+ ... [1.0, 2.33333, np.nan], [1.0, 2.33339, np.nan], decimal=5
904
+ ... )
905
+ Traceback (most recent call last):
906
+ ...
907
+ AssertionError:
908
+ Arrays are not almost equal to 5 decimals
909
+ <BLANKLINE>
910
+ Mismatched elements: 1 / 3 (33.3%)
911
+ Max absolute difference: 5.999999999994898e-05
912
+ Max relative difference: 2.5713661239633743e-05
913
+ x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64)
914
+ y: torch.ndarray([1.0000, 2.3334, nan], dtype=float64)
915
+
916
+ >>> np.testing.assert_array_almost_equal(
917
+ ... [1.0, 2.33333, np.nan], [1.0, 2.33333, 5], decimal=5
918
+ ... )
919
+ Traceback (most recent call last):
920
+ ...
921
+ AssertionError:
922
+ Arrays are not almost equal to 5 decimals
923
+ <BLANKLINE>
924
+ x and y nan location mismatch:
925
+ x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64)
926
+ y: torch.ndarray([1.0000, 2.3333, 5.0000], dtype=float64)
927
+
928
+ """
929
+ __tracebackhide__ = True # Hide traceback for py.test
930
+ from torch._numpy import any as npany, float_, issubdtype, number, result_type
931
+
932
+ def compare(x, y):
933
+ try:
934
+ if npany(gisinf(x)) or npany(gisinf(y)):
935
+ xinfid = gisinf(x)
936
+ yinfid = gisinf(y)
937
+ if not (xinfid == yinfid).all():
938
+ return False
939
+ # if one item, x and y is +- inf
940
+ if x.size == y.size == 1:
941
+ return x == y
942
+ x = x[~xinfid]
943
+ y = y[~yinfid]
944
+ except (TypeError, NotImplementedError):
945
+ pass
946
+
947
+ # make sure y is an inexact type to avoid abs(MIN_INT); will cause
948
+ # casting of x later.
949
+ dtype = result_type(y, 1.0)
950
+ y = asanyarray(y, dtype)
951
+ z = abs(x - y)
952
+
953
+ if not issubdtype(z.dtype, number):
954
+ z = z.astype(float_) # handle object arrays
955
+
956
+ return z < 1.5 * 10.0 ** (-decimal)
957
+
958
+ assert_array_compare(
959
+ compare,
960
+ x,
961
+ y,
962
+ err_msg=err_msg,
963
+ verbose=verbose,
964
+ header=f"Arrays are not almost equal to {decimal:d} decimals",
965
+ precision=decimal,
966
+ )
967
+
968
+
969
+ def assert_array_less(x, y, err_msg="", verbose=True):
970
+ """
971
+ Raises an AssertionError if two array_like objects are not ordered by less
972
+ than.
973
+
974
+ Given two array_like objects, check that the shape is equal and all
975
+ elements of the first object are strictly smaller than those of the
976
+ second object. An exception is raised at shape mismatch or incorrectly
977
+ ordered values. Shape mismatch does not raise if an object has zero
978
+ dimension. In contrast to the standard usage in numpy, NaNs are
979
+ compared, no assertion is raised if both objects have NaNs in the same
980
+ positions.
981
+
982
+
983
+
984
+ Parameters
985
+ ----------
986
+ x : array_like
987
+ The smaller object to check.
988
+ y : array_like
989
+ The larger object to compare.
990
+ err_msg : string
991
+ The error message to be printed in case of failure.
992
+ verbose : bool
993
+ If True, the conflicting values are appended to the error message.
994
+
995
+ Raises
996
+ ------
997
+ AssertionError
998
+ If actual and desired objects are not equal.
999
+
1000
+ See Also
1001
+ --------
1002
+ assert_array_equal: tests objects for equality
1003
+ assert_array_almost_equal: test objects for equality up to precision
1004
+
1005
+
1006
+
1007
+ Examples
1008
+ --------
1009
+ >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
1010
+ >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
1011
+ Traceback (most recent call last):
1012
+ ...
1013
+ AssertionError:
1014
+ Arrays are not less-ordered
1015
+ <BLANKLINE>
1016
+ Mismatched elements: 1 / 3 (33.3%)
1017
+ Max absolute difference: 1.0
1018
+ Max relative difference: 0.5
1019
+ x: torch.ndarray([1., 1., nan], dtype=float64)
1020
+ y: torch.ndarray([1., 2., nan], dtype=float64)
1021
+
1022
+ >>> np.testing.assert_array_less([1.0, 4.0], 3)
1023
+ Traceback (most recent call last):
1024
+ ...
1025
+ AssertionError:
1026
+ Arrays are not less-ordered
1027
+ <BLANKLINE>
1028
+ Mismatched elements: 1 / 2 (50%)
1029
+ Max absolute difference: 2.0
1030
+ Max relative difference: 0.6666666666666666
1031
+ x: torch.ndarray([1., 4.], dtype=float64)
1032
+ y: torch.ndarray(3)
1033
+
1034
+ >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
1035
+ Traceback (most recent call last):
1036
+ ...
1037
+ AssertionError:
1038
+ Arrays are not less-ordered
1039
+ <BLANKLINE>
1040
+ (shapes (3,), (1,) mismatch)
1041
+ x: torch.ndarray([1., 2., 3.], dtype=float64)
1042
+ y: torch.ndarray([4])
1043
+
1044
+ """
1045
+ __tracebackhide__ = True # Hide traceback for py.test
1046
+ assert_array_compare(
1047
+ operator.__lt__,
1048
+ x,
1049
+ y,
1050
+ err_msg=err_msg,
1051
+ verbose=verbose,
1052
+ header="Arrays are not less-ordered",
1053
+ equal_inf=False,
1054
+ )
1055
+
1056
+
1057
+ def assert_string_equal(actual, desired):
1058
+ """
1059
+ Test if two strings are equal.
1060
+
1061
+ If the given strings are equal, `assert_string_equal` does nothing.
1062
+ If they are not equal, an AssertionError is raised, and the diff
1063
+ between the strings is shown.
1064
+
1065
+ Parameters
1066
+ ----------
1067
+ actual : str
1068
+ The string to test for equality against the expected string.
1069
+ desired : str
1070
+ The expected string.
1071
+
1072
+ Examples
1073
+ --------
1074
+ >>> np.testing.assert_string_equal("abc", "abc") # doctest: +SKIP
1075
+ >>> np.testing.assert_string_equal("abc", "abcd") # doctest: +SKIP
1076
+ Traceback (most recent call last):
1077
+ File "<stdin>", line 1, in <module>
1078
+ ...
1079
+ AssertionError: Differences in strings:
1080
+ - abc+ abcd? +
1081
+
1082
+ """
1083
+ # delay import of difflib to reduce startup time
1084
+ __tracebackhide__ = True # Hide traceback for py.test
1085
+ import difflib
1086
+
1087
+ if not isinstance(actual, str):
1088
+ raise AssertionError(repr(type(actual)))
1089
+ if not isinstance(desired, str):
1090
+ raise AssertionError(repr(type(desired)))
1091
+ if desired == actual:
1092
+ return
1093
+
1094
+ diff = list(
1095
+ difflib.Differ().compare(actual.splitlines(True), desired.splitlines(True))
1096
+ )
1097
+ diff_list = []
1098
+ while diff:
1099
+ d1 = diff.pop(0)
1100
+ if d1.startswith(" "):
1101
+ continue
1102
+ if d1.startswith("- "):
1103
+ l = [d1]
1104
+ d2 = diff.pop(0)
1105
+ if d2.startswith("? "):
1106
+ l.append(d2)
1107
+ d2 = diff.pop(0)
1108
+ if not d2.startswith("+ "):
1109
+ raise AssertionError(repr(d2))
1110
+ l.append(d2)
1111
+ if diff:
1112
+ d3 = diff.pop(0)
1113
+ if d3.startswith("? "):
1114
+ l.append(d3)
1115
+ else:
1116
+ diff.insert(0, d3)
1117
+ if d2[2:] == d1[2:]:
1118
+ continue
1119
+ diff_list.extend(l)
1120
+ continue
1121
+ raise AssertionError(repr(d1))
1122
+ if not diff_list:
1123
+ return
1124
+ msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}"
1125
+ if actual != desired:
1126
+ raise AssertionError(msg)
1127
+
1128
+
1129
+ import unittest
1130
+
1131
+
1132
+ class _Dummy(unittest.TestCase):
1133
+ def nop(self):
1134
+ pass
1135
+
1136
+
1137
+ _d = _Dummy("nop")
1138
+
1139
+
1140
+ def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
1141
+ """
1142
+ assert_raises_regex(exception_class, expected_regexp, callable, *args,
1143
+ **kwargs)
1144
+ assert_raises_regex(exception_class, expected_regexp)
1145
+
1146
+ Fail unless an exception of class exception_class and with message that
1147
+ matches expected_regexp is thrown by callable when invoked with arguments
1148
+ args and keyword arguments kwargs.
1149
+
1150
+ Alternatively, can be used as a context manager like `assert_raises`.
1151
+
1152
+ Notes
1153
+ -----
1154
+ .. versionadded:: 1.9.0
1155
+
1156
+ """
1157
+ __tracebackhide__ = True # Hide traceback for py.test
1158
+ return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs)
1159
+
1160
+
1161
+ def decorate_methods(cls, decorator, testmatch=None):
1162
+ """
1163
+ Apply a decorator to all methods in a class matching a regular expression.
1164
+
1165
+ The given decorator is applied to all public methods of `cls` that are
1166
+ matched by the regular expression `testmatch`
1167
+ (``testmatch.search(methodname)``). Methods that are private, i.e. start
1168
+ with an underscore, are ignored.
1169
+
1170
+ Parameters
1171
+ ----------
1172
+ cls : class
1173
+ Class whose methods to decorate.
1174
+ decorator : function
1175
+ Decorator to apply to methods
1176
+ testmatch : compiled regexp or str, optional
1177
+ The regular expression. Default value is None, in which case the
1178
+ nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
1179
+ is used.
1180
+ If `testmatch` is a string, it is compiled to a regular expression
1181
+ first.
1182
+
1183
+ """
1184
+ if testmatch is None:
1185
+ testmatch = re.compile(rf"(?:^|[\\b_\\.{os.sep}-])[Tt]est")
1186
+ else:
1187
+ testmatch = re.compile(testmatch)
1188
+ cls_attr = cls.__dict__
1189
+
1190
+ # delayed import to reduce startup time
1191
+ from inspect import isfunction
1192
+
1193
+ methods = [_m for _m in cls_attr.values() if isfunction(_m)]
1194
+ for function in methods:
1195
+ try:
1196
+ if hasattr(function, "compat_func_name"):
1197
+ funcname = function.compat_func_name
1198
+ else:
1199
+ funcname = function.__name__
1200
+ except AttributeError:
1201
+ # not a function
1202
+ continue
1203
+ if testmatch.search(funcname) and not funcname.startswith("_"):
1204
+ setattr(cls, funcname, decorator(function))
1205
+ return
1206
+
1207
+
1208
+ def _assert_valid_refcount(op):
1209
+ """
1210
+ Check that ufuncs don't mishandle refcount of object `1`.
1211
+ Used in a few regression tests.
1212
+ """
1213
+ if not HAS_REFCOUNT:
1214
+ return True
1215
+
1216
+ import gc
1217
+
1218
+ import numpy as np
1219
+
1220
+ b = np.arange(100 * 100).reshape(100, 100)
1221
+ c = b
1222
+ i = 1
1223
+
1224
+ gc.disable()
1225
+ try:
1226
+ rc = sys.getrefcount(i)
1227
+ for _ in range(15):
1228
+ d = op(b, c)
1229
+ assert_(sys.getrefcount(i) >= rc)
1230
+ finally:
1231
+ gc.enable()
1232
+ del d # for pyflakes
1233
+
1234
+
1235
+ def assert_allclose(
1236
+ actual,
1237
+ desired,
1238
+ rtol=1e-7,
1239
+ atol=0,
1240
+ equal_nan=True,
1241
+ err_msg="",
1242
+ verbose=True,
1243
+ check_dtype=False,
1244
+ ):
1245
+ """
1246
+ Raises an AssertionError if two objects are not equal up to desired
1247
+ tolerance.
1248
+
1249
+ Given two array_like objects, check that their shapes and all elements
1250
+ are equal (but see the Notes for the special handling of a scalar). An
1251
+ exception is raised if the shapes mismatch or any values conflict. In
1252
+ contrast to the standard usage in numpy, NaNs are compared like numbers,
1253
+ no assertion is raised if both objects have NaNs in the same positions.
1254
+
1255
+ The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
1256
+ that ``allclose`` has different default values). It compares the difference
1257
+ between `actual` and `desired` to ``atol + rtol * abs(desired)``.
1258
+
1259
+ .. versionadded:: 1.5.0
1260
+
1261
+ Parameters
1262
+ ----------
1263
+ actual : array_like
1264
+ Array obtained.
1265
+ desired : array_like
1266
+ Array desired.
1267
+ rtol : float, optional
1268
+ Relative tolerance.
1269
+ atol : float, optional
1270
+ Absolute tolerance.
1271
+ equal_nan : bool, optional.
1272
+ If True, NaNs will compare equal.
1273
+ err_msg : str, optional
1274
+ The error message to be printed in case of failure.
1275
+ verbose : bool, optional
1276
+ If True, the conflicting values are appended to the error message.
1277
+
1278
+ Raises
1279
+ ------
1280
+ AssertionError
1281
+ If actual and desired are not equal up to specified precision.
1282
+
1283
+ See Also
1284
+ --------
1285
+ assert_array_almost_equal_nulp, assert_array_max_ulp
1286
+
1287
+ Notes
1288
+ -----
1289
+ When one of `actual` and `desired` is a scalar and the other is
1290
+ array_like, the function checks that each element of the array_like
1291
+ object is equal to the scalar.
1292
+
1293
+ Examples
1294
+ --------
1295
+ >>> x = [1e-5, 1e-3, 1e-1]
1296
+ >>> y = np.arccos(np.cos(x))
1297
+ >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
1298
+
1299
+ """
1300
+ __tracebackhide__ = True # Hide traceback for py.test
1301
+
1302
+ def compare(x, y):
1303
+ return np.isclose(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan)
1304
+
1305
+ actual, desired = asanyarray(actual), asanyarray(desired)
1306
+ header = f"Not equal to tolerance rtol={rtol:g}, atol={atol:g}"
1307
+
1308
+ if check_dtype:
1309
+ if actual.dtype != desired.dtype:
1310
+ raise AssertionError(f"dtype mismatch: {actual.dtype} != {desired.dtype}")
1311
+
1312
+ assert_array_compare(
1313
+ compare,
1314
+ actual,
1315
+ desired,
1316
+ err_msg=str(err_msg),
1317
+ verbose=verbose,
1318
+ header=header,
1319
+ equal_nan=equal_nan,
1320
+ )
1321
+
1322
+
1323
+ def assert_array_almost_equal_nulp(x, y, nulp=1):
1324
+ """
1325
+ Compare two arrays relatively to their spacing.
1326
+
1327
+ This is a relatively robust method to compare two arrays whose amplitude
1328
+ is variable.
1329
+
1330
+ Parameters
1331
+ ----------
1332
+ x, y : array_like
1333
+ Input arrays.
1334
+ nulp : int, optional
1335
+ The maximum number of unit in the last place for tolerance (see Notes).
1336
+ Default is 1.
1337
+
1338
+ Returns
1339
+ -------
1340
+ None
1341
+
1342
+ Raises
1343
+ ------
1344
+ AssertionError
1345
+ If the spacing between `x` and `y` for one or more elements is larger
1346
+ than `nulp`.
1347
+
1348
+ See Also
1349
+ --------
1350
+ assert_array_max_ulp : Check that all items of arrays differ in at most
1351
+ N Units in the Last Place.
1352
+ spacing : Return the distance between x and the nearest adjacent number.
1353
+
1354
+ Notes
1355
+ -----
1356
+ An assertion is raised if the following condition is not met::
1357
+
1358
+ abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y)))
1359
+
1360
+ Examples
1361
+ --------
1362
+ >>> x = np.array([1.0, 1e-10, 1e-20])
1363
+ >>> eps = np.finfo(x.dtype).eps
1364
+ >>> np.testing.assert_array_almost_equal_nulp(x, x * eps / 2 + x) # doctest: +SKIP
1365
+
1366
+ >>> np.testing.assert_array_almost_equal_nulp(x, x * eps + x) # doctest: +SKIP
1367
+ Traceback (most recent call last):
1368
+ ...
1369
+ AssertionError: X and Y are not equal to 1 ULP (max is 2)
1370
+
1371
+ """
1372
+ __tracebackhide__ = True # Hide traceback for py.test
1373
+ import numpy as np
1374
+
1375
+ ax = np.abs(x)
1376
+ ay = np.abs(y)
1377
+ ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
1378
+ if not np.all(np.abs(x - y) <= ref):
1379
+ if np.iscomplexobj(x) or np.iscomplexobj(y):
1380
+ msg = f"X and Y are not equal to {nulp:d} ULP"
1381
+ else:
1382
+ max_nulp = np.max(nulp_diff(x, y))
1383
+ msg = f"X and Y are not equal to {nulp:d} ULP (max is {max_nulp:g})"
1384
+ raise AssertionError(msg)
1385
+
1386
+
1387
+ def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
1388
+ """
1389
+ Check that all items of arrays differ in at most N Units in the Last Place.
1390
+
1391
+ Parameters
1392
+ ----------
1393
+ a, b : array_like
1394
+ Input arrays to be compared.
1395
+ maxulp : int, optional
1396
+ The maximum number of units in the last place that elements of `a` and
1397
+ `b` can differ. Default is 1.
1398
+ dtype : dtype, optional
1399
+ Data-type to convert `a` and `b` to if given. Default is None.
1400
+
1401
+ Returns
1402
+ -------
1403
+ ret : ndarray
1404
+ Array containing number of representable floating point numbers between
1405
+ items in `a` and `b`.
1406
+
1407
+ Raises
1408
+ ------
1409
+ AssertionError
1410
+ If one or more elements differ by more than `maxulp`.
1411
+
1412
+ Notes
1413
+ -----
1414
+ For computing the ULP difference, this API does not differentiate between
1415
+ various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
1416
+ is zero).
1417
+
1418
+ See Also
1419
+ --------
1420
+ assert_array_almost_equal_nulp : Compare two arrays relatively to their
1421
+ spacing.
1422
+
1423
+ Examples
1424
+ --------
1425
+ >>> a = np.linspace(0.0, 1.0, 100)
1426
+ >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a))) # doctest: +SKIP
1427
+
1428
+ """
1429
+ __tracebackhide__ = True # Hide traceback for py.test
1430
+ import numpy as np
1431
+
1432
+ ret = nulp_diff(a, b, dtype)
1433
+ if not np.all(ret <= maxulp):
1434
+ raise AssertionError(
1435
+ f"Arrays are not almost equal up to {maxulp:g} "
1436
+ f"ULP (max difference is {np.max(ret):g} ULP)"
1437
+ )
1438
+ return ret
1439
+
1440
+
1441
+ def nulp_diff(x, y, dtype=None):
1442
+ """For each item in x and y, return the number of representable floating
1443
+ points between them.
1444
+
1445
+ Parameters
1446
+ ----------
1447
+ x : array_like
1448
+ first input array
1449
+ y : array_like
1450
+ second input array
1451
+ dtype : dtype, optional
1452
+ Data-type to convert `x` and `y` to if given. Default is None.
1453
+
1454
+ Returns
1455
+ -------
1456
+ nulp : array_like
1457
+ number of representable floating point numbers between each item in x
1458
+ and y.
1459
+
1460
+ Notes
1461
+ -----
1462
+ For computing the ULP difference, this API does not differentiate between
1463
+ various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
1464
+ is zero).
1465
+
1466
+ Examples
1467
+ --------
1468
+ # By definition, epsilon is the smallest number such as 1 + eps != 1, so
1469
+ # there should be exactly one ULP between 1 and 1 + eps
1470
+ >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) # doctest: +SKIP
1471
+ 1.0
1472
+ """
1473
+ import numpy as np
1474
+
1475
+ if dtype:
1476
+ x = np.asarray(x, dtype=dtype)
1477
+ y = np.asarray(y, dtype=dtype)
1478
+ else:
1479
+ x = np.asarray(x)
1480
+ y = np.asarray(y)
1481
+
1482
+ t = np.common_type(x, y)
1483
+ if np.iscomplexobj(x) or np.iscomplexobj(y):
1484
+ raise NotImplementedError("_nulp not implemented for complex array")
1485
+
1486
+ x = np.array([x], dtype=t)
1487
+ y = np.array([y], dtype=t)
1488
+
1489
+ x[np.isnan(x)] = np.nan
1490
+ y[np.isnan(y)] = np.nan
1491
+
1492
+ if not x.shape == y.shape:
1493
+ raise ValueError(f"x and y do not have the same shape: {x.shape} - {y.shape}")
1494
+
1495
+ def _diff(rx, ry, vdt):
1496
+ diff = np.asarray(rx - ry, dtype=vdt)
1497
+ return np.abs(diff)
1498
+
1499
+ rx = integer_repr(x)
1500
+ ry = integer_repr(y)
1501
+ return _diff(rx, ry, t)
1502
+
1503
+
1504
+ def _integer_repr(x, vdt, comp):
1505
+ # Reinterpret binary representation of the float as sign-magnitude:
1506
+ # take into account two's-complement representation
1507
+ # See also
1508
+ # https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
1509
+ rx = x.view(vdt)
1510
+ if rx.size != 1:
1511
+ rx[rx < 0] = comp - rx[rx < 0]
1512
+ else:
1513
+ if rx < 0:
1514
+ rx = comp - rx
1515
+
1516
+ return rx
1517
+
1518
+
1519
+ def integer_repr(x):
1520
+ """Return the signed-magnitude interpretation of the binary representation
1521
+ of x."""
1522
+ import numpy as np
1523
+
1524
+ if x.dtype == np.float16:
1525
+ return _integer_repr(x, np.int16, np.int16(-(2**15)))
1526
+ elif x.dtype == np.float32:
1527
+ return _integer_repr(x, np.int32, np.int32(-(2**31)))
1528
+ elif x.dtype == np.float64:
1529
+ return _integer_repr(x, np.int64, np.int64(-(2**63)))
1530
+ else:
1531
+ raise ValueError(f"Unsupported dtype {x.dtype}")
1532
+
1533
+
1534
+ @contextlib.contextmanager
1535
+ def _assert_warns_context(warning_class, name=None):
1536
+ __tracebackhide__ = True # Hide traceback for py.test
1537
+ with suppress_warnings() as sup:
1538
+ l = sup.record(warning_class)
1539
+ yield
1540
+ if not len(l) > 0:
1541
+ name_str = f" when calling {name}" if name is not None else ""
1542
+ raise AssertionError("No warning raised" + name_str)
1543
+
1544
+
1545
+ def assert_warns(warning_class, *args, **kwargs):
1546
+ """
1547
+ Fail unless the given callable throws the specified warning.
1548
+
1549
+ A warning of class warning_class should be thrown by the callable when
1550
+ invoked with arguments args and keyword arguments kwargs.
1551
+ If a different type of warning is thrown, it will not be caught.
1552
+
1553
+ If called with all arguments other than the warning class omitted, may be
1554
+ used as a context manager:
1555
+
1556
+ with assert_warns(SomeWarning):
1557
+ do_something()
1558
+
1559
+ The ability to be used as a context manager is new in NumPy v1.11.0.
1560
+
1561
+ .. versionadded:: 1.4.0
1562
+
1563
+ Parameters
1564
+ ----------
1565
+ warning_class : class
1566
+ The class defining the warning that `func` is expected to throw.
1567
+ func : callable, optional
1568
+ Callable to test
1569
+ *args : Arguments
1570
+ Arguments for `func`.
1571
+ **kwargs : Kwargs
1572
+ Keyword arguments for `func`.
1573
+
1574
+ Returns
1575
+ -------
1576
+ The value returned by `func`.
1577
+
1578
+ Examples
1579
+ --------
1580
+ >>> import warnings
1581
+ >>> def deprecated_func(num):
1582
+ ... warnings.warn("Please upgrade", DeprecationWarning)
1583
+ ... return num * num
1584
+ >>> with np.testing.assert_warns(DeprecationWarning):
1585
+ ... assert deprecated_func(4) == 16
1586
+ >>> # or passing a func
1587
+ >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4)
1588
+ >>> assert ret == 16
1589
+ """
1590
+ if not args:
1591
+ return _assert_warns_context(warning_class)
1592
+
1593
+ func = args[0]
1594
+ args = args[1:]
1595
+ with _assert_warns_context(warning_class, name=func.__name__):
1596
+ return func(*args, **kwargs)
1597
+
1598
+
1599
+ @contextlib.contextmanager
1600
+ def _assert_no_warnings_context(name=None):
1601
+ __tracebackhide__ = True # Hide traceback for py.test
1602
+ with warnings.catch_warnings(record=True) as l:
1603
+ warnings.simplefilter("always")
1604
+ yield
1605
+ if len(l) > 0:
1606
+ name_str = f" when calling {name}" if name is not None else ""
1607
+ raise AssertionError(f"Got warnings{name_str}: {l}")
1608
+
1609
+
1610
+ def assert_no_warnings(*args, **kwargs):
1611
+ """
1612
+ Fail if the given callable produces any warnings.
1613
+
1614
+ If called with all arguments omitted, may be used as a context manager:
1615
+
1616
+ with assert_no_warnings():
1617
+ do_something()
1618
+
1619
+ The ability to be used as a context manager is new in NumPy v1.11.0.
1620
+
1621
+ .. versionadded:: 1.7.0
1622
+
1623
+ Parameters
1624
+ ----------
1625
+ func : callable
1626
+ The callable to test.
1627
+ \\*args : Arguments
1628
+ Arguments passed to `func`.
1629
+ \\*\\*kwargs : Kwargs
1630
+ Keyword arguments passed to `func`.
1631
+
1632
+ Returns
1633
+ -------
1634
+ The value returned by `func`.
1635
+
1636
+ """
1637
+ if not args:
1638
+ return _assert_no_warnings_context()
1639
+
1640
+ func = args[0]
1641
+ args = args[1:]
1642
+ with _assert_no_warnings_context(name=func.__name__):
1643
+ return func(*args, **kwargs)
1644
+
1645
+
1646
+ def _gen_alignment_data(dtype=float32, type="binary", max_size=24):
1647
+ """
1648
+ generator producing data with different alignment and offsets
1649
+ to test simd vectorization
1650
+
1651
+ Parameters
1652
+ ----------
1653
+ dtype : dtype
1654
+ data type to produce
1655
+ type : string
1656
+ 'unary': create data for unary operations, creates one input
1657
+ and output array
1658
+ 'binary': create data for binary operations, creates two input
1659
+ and output array
1660
+ max_size : integer
1661
+ maximum size of data to produce
1662
+
1663
+ Returns
1664
+ -------
1665
+ if type is 'unary' yields one output, one input array and a message
1666
+ containing information on the data
1667
+ if type is 'binary' yields one output array, two input array and a message
1668
+ containing information on the data
1669
+
1670
+ """
1671
+ ufmt = "unary offset=(%d, %d), size=%d, dtype=%r, %s"
1672
+ bfmt = "binary offset=(%d, %d, %d), size=%d, dtype=%r, %s"
1673
+ for o in range(3):
1674
+ for s in range(o + 2, max(o + 3, max_size)):
1675
+ if type == "unary":
1676
+
1677
+ def inp():
1678
+ return arange(s, dtype=dtype)[o:]
1679
+
1680
+ out = empty((s,), dtype=dtype)[o:]
1681
+ yield out, inp(), ufmt % (o, o, s, dtype, "out of place")
1682
+ d = inp()
1683
+ yield d, d, ufmt % (o, o, s, dtype, "in place")
1684
+ yield (
1685
+ out[1:],
1686
+ inp()[:-1],
1687
+ ufmt
1688
+ % (
1689
+ o + 1,
1690
+ o,
1691
+ s - 1,
1692
+ dtype,
1693
+ "out of place",
1694
+ ),
1695
+ )
1696
+ yield (
1697
+ out[:-1],
1698
+ inp()[1:],
1699
+ ufmt
1700
+ % (
1701
+ o,
1702
+ o + 1,
1703
+ s - 1,
1704
+ dtype,
1705
+ "out of place",
1706
+ ),
1707
+ )
1708
+ yield inp()[:-1], inp()[1:], ufmt % (o, o + 1, s - 1, dtype, "aliased")
1709
+ yield inp()[1:], inp()[:-1], ufmt % (o + 1, o, s - 1, dtype, "aliased")
1710
+ if type == "binary":
1711
+
1712
+ def inp1():
1713
+ return arange(s, dtype=dtype)[o:]
1714
+
1715
+ inp2 = inp1
1716
+ out = empty((s,), dtype=dtype)[o:]
1717
+ yield out, inp1(), inp2(), bfmt % (o, o, o, s, dtype, "out of place")
1718
+ d = inp1()
1719
+ yield d, d, inp2(), bfmt % (o, o, o, s, dtype, "in place1")
1720
+ d = inp2()
1721
+ yield d, inp1(), d, bfmt % (o, o, o, s, dtype, "in place2")
1722
+ yield (
1723
+ out[1:],
1724
+ inp1()[:-1],
1725
+ inp2()[:-1],
1726
+ bfmt
1727
+ % (
1728
+ o + 1,
1729
+ o,
1730
+ o,
1731
+ s - 1,
1732
+ dtype,
1733
+ "out of place",
1734
+ ),
1735
+ )
1736
+ yield (
1737
+ out[:-1],
1738
+ inp1()[1:],
1739
+ inp2()[:-1],
1740
+ bfmt
1741
+ % (
1742
+ o,
1743
+ o + 1,
1744
+ o,
1745
+ s - 1,
1746
+ dtype,
1747
+ "out of place",
1748
+ ),
1749
+ )
1750
+ yield (
1751
+ out[:-1],
1752
+ inp1()[:-1],
1753
+ inp2()[1:],
1754
+ bfmt
1755
+ % (
1756
+ o,
1757
+ o,
1758
+ o + 1,
1759
+ s - 1,
1760
+ dtype,
1761
+ "out of place",
1762
+ ),
1763
+ )
1764
+ yield (
1765
+ inp1()[1:],
1766
+ inp1()[:-1],
1767
+ inp2()[:-1],
1768
+ bfmt
1769
+ % (
1770
+ o + 1,
1771
+ o,
1772
+ o,
1773
+ s - 1,
1774
+ dtype,
1775
+ "aliased",
1776
+ ),
1777
+ )
1778
+ yield (
1779
+ inp1()[:-1],
1780
+ inp1()[1:],
1781
+ inp2()[:-1],
1782
+ bfmt
1783
+ % (
1784
+ o,
1785
+ o + 1,
1786
+ o,
1787
+ s - 1,
1788
+ dtype,
1789
+ "aliased",
1790
+ ),
1791
+ )
1792
+ yield (
1793
+ inp1()[:-1],
1794
+ inp1()[:-1],
1795
+ inp2()[1:],
1796
+ bfmt
1797
+ % (
1798
+ o,
1799
+ o,
1800
+ o + 1,
1801
+ s - 1,
1802
+ dtype,
1803
+ "aliased",
1804
+ ),
1805
+ )
1806
+
1807
+
1808
+ class IgnoreException(Exception):
1809
+ "Ignoring this exception due to disabled feature"
1810
+
1811
+
1812
+ @contextlib.contextmanager
1813
+ def tempdir(*args, **kwargs):
1814
+ """Context manager to provide a temporary test folder.
1815
+
1816
+ All arguments are passed as this to the underlying tempfile.mkdtemp
1817
+ function.
1818
+
1819
+ """
1820
+ tmpdir = mkdtemp(*args, **kwargs)
1821
+ try:
1822
+ yield tmpdir
1823
+ finally:
1824
+ shutil.rmtree(tmpdir)
1825
+
1826
+
1827
+ @contextlib.contextmanager
1828
+ def temppath(*args, **kwargs):
1829
+ """Context manager for temporary files.
1830
+
1831
+ Context manager that returns the path to a closed temporary file. Its
1832
+ parameters are the same as for tempfile.mkstemp and are passed directly
1833
+ to that function. The underlying file is removed when the context is
1834
+ exited, so it should be closed at that time.
1835
+
1836
+ Windows does not allow a temporary file to be opened if it is already
1837
+ open, so the underlying file must be closed after opening before it
1838
+ can be opened again.
1839
+
1840
+ """
1841
+ fd, path = mkstemp(*args, **kwargs)
1842
+ os.close(fd)
1843
+ try:
1844
+ yield path
1845
+ finally:
1846
+ os.remove(path)
1847
+
1848
+
1849
+ class clear_and_catch_warnings(warnings.catch_warnings):
1850
+ """Context manager that resets warning registry for catching warnings
1851
+
1852
+ Warnings can be slippery, because, whenever a warning is triggered, Python
1853
+ adds a ``__warningregistry__`` member to the *calling* module. This makes
1854
+ it impossible to retrigger the warning in this module, whatever you put in
1855
+ the warnings filters. This context manager accepts a sequence of `modules`
1856
+ as a keyword argument to its constructor and:
1857
+
1858
+ * stores and removes any ``__warningregistry__`` entries in given `modules`
1859
+ on entry;
1860
+ * resets ``__warningregistry__`` to its previous state on exit.
1861
+
1862
+ This makes it possible to trigger any warning afresh inside the context
1863
+ manager without disturbing the state of warnings outside.
1864
+
1865
+ For compatibility with Python 3.0, please consider all arguments to be
1866
+ keyword-only.
1867
+
1868
+ Parameters
1869
+ ----------
1870
+ record : bool, optional
1871
+ Specifies whether warnings should be captured by a custom
1872
+ implementation of ``warnings.showwarning()`` and be appended to a list
1873
+ returned by the context manager. Otherwise None is returned by the
1874
+ context manager. The objects appended to the list are arguments whose
1875
+ attributes mirror the arguments to ``showwarning()``.
1876
+ modules : sequence, optional
1877
+ Sequence of modules for which to reset warnings registry on entry and
1878
+ restore on exit. To work correctly, all 'ignore' filters should
1879
+ filter by one of these modules.
1880
+
1881
+ Examples
1882
+ --------
1883
+ >>> import warnings
1884
+ >>> with np.testing.clear_and_catch_warnings( # doctest: +SKIP
1885
+ ... modules=[np.core.fromnumeric]
1886
+ ... ):
1887
+ ... warnings.simplefilter("always")
1888
+ ... warnings.filterwarnings("ignore", module="np.core.fromnumeric")
1889
+ ... # do something that raises a warning but ignore those in
1890
+ ... # np.core.fromnumeric
1891
+ """
1892
+
1893
+ class_modules = ()
1894
+
1895
+ def __init__(self, record=False, modules=()):
1896
+ self.modules = set(modules).union(self.class_modules)
1897
+ self._warnreg_copies = {}
1898
+ super().__init__(record=record)
1899
+
1900
+ def __enter__(self):
1901
+ for mod in self.modules:
1902
+ if hasattr(mod, "__warningregistry__"):
1903
+ mod_reg = mod.__warningregistry__
1904
+ self._warnreg_copies[mod] = mod_reg.copy()
1905
+ mod_reg.clear()
1906
+ return super().__enter__()
1907
+
1908
+ def __exit__(self, *exc_info):
1909
+ super().__exit__(*exc_info)
1910
+ for mod in self.modules:
1911
+ if hasattr(mod, "__warningregistry__"):
1912
+ mod.__warningregistry__.clear()
1913
+ if mod in self._warnreg_copies:
1914
+ mod.__warningregistry__.update(self._warnreg_copies[mod])
1915
+
1916
+
1917
+ class suppress_warnings:
1918
+ """
1919
+ Context manager and decorator doing much the same as
1920
+ ``warnings.catch_warnings``.
1921
+
1922
+ However, it also provides a filter mechanism to work around
1923
+ https://bugs.python.org/issue4180.
1924
+
1925
+ This bug causes Python before 3.4 to not reliably show warnings again
1926
+ after they have been ignored once (even within catch_warnings). It
1927
+ means that no "ignore" filter can be used easily, since following
1928
+ tests might need to see the warning. Additionally it allows easier
1929
+ specificity for testing warnings and can be nested.
1930
+
1931
+ Parameters
1932
+ ----------
1933
+ forwarding_rule : str, optional
1934
+ One of "always", "once", "module", or "location". Analogous to
1935
+ the usual warnings module filter mode, it is useful to reduce
1936
+ noise mostly on the outmost level. Unsuppressed and unrecorded
1937
+ warnings will be forwarded based on this rule. Defaults to "always".
1938
+ "location" is equivalent to the warnings "default", match by exact
1939
+ location the warning originated from.
1940
+
1941
+ Notes
1942
+ -----
1943
+ Filters added inside the context manager will be discarded again
1944
+ when leaving it. Upon entering all filters defined outside a
1945
+ context will be applied automatically.
1946
+
1947
+ When a recording filter is added, matching warnings are stored in the
1948
+ ``log`` attribute as well as in the list returned by ``record``.
1949
+
1950
+ If filters are added and the ``module`` keyword is given, the
1951
+ warning registry of this module will additionally be cleared when
1952
+ applying it, entering the context, or exiting it. This could cause
1953
+ warnings to appear a second time after leaving the context if they
1954
+ were configured to be printed once (default) and were already
1955
+ printed before the context was entered.
1956
+
1957
+ Nesting this context manager will work as expected when the
1958
+ forwarding rule is "always" (default). Unfiltered and unrecorded
1959
+ warnings will be passed out and be matched by the outer level.
1960
+ On the outmost level they will be printed (or caught by another
1961
+ warnings context). The forwarding rule argument can modify this
1962
+ behaviour.
1963
+
1964
+ Like ``catch_warnings`` this context manager is not threadsafe.
1965
+
1966
+ Examples
1967
+ --------
1968
+
1969
+ With a context manager::
1970
+
1971
+ with np.testing.suppress_warnings() as sup:
1972
+ sup.filter(DeprecationWarning, "Some text")
1973
+ sup.filter(module=np.ma.core)
1974
+ log = sup.record(FutureWarning, "Does this occur?")
1975
+ command_giving_warnings()
1976
+ # The FutureWarning was given once, the filtered warnings were
1977
+ # ignored. All other warnings abide outside settings (may be
1978
+ # printed/error)
1979
+ assert_(len(log) == 1)
1980
+ assert_(len(sup.log) == 1) # also stored in log attribute
1981
+
1982
+ Or as a decorator::
1983
+
1984
+ sup = np.testing.suppress_warnings()
1985
+ sup.filter(module=np.ma.core) # module must match exactly
1986
+
1987
+
1988
+ @sup
1989
+ def some_function():
1990
+ # do something which causes a warning in np.ma.core
1991
+ pass
1992
+ """
1993
+
1994
+ def __init__(self, forwarding_rule="always"):
1995
+ self._entered = False
1996
+
1997
+ # Suppressions are either instance or defined inside one with block:
1998
+ self._suppressions = []
1999
+
2000
+ if forwarding_rule not in {"always", "module", "once", "location"}:
2001
+ raise ValueError("unsupported forwarding rule.")
2002
+ self._forwarding_rule = forwarding_rule
2003
+
2004
+ def _clear_registries(self):
2005
+ if hasattr(warnings, "_filters_mutated"):
2006
+ # clearing the registry should not be necessary on new pythons,
2007
+ # instead the filters should be mutated.
2008
+ warnings._filters_mutated()
2009
+ return
2010
+ # Simply clear the registry, this should normally be harmless,
2011
+ # note that on new pythons it would be invalidated anyway.
2012
+ for module in self._tmp_modules:
2013
+ if hasattr(module, "__warningregistry__"):
2014
+ module.__warningregistry__.clear()
2015
+
2016
+ def _filter(self, category=Warning, message="", module=None, record=False):
2017
+ if record:
2018
+ record = [] # The log where to store warnings
2019
+ else:
2020
+ record = None
2021
+ if self._entered:
2022
+ if module is None:
2023
+ warnings.filterwarnings("always", category=category, message=message)
2024
+ else:
2025
+ module_regex = module.__name__.replace(".", r"\.") + "$"
2026
+ warnings.filterwarnings(
2027
+ "always", category=category, message=message, module=module_regex
2028
+ )
2029
+ self._tmp_modules.add(module)
2030
+ self._clear_registries()
2031
+
2032
+ self._tmp_suppressions.append(
2033
+ (category, message, re.compile(message, re.IGNORECASE), module, record)
2034
+ )
2035
+ else:
2036
+ self._suppressions.append(
2037
+ (category, message, re.compile(message, re.IGNORECASE), module, record)
2038
+ )
2039
+
2040
+ return record
2041
+
2042
+ def filter(self, category=Warning, message="", module=None):
2043
+ """
2044
+ Add a new suppressing filter or apply it if the state is entered.
2045
+
2046
+ Parameters
2047
+ ----------
2048
+ category : class, optional
2049
+ Warning class to filter
2050
+ message : string, optional
2051
+ Regular expression matching the warning message.
2052
+ module : module, optional
2053
+ Module to filter for. Note that the module (and its file)
2054
+ must match exactly and cannot be a submodule. This may make
2055
+ it unreliable for external modules.
2056
+
2057
+ Notes
2058
+ -----
2059
+ When added within a context, filters are only added inside
2060
+ the context and will be forgotten when the context is exited.
2061
+ """
2062
+ self._filter(category=category, message=message, module=module, record=False)
2063
+
2064
+ def record(self, category=Warning, message="", module=None):
2065
+ """
2066
+ Append a new recording filter or apply it if the state is entered.
2067
+
2068
+ All warnings matching will be appended to the ``log`` attribute.
2069
+
2070
+ Parameters
2071
+ ----------
2072
+ category : class, optional
2073
+ Warning class to filter
2074
+ message : string, optional
2075
+ Regular expression matching the warning message.
2076
+ module : module, optional
2077
+ Module to filter for. Note that the module (and its file)
2078
+ must match exactly and cannot be a submodule. This may make
2079
+ it unreliable for external modules.
2080
+
2081
+ Returns
2082
+ -------
2083
+ log : list
2084
+ A list which will be filled with all matched warnings.
2085
+
2086
+ Notes
2087
+ -----
2088
+ When added within a context, filters are only added inside
2089
+ the context and will be forgotten when the context is exited.
2090
+ """
2091
+ return self._filter(
2092
+ category=category, message=message, module=module, record=True
2093
+ )
2094
+
2095
+ def __enter__(self):
2096
+ if self._entered:
2097
+ raise RuntimeError("cannot enter suppress_warnings twice.")
2098
+
2099
+ self._orig_show = warnings.showwarning
2100
+ self._filters = warnings.filters
2101
+ warnings.filters = self._filters[:]
2102
+
2103
+ self._entered = True
2104
+ self._tmp_suppressions = []
2105
+ self._tmp_modules = set()
2106
+ self._forwarded = set()
2107
+
2108
+ self.log = [] # reset global log (no need to keep same list)
2109
+
2110
+ for cat, mess, _, mod, log in self._suppressions:
2111
+ if log is not None:
2112
+ del log[:] # clear the log
2113
+ if mod is None:
2114
+ warnings.filterwarnings("always", category=cat, message=mess)
2115
+ else:
2116
+ module_regex = mod.__name__.replace(".", r"\.") + "$"
2117
+ warnings.filterwarnings(
2118
+ "always", category=cat, message=mess, module=module_regex
2119
+ )
2120
+ self._tmp_modules.add(mod)
2121
+ warnings.showwarning = self._showwarning
2122
+ self._clear_registries()
2123
+
2124
+ return self
2125
+
2126
+ def __exit__(self, *exc_info):
2127
+ warnings.showwarning = self._orig_show
2128
+ warnings.filters = self._filters
2129
+ self._clear_registries()
2130
+ self._entered = False
2131
+ del self._orig_show
2132
+ del self._filters
2133
+
2134
+ def _showwarning(
2135
+ self, message, category, filename, lineno, *args, use_warnmsg=None, **kwargs
2136
+ ):
2137
+ for cat, _, pattern, mod, rec in (self._suppressions + self._tmp_suppressions)[
2138
+ ::-1
2139
+ ]:
2140
+ if issubclass(category, cat) and pattern.match(message.args[0]) is not None:
2141
+ if mod is None:
2142
+ # Message and category match, either recorded or ignored
2143
+ if rec is not None:
2144
+ msg = WarningMessage(
2145
+ message, category, filename, lineno, **kwargs
2146
+ )
2147
+ self.log.append(msg)
2148
+ rec.append(msg)
2149
+ return
2150
+ # Use startswith, because warnings strips the c or o from
2151
+ # .pyc/.pyo files.
2152
+ elif mod.__file__.startswith(filename):
2153
+ # The message and module (filename) match
2154
+ if rec is not None:
2155
+ msg = WarningMessage(
2156
+ message, category, filename, lineno, **kwargs
2157
+ )
2158
+ self.log.append(msg)
2159
+ rec.append(msg)
2160
+ return
2161
+
2162
+ # There is no filter in place, so pass to the outside handler
2163
+ # unless we should only pass it once
2164
+ if self._forwarding_rule == "always":
2165
+ if use_warnmsg is None:
2166
+ self._orig_show(message, category, filename, lineno, *args, **kwargs)
2167
+ else:
2168
+ self._orig_showmsg(use_warnmsg)
2169
+ return
2170
+
2171
+ if self._forwarding_rule == "once":
2172
+ signature = (message.args, category)
2173
+ elif self._forwarding_rule == "module":
2174
+ signature = (message.args, category, filename)
2175
+ elif self._forwarding_rule == "location":
2176
+ signature = (message.args, category, filename, lineno)
2177
+
2178
+ if signature in self._forwarded:
2179
+ return
2180
+ self._forwarded.add(signature)
2181
+ if use_warnmsg is None:
2182
+ self._orig_show(message, category, filename, lineno, *args, **kwargs)
2183
+ else:
2184
+ self._orig_showmsg(use_warnmsg)
2185
+
2186
+ def __call__(self, func):
2187
+ """
2188
+ Function decorator to apply certain suppressions to a whole
2189
+ function.
2190
+ """
2191
+
2192
+ @wraps(func)
2193
+ def new_func(*args, **kwargs):
2194
+ with self:
2195
+ return func(*args, **kwargs)
2196
+
2197
+ return new_func
2198
+
2199
+
2200
+ @contextlib.contextmanager
2201
+ def _assert_no_gc_cycles_context(name=None):
2202
+ __tracebackhide__ = True # Hide traceback for py.test
2203
+
2204
+ # not meaningful to test if there is no refcounting
2205
+ if not HAS_REFCOUNT:
2206
+ yield
2207
+ return
2208
+
2209
+ assert_(gc.isenabled())
2210
+ gc.disable()
2211
+ gc_debug = gc.get_debug()
2212
+ try:
2213
+ for _ in range(100):
2214
+ if gc.collect() == 0:
2215
+ break
2216
+ else:
2217
+ raise RuntimeError(
2218
+ "Unable to fully collect garbage - perhaps a __del__ method "
2219
+ "is creating more reference cycles?"
2220
+ )
2221
+
2222
+ gc.set_debug(gc.DEBUG_SAVEALL)
2223
+ yield
2224
+ # gc.collect returns the number of unreachable objects in cycles that
2225
+ # were found -- we are checking that no cycles were created in the context
2226
+ n_objects_in_cycles = gc.collect()
2227
+ objects_in_cycles = gc.garbage[:]
2228
+ finally:
2229
+ del gc.garbage[:]
2230
+ gc.set_debug(gc_debug)
2231
+ gc.enable()
2232
+
2233
+ if n_objects_in_cycles:
2234
+ name_str = f" when calling {name}" if name is not None else ""
2235
+ raise AssertionError(
2236
+ "Reference cycles were found{}: {} objects were collected, "
2237
+ "of which {} are shown below:{}".format(
2238
+ name_str,
2239
+ n_objects_in_cycles,
2240
+ len(objects_in_cycles),
2241
+ "".join(
2242
+ "\n {} object with id={}:\n {}".format(
2243
+ type(o).__name__,
2244
+ id(o),
2245
+ pprint.pformat(o).replace("\n", "\n "),
2246
+ )
2247
+ for o in objects_in_cycles
2248
+ ),
2249
+ )
2250
+ )
2251
+
2252
+
2253
+ def assert_no_gc_cycles(*args, **kwargs):
2254
+ """
2255
+ Fail if the given callable produces any reference cycles.
2256
+
2257
+ If called with all arguments omitted, may be used as a context manager:
2258
+
2259
+ with assert_no_gc_cycles():
2260
+ do_something()
2261
+
2262
+ .. versionadded:: 1.15.0
2263
+
2264
+ Parameters
2265
+ ----------
2266
+ func : callable
2267
+ The callable to test.
2268
+ \\*args : Arguments
2269
+ Arguments passed to `func`.
2270
+ \\*\\*kwargs : Kwargs
2271
+ Keyword arguments passed to `func`.
2272
+
2273
+ Returns
2274
+ -------
2275
+ Nothing. The result is deliberately discarded to ensure that all cycles
2276
+ are found.
2277
+
2278
+ """
2279
+ if not args:
2280
+ return _assert_no_gc_cycles_context()
2281
+
2282
+ func = args[0]
2283
+ args = args[1:]
2284
+ with _assert_no_gc_cycles_context(name=func.__name__):
2285
+ func(*args, **kwargs)
2286
+
2287
+
2288
+ def break_cycles():
2289
+ """
2290
+ Break reference cycles by calling gc.collect
2291
+ Objects can call other objects' methods (for instance, another object's
2292
+ __del__) inside their own __del__. On PyPy, the interpreter only runs
2293
+ between calls to gc.collect, so multiple calls are needed to completely
2294
+ release all cycles.
2295
+ """
2296
+
2297
+ gc.collect()
2298
+ if IS_PYPY:
2299
+ # a few more, just to make sure all the finalizers are called
2300
+ gc.collect()
2301
+ gc.collect()
2302
+ gc.collect()
2303
+ gc.collect()
2304
+
2305
+
2306
+ def requires_memory(free_bytes):
2307
+ """Decorator to skip a test if not enough memory is available"""
2308
+ import pytest
2309
+
2310
+ def decorator(func):
2311
+ @wraps(func)
2312
+ def wrapper(*a, **kw):
2313
+ msg = check_free_memory(free_bytes)
2314
+ if msg is not None:
2315
+ pytest.skip(msg)
2316
+
2317
+ try:
2318
+ return func(*a, **kw)
2319
+ except MemoryError:
2320
+ # Probably ran out of memory regardless: don't regard as failure
2321
+ pytest.xfail("MemoryError raised")
2322
+
2323
+ return wrapper
2324
+
2325
+ return decorator
2326
+
2327
+
2328
+ def check_free_memory(free_bytes):
2329
+ """
2330
+ Check whether `free_bytes` amount of memory is currently free.
2331
+ Returns: None if enough memory available, otherwise error message
2332
+ """
2333
+ env_var = "NPY_AVAILABLE_MEM"
2334
+ env_value = os.environ.get(env_var)
2335
+ if env_value is not None:
2336
+ try:
2337
+ mem_free = _parse_size(env_value)
2338
+ except ValueError as exc:
2339
+ raise ValueError( # noqa: B904
2340
+ f"Invalid environment variable {env_var}: {exc}"
2341
+ )
2342
+
2343
+ msg = (
2344
+ f"{free_bytes / 1e9} GB memory required, but environment variable "
2345
+ f"NPY_AVAILABLE_MEM={env_value} set"
2346
+ )
2347
+ else:
2348
+ mem_free = _get_mem_available()
2349
+
2350
+ if mem_free is None:
2351
+ msg = (
2352
+ "Could not determine available memory; set NPY_AVAILABLE_MEM "
2353
+ "environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run "
2354
+ "the test."
2355
+ )
2356
+ mem_free = -1
2357
+ else:
2358
+ msg = f"{free_bytes / 1e9} GB memory required, but {mem_free / 1e9} GB available"
2359
+
2360
+ return msg if mem_free < free_bytes else None
2361
+
2362
+
2363
+ def _parse_size(size_str):
2364
+ """Convert memory size strings ('12 GB' etc.) to float"""
2365
+ suffixes = {
2366
+ "": 1,
2367
+ "b": 1,
2368
+ "k": 1000,
2369
+ "m": 1000**2,
2370
+ "g": 1000**3,
2371
+ "t": 1000**4,
2372
+ "kb": 1000,
2373
+ "mb": 1000**2,
2374
+ "gb": 1000**3,
2375
+ "tb": 1000**4,
2376
+ "kib": 1024,
2377
+ "mib": 1024**2,
2378
+ "gib": 1024**3,
2379
+ "tib": 1024**4,
2380
+ }
2381
+
2382
+ size_re = re.compile(
2383
+ r"^\s*(\d+|\d+\.\d+)\s*({})\s*$".format("|".join(suffixes.keys())),
2384
+ re.IGNORECASE,
2385
+ )
2386
+
2387
+ m = size_re.match(size_str.lower())
2388
+ if not m or m.group(2) not in suffixes:
2389
+ raise ValueError(f"value {size_str!r} not a valid size")
2390
+ return int(float(m.group(1)) * suffixes[m.group(2)])
2391
+
2392
+
2393
+ def _get_mem_available():
2394
+ """Return available memory in bytes, or None if unknown."""
2395
+ try:
2396
+ import psutil
2397
+
2398
+ return psutil.virtual_memory().available
2399
+ except (ImportError, AttributeError):
2400
+ pass
2401
+
2402
+ if sys.platform.startswith("linux"):
2403
+ info = {}
2404
+ with open("/proc/meminfo") as f:
2405
+ for line in f:
2406
+ p = line.split()
2407
+ info[p[0].strip(":").lower()] = int(p[1]) * 1024
2408
+
2409
+ if "memavailable" in info:
2410
+ # Linux >= 3.14
2411
+ return info["memavailable"]
2412
+ else:
2413
+ return info["memfree"] + info["cached"]
2414
+
2415
+ return None
2416
+
2417
+
2418
+ def _no_tracing(func):
2419
+ """
2420
+ Decorator to temporarily turn off tracing for the duration of a test.
2421
+ Needed in tests that check refcounting, otherwise the tracing itself
2422
+ influences the refcounts
2423
+ """
2424
+ if not hasattr(sys, "gettrace"):
2425
+ return func
2426
+ else:
2427
+
2428
+ @wraps(func)
2429
+ def wrapper(*args, **kwargs):
2430
+ original_trace = sys.gettrace()
2431
+ try:
2432
+ sys.settrace(None)
2433
+ return func(*args, **kwargs)
2434
+ finally:
2435
+ sys.settrace(original_trace)
2436
+
2437
+ return wrapper
2438
+
2439
+
2440
+ def _get_glibc_version():
2441
+ try:
2442
+ ver = os.confstr("CS_GNU_LIBC_VERSION").rsplit(" ")[1]
2443
+ except Exception:
2444
+ ver = "0.0"
2445
+
2446
+ return ver
2447
+
2448
+
2449
+ _glibcver = _get_glibc_version()
2450
+
2451
+
2452
+ def _glibc_older_than(x):
2453
+ return _glibcver != "0.0" and _glibcver < x
.venv/lib/python3.12/site-packages/torch/_opaque_base.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+
4
+ log = logging.getLogger(__name__)
5
+
6
+ log.warning("torch._opaque_base is deprecated, use torch._custom_class_base instead")
7
+
8
+ from torch._custom_class_base import ( # noqa: F401
9
+ CustomClassBase as OpaqueBase,
10
+ CustomClassBaseMeta as OpaqueBaseMeta,
11
+ )