forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_funcs_impl.py
2055 lines (1557 loc) · 57.8 KB
/
_funcs_impl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mypy: ignore-errors
"""A thin pytorch / numpy compat layer.
Things imported from here have numpy-compatible signatures but operate on
pytorch tensors.
"""
# Contents of this module ends up in the main namespace via _funcs.py
# where type annotations are used in conjunction with the @normalizer decorator.
from __future__ import annotations
import builtins
import itertools
import operator
from typing import Optional, Sequence, TYPE_CHECKING
import torch
from . import _dtypes_impl, _util
if TYPE_CHECKING:
from ._normalizations import (
ArrayLike,
ArrayLikeOrScalar,
CastingModes,
DTypeLike,
NDArray,
NotImplementedType,
OutArray,
)
def copy(
a: ArrayLike, order: NotImplementedType = "K", subok: NotImplementedType = False
):
return a.clone()
def copyto(
dst: NDArray,
src: ArrayLike,
casting: Optional[CastingModes] = "same_kind",
where: NotImplementedType = None,
):
(src,) = _util.typecast_tensors((src,), dst.dtype, casting=casting)
dst.copy_(src)
def atleast_1d(*arys: ArrayLike):
res = torch.atleast_1d(*arys)
if isinstance(res, tuple):
return list(res)
else:
return res
def atleast_2d(*arys: ArrayLike):
res = torch.atleast_2d(*arys)
if isinstance(res, tuple):
return list(res)
else:
return res
def atleast_3d(*arys: ArrayLike):
res = torch.atleast_3d(*arys)
if isinstance(res, tuple):
return list(res)
else:
return res
def _concat_check(tup, dtype, out):
if tup == ():
raise ValueError("need at least one array to concatenate")
"""Check inputs in concatenate et al."""
if out is not None and dtype is not None:
# mimic numpy
raise TypeError(
"concatenate() only takes `out` or `dtype` as an "
"argument, but both were provided."
)
def _concat_cast_helper(tensors, out=None, dtype=None, casting="same_kind"):
"""Figure out dtypes, cast if necessary."""
if out is not None or dtype is not None:
# figure out the type of the inputs and outputs
out_dtype = out.dtype.torch_dtype if dtype is None else dtype
else:
out_dtype = _dtypes_impl.result_type_impl(*tensors)
# cast input arrays if necessary; do not broadcast them agains `out`
tensors = _util.typecast_tensors(tensors, out_dtype, casting)
return tensors
def _concatenate(
tensors, axis=0, out=None, dtype=None, casting: Optional[CastingModes] = "same_kind"
):
# pure torch implementation, used below and in cov/corrcoef below
tensors, axis = _util.axis_none_flatten(*tensors, axis=axis)
tensors = _concat_cast_helper(tensors, out, dtype, casting)
return torch.cat(tensors, axis)
def concatenate(
ar_tuple: Sequence[ArrayLike],
axis=0,
out: Optional[OutArray] = None,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(ar_tuple, dtype, out=out)
result = _concatenate(ar_tuple, axis=axis, out=out, dtype=dtype, casting=casting)
return result
def vstack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.vstack(tensors)
row_stack = vstack
def hstack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.hstack(tensors)
def dstack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
# XXX: in numpy 1.24 dstack does not have dtype and casting keywords
# but {h,v}stack do. Hence add them here for consistency.
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.dstack(tensors)
def column_stack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
# XXX: in numpy 1.24 column_stack does not have dtype and casting keywords
# but row_stack does. (because row_stack is an alias for vstack, really).
# Hence add these keywords here for consistency.
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.column_stack(tensors)
def stack(
arrays: Sequence[ArrayLike],
axis=0,
out: Optional[OutArray] = None,
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(arrays, dtype, out=out)
tensors = _concat_cast_helper(arrays, dtype=dtype, casting=casting)
result_ndim = tensors[0].ndim + 1
axis = _util.normalize_axis_index(axis, result_ndim)
return torch.stack(tensors, axis=axis)
def append(arr: ArrayLike, values: ArrayLike, axis=None):
if axis is None:
if arr.ndim != 1:
arr = arr.flatten()
values = values.flatten()
axis = arr.ndim - 1
return _concatenate((arr, values), axis=axis)
# ### split ###
def _split_helper(tensor, indices_or_sections, axis, strict=False):
if isinstance(indices_or_sections, int):
return _split_helper_int(tensor, indices_or_sections, axis, strict)
elif isinstance(indices_or_sections, (list, tuple)):
# NB: drop split=..., it only applies to split_helper_int
return _split_helper_list(tensor, list(indices_or_sections), axis)
else:
raise TypeError("split_helper: ", type(indices_or_sections))
def _split_helper_int(tensor, indices_or_sections, axis, strict=False):
if not isinstance(indices_or_sections, int):
raise NotImplementedError("split: indices_or_sections")
axis = _util.normalize_axis_index(axis, tensor.ndim)
# numpy: l%n chunks of size (l//n + 1), the rest are sized l//n
l, n = tensor.shape[axis], indices_or_sections
if n <= 0:
raise ValueError
if l % n == 0:
num, sz = n, l // n
lst = [sz] * num
else:
if strict:
raise ValueError("array split does not result in an equal division")
num, sz = l % n, l // n + 1
lst = [sz] * num
lst += [sz - 1] * (n - num)
return torch.split(tensor, lst, axis)
def _split_helper_list(tensor, indices_or_sections, axis):
if not isinstance(indices_or_sections, list):
raise NotImplementedError("split: indices_or_sections: list")
# numpy expects indices, while torch expects lengths of sections
# also, numpy appends zero-size arrays for indices above the shape[axis]
lst = [x for x in indices_or_sections if x <= tensor.shape[axis]]
num_extra = len(indices_or_sections) - len(lst)
lst.append(tensor.shape[axis])
lst = [
lst[0],
] + [a - b for a, b in zip(lst[1:], lst[:-1])]
lst += [0] * num_extra
return torch.split(tensor, lst, axis)
def array_split(ary: ArrayLike, indices_or_sections, axis=0):
return _split_helper(ary, indices_or_sections, axis)
def split(ary: ArrayLike, indices_or_sections, axis=0):
return _split_helper(ary, indices_or_sections, axis, strict=True)
def hsplit(ary: ArrayLike, indices_or_sections):
if ary.ndim == 0:
raise ValueError("hsplit only works on arrays of 1 or more dimensions")
axis = 1 if ary.ndim > 1 else 0
return _split_helper(ary, indices_or_sections, axis, strict=True)
def vsplit(ary: ArrayLike, indices_or_sections):
if ary.ndim < 2:
raise ValueError("vsplit only works on arrays of 2 or more dimensions")
return _split_helper(ary, indices_or_sections, 0, strict=True)
def dsplit(ary: ArrayLike, indices_or_sections):
if ary.ndim < 3:
raise ValueError("dsplit only works on arrays of 3 or more dimensions")
return _split_helper(ary, indices_or_sections, 2, strict=True)
def kron(a: ArrayLike, b: ArrayLike):
return torch.kron(a, b)
def vander(x: ArrayLike, N=None, increasing=False):
return torch.vander(x, N, increasing)
# ### linspace, geomspace, logspace and arange ###
def linspace(
start: ArrayLike,
stop: ArrayLike,
num=50,
endpoint=True,
retstep=False,
dtype: Optional[DTypeLike] = None,
axis=0,
):
if axis != 0 or retstep or not endpoint:
raise NotImplementedError
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
# XXX: raises TypeError if start or stop are not scalars
return torch.linspace(start, stop, num, dtype=dtype)
def geomspace(
start: ArrayLike,
stop: ArrayLike,
num=50,
endpoint=True,
dtype: Optional[DTypeLike] = None,
axis=0,
):
if axis != 0 or not endpoint:
raise NotImplementedError
base = torch.pow(stop / start, 1.0 / (num - 1))
logbase = torch.log(base)
return torch.logspace(
torch.log(start) / logbase,
torch.log(stop) / logbase,
num,
base=base,
)
def logspace(
start,
stop,
num=50,
endpoint=True,
base=10.0,
dtype: Optional[DTypeLike] = None,
axis=0,
):
if axis != 0 or not endpoint:
raise NotImplementedError
return torch.logspace(start, stop, num, base=base, dtype=dtype)
def arange(
start: Optional[ArrayLikeOrScalar] = None,
stop: Optional[ArrayLikeOrScalar] = None,
step: Optional[ArrayLikeOrScalar] = 1,
dtype: Optional[DTypeLike] = None,
*,
like: NotImplementedType = None,
):
if step == 0:
raise ZeroDivisionError
if stop is None and start is None:
raise TypeError
if stop is None:
# XXX: this breaks if start is passed as a kwarg:
# arange(start=4) should raise (no stop) but doesn't
start, stop = 0, start
if start is None:
start = 0
# the dtype of the result
if dtype is None:
dtype = (
_dtypes_impl.default_dtypes().float_dtype
if any(_dtypes_impl.is_float_or_fp_tensor(x) for x in (start, stop, step))
else _dtypes_impl.default_dtypes().int_dtype
)
work_dtype = torch.float64 if dtype.is_complex else dtype
# RuntimeError: "lt_cpu" not implemented for 'ComplexFloat'. Fall back to eager.
if any(_dtypes_impl.is_complex_or_complex_tensor(x) for x in (start, stop, step)):
raise NotImplementedError
if (step > 0 and start > stop) or (step < 0 and start < stop):
# empty range
return torch.empty(0, dtype=dtype)
result = torch.arange(start, stop, step, dtype=work_dtype)
result = _util.cast_if_needed(result, dtype)
return result
# ### zeros/ones/empty/full ###
def empty(
shape,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.empty(shape, dtype=dtype)
# NB: *_like functions deliberately deviate from numpy: it has subok=True
# as the default; we set subok=False and raise on anything else.
def empty_like(
prototype: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
result = torch.empty_like(prototype, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
def full(
shape,
fill_value: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if isinstance(shape, int):
shape = (shape,)
if dtype is None:
dtype = fill_value.dtype
if not isinstance(shape, (tuple, list)):
shape = (shape,)
return torch.full(shape, fill_value, dtype=dtype)
def full_like(
a: ArrayLike,
fill_value,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
# XXX: fill_value broadcasts
result = torch.full_like(a, fill_value, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
def ones(
shape,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.ones(shape, dtype=dtype)
def ones_like(
a: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
result = torch.ones_like(a, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
def zeros(
shape,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.zeros(shape, dtype=dtype)
def zeros_like(
a: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
result = torch.zeros_like(a, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
# ### cov & corrcoef ###
def _xy_helper_corrcoef(x_tensor, y_tensor=None, rowvar=True):
"""Prepare inputs for cov and corrcoef."""
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/function_base.py#L2636
if y_tensor is not None:
# make sure x and y are at least 2D
ndim_extra = 2 - x_tensor.ndim
if ndim_extra > 0:
x_tensor = x_tensor.view((1,) * ndim_extra + x_tensor.shape)
if not rowvar and x_tensor.shape[0] != 1:
x_tensor = x_tensor.mT
x_tensor = x_tensor.clone()
ndim_extra = 2 - y_tensor.ndim
if ndim_extra > 0:
y_tensor = y_tensor.view((1,) * ndim_extra + y_tensor.shape)
if not rowvar and y_tensor.shape[0] != 1:
y_tensor = y_tensor.mT
y_tensor = y_tensor.clone()
x_tensor = _concatenate((x_tensor, y_tensor), axis=0)
return x_tensor
def corrcoef(
x: ArrayLike,
y: Optional[ArrayLike] = None,
rowvar=True,
bias=None,
ddof=None,
*,
dtype: Optional[DTypeLike] = None,
):
if bias is not None or ddof is not None:
# deprecated in NumPy
raise NotImplementedError
xy_tensor = _xy_helper_corrcoef(x, y, rowvar)
is_half = (xy_tensor.dtype == torch.float16) and xy_tensor.is_cpu
if is_half:
# work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
dtype = torch.float32
xy_tensor = _util.cast_if_needed(xy_tensor, dtype)
result = torch.corrcoef(xy_tensor)
if is_half:
result = result.to(torch.float16)
return result
def cov(
m: ArrayLike,
y: Optional[ArrayLike] = None,
rowvar=True,
bias=False,
ddof=None,
fweights: Optional[ArrayLike] = None,
aweights: Optional[ArrayLike] = None,
*,
dtype: Optional[DTypeLike] = None,
):
m = _xy_helper_corrcoef(m, y, rowvar)
if ddof is None:
ddof = 1 if bias == 0 else 0
is_half = (m.dtype == torch.float16) and m.is_cpu
if is_half:
# work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
dtype = torch.float32
m = _util.cast_if_needed(m, dtype)
result = torch.cov(m, correction=ddof, aweights=aweights, fweights=fweights)
if is_half:
result = result.to(torch.float16)
return result
def _conv_corr_impl(a, v, mode):
dt = _dtypes_impl.result_type_impl(a, v)
a = _util.cast_if_needed(a, dt)
v = _util.cast_if_needed(v, dt)
padding = v.shape[0] - 1 if mode == "full" else mode
if padding == "same" and v.shape[0] % 2 == 0:
# UserWarning: Using padding='same' with even kernel lengths and odd
# dilation may require a zero-padded copy of the input be created
# (Triggered internally at pytorch/aten/src/ATen/native/Convolution.cpp:1010.)
raise NotImplementedError("mode='same' and even-length weights")
# NumPy only accepts 1D arrays; PyTorch requires 2D inputs and 3D weights
aa = a[None, :]
vv = v[None, None, :]
result = torch.nn.functional.conv1d(aa, vv, padding=padding)
# torch returns a 2D result, numpy returns a 1D array
return result[0, :]
def convolve(a: ArrayLike, v: ArrayLike, mode="full"):
# NumPy: if v is longer than a, the arrays are swapped before computation
if a.shape[0] < v.shape[0]:
a, v = v, a
# flip the weights since numpy does and torch does not
v = torch.flip(v, (0,))
return _conv_corr_impl(a, v, mode)
def correlate(a: ArrayLike, v: ArrayLike, mode="valid"):
v = torch.conj_physical(v)
return _conv_corr_impl(a, v, mode)
# ### logic & element selection ###
def bincount(x: ArrayLike, /, weights: Optional[ArrayLike] = None, minlength=0):
if x.numel() == 0:
# edge case allowed by numpy
x = x.new_empty(0, dtype=int)
int_dtype = _dtypes_impl.default_dtypes().int_dtype
(x,) = _util.typecast_tensors((x,), int_dtype, casting="safe")
return torch.bincount(x, weights, minlength)
def where(
condition: ArrayLike,
x: Optional[ArrayLikeOrScalar] = None,
y: Optional[ArrayLikeOrScalar] = None,
/,
):
if (x is None) != (y is None):
raise ValueError("either both or neither of x and y should be given")
if condition.dtype != torch.bool:
condition = condition.to(torch.bool)
if x is None and y is None:
result = torch.where(condition)
else:
result = torch.where(condition, x, y)
return result
# ###### module-level queries of object properties
def ndim(a: ArrayLike):
return a.ndim
def shape(a: ArrayLike):
return tuple(a.shape)
def size(a: ArrayLike, axis=None):
if axis is None:
return a.numel()
else:
return a.shape[axis]
# ###### shape manipulations and indexing
def expand_dims(a: ArrayLike, axis):
shape = _util.expand_shape(a.shape, axis)
return a.view(shape) # never copies
def flip(m: ArrayLike, axis=None):
# XXX: semantic difference: np.flip returns a view, torch.flip copies
if axis is None:
axis = tuple(range(m.ndim))
else:
axis = _util.normalize_axis_tuple(axis, m.ndim)
return torch.flip(m, axis)
def flipud(m: ArrayLike):
return torch.flipud(m)
def fliplr(m: ArrayLike):
return torch.fliplr(m)
def rot90(m: ArrayLike, k=1, axes=(0, 1)):
axes = _util.normalize_axis_tuple(axes, m.ndim)
return torch.rot90(m, k, axes)
# ### broadcasting and indices ###
def broadcast_to(array: ArrayLike, shape, subok: NotImplementedType = False):
return torch.broadcast_to(array, size=shape)
# This is a function from tuples to tuples, so we just reuse it
from torch import broadcast_shapes
def broadcast_arrays(*args: ArrayLike, subok: NotImplementedType = False):
return torch.broadcast_tensors(*args)
def meshgrid(*xi: ArrayLike, copy=True, sparse=False, indexing="xy"):
ndim = len(xi)
if indexing not in ["xy", "ij"]:
raise ValueError("Valid values for `indexing` are 'xy' and 'ij'.")
s0 = (1,) * ndim
output = [x.reshape(s0[:i] + (-1,) + s0[i + 1 :]) for i, x in enumerate(xi)]
if indexing == "xy" and ndim > 1:
# switch first and second axis
output[0] = output[0].reshape((1, -1) + s0[2:])
output[1] = output[1].reshape((-1, 1) + s0[2:])
if not sparse:
# Return the full N-D matrix (not only the 1-D vector)
output = torch.broadcast_tensors(*output)
if copy:
output = [x.clone() for x in output]
return list(output) # match numpy, return a list
def indices(dimensions, dtype: Optional[DTypeLike] = int, sparse=False):
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1691-L1791
dimensions = tuple(dimensions)
N = len(dimensions)
shape = (1,) * N
if sparse:
res = tuple()
else:
res = torch.empty((N,) + dimensions, dtype=dtype)
for i, dim in enumerate(dimensions):
idx = torch.arange(dim, dtype=dtype).reshape(
shape[:i] + (dim,) + shape[i + 1 :]
)
if sparse:
res = res + (idx,)
else:
res[i] = idx
return res
# ### tri*-something ###
def tril(m: ArrayLike, k=0):
return torch.tril(m, k)
def triu(m: ArrayLike, k=0):
return torch.triu(m, k)
def tril_indices(n, k=0, m=None):
if m is None:
m = n
return torch.tril_indices(n, m, offset=k)
def triu_indices(n, k=0, m=None):
if m is None:
m = n
return torch.triu_indices(n, m, offset=k)
def tril_indices_from(arr: ArrayLike, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
# Return a tensor rather than a tuple to avoid a graphbreak
return torch.tril_indices(arr.shape[0], arr.shape[1], offset=k)
def triu_indices_from(arr: ArrayLike, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
# Return a tensor rather than a tuple to avoid a graphbreak
return torch.triu_indices(arr.shape[0], arr.shape[1], offset=k)
def tri(
N,
M=None,
k=0,
dtype: Optional[DTypeLike] = None,
*,
like: NotImplementedType = None,
):
if M is None:
M = N
tensor = torch.ones((N, M), dtype=dtype)
return torch.tril(tensor, diagonal=k)
# ### equality, equivalence, allclose ###
def isclose(a: ArrayLike, b: ArrayLike, rtol=1.0e-5, atol=1.0e-8, equal_nan=False):
dtype = _dtypes_impl.result_type_impl(a, b)
a = _util.cast_if_needed(a, dtype)
b = _util.cast_if_needed(b, dtype)
return torch.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
def allclose(a: ArrayLike, b: ArrayLike, rtol=1e-05, atol=1e-08, equal_nan=False):
dtype = _dtypes_impl.result_type_impl(a, b)
a = _util.cast_if_needed(a, dtype)
b = _util.cast_if_needed(b, dtype)
return torch.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
def _tensor_equal(a1, a2, equal_nan=False):
# Implementation of array_equal/array_equiv.
if a1.shape != a2.shape:
return False
cond = a1 == a2
if equal_nan:
cond = cond | (torch.isnan(a1) & torch.isnan(a2))
return cond.all().item()
def array_equal(a1: ArrayLike, a2: ArrayLike, equal_nan=False):
return _tensor_equal(a1, a2, equal_nan=equal_nan)
def array_equiv(a1: ArrayLike, a2: ArrayLike):
# *almost* the same as array_equal: _equiv tries to broadcast, _equal does not
try:
a1_t, a2_t = torch.broadcast_tensors(a1, a2)
except RuntimeError:
# failed to broadcast => not equivalent
return False
return _tensor_equal(a1_t, a2_t)
def nan_to_num(
x: ArrayLike, copy: NotImplementedType = True, nan=0.0, posinf=None, neginf=None
):
# work around RuntimeError: "nan_to_num" not implemented for 'ComplexDouble'
if x.is_complex():
re = torch.nan_to_num(x.real, nan=nan, posinf=posinf, neginf=neginf)
im = torch.nan_to_num(x.imag, nan=nan, posinf=posinf, neginf=neginf)
return re + 1j * im
else:
return torch.nan_to_num(x, nan=nan, posinf=posinf, neginf=neginf)
# ### put/take_along_axis ###
def take(
a: ArrayLike,
indices: ArrayLike,
axis=None,
out: Optional[OutArray] = None,
mode: NotImplementedType = "raise",
):
(a,), axis = _util.axis_none_flatten(a, axis=axis)
axis = _util.normalize_axis_index(axis, a.ndim)
idx = (slice(None),) * axis + (indices, ...)
result = a[idx]
return result
def take_along_axis(arr: ArrayLike, indices: ArrayLike, axis):
(arr,), axis = _util.axis_none_flatten(arr, axis=axis)
axis = _util.normalize_axis_index(axis, arr.ndim)
return torch.take_along_dim(arr, indices, axis)
def put(
a: NDArray,
indices: ArrayLike,
values: ArrayLike,
mode: NotImplementedType = "raise",
):
v = values.type(a.dtype)
# If indices is larger than v, expand v to at least the size of indices. Any
# unnecessary trailing elements are then trimmed.
if indices.numel() > v.numel():
ratio = (indices.numel() + v.numel() - 1) // v.numel()
v = v.unsqueeze(0).expand((ratio,) + v.shape)
# Trim unnecessary elements, regardless if v was expanded or not. Note
# np.put() trims v to match indices by default too.
if indices.numel() < v.numel():
v = v.flatten()
v = v[: indices.numel()]
a.put_(indices, v)
return None
def put_along_axis(arr: ArrayLike, indices: ArrayLike, values: ArrayLike, axis):
(arr,), axis = _util.axis_none_flatten(arr, axis=axis)
axis = _util.normalize_axis_index(axis, arr.ndim)
indices, values = torch.broadcast_tensors(indices, values)
values = _util.cast_if_needed(values, arr.dtype)
result = torch.scatter(arr, axis, indices, values)
arr.copy_(result.reshape(arr.shape))
return None
def choose(
a: ArrayLike,
choices: Sequence[ArrayLike],
out: Optional[OutArray] = None,
mode: NotImplementedType = "raise",
):
# First, broadcast elements of `choices`
choices = torch.stack(torch.broadcast_tensors(*choices))
# Use an analog of `gather(choices, 0, a)` which broadcasts `choices` vs `a`:
# (taken from https://github.com/pytorch/pytorch/issues/9407#issuecomment-1427907939)
idx_list = [
torch.arange(dim).view((1,) * i + (dim,) + (1,) * (choices.ndim - i - 1))
for i, dim in enumerate(choices.shape)
]
idx_list[0] = a
return choices[idx_list].squeeze(0)
# ### unique et al ###
def unique(
ar: ArrayLike,
return_index: NotImplementedType = False,
return_inverse=False,
return_counts=False,
axis=None,
*,
equal_nan: NotImplementedType = True,
):
(ar,), axis = _util.axis_none_flatten(ar, axis=axis)
axis = _util.normalize_axis_index(axis, ar.ndim)
result = torch.unique(
ar, return_inverse=return_inverse, return_counts=return_counts, dim=axis
)
return result
def nonzero(a: ArrayLike):
return torch.nonzero(a, as_tuple=True)
def argwhere(a: ArrayLike):
return torch.argwhere(a)
def flatnonzero(a: ArrayLike):
return torch.flatten(a).nonzero(as_tuple=True)[0]
def clip(
a: ArrayLike,
min: Optional[ArrayLike] = None,
max: Optional[ArrayLike] = None,
out: Optional[OutArray] = None,
):
return torch.clamp(a, min, max)
def repeat(a: ArrayLike, repeats: ArrayLikeOrScalar, axis=None):
return torch.repeat_interleave(a, repeats, axis)
def tile(A: ArrayLike, reps):
if isinstance(reps, int):
reps = (reps,)
return torch.tile(A, reps)
def resize(a: ArrayLike, new_shape=None):
# implementation vendored from
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/fromnumeric.py#L1420-L1497
if new_shape is None: