Repository navigation
Expand file tree
/
Copy pathreduction.v
More file actions
1379 lines (1294 loc) · 38.1 KB
/
Copy pathreduction.v
File metadata and controls
1379 lines (1294 loc) · 38.1 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
module vtl
import math
// argmax_axis returns the indices of the maximum values along the given axis.
// argmax_axis exposes this operation as part of the public API.
// argmax_axis exposes this operation as part of the public API.
@[inline]
pub fn (t &Tensor[T]) argmax_axis[T](axis int) !&Tensor[int] {
shape := t.shape
rank := shape.len
if rank == 0 {
return error('argmax_axis: tensor has no dimensions')
}
mut na := axis
if axis < 0 {
na = axis + rank
}
if na < 0 || na >= rank {
return error('argmax_axis: axis ${axis} out of bounds for shape ${shape}')
}
if shape[na] == 0 {
return error('argmax_axis: cannot reduce an empty axis')
}
mut out_shape := shape.clone()
out_shape[na] = 1
mut result := empty[int](out_shape)
if result.size == 0 {
return result
}
// Dense row-major fast path: linear indexing with no per-row
// allocation and no multi-index decode. A leading NaN wins; otherwise
// the first NaN wins, matching NumPy. Ties keep the earlier index.
if t.is_row_major_contiguous() && t.data.data.len >= t.size {
arg_extrema_axis_contiguous[T](t, na, mut result, true)
return result
}
mut out_strides := []int{len: rank}
out_strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
out_strides[i] = out_strides[i + 1] * out_shape[i + 1]
}
mut outer_idx := []int{len: rank}
for {
mut input_idx := outer_idx.clone()
mut best_val := t.get(input_idx)
mut best_is_nan := math.is_nan(f64(best_val))
mut best_arg := 0
for j := 1; j < shape[na]; j++ {
input_idx[na] = j
val := t.get(input_idx)
if best_is_nan {
break
}
if math.is_nan(f64(val)) {
best_arg = j
break
}
if val > best_val {
best_val = val
best_arg = j
}
}
mut out_lin := 0
for i := 0; i < rank; i++ {
out_lin += outer_idx[i] * out_strides[i]
}
result.set_nth(out_lin, best_arg)
mut done := true
for i := rank - 1; i >= 0; i-- {
if i == na {
continue
}
outer_idx[i]++
if outer_idx[i] < shape[i] {
done = false
break
}
outer_idx[i] = 0
}
if done {
break
}
}
return result
}
// argmin_axis returns the indices of the minimum values along the given axis.
// argmin_axis exposes this operation as part of the public API.
// argmin_axis exposes this operation as part of the public API.
@[inline]
pub fn (t &Tensor[T]) argmin_axis[T](axis int) !&Tensor[int] {
shape := t.shape
rank := shape.len
if rank == 0 {
return error('argmin_axis: tensor has no dimensions')
}
mut na := axis
if axis < 0 {
na = axis + rank
}
if na < 0 || na >= rank {
return error('argmin_axis: axis ${axis} out of bounds for shape ${shape}')
}
if shape[na] == 0 {
return error('argmin_axis: cannot reduce an empty axis')
}
mut out_shape := shape.clone()
out_shape[na] = 1
mut result := empty[int](out_shape)
if result.size == 0 {
return result
}
// Dense row-major fast path: linear indexing with no per-row
// allocation and no multi-index decode. A leading NaN wins; otherwise
// the first NaN wins, matching NumPy. Ties keep the earlier index.
if t.is_row_major_contiguous() && t.data.data.len >= t.size {
arg_extrema_axis_contiguous[T](t, na, mut result, false)
return result
}
mut out_strides := []int{len: rank}
out_strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
out_strides[i] = out_strides[i + 1] * out_shape[i + 1]
}
mut outer_idx := []int{len: rank}
for {
mut input_idx := outer_idx.clone()
mut best_val := t.get(input_idx)
mut best_is_nan := math.is_nan(f64(best_val))
mut best_arg := 0
for j := 1; j < shape[na]; j++ {
input_idx[na] = j
val := t.get(input_idx)
if best_is_nan {
break
}
if math.is_nan(f64(val)) {
best_arg = j
break
}
if val < best_val {
best_val = val
best_arg = j
}
}
mut out_lin := 0
for i := 0; i < rank; i++ {
out_lin += outer_idx[i] * out_strides[i]
}
result.set_nth(out_lin, best_arg)
mut done := true
for i := rank - 1; i >= 0; i-- {
if i == na {
continue
}
outer_idx[i]++
if outer_idx[i] < shape[i] {
done = false
break
}
outer_idx[i] = 0
}
if done {
break
}
}
return result
}
// arg_extrema_axis_contiguous is the dense row-major fast path behind
// argmax_axis (maximum=true) and argmin_axis (maximum=false). The caller
// guarantees validated shapes and dense storage, so indexing is linear
// with no per-row allocation and no multi-index decode. A leading NaN wins;
// otherwise the first NaN wins, matching NumPy. Ties keep the earlier index.
@[direct_array_access]
fn arg_extrema_axis_contiguous[T](t &Tensor[T], na int, mut result &Tensor[int], maximum bool) {
shape := t.shape
rank := shape.len
axis_size := shape[na]
// Dense row-major strides, computed once (mirrors extrema_axis).
mut in_strides := []int{len: rank}
in_strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
in_strides[i] = in_strides[i + 1] * shape[i + 1]
}
axis_stride := in_strides[na]
// Output strides: the reduced axis has extent 1.
mut out_strides := []int{len: rank}
out_strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
d := if i + 1 == na { 1 } else { shape[i + 1] }
out_strides[i] = out_strides[i + 1] * d
}
mut outer := []int{len: rank}
for {
mut base := 0
for i in 0 .. rank {
base += outer[i] * in_strides[i]
}
mut best_arg := 0
mut best_val := t.data.data[base]
mut best_is_nan := math.is_nan(f64(best_val))
for j := 1; j < axis_size; j++ {
val := t.data.data[base + j * axis_stride]
if best_is_nan {
break
}
if math.is_nan(f64(val)) {
best_arg = j
break
}
if maximum && val > best_val {
best_val = val
best_arg = j
}
if !maximum && val < best_val {
best_val = val
best_arg = j
}
}
mut out_lin := 0
for i in 0 .. rank {
out_lin += outer[i] * out_strides[i]
}
result.set_nth(out_lin, best_arg)
// Odometer over outer dims; one index array reused, never cloned.
mut done := true
for i := rank - 1; i >= 0; i-- {
if i == na {
continue
}
outer[i]++
if outer[i] < shape[i] {
done = false
break
}
outer[i] = 0
}
if done {
break
}
}
}
// max_axis returns the maximum value along the given axis as a reduced tensor.
// max_axis exposes this operation as part of the public API.
// max_axis exposes this operation as part of the public API.
@[inline]
pub fn (t &Tensor[T]) max_axis[T](axis int) !&Tensor[T] {
return extrema_axis[T](t, axis, true)
}
// min_axis returns the minimum value along the given axis as a reduced tensor.
// min_axis exposes this operation as part of the public API.
// min_axis exposes this operation as part of the public API.
@[inline]
pub fn (t &Tensor[T]) min_axis[T](axis int) !&Tensor[T] {
return extrema_axis[T](t, axis, false)
}
// max_axis_with_keepdims returns maximum values with the reduced axis
// optionally retained with length one.
pub fn (t &Tensor[T]) max_axis_with_keepdims[T](axis int, keepdims bool) !&Tensor[T] {
if keepdims {
return t.max_axis[T](axis)
}
return t.max_axis_squeeze[T](axis)
}
// min_axis_with_keepdims returns minimum values with the reduced axis
// optionally retained with length one.
pub fn (t &Tensor[T]) min_axis_with_keepdims[T](axis int, keepdims bool) !&Tensor[T] {
if keepdims {
return t.min_axis[T](axis)
}
return t.min_axis_squeeze[T](axis)
}
fn extrema_axis[T](t &Tensor[T], axis int, maximum bool) !&Tensor[T] {
shape := t.shape
rank := shape.len
if rank == 0 {
return error('extrema_axis: tensor has no dimensions')
}
axis_index := if axis < 0 { axis + rank } else { axis }
if axis_index < 0 || axis_index >= rank {
return error('axis ${axis} out of bounds for shape ${shape}')
}
if shape[axis_index] == 0 {
return error('cannot reduce an empty axis')
}
mut output_shape := shape.clone()
output_shape[axis_index] = 1
mut result := empty[T](output_shape)
if result.size == 0 {
return result
}
// Dense row-major fast path: linear indexing with no multi-index
// decode (mirrors the contiguous branch convention of cumsum/cumprod
// and arg_extrema_axis_contiguous). NaN semantics match exactly:
// any NaN poisons the line, otherwise the extremum wins ties by
// first occurrence.
if t.is_row_major_contiguous() && t.data.data.len >= t.size {
extrema_axis_contiguous[T](t, axis_index, maximum, mut result)
return result
}
mut output_strides := []int{len: rank}
output_strides[rank - 1] = 1
for dimension := rank - 2; dimension >= 0; dimension-- {
output_strides[dimension] = output_strides[dimension + 1] * output_shape[dimension + 1]
}
mut axis_stride := 1
for dimension in axis_index + 1 .. rank {
axis_stride *= shape[dimension]
}
mut outer_index := []int{len: rank}
for {
mut base_index := 0
for dimension, coordinate in outer_index {
base_index = base_index * shape[dimension] + coordinate
}
mut best_value := t.get_nth(base_index)
mut best_is_nan := value_is_nan[T](best_value)
for position in 1 .. shape[axis_index] {
value := t.get_nth(base_index + position * axis_stride)
value_nan := value_is_nan[T](value)
if value_nan {
best_value = value
best_is_nan = true
} else if !best_is_nan && (if maximum { value > best_value } else { value < best_value }) {
best_value = value
}
}
mut output_index := 0
for dimension, coordinate in outer_index {
output_index += coordinate * output_strides[dimension]
}
result.set_nth(output_index, best_value)
mut done := true
for dimension := rank - 1; dimension >= 0; dimension-- {
if dimension == axis_index {
continue
}
outer_index[dimension]++
if outer_index[dimension] < shape[dimension] {
done = false
break
}
outer_index[dimension] = 0
}
if done {
break
}
}
return result
}
// extrema_axis_contiguous is the dense row-major fast path behind
// max_axis/min_axis (via extrema_axis). The caller guarantees validated
// shapes and dense storage, so indexing is linear with no multi-index
// decode. NaN semantics match the generic path exactly.
@[direct_array_access]
fn extrema_axis_contiguous[T](t &Tensor[T], axis_index int, maximum bool, mut result &Tensor[T]) {
shape := t.shape
rank := shape.len
axis_size := shape[axis_index]
mut in_strides := []int{len: rank}
in_strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
in_strides[i] = in_strides[i + 1] * shape[i + 1]
}
axis_stride := in_strides[axis_index]
mut out_strides := []int{len: rank}
out_strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
d := if i + 1 == axis_index { 1 } else { shape[i + 1] }
out_strides[i] = out_strides[i + 1] * d
}
mut outer := []int{len: rank}
for {
mut base := 0
for i in 0 .. rank {
base += outer[i] * in_strides[i]
}
mut best_value := t.data.data[base]
mut best_is_nan := value_is_nan[T](best_value)
for position in 1 .. axis_size {
value := t.data.data[base + position * axis_stride]
value_nan := value_is_nan[T](value)
if value_nan {
best_value = value
best_is_nan = true
} else if !best_is_nan && (if maximum { value > best_value } else { value < best_value }) {
best_value = value
}
}
mut out_lin := 0
for i in 0 .. rank {
out_lin += outer[i] * out_strides[i]
}
result.set_nth(out_lin, best_value)
mut done := true
for i := rank - 1; i >= 0; i-- {
if i == axis_index {
continue
}
outer[i]++
if outer[i] < shape[i] {
done = false
break
}
outer[i] = 0
}
if done {
break
}
}
}
fn value_is_nan[T](value T) bool {
$if T is $float {
return math.is_nan(f64(value))
} $else {
return false
}
}
// max_axis_squeeze returns maximum values with the reduced axis removed,
// matching NumPy's default keepdims=false shape behavior.
pub fn (t &Tensor[T]) max_axis_squeeze[T](axis int) !&Tensor[T] {
result := t.max_axis[T](axis)!
na := if axis < 0 { axis + t.rank() } else { axis }
return squeeze_reduction_axis[T](result, na)
}
// min_axis_squeeze returns minimum values with the reduced axis removed,
// matching NumPy's default keepdims=false shape behavior.
pub fn (t &Tensor[T]) min_axis_squeeze[T](axis int) !&Tensor[T] {
result := t.min_axis[T](axis)!
na := if axis < 0 { axis + t.rank() } else { axis }
return squeeze_reduction_axis[T](result, na)
}
// max_axes reduces several axes by maximum. Negative axes are supported;
// duplicate axes return an error. An empty axes list returns a copy.
pub fn (t &Tensor[T]) max_axes[T](axes []int, keepdims bool) !&Tensor[T] {
return extrema_axes[T](t, axes, keepdims, true)
}
// min_axes reduces several axes by minimum. Negative axes are supported;
// duplicate axes return an error. An empty axes list returns a copy.
pub fn (t &Tensor[T]) min_axes[T](axes []int, keepdims bool) !&Tensor[T] {
return extrema_axes[T](t, axes, keepdims, false)
}
fn extrema_axes[T](t &Tensor[T], axes []int, keepdims bool, maximum bool) !&Tensor[T] {
if axes.len == 0 {
return t.copy(.row_major)
}
mut normalized := []int{cap: axes.len}
for axis in axes {
axis_index := if axis < 0 { axis + t.rank() } else { axis }
if axis_index < 0 || axis_index >= t.rank() {
return error('axis ${axis} out of bounds for rank ${t.rank()}')
}
if axis_index in normalized {
return error('duplicate axis ${axis}')
}
normalized << axis_index
}
for i in 0 .. normalized.len {
for j in i + 1 .. normalized.len {
if normalized[i] < normalized[j] {
normalized[i], normalized[j] = normalized[j], normalized[i]
}
}
}
mut output_shape := t.shape.clone()
for axis_index in normalized {
if output_shape[axis_index] == 0 {
return error('cannot reduce an empty axis')
}
if keepdims {
output_shape[axis_index] = 1
}
}
if !keepdims {
for axis_index in normalized {
output_shape.delete(axis_index)
}
}
if 0 in output_shape {
return empty[T](output_shape)
}
mut result := t.copy(.row_major)
for axis_index in normalized {
if maximum {
if keepdims {
result = result.max_axis[T](axis_index)!
} else {
result = result.max_axis_squeeze[T](axis_index)!
}
} else if keepdims {
result = result.min_axis[T](axis_index)!
} else {
result = result.min_axis_squeeze[T](axis_index)!
}
}
return result
}
fn squeeze_reduction_axis[T](t &Tensor[T], axis int) !&Tensor[T] {
mut shape := t.shape.clone()
shape.delete(axis)
if shape.len == 0 {
shape = [1]
}
return t.reshape[T](shape)
}
// argmax_axis_with_keepdims returns maximum indices with optional axis
// retention.
pub fn (t &Tensor[T]) argmax_axis_with_keepdims[T](axis int, keepdims bool) !&Tensor[int] {
result := t.argmax_axis[T](axis)!
if keepdims {
return result
}
na := if axis < 0 { axis + t.rank() } else { axis }
return squeeze_reduction_axis[int](result, na)
}
// argmin_axis_with_keepdims returns minimum indices with optional axis
// retention.
pub fn (t &Tensor[T]) argmin_axis_with_keepdims[T](axis int, keepdims bool) !&Tensor[int] {
result := t.argmin_axis[T](axis)!
if keepdims {
return result
}
na := if axis < 0 { axis + t.rank() } else { axis }
return squeeze_reduction_axis[int](result, na)
}
// argmax_axis_squeeze returns the maximum indices with the reduced axis
// removed, matching NumPy's default keepdims=false behavior.
pub fn (t &Tensor[T]) argmax_axis_squeeze[T](axis int) !&Tensor[int] {
return t.argmax_axis_with_keepdims[T](axis, false)
}
// argmin_axis_squeeze returns the minimum indices with the reduced axis
// removed, matching NumPy's default keepdims=false behavior.
pub fn (t &Tensor[T]) argmin_axis_squeeze[T](axis int) !&Tensor[int] {
return t.argmin_axis_with_keepdims[T](axis, false)
}
// argmax returns the indices of the maximum values along the given axis.
// argmax exposes this operation as part of the public API.
// argmax exposes this operation as part of the public API.
@[inline]
pub fn (t &Tensor[T]) argmax[T](axis int) !&Tensor[int] {
return t.argmax_axis(axis)
}
// argmin returns the indices of the minimum values along the given axis.
// argmin exposes this operation as part of the public API.
// argmin exposes this operation as part of the public API.
@[inline]
pub fn (t &Tensor[T]) argmin[T](axis int) !&Tensor[int] {
return t.argmin_axis(axis)
}
// argmax_flat returns the flattened index of the first largest value. A NaN
// value is returned immediately, matching NumPy's argmax behavior.
pub fn (t &Tensor[T]) argmax_flat[T]() !int {
if t.size == 0 {
return error('argmax_flat: cannot reduce an empty tensor')
}
mut best_index := 0
mut best_value := t.get_nth(0)
if math.is_nan(f64(best_value)) {
return best_index
}
for index in 1 .. t.size {
value := t.get_nth(index)
if math.is_nan(f64(value)) {
return index
}
if value > best_value {
best_value = value
best_index = index
}
}
return best_index
}
// argmin_flat returns the flattened index of the first smallest value. A NaN
// value is returned immediately, matching NumPy's argmin behavior.
pub fn (t &Tensor[T]) argmin_flat[T]() !int {
if t.size == 0 {
return error('argmin_flat: cannot reduce an empty tensor')
}
mut best_index := 0
mut best_value := t.get_nth(0)
if math.is_nan(f64(best_value)) {
return best_index
}
for index in 1 .. t.size {
value := t.get_nth(index)
if math.is_nan(f64(value)) {
return index
}
if value < best_value {
best_value = value
best_index = index
}
}
return best_index
}
// nanargmax returns the flattened index of the largest non-NaN value. The
// first index wins ties, matching NumPy. Empty and all-NaN tensors return an error.
pub fn (t &Tensor[T]) nanargmax[T]() !int {
if t.size == 0 {
return error('nanargmax: tensor contains no non-NaN values')
}
mut found := false
mut best_value := t.get_nth(0)
mut best_index := 0
for index in 0 .. t.size {
value := t.get_nth(index)
if math.is_nan(f64(value)) {
continue
}
if !found || value > best_value {
found = true
best_value = value
best_index = index
}
}
if !found {
return error('nanargmax: tensor contains no non-NaN values')
}
return best_index
}
// nanargmin returns the flattened index of the smallest non-NaN value. The
// first index wins ties, matching NumPy. Empty and all-NaN tensors return an error.
pub fn (t &Tensor[T]) nanargmin[T]() !int {
if t.size == 0 {
return error('nanargmin: tensor contains no non-NaN values')
}
mut found := false
mut best_value := t.get_nth(0)
mut best_index := 0
for index in 0 .. t.size {
value := t.get_nth(index)
if math.is_nan(f64(value)) {
continue
}
if !found || value < best_value {
found = true
best_value = value
best_index = index
}
}
if !found {
return error('nanargmin: tensor contains no non-NaN values')
}
return best_index
}
// argmax_flat_with_keepdims returns the flattened maximum index as a tensor.
// When keepdims is true, the tensor retains the input rank with all dimensions
// set to one; otherwise it is scalar-shaped.
pub fn (t &Tensor[T]) argmax_flat_with_keepdims[T](keepdims bool) !&Tensor[int] {
index := t.argmax_flat()!
return flat_arg_index_tensor(index, t.rank(), keepdims)
}
// argmin_flat_with_keepdims returns the flattened minimum index as a tensor.
// When keepdims is true, the tensor retains the input rank with all dimensions
// set to one; otherwise it is scalar-shaped.
pub fn (t &Tensor[T]) argmin_flat_with_keepdims[T](keepdims bool) !&Tensor[int] {
index := t.argmin_flat()!
return flat_arg_index_tensor(index, t.rank(), keepdims)
}
// nanargmax_flat_with_keepdims returns the flattened non-NaN maximum index as
// a tensor, optionally retaining the input rank with length-one dimensions.
pub fn (t &Tensor[T]) nanargmax_flat_with_keepdims[T](keepdims bool) !&Tensor[int] {
index := t.nanargmax()!
return flat_arg_index_tensor(index, t.rank(), keepdims)
}
// nanargmin_flat_with_keepdims returns the flattened non-NaN minimum index as
// a tensor, optionally retaining the input rank with length-one dimensions.
pub fn (t &Tensor[T]) nanargmin_flat_with_keepdims[T](keepdims bool) !&Tensor[int] {
index := t.nanargmin()!
return flat_arg_index_tensor(index, t.rank(), keepdims)
}
fn flat_arg_index_tensor(index int, rank int, keepdims bool) &Tensor[int] {
shape := if keepdims { []int{len: rank, init: 1} } else { []int{} }
mut result := zeros[int](shape)
result.set_nth(0, index)
return result
}
// nanargmax_axis returns the index of the largest non-NaN value on axis.
// Set keepdims to retain the reduced axis as a length-one dimension.
pub fn (t &Tensor[T]) nanargmax_axis[T](axis int, keepdims bool) !&Tensor[int] {
return nanarg_axis[T](t, axis, keepdims, true)
}
// nanargmin_axis returns the index of the smallest non-NaN value on axis.
// Set keepdims to retain the reduced axis as a length-one dimension.
pub fn (t &Tensor[T]) nanargmin_axis[T](axis int, keepdims bool) !&Tensor[int] {
return nanarg_axis[T](t, axis, keepdims, false)
}
fn nanarg_axis[T](t &Tensor[T], axis int, keepdims bool, maximum bool) !&Tensor[int] {
rank := t.rank()
if rank == 0 {
return error('NaN arg reduction requires a tensor with at least one dimension')
}
axis_index := if axis < 0 { axis + rank } else { axis }
if axis_index < 0 || axis_index >= rank {
return error('NaN arg reduction axis ${axis} out of bounds for rank ${rank}')
}
if t.shape[axis_index] == 0 {
return error('NaN arg reduction cannot reduce an empty axis')
}
mut output_shape := []int{cap: rank}
for dimension, size in t.shape {
if dimension == axis_index {
if keepdims {
output_shape << 1
}
} else {
output_shape << size
}
}
if output_shape.len == 0 {
output_shape = [1]
}
mut result := empty[int](output_shape, memory: .row_major)
mut output_index := []int{len: output_shape.len}
for output_flat in 0 .. result.size {
mut remainder := output_flat
for dimension := output_shape.len - 1; dimension >= 0; dimension-- {
output_index[dimension] = remainder % output_shape[dimension]
remainder /= output_shape[dimension]
}
mut input_index := []int{len: rank}
mut output_dimension := 0
for dimension in 0 .. rank {
if dimension == axis_index {
if keepdims {
output_dimension++
}
continue
}
input_index[dimension] = output_index[output_dimension]
output_dimension++
}
mut found := false
mut best_value := t.get(input_index)
mut best_index := 0
for position in 0 .. t.shape[axis_index] {
input_index[axis_index] = position
value := t.get(input_index)
if math.is_nan(f64(value)) {
continue
}
if !found || (maximum && value > best_value) || (!maximum && value < best_value) {
found = true
best_value = value
best_index = position
}
}
if !found {
return error('NaN arg reduction found a slice with no non-NaN values')
}
result.set_nth(output_flat, best_index)
}
return result
}
// cumsum returns the cumulative sum along the given axis.
// Only meaningful for numeric types; bool and string follow their respective + semantics.
// cumsum exposes this operation as part of the public API.
// cumsum exposes this operation as part of the public API.
// Axis normalization and shape-derived loop bounds keep the direct array
// accesses below within the input and output buffers for valid tensors.
@[direct_array_access; inline]
pub fn (t &Tensor[T]) cumsum[T](axis int) !&Tensor[T] {
shape := t.shape
rank := shape.len
if rank == 0 {
return error('cumsum: tensor has no dimensions')
}
mut na := axis
if axis < 0 {
na = axis + rank
}
if na < 0 || na >= rank {
return error('cumsum: axis ${axis} out of bounds for shape ${shape}')
}
if t.strides.len != rank || t.size != size_from_shape(shape) {
return error('cumsum: inconsistent tensor shape, strides, or size')
}
mut strides := []int{len: rank}
strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
strides[i] = strides[i + 1] * shape[i + 1]
}
axis_stride := strides[na]
n_axis := shape[na]
mut result := zeros[T](shape)
if result.size == 0 {
return result
}
input_is_contiguous := t.is_row_major_contiguous()
if input_is_contiguous && t.data.data.len < t.size {
return error('cumsum: contiguous tensor storage is shorter than its size')
}
mut outer_idx := []int{len: rank}
for {
mut base_lin := 0
for i := 0; i < rank; i++ {
base_lin += outer_idx[i] * strides[i]
}
$if T is bool {
mut acc := false
for j := 0; j < n_axis; j++ {
lin := base_lin + j * axis_stride
value := if input_is_contiguous { t.data.data[lin] } else { t.get_nth(lin) }
acc = acc || value
result.data.data[lin] = acc
}
} $else $if T is string {
mut acc := ''
for j := 0; j < n_axis; j++ {
lin := base_lin + j * axis_stride
value := if input_is_contiguous { t.data.data[lin] } else { t.get_nth(lin) }
acc = acc + value
result.data.data[lin] = acc
}
} $else {
mut acc := cast[T](0)
for j := 0; j < n_axis; j++ {
lin := base_lin + j * axis_stride
value := if input_is_contiguous { t.data.data[lin] } else { t.get_nth(lin) }
acc = acc + value
result.data.data[lin] = acc
}
}
mut done := true
for i := rank - 1; i >= 0; i-- {
if i == na {
continue
}
outer_idx[i]++
if outer_idx[i] < shape[i] {
done = false
break
}
outer_idx[i] = 0
}
if done {
break
}
}
return result
}
// cumprod returns the cumulative product along the given axis.
// Only meaningful for numeric types; bool follows && semantics.
// cumprod exposes this operation as part of the public API.
// cumprod exposes this operation as part of the public API.
// Axis normalization and shape-derived loop bounds keep the direct array
// accesses below within the input and output buffers for valid tensors.
@[direct_array_access; inline]
pub fn (t &Tensor[T]) cumprod[T](axis int) !&Tensor[T] {
shape := t.shape
rank := shape.len
if rank == 0 {
return error('cumprod: tensor has no dimensions')
}
mut na := axis
if axis < 0 {
na = axis + rank
}
if na < 0 || na >= rank {
return error('cumprod: axis ${axis} out of bounds for shape ${shape}')
}
if t.strides.len != rank || t.size != size_from_shape(shape) {
return error('cumprod: inconsistent tensor shape, strides, or size')
}
mut strides := []int{len: rank}
strides[rank - 1] = 1
for i := rank - 2; i >= 0; i-- {
strides[i] = strides[i + 1] * shape[i + 1]
}
axis_stride := strides[na]
n_axis := shape[na]
mut result := zeros[T](shape)
if result.size == 0 {
return result
}
input_is_contiguous := t.is_row_major_contiguous()
if input_is_contiguous && t.data.data.len < t.size {
return error('cumprod: contiguous tensor storage is shorter than its size')
}
mut outer_idx := []int{len: rank}
for {
mut base_lin := 0
for i := 0; i < rank; i++ {
base_lin += outer_idx[i] * strides[i]
}
$if T is bool {
mut acc := true
for j := 0; j < n_axis; j++ {
lin := base_lin + j * axis_stride
value := if input_is_contiguous { t.data.data[lin] } else { t.get_nth(lin) }
acc = acc && value
result.data.data[lin] = acc
}
} $else $if T is string {
// cumprod on string is not meaningful; return zeros (empty strings)
_ = n_axis
} $else {
mut acc := cast[T](1)
for j := 0; j < n_axis; j++ {
lin := base_lin + j * axis_stride
value := if input_is_contiguous { t.data.data[lin] } else { t.get_nth(lin) }
acc = acc * value
result.data.data[lin] = acc
}
}
mut done := true
for i := rank - 1; i >= 0; i-- {
if i == na {
continue
}
outer_idx[i]++
if outer_idx[i] < shape[i] {
done = false
break
}
outer_idx[i] = 0
}
if done {
break
}
}
return result
}
// cumsum_as computes a cumulative sum using an explicitly selected output
// accumulator type. This is useful when the input type has insufficient
// precision or range for the running total.
pub fn (t &Tensor[T]) cumsum_as[U](axis int) !&Tensor[U] {
shape := t.shape
rank := shape.len
if rank == 0 {
return error('cumsum_as: tensor has no dimensions')
}
na := if axis < 0 { axis + rank } else { axis }
if na < 0 || na >= rank {