Repository navigation
Expand file tree
/
Copy pathops.cpp
More file actions
7051 lines (6354 loc) · 208 KB
/
Copy pathops.cpp
File metadata and controls
7051 lines (6354 loc) · 208 KB
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
// Copyright © 2023-2026 Apple Inc.
// Required for using M_PI in MSVC.
#define _USE_MATH_DEFINES
#include <algorithm>
#include <climits>
#include <cmath>
#include <numeric>
#include <set>
#include <sstream>
#include "mlx/backend/cuda/cuda.h"
#include "mlx/backend/metal/metal.h"
#include "mlx/fast_primitives.h"
#include "mlx/ops.h"
#include "mlx/primitives.h"
#include "mlx/transforms.h"
#include "mlx/transforms_impl.h"
#include "mlx/types/limits.h"
#include "mlx/utils.h"
namespace mlx::core {
namespace {
// Pass the reduction's name in `op_without_identity` when it has no identity
// element, as max and min do not. Those are undefined over an empty axis, so
// naming them here has that checked. Reductions with an identity, such as sum
// and any, reduce an empty axis fine and leave it unset.
std::tuple<Shape, std::vector<int>, bool> compute_reduce_shape(
const std::vector<int>& axes,
const Shape& shape,
std::string_view op_without_identity = {}) {
bool is_noop = true;
std::set<int> axes_set;
auto ndim = shape.size();
for (auto ax : axes) {
int ax_ = (ax < 0) ? ax + ndim : ax;
if (ax_ < 0 || ax_ >= ndim) {
std::ostringstream msg;
msg << "Invalid axis " << ax << " for array with " << ndim
<< " dimensions.";
throw std::out_of_range(msg.str());
}
axes_set.insert(ax_);
}
if (axes_set.size() != axes.size()) {
throw std::invalid_argument("Duplicate axes detected in reduction.");
}
Shape out_shape;
for (int i = 0; i < ndim; ++i) {
if (axes_set.count(i) == 0) {
out_shape.push_back(shape[i]);
} else {
if (!op_without_identity.empty() && shape[i] == 0) {
std::ostringstream msg;
msg << "[" << op_without_identity << "] Cannot " << op_without_identity
<< " reduce over axis " << i << " with size 0.";
throw std::invalid_argument(msg.str());
}
out_shape.push_back(1);
}
is_noop &= (out_shape.back() == shape[i]);
}
std::vector<int> sorted_axes(axes_set.begin(), axes_set.end());
// Dimensions that are size 1 at trace time can be dynamic when compiling
// shapeless, so the reduction cannot be elided from the graph. Reductions
// over no axes stay no-ops since they are shape independent.
if (is_noop && !sorted_axes.empty() && detail::in_dynamic_tracing()) {
is_noop = false;
}
return {out_shape, sorted_axes, is_noop};
}
Dtype at_least_float(const Dtype& d) {
return issubdtype(d, inexact) ? d : promote_types(d, float32);
}
array indices_or_default(
std::string_view tag,
const std::optional<array>& indices,
const array& x,
StreamOrDevice s) {
if (x.ndim() < 2) {
std::ostringstream msg;
msg << tag
<< " Input must have at least two dimensions but got input with shape "
<< x.shape() << ".";
throw std::invalid_argument(msg.str());
}
if (indices.has_value()) {
if (!issubdtype(indices->dtype(), integer)) {
std::ostringstream msg;
msg << tag
<< " Got indices with invalid dtype. Indices must be integral.";
throw std::invalid_argument(msg.str());
}
return astype(indices.value(), uint32, s);
}
Shape shape(x.shape().begin(), x.shape().end() - 2);
int total = safe_cast(
std::reduce(
shape.begin(), shape.end(), int64_t{1}, std::multiplies<int64_t>{}),
"gather");
return reshape(arange(total, uint32, s), std::move(shape), s);
}
void validate_quantized_input(
std::string_view tag,
const array& w,
const array& scales,
int group_size,
int bits,
const std::optional<array>& biases = std::nullopt) {
if (w.dtype() != uint32) {
std::ostringstream msg;
msg << "[" << tag << "] The weight matrix should be uint32 "
<< "but received " << w.dtype();
throw std::invalid_argument(msg.str());
}
if (biases && scales.shape() != biases->shape()) {
std::ostringstream msg;
msg << "[" << tag << "] Scales and biases should have the same shape. "
<< "Received scales with shape " << scales.shape()
<< " and biases with " << biases->shape();
throw std::invalid_argument(msg.str());
}
if (!std::equal(
w.shape().begin(), w.shape().end() - 2, scales.shape().begin())) {
std::ostringstream msg;
msg << "[" << tag
<< "] Weight and scales should have the same batch shape. "
<< "Received weight with shape " << w.shape() << ", scales with "
<< scales.shape() << ".";
throw std::invalid_argument(msg.str());
}
if (w.shape(-1) * 32 / bits != scales.shape(-1) * group_size) {
std::ostringstream msg;
msg << "[" << tag << "] The shapes of the weight and scales are "
<< "incompatible based on bits and group_size. w.shape() == "
<< w.shape() << " and scales.shape() == " << scales.shape()
<< " with group_size=" << group_size << " and bits=" << bits;
throw std::invalid_argument(msg.str());
}
}
std::pair<int, int> extract_quantized_matmul_dims(
std::string_view tag,
const array& x,
const array& w,
const array& scales,
const std::optional<array>& biases,
bool transpose,
int group_size,
int bits) {
validate_quantized_input(tag, w, scales, group_size, bits, biases);
int x_inner_dims = x.shape(-1);
// Calculate the expanded w's dims
int w_inner_dims = (transpose) ? w.shape(-1) * 32 / bits : w.shape(-2);
int w_outer_dims = (transpose) ? w.shape(-2) : w.shape(-1) * 32 / bits;
if (w_inner_dims != x_inner_dims) {
std::ostringstream msg;
msg << "[" << tag << "] Last dimension of first input with "
<< "shape (..., " << x_inner_dims << ") does not match "
<< "the expanded quantized matrix (" << w_inner_dims << ", "
<< w_outer_dims << ") computed from shape " << w.shape()
<< " with group_size=" << group_size << ", bits=" << bits
<< " and transpose=" << std::boolalpha << transpose;
throw std::invalid_argument(msg.str());
}
return {w_inner_dims, w_outer_dims};
}
} // namespace
array arange(
double start,
double stop,
double step,
Dtype dtype,
StreamOrDevice s /* = {} */) {
if (dtype == bool_) {
std::ostringstream msg;
msg << bool_ << " not supported for arange.";
throw std::invalid_argument(msg.str());
}
if (std::isnan(start) || std::isnan(step) || std::isnan(stop)) {
throw std::invalid_argument("[arange] Cannot compute length.");
}
if (std::isinf(start) || std::isinf(stop)) {
throw std::invalid_argument("[arange] Cannot compute length.");
}
if (step == 0) {
throw std::invalid_argument("[arange] step must be nonzero.");
}
// Check if start and stop specify a valid range because if not, we have to
// return an empty array
if (std::isinf(step) &&
((step > 0 && start < stop) || (step < 0 && start > stop))) {
return array({start}, dtype);
}
double real_size = std::ceil((stop - start) / step);
if (real_size > INT_MAX) {
throw std::invalid_argument("[arange] Maximum size exceeded.");
}
int size = std::max(static_cast<int>(real_size), 0);
return array(
{size},
dtype,
std::make_shared<Arange>(to_stream(s), start, stop, step),
{});
}
array arange(
double start,
double stop,
double step,
StreamOrDevice s /* = {} */) {
return arange(start, stop, step, float32, to_stream(s));
}
array arange(
double start,
double stop,
Dtype dtype,
StreamOrDevice s /* = {} */) {
return arange(start, stop, 1.0, dtype, to_stream(s));
}
array arange(double start, double stop, StreamOrDevice s /* = {} */) {
return arange(start, stop, 1.0, float32, to_stream(s));
}
array arange(double stop, Dtype dtype, StreamOrDevice s /* = {} */) {
return arange(0.0, stop, 1.0, dtype, to_stream(s));
}
array arange(double stop, StreamOrDevice s /* = {} */) {
return arange(0.0, stop, 1.0, float32, to_stream(s));
}
array arange(int start, int stop, int step, StreamOrDevice s /* = {} */) {
return arange(
static_cast<double>(start),
static_cast<double>(stop),
static_cast<double>(step),
int32,
to_stream(s));
}
array arange(int start, int stop, StreamOrDevice s /* = {} */) {
return arange(
static_cast<double>(start),
static_cast<double>(stop),
1.0,
int32,
to_stream(s));
}
array arange(int stop, StreamOrDevice s /* = {} */) {
return arange(0.0, static_cast<double>(stop), 1.0, int32, to_stream(s));
}
array linspace(
double start,
double stop,
int num /* = 50 */,
bool endpoint /* = true */,
Dtype dtype /* = float32 */,
StreamOrDevice s /* = {} */) {
if (num < 0) {
std::ostringstream msg;
msg << "[linspace] number of samples, " << num << ", must be non-negative.";
throw std::invalid_argument(msg.str());
}
if (num == 1) {
return astype(array({start}), dtype, s);
}
auto inner_type = dtype == float64 ? float64 : float32;
// Without the endpoint the samples are spaced so that `stop` would be the
// next one after the last, i.e. the step is (stop - start) / num.
auto denominator = endpoint ? num - 1 : num;
array t =
divide(arange(0, num, inner_type, s), array(denominator, inner_type), s);
array t_bar = subtract(array(1, inner_type), t, s);
return astype(
add(multiply(t_bar, array(start, inner_type), s),
multiply(t, array(stop, inner_type), s),
s),
dtype,
s);
}
// Private API used by python bindings.
MLX_API array
astype(array a, Dtype dtype, bool force_copy, StreamOrDevice s = {}) {
if (dtype == a.dtype() && !force_copy) {
return a;
}
auto copied_shape = a.shape(); // |a| will be moved
return array(
std::move(copied_shape),
dtype,
std::make_shared<AsType>(to_stream(s), dtype),
{std::move(a)});
}
array astype(array a, Dtype dtype, StreamOrDevice s /* = {} */) {
return astype(std::move(a), dtype, false, s);
}
array as_strided(
array a,
Shape shape,
Strides strides,
size_t offset,
StreamOrDevice s /* = {} */) {
if (std::any_of(shape.begin(), shape.end(), [](auto i) { return i < 0; })) {
throw std::invalid_argument(
"[as_strided] Negative dimensions not allowed.");
}
auto copied_shape = shape; // |shape| will be moved
auto dtype = a.dtype(); // |a| will be moved
return array(
std::move(copied_shape),
dtype,
std::make_shared<AsStrided>(
to_stream(s), std::move(shape), std::move(strides), offset),
{std::move(a)});
}
array copy(array a, StreamOrDevice s /* = {} */) {
auto copied_shape = a.shape(); // |a| will be moved
auto dtype = a.dtype();
return array(
std::move(copied_shape),
dtype,
std::make_shared<Copy>(to_stream(s)),
{std::move(a)});
}
array full_impl(array vals, Dtype dtype, StreamOrDevice s /* = {} */) {
return array(
vals.shape(),
dtype,
std::make_shared<Full>(to_stream(s)),
{astype(vals, dtype, s)});
}
array full(Shape shape, array vals, Dtype dtype, StreamOrDevice s /* = {} */) {
if (std::any_of(shape.begin(), shape.end(), [](auto i) { return i < 0; })) {
throw std::invalid_argument("[full] Negative dimensions not allowed.");
}
return full_impl(broadcast_to(vals, std::move(shape), s), dtype, s);
}
array full(Shape shape, array vals, StreamOrDevice s /* = {} */) {
auto dtype = vals.dtype(); // |vals| will be moved
return full(std::move(shape), std::move(vals), dtype, to_stream(s));
}
array full_like(
const array& a,
array vals,
Dtype dtype,
StreamOrDevice s /* = {} */) {
auto inputs = broadcast_arrays({a, std::move(vals)}, s);
return full_impl(std::move(inputs[1]), dtype, s);
}
array full_like(const array& a, array vals, StreamOrDevice s /* = {} */) {
return full_like(a, std::move(vals), a.dtype(), to_stream(s));
}
array zeros(const Shape& shape, Dtype dtype, StreamOrDevice s /* = {} */) {
return full(shape, array(0, dtype), to_stream(s));
}
array zeros_like(const array& a, StreamOrDevice s /* = {} */) {
return zeros_like(a, a.dtype(), s);
}
array zeros_like(const array& a, Dtype dtype, StreamOrDevice s /* = {} */) {
return full_like(a, 0, dtype, to_stream(s));
}
array ones(const Shape& shape, Dtype dtype, StreamOrDevice s /* = {} */) {
return full(shape, array(1, dtype), to_stream(s));
}
array ones_like(const array& a, StreamOrDevice s /* = {} */) {
return ones_like(a, a.dtype(), s);
}
array ones_like(const array& a, Dtype dtype, StreamOrDevice s /* = {} */) {
return full_like(a, 1, dtype, to_stream(s));
}
array eye(int n, int m, int k, Dtype dtype, StreamOrDevice s /* = {} */) {
if (n < 0 || m < 0) {
throw std::invalid_argument("[eye] N and M must be positive integers.");
}
array result = zeros({n, m}, dtype, s);
if (n == 0 || m == 0) {
return result;
}
if (k >= m || -k >= n) {
return result;
}
int diagonal_length = k >= 0 ? std::min(n, m - k) : std::min(n + k, m);
std::vector<array> indices;
auto s1 = std::max(0, -k);
auto s2 = std::max(0, k);
indices.push_back(arange(s1, diagonal_length + s1, int32, s));
indices.push_back(arange(s2, diagonal_length + s2, int32, s));
array ones_array = ones({diagonal_length, 1, 1}, dtype, s);
return scatter(result, indices, ones_array, {0, 1}, s);
}
array identity(int n, Dtype dtype, StreamOrDevice s /* = {} */) {
return eye(n, n, 0, dtype, s);
}
array tri(int n, int m, int k, Dtype type, StreamOrDevice s /* = {} */) {
auto l = expand_dims(arange(n, s), 1, s);
auto r = expand_dims(arange(-k, m - k, s), 0, s);
return astype(greater_equal(l, r, s), type, s);
}
array tril(array x, int k /* = 0 */, StreamOrDevice s /* = {} */) {
if (x.ndim() < 2) {
throw std::invalid_argument("[tril] array must be at least 2-D");
}
auto mask = tri(x.shape(-2), x.shape(-1), k, bool_, s);
return where(mask, x, array(0, x.dtype()), s);
}
array triu(array x, int k /* = 0 */, StreamOrDevice s /* = {} */) {
if (x.ndim() < 2) {
throw std::invalid_argument("[triu] array must be at least 2-D");
}
auto mask = tri(x.shape(-2), x.shape(-1), k - 1, bool_, s);
return where(mask, array(0, x.dtype()), x, s);
}
array reshape(const array& a, Shape shape, StreamOrDevice s /* = {} */) {
if (a.shape() == shape) {
return a;
}
auto out_shape = Reshape::output_shape(a, shape);
return array(
std::move(out_shape),
a.dtype(),
std::make_shared<Reshape>(to_stream(s), std::move(shape)),
{a});
}
array unflatten(
const array& a,
int axis,
Shape shape,
StreamOrDevice s /* = {} */) {
if (shape.empty()) {
throw std::invalid_argument(
"[unflatten] Shape to unflatten to cannot be empty.");
}
auto ndim = static_cast<int>(a.ndim());
auto ax = axis < 0 ? axis + ndim : axis;
if (ax < 0 || ax >= ndim) {
std::ostringstream msg;
msg << "[unflatten] Invalid axes " << ax << " for array with " << a.ndim()
<< " dimensions.";
throw std::out_of_range(msg.str());
}
auto out_shape = Unflatten::output_shape(a, ax, shape);
if (shape.size() == 1 && (shape[0] == -1 || !detail::in_dynamic_tracing())) {
return a;
}
return array(
std::move(out_shape),
a.dtype(),
std::make_shared<Unflatten>(to_stream(s), ax, std::move(shape)),
{a});
}
array flatten(
const array& a,
int start_axis,
int end_axis /* = -1 */,
StreamOrDevice s /* = {} */) {
auto ndim = static_cast<int>(a.ndim());
auto start_ax = start_axis + (start_axis < 0 ? ndim : 0);
auto end_ax = end_axis + (end_axis < 0 ? ndim : 0);
start_ax = std::max(0, start_ax);
end_ax = std::min(ndim - 1, end_ax);
if (a.ndim() == 0) {
return reshape(a, {1}, s);
}
if (end_ax < start_ax) {
throw std::invalid_argument(
"[flatten] start_axis must be less than or equal to end_axis");
}
if (start_ax >= ndim) {
std::ostringstream msg;
msg << "[flatten] Invalid start_axis " << start_axis << " for array with "
<< ndim << " dimensions.";
throw std::invalid_argument(msg.str());
}
if (end_ax < 0) {
std::ostringstream msg;
msg << "[flatten] Invalid end_axis " << end_axis << " for array with "
<< ndim << " dimensions.";
throw std::invalid_argument(msg.str());
}
if (start_ax == end_ax) {
return a;
}
return array(
Flatten::output_shape(a, start_ax, end_ax),
a.dtype(),
std::make_shared<Flatten>(to_stream(s), start_ax, end_ax),
{a});
}
array flatten(const array& a, StreamOrDevice s /* = {} */) {
return flatten(a, 0, a.ndim() - 1, s);
}
array hadamard_transform(
const array& a,
std::optional<float> scale_ /* = std::nullopt */,
StreamOrDevice s /* = {} */) {
if (a.size() == 0) {
throw std::invalid_argument(
"[hadamard_transform] Does not support empty arrays.");
}
// Default to an orthonormal Hadamard matrix scaled by 1/sqrt(N)
int n = a.ndim() > 0 ? a.shape(-1) : 1;
float scale = scale_.has_value() ? *scale_ : 1.0f / std::sqrt(n);
auto dtype = issubdtype(a.dtype(), floating) ? a.dtype() : float32;
// Nothing to do for a scalar
if (n == 1) {
if (scale == 1) {
return a;
}
return multiply(a, array(scale, dtype), s);
}
return array(
a.shape(),
dtype,
std::make_shared<Hadamard>(to_stream(s), scale),
{astype(a, dtype, s)});
}
namespace {
std::vector<int> normalize_squeeze_axes(
const array& a,
const std::vector<int>& axes) {
int ndim = a.ndim();
std::set<int> unique_axes;
for (auto ax : axes) {
int new_ax = normalize_axis_index(ax, ndim, "[squeeze] ");
if (a.shape(new_ax) != 1) {
std::ostringstream msg;
msg << "[squeeze] Cannot squeeze axis " << ax << " with size "
<< a.shape(new_ax) << " which is not equal to 1.";
throw std::invalid_argument(msg.str());
}
unique_axes.insert(new_ax);
}
if (unique_axes.size() != axes.size()) {
throw std::invalid_argument("[squeeze] Received duplicate axes.");
}
return std::vector<int>(unique_axes.begin(), unique_axes.end());
}
std::vector<int> normalize_expand_dims_axes(
const array& a,
const std::vector<int>& axes) {
int out_ndim = a.ndim() + axes.size();
std::set<int> unique_axes;
for (auto ax : axes) {
unique_axes.insert(normalize_axis_index(ax, out_ndim, "[expand_dims] "));
}
if (unique_axes.size() != axes.size()) {
throw std::invalid_argument("[expand_dims] Received duplicate axes.");
}
return std::vector<int>(unique_axes.begin(), unique_axes.end());
}
} // namespace
// Assumes the axes are non-negative, sorted, unique, and valid for a.
array squeeze_impl(
const array& a,
std::vector<int> axes,
StreamOrDevice s /* = {} */) {
auto shape = Squeeze::output_shape(a, axes);
return array(
std::move(shape),
a.dtype(),
std::make_shared<Squeeze>(to_stream(s), std::move(axes)),
{a});
}
array squeeze(
const array& a,
const std::vector<int>& axes,
StreamOrDevice s /* = {} */) {
if (axes.empty()) {
return a;
}
return squeeze_impl(a, normalize_squeeze_axes(a, axes), s);
}
array squeeze(const array& a, int axis, StreamOrDevice s /* = {} */) {
return squeeze_impl(a, normalize_squeeze_axes(a, {axis}), s);
}
array squeeze(const array& a, StreamOrDevice s /* = {} */) {
std::vector<int> axes;
for (int i = 0; i < a.ndim(); ++i) {
if (a.shape(i) == 1) {
axes.push_back(i);
}
}
return squeeze_impl(a, std::move(axes), s);
}
// Assumes the axes are non-negative, sorted, unique and valid for the output.
array expand_dims_impl(
const array& a,
std::vector<int> axes,
StreamOrDevice s /* = {} */) {
auto shape = ExpandDims::output_shape(a, axes);
return array(
std::move(shape),
a.dtype(),
std::make_shared<ExpandDims>(to_stream(s), std::move(axes)),
{a});
}
array expand_dims(const array& a, int axis, StreamOrDevice s /* = {} */) {
return expand_dims_impl(a, normalize_expand_dims_axes(a, {axis}), s);
}
array expand_dims(
const array& a,
const std::vector<int>& axes,
StreamOrDevice s /* = {} */) {
if (axes.empty()) {
return a;
}
return expand_dims_impl(a, normalize_expand_dims_axes(a, axes), s);
}
array flip(
const array& a,
const std::vector<int>& axes,
StreamOrDevice s /* = {} */) {
auto ndim = static_cast<int>(a.ndim());
Shape start(ndim, 0);
Shape stop = a.shape();
Shape strides(ndim, 1);
for (auto ax : axes) {
int axis = normalize_axis_index(ax, ndim, "[flip] ");
start[axis] = a.shape(axis) - 1;
stop[axis] = -a.shape(axis) - 1;
strides[axis] = -1;
}
return slice(a, std::move(start), std::move(stop), std::move(strides), s);
}
array flip(const array& a, int axis, StreamOrDevice s /* = {} */) {
return flip(a, std::vector<int>{axis}, s);
}
array flip(const array& a, StreamOrDevice s /* = {} */) {
std::vector<int> axes(a.ndim());
std::iota(axes.begin(), axes.end(), 0);
return flip(a, axes, s);
}
// Slice helper
namespace {
inline auto
normalize_slice(const Shape& shape, Shape& start, Shape& stop, Shape& strides) {
// - Start indices are normalized
// - End indices are unchanged as -1 means something different
// pre-normalization (the end of the axis) versus post normalization (the
// position left of 0).
// - Any strides corresponding to singleton dimension are set to 1
Shape out_shape(shape.size());
bool has_neg_strides = false;
for (int i = 0; i < shape.size(); ++i) {
// Following numpy docs
// Negative i and j are interpreted as n + i and n + j where n is
// the number of elements in the corresponding dimension. Negative
// k makes stepping go towards smaller indices
auto n = shape[i];
auto s = start[i];
s = s < 0 ? s + n : s;
auto e = stop[i];
e = e < 0 ? e + n : e;
// Note: -ve strides require start >= stop
if (strides[i] < 0) {
has_neg_strides = true;
// Clamp to bounds
auto st = std::min(s, n - 1);
auto ed = e > -1 ? e : -1;
start[i] = st;
ed = ed > st ? st : ed;
auto str = -strides[i];
out_shape[i] = (start[i] - ed + str - 1) / str;
} else {
// Clamp to bounds
auto st = std::max(static_cast<ShapeElem>(0), std::min(s, n));
auto ed = std::max(static_cast<ShapeElem>(0), std::min(e, n));
start[i] = st;
ed = ed < st ? st : ed;
out_shape[i] = (ed - start[i] + strides[i] - 1) / strides[i];
}
// Simplify the stride if it's unused
if (out_shape[i] == 1) {
if (strides[i] < 0 && start[i] > 0) {
strides[i] = -1;
stop[i] = start[i] - 1;
} else {
strides[i] = 1;
stop[i] = start[i] + 1;
}
}
}
return std::make_pair(has_neg_strides, out_shape);
}
void normalize_dynamic_slice_inputs(
const array& a,
const array& start,
std::vector<int>& axes,
std::string_view prefix) {
if (start.size() > a.ndim()) {
std::ostringstream msg;
msg << prefix << " Invalid number of starting positions for "
<< "array with dimension " << a.ndim() << ".";
throw std::invalid_argument(msg.str());
}
if (start.ndim() > 1) {
std::ostringstream msg;
msg << prefix << " array of starting indices "
<< "must be zero or one dimensional but has dimension " << start.ndim()
<< ".";
throw std::invalid_argument(msg.str());
}
if (start.size() != axes.size()) {
std::ostringstream msg;
msg << prefix << " Number of starting indices " << start.size()
<< " does not match number of axes " << axes.size() << ".";
throw std::invalid_argument(msg.str());
}
if (!issubdtype(start.dtype(), integer)) {
std::ostringstream msg;
msg << prefix << " Start indices must be integers, got type "
<< start.dtype() << ".";
throw std::invalid_argument(msg.str());
}
for (auto& ax : axes) {
auto new_ax = ax < 0 ? ax + a.ndim() : ax;
if (new_ax < 0 || new_ax >= a.ndim()) {
std::ostringstream msg;
msg << prefix << " Invalid axis " << ax << " for array with dimension "
<< a.ndim() << ".";
throw std::out_of_range(msg.str());
}
ax = new_ax;
}
std::set dims(axes.begin(), axes.end());
if (dims.size() != axes.size()) {
std::ostringstream msg;
msg << prefix << " Repeat axes not allowed.";
throw std::invalid_argument(msg.str());
}
}
} // namespace
array slice(
const array& a,
Shape start,
Shape stop,
Shape strides,
StreamOrDevice s /* = {} */) {
if (start.size() != a.ndim() || stop.size() != a.ndim() ||
strides.size() != a.ndim()) {
std::ostringstream msg;
msg << "[slice] Invalid number of indices or strides for "
<< "array with dimension " << a.ndim() << ".";
throw std::invalid_argument(msg.str());
}
auto [has_neg_strides, out_shape] =
normalize_slice(a.shape(), start, stop, strides);
if (!has_neg_strides && out_shape == a.shape()) {
return a;
}
return array(
out_shape,
a.dtype(),
std::make_shared<Slice>(
to_stream(s), std::move(start), std::move(stop), std::move(strides)),
{a});
}
array slice(
const array& a,
Shape start,
Shape stop,
StreamOrDevice s /* = {} */) {
return slice(
a, std::move(start), std::move(stop), Shape(a.ndim(), 1), to_stream(s));
}
array slice(
const array& a,
const array& start,
std::vector<int> axes,
Shape slice_size,
StreamOrDevice s /* = {} */) {
normalize_dynamic_slice_inputs(a, start, axes, "[slice]");
// Check the slice_size
if (slice_size.size() != a.ndim()) {
std::ostringstream msg;
msg << "[slice] Invalid slice size for array with " << a.ndim()
<< " dimensions.";
throw std::invalid_argument(msg.str());
}
for (int i = 0; i < a.ndim(); ++i) {
if (slice_size[i] > a.shape(i)) {
std::ostringstream msg;
msg << "[slice] Invalid slice size " << slice_size
<< " for array with shape " << a.shape() << ".";
throw std::invalid_argument(msg.str());
}
}
auto out_shape = slice_size;
return array(
std::move(out_shape),
a.dtype(),
std::make_shared<DynamicSlice>(
to_stream(s), std::move(axes), std::move(slice_size)),
{a, start});
}
/** Update a slice from the source array */
array slice_update(
const array& src,
const array& update,
Shape start,
Shape stop,
Shape strides,
StreamOrDevice s /* = {} */) {
// Check dimensions
if (start.size() != src.ndim() || stop.size() != src.ndim() ||
strides.size() != src.ndim()) {
std::ostringstream msg;
msg << "[slice_update] Invalid number of indices or strides for "
<< "array with dimension " << src.ndim() << ".";
throw std::invalid_argument(msg.str());
}
// Process slice dimensions
auto [has_neg_strides, upd_shape] =
normalize_slice(src.shape(), start, stop, strides);
// Cast update to src type and broadcast update shape to slice shape
auto upd = broadcast_to(astype(update, src.dtype(), s), upd_shape, s);
// If the entire src is the slice, just return the update
if (!has_neg_strides && upd_shape == src.shape()) {
return upd;
}
return array(
src.shape(),
src.dtype(),
std::make_shared<SliceUpdate>(
to_stream(s),
SliceUpdate::None,
std::move(start),
std::move(stop),
std::move(strides)),
{src, upd});
}
/** Update a slice from the source array with stride 1 in each dimension */
array slice_update(
const array& src,
const array& update,
Shape start,
Shape stop,
StreamOrDevice s /* = {} */) {
return slice_update(
src, update, std::move(start), std::move(stop), Shape(src.ndim(), 1), s);
}
/** Update a slice from the source array */
array slice_update(
const array& src,
const array& update,
const array& start,
std::vector<int> axes,
StreamOrDevice s /* = {} */) {
normalize_dynamic_slice_inputs(src, start, axes, "[slice_update]");
// Broadcast update with unspecified axes
auto up_shape = update.shape();
auto dim_diff = std::max(src.ndim() - update.ndim(), size_t(0));
up_shape.insert(
up_shape.begin(), src.shape().begin(), src.shape().begin() + dim_diff);
for (int d = dim_diff; d < src.ndim(); ++d) {
up_shape[d] = std::min(up_shape[d], src.shape(d));
}
for (auto ax : axes) {
if (ax < dim_diff) {
up_shape[ax] = 1;
}
}
auto upd = broadcast_to(astype(update, src.dtype(), s), up_shape, s);
return array(
src.shape(),
src.dtype(),
std::make_shared<DynamicSliceUpdate>(to_stream(s), std::move(axes)),
{src, upd, start});
}
array slice_update(
const array& src,
const array& update,
Shape start,
Shape stop,
Shape strides,
SliceUpdate::ReduceType mode,
StreamOrDevice s) {
if (start.size() != src.ndim() || stop.size() != src.ndim() ||
strides.size() != src.ndim()) {
std::ostringstream msg;
msg << "[slice_update] Invalid number of indices or strides for "
<< "array with dimension " << src.ndim() << ".";
throw std::invalid_argument(msg.str());
}
auto [has_neg_strides, upd_shape] =
normalize_slice(src.shape(), start, stop, strides);
auto upd = broadcast_to(astype(update, src.dtype(), s), upd_shape, s);
if (!has_neg_strides && upd_shape == src.shape()) {
switch (mode) {
case SliceUpdate::None:
return upd;
case SliceUpdate::Sum:
return add(src, upd, s);
case SliceUpdate::Prod:
return multiply(src, upd, s);
case SliceUpdate::Max:
return maximum(src, upd, s);
case SliceUpdate::Min:
return minimum(src, upd, s);
}