Repository navigation
Expand file tree
/
Copy pathDirectILKernelGenerator.Reduction.Axis.Simd.cs
More file actions
1985 lines (1839 loc) · 102 KB
/
Copy pathDirectILKernelGenerator.Reduction.Axis.Simd.cs
File metadata and controls
1985 lines (1839 loc) · 102 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
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using NumSharp.Utilities;
// =============================================================================
// DirectILKernelGenerator.Reduction.Axis.Simd.cs - SIMD Axis Reduction Kernels
// =============================================================================
//
// RESPONSIBILITY:
// - CreateAxisReductionKernelTyped<T> - typed SIMD kernel
// - AxisReductionSimdHelper<T> - main SIMD helper
// - ReduceContiguousAxis variants (SIMD256, SIMD128, scalar)
// - ReduceStridedAxis with AVX2 gather for float/double
// - Vector identity/combine/horizontal helpers
// - SIMD helper methods for DefaultEngine
//
// =============================================================================
namespace NumSharp.Backends.Kernels
{
public static partial class DirectILKernelGenerator
{
#region Typed SIMD Axis Reduction
private static unsafe AxisReductionKernel CreateAxisReductionKernelTyped<T>(AxisReductionKernelKey key)
where T : unmanaged
{
return (void* input, void* output, long* inputStrides, long* inputShape,
long* outputStrides, int axis, long axisSize, int ndim, long outputSize) =>
{
AxisReductionSimdHelper<T>(
(T*)input, (T*)output,
inputStrides, inputShape, outputStrides,
axis, axisSize, ndim, outputSize,
key.Op);
};
}
/// <summary>
/// SIMD helper for axis reduction operations.
/// Reduces along a specific axis, writing results to output array.
/// </summary>
/// <typeparam name="T">Element type</typeparam>
/// <param name="input">Input data pointer</param>
/// <param name="output">Output data pointer</param>
/// <param name="inputStrides">Input strides (element units)</param>
/// <param name="inputShape">Input shape</param>
/// <param name="outputStrides">Output strides (element units)</param>
/// <param name="axis">Axis to reduce along</param>
/// <param name="axisSize">Size of the axis being reduced</param>
/// <param name="ndim">Number of input dimensions</param>
/// <param name="outputSize">Total number of output elements</param>
/// <param name="op">Reduction operation</param>
internal static unsafe void AxisReductionSimdHelper<T>(
T* input, T* output,
long* inputStrides, long* inputShape, long* outputStrides,
int axis, long axisSize, int ndim, long outputSize,
ReductionOp op)
where T : unmanaged
{
long axisStride = inputStrides[axis];
// ─────────────────────────────────────────────────────────────────
// FAST PATH — leading-axis on C-contiguous input.
//
// For C-contig input with axis < ndim-1, the inner slab
// (dims axis+1..ndim-1) is contiguous, and the axis stride equals
// innerSize. We walk axis rows sequentially and SIMD-elementwise-
// reduce each row into the output slab — output stays hot in cache,
// input streams sequentially. This is the NumPy reduction pattern
// and turns axis=0 from O(out × stridedGather) into O(in_bytes).
// For axis = ndim-1 (innermost) the existing per-output contig
// SIMD reduce is optimal; we don't take this path.
// ─────────────────────────────────────────────────────────────────
if (axis < ndim - 1 && IsCContig(inputStrides, inputShape, ndim))
{
long innerSize = 1;
for (int d = axis + 1; d < ndim; d++) innerSize *= inputShape[d];
long outerSize = 1;
for (int d = 0; d < axis; d++) outerSize *= inputShape[d];
ReductionOp innerOp = op == ReductionOp.Mean ? ReductionOp.Sum : op;
DispatchLeading<T>(input, output, outerSize, axisSize, innerSize, innerOp);
if (op == ReductionOp.Mean)
DivideArrayByCount<T>(output, outerSize * innerSize, axisSize);
return;
}
// ─────────────────────────────────────────────────────────────────
// FAST PATH — innermost-axis on C-contiguous input.
//
// axis == ndim-1 and the array is C-contig: each output reduces a
// single contiguous run of axisSize elements. Walk outputs sequentially
// and call the typed per-row reducer (struct-generic op tag → JIT
// inlines the SIMD intrinsic with no per-output runtime switch).
// ─────────────────────────────────────────────────────────────────
if (axis == ndim - 1 && IsCContig(inputStrides, inputShape, ndim))
{
ReductionOp innerOp = op == ReductionOp.Mean ? ReductionOp.Sum : op;
DispatchInnermost<T>(input, output, outputSize, axisSize, innerOp);
if (op == ReductionOp.Mean)
DivideArrayByCount<T>(output, outputSize, axisSize);
return;
}
// ─────────────────────────────────────────────────────────────────
// FAST PATH — axis=0 with INNER SLAB C-contig (covers sliced inputs
// like a[::2,:], a[::-1,:], a[100:900, 100:900]). The slab traversal
// is identical to the C-contig leading-axis case, but axis-row spacing
// uses the natural axis stride (could be != innerSize for sliced inputs,
// could be negative for reversed views). Output is shape (inner...,)
// which is freshly allocated C-contig — matches the slab layout.
// ─────────────────────────────────────────────────────────────────
if (axis == 0 && ndim >= 2 && IsInnerSlabCContig(inputStrides, inputShape, 0, ndim))
{
long innerSize = 1;
for (int d = 1; d < ndim; d++) innerSize *= inputShape[d];
long axisStrideEl = inputStrides[0];
ReductionOp innerOp = op == ReductionOp.Mean ? ReductionOp.Sum : op;
DispatchLeadingStrided<T>(input, output, axisSize, innerSize, axisStrideEl, innerOp);
if (op == ReductionOp.Mean)
DivideArrayByCount<T>(output, innerSize, axisSize);
return;
}
// ─────────────────────────────────────────────────────────────────
// FAST PATH — F-contig leading-axis (axis == ndim-1 on F-contig).
//
// For F-contig input, axis=ndim-1 has the LARGEST stride (analogous
// to axis=0 on C-contig). The slab below it (axes 0..ndim-2) is
// contiguous (it's just F-contig of size prod(shape[0..ndim-2])).
// Same memory access pattern as the C-contig leading-axis case:
// walk the axis row-by-row, SIMD-fold each into the output buffer.
//
// Output is 1D (or higher with F-contig layout — the output buffer
// happens to be C-contig but for a 1D output that's identical).
// For higher-rank F-contig with non-innermost axis the slab/output
// layouts mismatch, so we restrict to the common case.
// ─────────────────────────────────────────────────────────────────
if (axis == ndim - 1 && ndim == 2 && IsFContig(inputStrides, inputShape, ndim))
{
long innerSize = inputShape[0]; // the contig slab (axis 0)
long outerSize = 1; // no outer dims
ReductionOp innerOp = op == ReductionOp.Mean ? ReductionOp.Sum : op;
DispatchLeading<T>(input, output, outerSize, axisSize, innerSize, innerOp);
if (op == ReductionOp.Mean)
DivideArrayByCount<T>(output, innerSize, axisSize);
return;
}
// ─────────────────────────────────────────────────────────────────
// FAST PATH — F-contig innermost-axis (axis == 0 on F-contig).
//
// For F-contig axis=0, each output reduces a contiguous run of
// axisSize elements (stride 1). Same pattern as C-contig innermost
// — route through the same typed kernel. Output is 1D (for 2D
// input) or F-contig higher-rank; for 2D input the output is 1D
// so layout doesn't matter.
// ─────────────────────────────────────────────────────────────────
if (axis == 0 && ndim == 2 && IsFContig(inputStrides, inputShape, ndim))
{
long inner = inputShape[1]; // number of contig rows along axis=1
ReductionOp innerOp = op == ReductionOp.Mean ? ReductionOp.Sum : op;
DispatchInnermost<T>(input, output, inner, axisSize, innerOp);
if (op == ReductionOp.Mean)
DivideArrayByCount<T>(output, inner, axisSize);
return;
}
// ─────────────────────────────────────────────────────────────────
// GENERAL PATH — strided / transposed / non-contiguous inputs.
//
// REUSE_REDUCE_LOOPS (NumPy NPY_ITFLAG_REUSE_REDUCE_LOOPS shape).
//
// The previous shape re-derived each output's input base via a div/mod
// coordinate decode PER output element, then did a cache-hostile strided
// gather down the reduce axis PER output — O(outputs × stridedGather),
// which measured 9–24× slower than NumPy on strided / transposed axis
// reductions (e.g. a[:, ::2] sum axis 0, or transpose(2,0,1) sum axis 2).
//
// Instead we walk the reduce axis as the OUTER loop and FOLD each slab
// into the output buffer with an incremental odometer over the
// non-reduced dims: the input/output base pointers advance by their
// strides each step (no div/mod re-derivation — the "reduce loop" is
// reused across successive output positions), and the smallest-input-
// stride non-reduced dim is iterated innermost so the (cold, largest)
// input operand streams sequentially instead of being gathered. The
// output accumulator stays hot. This is NumPy's reduce-loop shape and
// turns the access pattern from O(outputs × stridedGather) into
// O(in_bytes) streaming.
// ─────────────────────────────────────────────────────────────────
ReductionOp innerGenOp = op == ReductionOp.Mean ? ReductionOp.Sum : op;
bool isMeanGen = op == ReductionOp.Mean;
// Strategy selection (NumPy iterates the smallest-stride axis innermost):
// • Reduction axis is NOT the innermost memory axis (some non-reduced
// dim has a smaller |stride|) → slab-accumulate: reduce axis OUTER,
// smallest-stride non-reduced dim streams innermost. Turns the access
// pattern from O(outputs × stridedGather) into O(in_bytes) streaming
// (e.g. a[:, ::2] sum axis 0, transpose(2,0,1) sum axis 2).
// • Otherwise the reduction axis IS the innermost (smallest |stride|)
// run → reduce it per-output (each run is near-local / SIMD-friendly;
// slab-accumulation would read cache-hostile columns). This path is
// kept INLINE / verbatim from the original general loop: extracting it
// to a separate method regressed the typeof(T) gather/scalar inner-
// reducer codegen for double/int64 (~3–5× on strided innermost sum).
long minNonReduced = long.MaxValue;
for (int d = 0; d < ndim; d++)
{
if (d == axis) continue;
long s = inputStrides[d]; if (s < 0) s = -s;
if (s < minNonReduced) minNonReduced = s;
}
long axisAbsStride = axisStride < 0 ? -axisStride : axisStride;
if (axisAbsStride > minNonReduced)
{
DispatchSlabAccumulate<T>(
input, output, inputStrides, inputShape, outputStrides,
axis, axisSize, ndim, outputSize, innerGenOp, isMeanGen);
return;
}
// ── Per-output reduction (reduction axis is the innermost run). ──
bool axisContiguous = axisStride == 1;
int outputNdim = ndim - 1;
long[] outputDimStridesArray = new long[outputNdim > 0 ? outputNdim : 1];
if (outputNdim > 0)
{
outputDimStridesArray[outputNdim - 1] = 1;
for (int d = outputNdim - 2; d >= 0; d--)
{
int nextInputDim = (d + 1) >= axis ? d + 2 : d + 1;
outputDimStridesArray[d] = outputDimStridesArray[d + 1] * inputShape[nextInputDim];
}
}
ReductionOp actualOp = innerGenOp;
bool isMean = isMeanGen;
for (long outIdx = 0; outIdx < outputSize; outIdx++)
{
long remaining = outIdx;
long inputBaseOffset = 0;
long outputOffset = 0;
for (int d = 0; d < outputNdim; d++)
{
int inputDim = d >= axis ? d + 1 : d;
long coord = remaining / outputDimStridesArray[d];
remaining = remaining % outputDimStridesArray[d];
inputBaseOffset += coord * inputStrides[inputDim];
outputOffset += coord * outputStrides[d];
}
T* axisStart = input + inputBaseOffset;
T result = axisContiguous
? ReduceContiguousAxis(axisStart, axisSize, actualOp)
: ReduceStridedAxis(axisStart, axisSize, axisStride, actualOp);
if (isMean)
result = DivideByCountTyped(result, axisSize);
output[outputOffset] = result;
}
}
// Per-op dispatch into the slab-accumulation general reduction. The runtime
// branch on `op` happens ONCE here, routing to a kernel with the op
// hard-coded via the zero-sized ITypedReductionOp struct (JIT inlines the
// combine with no per-element switch).
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static unsafe void DispatchSlabAccumulate<T>(
T* input, T* output, long* inputStrides, long* inputShape, long* outputStrides,
int axis, long axisSize, int ndim, long outputSize, ReductionOp op, bool isMean)
where T : unmanaged
{
switch (op)
{
case ReductionOp.Sum: AxisReductionSlabAccumulate<T, AddOp<T>>(input, output, inputStrides, inputShape, outputStrides, axis, axisSize, ndim, outputSize, isMean); return;
case ReductionOp.Prod: AxisReductionSlabAccumulate<T, MulOp<T>>(input, output, inputStrides, inputShape, outputStrides, axis, axisSize, ndim, outputSize, isMean); return;
case ReductionOp.Min: AxisReductionSlabAccumulate<T, MinOp<T>>(input, output, inputStrides, inputShape, outputStrides, axis, axisSize, ndim, outputSize, isMean); return;
case ReductionOp.Max: AxisReductionSlabAccumulate<T, MaxOp<T>>(input, output, inputStrides, inputShape, outputStrides, axis, axisSize, ndim, outputSize, isMean); return;
default: throw new NotSupportedException($"DispatchSlabAccumulate: {op}");
}
}
// REUSE_REDUCE_LOOPS slab-accumulation reduction for the general
// (strided / transposed / non-contiguous) axis-reduction path.
//
// Reduces along `axis` by iterating the reduce axis as the outer loop and
// folding slab k into the output: slab 0 initializes the output, slabs
// 1..axisSize-1 combine into it (op-struct → JIT-inlined add/mul/min/max,
// NaN-propagating for float min/max via Math.Min/Max). The non-reduced dims
// are walked with an incremental odometer (base offsets advance by their
// strides — no per-output div/mod), ordered so the smallest-input-stride
// dim is innermost so input reads stream sequentially.
//
// Combination order along the axis is sequential (slab 0,1,2,…), matching
// the per-output ordering this path replaces for integer/min/max (exact)
// and NumPy's buffered strided reduce inner loop for float sum/prod.
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static unsafe void AxisReductionSlabAccumulate<T, TOp>(
T* input, T* output,
long* inputStrides, long* inputShape, long* outputStrides,
int axis, long axisSize, int ndim, long outputSize, bool isMean)
where T : unmanaged
where TOp : struct, ITypedReductionOp<T>
{
TOp op = default;
long axisStride = inputStrides[axis];
int K = ndim - 1; // number of non-reduced (output) dims
// ── Scalar output (ndim==1, reduce the only axis) ──
if (K <= 0)
{
T acc0 = op.Identity();
if (axisSize > 0)
{
acc0 = input[0];
for (long k = 1; k < axisSize; k++)
acc0 = op.CombineScalar(acc0, input[k * axisStride]);
}
output[0] = isMean ? DivideByCountTyped(acc0, axisSize) : acc0;
return;
}
// ── Gather non-reduced dims (size, input stride, output stride) ──
long* dSize = stackalloc long[K];
long* dIn = stackalloc long[K];
long* dOut = stackalloc long[K];
int m = 0;
for (int d = 0; d < ndim; d++)
{
if (d == axis) continue;
dSize[m] = inputShape[d];
dIn[m] = inputStrides[d];
dOut[m] = outputStrides[d < axis ? d : d - 1];
m++;
}
// ── Order dims so the smallest |input stride| is innermost (sequential
// input streaming). Insertion sort by input stride DESC. ──
for (int i = 1; i < K; i++)
{
long s = dSize[i], a = dIn[i], o = dOut[i];
int j = i - 1;
while (j >= 0 && dIn[j] < a)
{
dSize[j + 1] = dSize[j]; dIn[j + 1] = dIn[j]; dOut[j + 1] = dOut[j];
j--;
}
dSize[j + 1] = s; dIn[j + 1] = a; dOut[j + 1] = o;
}
long* idx = stackalloc long[K];
int inner = K - 1;
long innerSize = dSize[inner];
long innerIn = dIn[inner];
long innerOut = dOut[inner];
// ── Empty reduce axis: every output is the identity element. ──
if (axisSize == 0)
{
T ident = op.Identity();
for (int d = 0; d < K; d++) idx[d] = 0;
long off0 = 0;
for (long o = 0; o < outputSize; o++)
{
output[off0] = isMean ? DivideByCountTyped(ident, axisSize) : ident;
AdvanceOdometer(idx, dSize, dOut, K, ref off0);
}
return;
}
// ── Fold slabs: k==0 initializes, k>=1 combines. ──
for (long k = 0; k < axisSize; k++)
{
T* slab = input + k * axisStride;
for (int d = 0; d < K; d++) idx[d] = 0;
long inOff = 0, outOff = 0;
if (k == 0)
{
for (long o = 0; o < outputSize; )
{
// Innermost run: contiguous-output init.
long count = innerSize - idx[inner];
if (innerOut == 1)
for (long e = 0; e < count; e++) output[outOff + e] = slab[inOff + e * innerIn];
else
for (long e = 0; e < count; e++) output[outOff + e * innerOut] = slab[inOff + e * innerIn];
o += count; idx[inner] = innerSize;
inOff += count * innerIn; outOff += count * innerOut;
CarryOdometer(idx, dSize, dIn, dOut, K, ref inOff, ref outOff);
}
}
else
{
for (long o = 0; o < outputSize; )
{
long count = innerSize - idx[inner];
if (innerOut == 1)
for (long e = 0; e < count; e++) output[outOff + e] = op.CombineScalar(output[outOff + e], slab[inOff + e * innerIn]);
else
for (long e = 0; e < count; e++) output[outOff + e * innerOut] = op.CombineScalar(output[outOff + e * innerOut], slab[inOff + e * innerIn]);
o += count; idx[inner] = innerSize;
inOff += count * innerIn; outOff += count * innerOut;
CarryOdometer(idx, dSize, dIn, dOut, K, ref inOff, ref outOff);
}
}
}
// ── Mean: divide each output by the reduce count (respects output stride). ──
if (isMean)
{
for (int d = 0; d < K; d++) idx[d] = 0;
long off = 0;
for (long o = 0; o < outputSize; o++)
{
output[off] = DivideByCountTyped(output[off], axisSize);
AdvanceOdometer(idx, dSize, dOut, K, ref off);
}
}
}
// Advance a single-offset odometer (innermost dim K-1) by one step.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static unsafe void AdvanceOdometer(long* idx, long* dSize, long* dStride, int K, ref long off)
{
for (int d = K - 1; d >= 0; d--)
{
idx[d]++; off += dStride[d];
if (idx[d] < dSize[d]) return;
idx[d] = 0; off -= dSize[d] * dStride[d];
}
}
// After consuming a full innermost run (idx[K-1] == dSize[K-1]), carry into
// the outer dims, advancing both input and output offsets incrementally.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static unsafe void CarryOdometer(long* idx, long* dSize, long* dIn, long* dOut, int K, ref long inOff, ref long outOff)
{
// innermost just wrapped: reset it and carry.
idx[K - 1] = 0;
inOff -= dSize[K - 1] * dIn[K - 1];
outOff -= dSize[K - 1] * dOut[K - 1];
for (int d = K - 2; d >= 0; d--)
{
idx[d]++; inOff += dIn[d]; outOff += dOut[d];
if (idx[d] < dSize[d]) return;
idx[d] = 0; inOff -= dSize[d] * dIn[d]; outOff -= dSize[d] * dOut[d];
}
}
/// <summary>
/// Divide a typed value by count (for Mean operation in SIMD path).
/// </summary>
private static T DivideByCountTyped<T>(T value, long count) where T : unmanaged
{
if (typeof(T) == typeof(float))
{
float result = (float)(object)value / count;
return (T)(object)result;
}
if (typeof(T) == typeof(double))
{
double result = (double)(object)value / count;
return (T)(object)result;
}
if (typeof(T) == typeof(int))
{
// Integer division
int result = (int)((int)(object)value / count);
return (T)(object)result;
}
if (typeof(T) == typeof(long))
{
long result = (long)(object)value / count;
return (T)(object)result;
}
if (typeof(T) == typeof(byte))
{
byte result = (byte)((byte)(object)value / count);
return (T)(object)result;
}
if (typeof(T) == typeof(short))
{
short result = (short)((short)(object)value / count);
return (T)(object)result;
}
if (typeof(T) == typeof(ushort))
{
ushort result = (ushort)((ushort)(object)value / count);
return (T)(object)result;
}
if (typeof(T) == typeof(uint))
{
uint result = (uint)(object)value / (uint)count;
return (T)(object)result;
}
if (typeof(T) == typeof(ulong))
{
ulong result = (ulong)(object)value / (ulong)count;
return (T)(object)result;
}
// Fallback via double
double dval = ConvertToDouble(value);
return ConvertFromDouble<T>(dval / count);
}
/// <summary>
/// Reduce a contiguous axis using SIMD.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static unsafe T ReduceContiguousAxis<T>(T* data, long size, ReductionOp op)
where T : unmanaged
{
if (size == 0)
{
return GetIdentityValue<T>(op);
}
if (size == 1)
{
return data[0];
}
// Use SIMD for Sum, Prod, Min, Max
if (Vector256.IsHardwareAccelerated && Vector256<T>.IsSupported && size >= Vector256<T>.Count)
{
return ReduceContiguousAxisSimd256(data, size, op);
}
else if (Vector128.IsHardwareAccelerated && Vector128<T>.IsSupported && size >= Vector128<T>.Count)
{
return ReduceContiguousAxisSimd128(data, size, op);
}
else
{
return ReduceContiguousAxisScalar(data, size, op);
}
}
/// <summary>
/// Reduce contiguous axis using Vector256 SIMD with 4x unrolling.
/// Uses 4 independent accumulators to break dependency chains.
/// </summary>
[MethodImpl(OptimizeAndInline)]
private static unsafe T ReduceContiguousAxisSimd256<T>(T* data, long size, ReductionOp op)
where T : unmanaged
{
int vectorCount = Vector256<T>.Count;
long vectorEnd = size - vectorCount;
// Initialize 4 independent accumulators for loop unrolling
var acc0 = CreateIdentityVector256<T>(op);
var acc1 = CreateIdentityVector256<T>(op);
var acc2 = CreateIdentityVector256<T>(op);
var acc3 = CreateIdentityVector256<T>(op);
long unrollStep = vectorCount * 4;
long unrollEnd = size - unrollStep;
long i = 0;
// 4x unrolled loop - process 4 vectors per iteration
for (; i <= unrollEnd; i += unrollStep)
{
var v0 = Vector256.Load(data + i);
var v1 = Vector256.Load(data + i + vectorCount);
var v2 = Vector256.Load(data + i + vectorCount * 2);
var v3 = Vector256.Load(data + i + vectorCount * 3);
acc0 = CombineVectors256(acc0, v0, op);
acc1 = CombineVectors256(acc1, v1, op);
acc2 = CombineVectors256(acc2, v2, op);
acc3 = CombineVectors256(acc3, v3, op);
}
// Tree reduction: 4 -> 2 -> 1
var acc01 = CombineVectors256(acc0, acc1, op);
var acc23 = CombineVectors256(acc2, acc3, op);
var accumVec = CombineVectors256(acc01, acc23, op);
// Remainder loop (0-3 vectors)
for (; i <= vectorEnd; i += vectorCount)
{
var vec = Vector256.Load(data + i);
accumVec = CombineVectors256(accumVec, vec, op);
}
// Horizontal reduce the vector
T result = HorizontalReduce256(accumVec, op);
// Process scalar tail
for (; i < size; i++)
{
result = CombineScalars(result, data[i], op);
}
return result;
}
/// <summary>
/// Reduce contiguous axis using Vector128 SIMD with 4x unrolling.
/// Uses 4 independent accumulators to break dependency chains.
/// </summary>
[MethodImpl(OptimizeAndInline)]
private static unsafe T ReduceContiguousAxisSimd128<T>(T* data, long size, ReductionOp op)
where T : unmanaged
{
int vectorCount = Vector128<T>.Count;
long vectorEnd = size - vectorCount;
// Initialize 4 independent accumulators for loop unrolling
var acc0 = CreateIdentityVector128<T>(op);
var acc1 = CreateIdentityVector128<T>(op);
var acc2 = CreateIdentityVector128<T>(op);
var acc3 = CreateIdentityVector128<T>(op);
long unrollStep = vectorCount * 4;
long unrollEnd = size - unrollStep;
long i = 0;
// 4x unrolled loop - process 4 vectors per iteration
for (; i <= unrollEnd; i += unrollStep)
{
var v0 = Vector128.Load(data + i);
var v1 = Vector128.Load(data + i + vectorCount);
var v2 = Vector128.Load(data + i + vectorCount * 2);
var v3 = Vector128.Load(data + i + vectorCount * 3);
acc0 = CombineVectors128(acc0, v0, op);
acc1 = CombineVectors128(acc1, v1, op);
acc2 = CombineVectors128(acc2, v2, op);
acc3 = CombineVectors128(acc3, v3, op);
}
// Tree reduction: 4 -> 2 -> 1
var acc01 = CombineVectors128(acc0, acc1, op);
var acc23 = CombineVectors128(acc2, acc3, op);
var accumVec = CombineVectors128(acc01, acc23, op);
// Remainder loop (0-3 vectors)
for (; i <= vectorEnd; i += vectorCount)
{
var vec = Vector128.Load(data + i);
accumVec = CombineVectors128(accumVec, vec, op);
}
// Horizontal reduce the vector
T result = HorizontalReduce128(accumVec, op);
// Process scalar tail
for (; i < size; i++)
{
result = CombineScalars(result, data[i], op);
}
return result;
}
/// <summary>
/// Reduce contiguous axis using scalar loop.
/// </summary>
private static unsafe T ReduceContiguousAxisScalar<T>(T* data, long size, ReductionOp op)
where T : unmanaged
{
T result = GetIdentityValue<T>(op);
for (long i = 0; i < size; i++)
{
result = CombineScalars(result, data[i], op);
}
return result;
}
/// <summary>
/// Reduce a strided axis (non-contiguous).
/// Uses AVX2 gather instructions for float/double when beneficial (stride fits in int32).
/// </summary>
private static unsafe T ReduceStridedAxis<T>(T* data, long size, long stride, ReductionOp op)
where T : unmanaged
{
if (size == 0)
return GetIdentityValue<T>(op);
if (size == 1)
return data[0];
// Try AVX2 gather for float/double - provides ~2-3x speedup for strided access
// Only beneficial when we have enough elements to amortize gather overhead
// AVX2 gather requires int32 indices, so stride must fit in int32
if (Avx2.IsSupported && size >= 8 && stride <= int.MaxValue)
{
if (typeof(T) == typeof(float))
{
return (T)(object)ReduceStridedAxisGatherFloat((float*)data, size, stride, op);
}
if (typeof(T) == typeof(double))
{
return (T)(object)ReduceStridedAxisGatherDouble((double*)data, size, stride, op);
}
}
// Scalar fallback with 4x loop unrolling for better ILP
return ReduceStridedAxisScalar(data, size, stride, op);
}
/// <summary>
/// Strided reduction using AVX2 gather for float.
/// Uses Vector256 gather to load 8 floats at once from strided positions.
/// </summary>
[MethodImpl(OptimizeAndInline)]
private static unsafe float ReduceStridedAxisGatherFloat(float* data, long size, long stride, ReductionOp op)
{
// Create index vector: [0, stride, 2*stride, ..., 7*stride]
// Note: AVX2 gather requires int32 indices, so stride must fit in int32
int strideInt = (int)stride;
var indices = Vector256.Create(
0, strideInt, strideInt * 2, strideInt * 3,
strideInt * 4, strideInt * 5, strideInt * 6, strideInt * 7);
int vectorCount = 8; // Vector256<float>.Count
long vectorEnd = size - vectorCount;
var accum = CreateIdentityVector256<float>(op);
long i = 0;
// Main gather loop - process 8 elements per iteration
for (; i <= vectorEnd; i += vectorCount)
{
// GatherVector256: load data[indices[j]] for j in 0..7
// Scale = 4 because float is 4 bytes
var gathered = Avx2.GatherVector256(data + i * stride, indices, 4);
accum = CombineVectors256(accum, gathered, op);
}
// Horizontal reduce the vector
float result = HorizontalReduce256(accum, op);
// Process remaining elements with scalar loop
for (; i < size; i++)
{
result = CombineScalars(result, data[i * stride], op);
}
return result;
}
/// <summary>
/// Strided reduction using AVX2 gather for double.
/// Uses Vector256 gather to load 4 doubles at once from strided positions.
/// </summary>
[MethodImpl(OptimizeAndInline)]
private static unsafe double ReduceStridedAxisGatherDouble(double* data, long size, long stride, ReductionOp op)
{
// Create index vector: [0, stride, 2*stride, 3*stride]
// Note: AVX2 gather requires int32 indices, so stride must fit in int32
int strideInt = (int)stride;
var indices = Vector128.Create(0, strideInt, strideInt * 2, strideInt * 3);
int vectorCount = 4; // Vector256<double>.Count
long vectorEnd = size - vectorCount;
var accum = CreateIdentityVector256<double>(op);
long i = 0;
// Main gather loop - process 4 elements per iteration
for (; i <= vectorEnd; i += vectorCount)
{
// GatherVector256: load data[indices[j]] for j in 0..3
// Scale = 8 because double is 8 bytes
var gathered = Avx2.GatherVector256(data + i * stride, indices, 8);
accum = CombineVectors256(accum, gathered, op);
}
// Horizontal reduce the vector
double result = HorizontalReduce256(accum, op);
// Process remaining elements with scalar loop
for (; i < size; i++)
{
result = CombineScalars(result, data[i * stride], op);
}
return result;
}
/// <summary>
/// Scalar strided reduction with 4x loop unrolling.
/// </summary>
private static unsafe T ReduceStridedAxisScalar<T>(T* data, long size, long stride, ReductionOp op)
where T : unmanaged
{
T result = GetIdentityValue<T>(op);
// 4x unrolled loop for better instruction-level parallelism
long unrollEnd = size - 4;
long i = 0;
for (; i <= unrollEnd; i += 4)
{
T v0 = data[i * stride];
T v1 = data[(i + 1) * stride];
T v2 = data[(i + 2) * stride];
T v3 = data[(i + 3) * stride];
result = CombineScalars(result, v0, op);
result = CombineScalars(result, v1, op);
result = CombineScalars(result, v2, op);
result = CombineScalars(result, v3, op);
}
// Handle remaining elements
for (; i < size; i++)
{
result = CombineScalars(result, data[i * stride], op);
}
return result;
}
/// <summary>
/// Get the identity value for a reduction operation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static T GetIdentityValue<T>(ReductionOp op) where T : unmanaged
{
if (typeof(T) == typeof(float))
{
float val = op switch
{
ReductionOp.Sum => 0f,
ReductionOp.Prod => 1f,
ReductionOp.Min => float.PositiveInfinity,
ReductionOp.Max => float.NegativeInfinity,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(double))
{
double val = op switch
{
ReductionOp.Sum => 0.0,
ReductionOp.Prod => 1.0,
ReductionOp.Min => double.PositiveInfinity,
ReductionOp.Max => double.NegativeInfinity,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(int))
{
int val = op switch
{
ReductionOp.Sum => 0,
ReductionOp.Prod => 1,
ReductionOp.Min => int.MaxValue,
ReductionOp.Max => int.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(long))
{
long val = op switch
{
ReductionOp.Sum => 0L,
ReductionOp.Prod => 1L,
ReductionOp.Min => long.MaxValue,
ReductionOp.Max => long.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(byte))
{
byte val = op switch
{
ReductionOp.Sum => 0,
ReductionOp.Prod => 1,
ReductionOp.Min => byte.MaxValue,
ReductionOp.Max => byte.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
// B5: Add SByte identity values for axis reductions.
if (typeof(T) == typeof(sbyte))
{
sbyte val = op switch
{
ReductionOp.Sum => (sbyte)0,
ReductionOp.Prod => (sbyte)1,
ReductionOp.Min => sbyte.MaxValue,
ReductionOp.Max => sbyte.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(short))
{
short val = op switch
{
ReductionOp.Sum => 0,
ReductionOp.Prod => 1,
ReductionOp.Min => short.MaxValue,
ReductionOp.Max => short.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(ushort))
{
ushort val = op switch
{
ReductionOp.Sum => 0,
ReductionOp.Prod => 1,
ReductionOp.Min => ushort.MaxValue,
ReductionOp.Max => ushort.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(uint))
{
uint val = op switch
{
ReductionOp.Sum => 0u,
ReductionOp.Prod => 1u,
ReductionOp.Min => uint.MaxValue,
ReductionOp.Max => uint.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
if (typeof(T) == typeof(ulong))
{
ulong val = op switch
{
ReductionOp.Sum => 0UL,
ReductionOp.Prod => 1UL,
ReductionOp.Min => ulong.MaxValue,
ReductionOp.Max => ulong.MinValue,
_ => throw new NotSupportedException()
};
return (T)(object)val;
}
throw new NotSupportedException($"Type {typeof(T)} not supported for axis reduction");
}
/// <summary>
/// Create identity Vector256 for reduction operation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static Vector256<T> CreateIdentityVector256<T>(ReductionOp op) where T : unmanaged
{
T identity = GetIdentityValue<T>(op);
return Vector256.Create(identity);
}
/// <summary>
/// Create identity Vector128 for reduction operation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static Vector128<T> CreateIdentityVector128<T>(ReductionOp op) where T : unmanaged
{
T identity = GetIdentityValue<T>(op);
return Vector128.Create(identity);
}
/// <summary>
/// Combine two Vector256 values using reduction operation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static Vector256<T> CombineVectors256<T>(Vector256<T> a, Vector256<T> b, ReductionOp op)
where T : unmanaged
{
return op switch
{
ReductionOp.Sum => Vector256.Add(a, b),
ReductionOp.Prod => Vector256.Multiply(a, b),
ReductionOp.Min => NaNAwareMinMax256(a, b, isMax: false),
ReductionOp.Max => NaNAwareMinMax256(a, b, isMax: true),
_ => throw new NotSupportedException()
};
}