Repository navigation
Expand file tree
/
Copy pathDirectILKernelGenerator.Reduction.cs
More file actions
1767 lines (1560 loc) · 72.8 KB
/
Copy pathDirectILKernelGenerator.Reduction.cs
File metadata and controls
1767 lines (1560 loc) · 72.8 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.Intrinsics;
// =============================================================================
// DirectILKernelGenerator.Reduction.cs - Element-wise Reduction Kernels
// =============================================================================
//
// RESPONSIBILITY:
// - Element-wise reduction kernel generation (Sum, Prod, Min, Max, Mean)
// - SIMD loop emission with 4x unrolling
// - Scalar and strided fallback loops
// - Shared IL emission helpers for reduction operations
//
// RELATED FILES:
// - DirectILKernelGenerator.Reduction.Boolean.cs - All/Any with early-exit
// - DirectILKernelGenerator.Reduction.Arg.cs - ArgMax/ArgMin
// - DirectILKernelGenerator.Reduction.Axis.cs - Axis reductions
// - DirectILKernelGenerator.Masking.cs - NonZero and boolean masking
//
// =============================================================================
namespace NumSharp.Backends.Kernels
{
public static partial class DirectILKernelGenerator
{
#region Element Reduction Kernel Generation
/// <summary>
/// Cache for element-wise reduction kernels.
/// Key: ElementReductionKernelKey
/// </summary>
internal static readonly ConcurrentDictionary<ElementReductionKernelKey, Delegate> _elementReductionCache = new();
/// <summary>
/// Get or generate a typed element-wise reduction kernel.
/// Returns a delegate that reduces all elements to a single value of type TResult.
/// </summary>
public static TypedElementReductionKernel<TResult> GetTypedElementReductionKernel<TResult>(ElementReductionKernelKey key)
where TResult : unmanaged
{
if (!Enabled)
throw new InvalidOperationException("IL generation is disabled");
var kernel = _elementReductionCache.GetOrAdd(key, GenerateTypedElementReductionKernel<TResult>);
return (TypedElementReductionKernel<TResult>)kernel;
}
/// <summary>
/// Try to get or generate an element reduction kernel.
/// </summary>
public static TypedElementReductionKernel<TResult>? TryGetTypedElementReductionKernel<TResult>(ElementReductionKernelKey key)
where TResult : unmanaged
{
if (!Enabled)
return null;
try
{
var kernel = _elementReductionCache.GetOrAdd(key, GenerateTypedElementReductionKernel<TResult>);
return (TypedElementReductionKernel<TResult>)kernel;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[ILKernel] TryGetTypedElementReductionKernel<{typeof(TResult).Name}>({key}): {ex.GetType().Name}: {ex.Message}");
return null;
}
}
/// <summary>
/// Generate a typed element-wise reduction kernel.
/// </summary>
private static Delegate GenerateTypedElementReductionKernel<TResult>(ElementReductionKernelKey key)
where TResult : unmanaged
{
// TypedElementReductionKernel<TResult> signature:
// TResult(void* input, long* strides, long* shape, int ndim, long totalSize)
var dm = new DynamicMethod(
name: $"ElemReduce_{key}",
returnType: typeof(TResult),
parameterTypes: new[]
{
typeof(void*), typeof(long*), typeof(long*), typeof(int), typeof(long)
},
owner: typeof(DirectILKernelGenerator),
skipVisibility: true
);
var il = dm.GetILGenerator();
int inputSize = GetTypeSize(key.InputType);
int accumSize = GetTypeSize(key.AccumulatorType);
if (key.IsContiguous)
{
// Check if we can use SIMD
bool canSimd = CanUseReductionSimd(key);
if (canSimd)
{
EmitReductionSimdLoop(il, key, inputSize);
}
else
{
EmitReductionScalarLoop(il, key, inputSize);
}
}
else
{
EmitReductionStridedLoop(il, key, inputSize);
}
il.Emit(OpCodes.Ret);
return dm.CreateDelegate<TypedElementReductionKernel<TResult>>();
}
/// <summary>
/// Check if SIMD can be used for this reduction operation.
/// </summary>
private static bool CanUseReductionSimd(ElementReductionKernelKey key)
{
// Must be contiguous
if (!key.IsContiguous)
return false;
// SIMD for numeric types (not bool, char, decimal).
// EXCEPTION: Boolean ArgMax/ArgMin — EmitReductionSimdLoop dispatches those straight
// to ArgMaxBoolHelper/ArgMinBoolHelper (first-True / first-False block scans, no
// Vector<bool> locals involved), the analogue of NumPy's dedicated BOOL_argmax /
// memchr BOOL_argmin. Without this carve-out bool argmax fell to the scalar
// full-scan loop: 24 ms on a 10M array whose first True sits at index ~1, vs
// NumPy's 0.2 µs early exit.
if (!CanUseSimd(key.InputType))
return key.InputType == NPTypeCode.Boolean &&
(key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin);
// For Sum/Prod, SIMD vectors work on same type - can't widen int32 to int64 in SIMD
// When accumulator type differs from input type, use scalar path to prevent overflow
if ((key.Op == ReductionOp.Sum || key.Op == ReductionOp.Prod) &&
key.InputType != key.AccumulatorType)
{
return false;
}
// Only certain operations have SIMD support
// Sum: Vector.Sum() or manual horizontal add
// Max/Min: Reduce vector then scalar reduce remainder
// Prod: Manual horizontal multiply
// All/Any: SIMD comparison with early-exit
// ArgMax/ArgMin: SIMD with index tracking
return key.Op == ReductionOp.Sum || key.Op == ReductionOp.Max || key.Op == ReductionOp.Min ||
key.Op == ReductionOp.Prod || key.Op == ReductionOp.All || key.Op == ReductionOp.Any ||
key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin;
}
/// <summary>
/// Gate for the gather-SIMD section of the 1-D strided reduction:
/// mirrors the contiguous CanUseReductionSimd whitelist minus the
/// early-exit (All/Any) and index-tracking (ArgMax/ArgMin) ops, and
/// requires same-type accumulation (vectors can't widen lanes).
/// </summary>
private static bool CanUseGatherReduction(ElementReductionKernelKey key)
{
if (key.InputType != key.AccumulatorType)
return false;
if (!CanUseSimd(key.InputType))
return false;
return key.Op == ReductionOp.Sum || key.Op == ReductionOp.Max ||
key.Op == ReductionOp.Min || key.Op == ReductionOp.Prod;
}
/// <summary>
/// Emit the gather-SIMD bulk of a 1-D strided reduction. On entry
/// locI == 0, locOffset == 0 and locStride0 holds the ELEMENT stride.
/// Runtime-guards the stride against the int32 gather-index budget;
/// on success processes ⌊count/(4·lanes)⌋·4·lanes elements into 4
/// independent vector accumulators, tree-merges, horizontally reduces,
/// combines into <paramref name="locAccum"/>, and advances locI /
/// locOffset so the scalar loop that follows finishes the tail.
/// </summary>
private static void EmitGatherReductionSection(
ILGenerator il, ElementReductionKernelKey key, int inputSize,
GatherSupport g,
LocalBuilder locI, LocalBuilder locOffset, LocalBuilder locStride0,
LocalBuilder locAccum)
{
long lanes = g.Lanes;
long step = lanes * 4;
long elemStrideLimit = GatherStrideLimit / inputSize;
var lblSkip = il.DefineLabel();
var lblLoop = il.DefineLabel();
var lblLoopEnd = il.DefineLabel();
// |stride0| must fit the byte-offset index budget.
il.Emit(OpCodes.Ldloc, locStride0);
il.Emit(OpCodes.Ldc_I8, elemStrideLimit);
il.Emit(OpCodes.Bgt, lblSkip);
il.Emit(OpCodes.Ldloc, locStride0);
il.Emit(OpCodes.Ldc_I8, -elemStrideLimit);
il.Emit(OpCodes.Blt, lblSkip);
// byteStride (long for addressing, int for the index vector).
var locBS = il.DeclareLocal(typeof(long));
var locBSInt = il.DeclareLocal(typeof(int));
il.Emit(OpCodes.Ldloc, locStride0);
il.Emit(OpCodes.Ldc_I8, (long)inputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Stloc, locBS);
il.Emit(OpCodes.Conv_I4);
il.Emit(OpCodes.Stloc, locBSInt);
// idx = Create(0, bs, 2bs, …, (lanes-1)·bs)
var locIdx = il.DeclareLocal(g.IndexVectorType);
for (int k = 0; k < g.Lanes; k++)
{
if (k == 0)
{
il.Emit(OpCodes.Ldc_I4_0);
}
else if (k == 1)
{
il.Emit(OpCodes.Ldloc, locBSInt);
}
else
{
il.Emit(OpCodes.Ldloc, locBSInt);
il.Emit(OpCodes.Ldc_I4, k);
il.Emit(OpCodes.Mul);
}
}
il.Emit(OpCodes.Call, g.IndexCreate);
il.Emit(OpCodes.Stloc, locIdx);
// 4 vector accumulators = identity.
var vectorType = GetVectorType(GetClrType(key.InputType));
var locAcc = new LocalBuilder[4];
for (int k = 0; k < 4; k++)
{
locAcc[k] = il.DeclareLocal(vectorType);
EmitVectorIdentity(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[k]);
}
// gatherEnd = totalSize - step
var locGatherEnd = il.DeclareLocal(typeof(long));
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.Emit(OpCodes.Ldc_I8, step);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Stloc, locGatherEnd);
il.MarkLabel(lblLoop);
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldloc, locGatherEnd);
il.Emit(OpCodes.Bgt, lblLoopEnd);
for (int k = 0; k < 4; k++)
{
// acc[k] = acc[k] OP gather(input + (i + k·lanes) · byteStride)
il.Emit(OpCodes.Ldloc, locAcc[k]);
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldloc, locI);
if (k != 0)
{
il.Emit(OpCodes.Ldc_I8, lanes * k);
il.Emit(OpCodes.Add);
}
il.Emit(OpCodes.Ldloc, locBS);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldloc, locIdx);
il.Emit(OpCodes.Ldc_I4_1); // scale = 1 (byte offsets)
il.Emit(OpCodes.Call, g.Gather);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[k]);
}
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, step);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locI);
il.Emit(OpCodes.Br, lblLoop);
il.MarkLabel(lblLoopEnd);
// Tree-merge 4 → 2 → 1, horizontal-reduce, fold into locAccum.
il.Emit(OpCodes.Ldloc, locAcc[0]);
il.Emit(OpCodes.Ldloc, locAcc[1]);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[0]);
il.Emit(OpCodes.Ldloc, locAcc[2]);
il.Emit(OpCodes.Ldloc, locAcc[3]);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[2]);
il.Emit(OpCodes.Ldloc, locAcc[0]);
il.Emit(OpCodes.Ldloc, locAcc[2]);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
EmitVectorHorizontalReduction(il, key.Op, key.InputType);
// Stack: [horizontal]; combine into the scalar accumulator the
// same way the scalar loop does ([value, accum] → combine).
il.Emit(OpCodes.Ldloc, locAccum);
EmitReductionCombine(il, key.Op, key.AccumulatorType);
il.Emit(OpCodes.Stloc, locAccum);
// offset = i * stride0 — position the scalar tail loop.
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldloc, locStride0);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Stloc, locOffset);
il.MarkLabel(lblSkip);
}
/// <summary>
/// Per-accumulator load+combine emit for the 8x unrolled SIMD reduction body.
/// Stack before: empty
/// Stack after: empty (the result is stored back to locAcc)
/// IL emitted (inline):
/// locAcc = locAcc OP Vector.Load(input + (i + offsetInVectorCounts) * inputSize)
/// </summary>
private static void EmitAccumLoadCombine(
ILGenerator il, ElementReductionKernelKey key,
LocalBuilder locAcc, LocalBuilder locI, int inputSize, long offsetInElements)
{
il.Emit(OpCodes.Ldloc, locAcc);
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldloc, locI);
if (offsetInElements != 0)
{
il.Emit(OpCodes.Ldc_I8, offsetInElements);
il.Emit(OpCodes.Add);
}
il.Emit(OpCodes.Ldc_I8, (long)inputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
EmitVectorLoad(il, key.InputType);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc);
}
/// <summary>
/// Emit a SIMD reduction loop for contiguous arrays with 8x unrolling.
/// Uses 8 independent vector accumulators to break dependency chains
/// across the FP add/mul pipeline (3-4 cycle latency, but issue rate of
/// 1-2 per cycle — 8 chains keeps both add ports saturated). Tree-merge
/// at the end matches NumPy's pairwise_sum.c shape, which also gives
/// better numerical accuracy on long reductions.
/// </summary>
private static void EmitReductionSimdLoop(ILGenerator il, ElementReductionKernelKey key, int inputSize)
{
// All/Any use special early-exit logic
if (key.Op == ReductionOp.All || key.Op == ReductionOp.Any)
{
EmitAllAnySimdLoop(il, key, inputSize);
return;
}
// ArgMax/ArgMin use special index-tracking logic
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
EmitArgMaxMinSimdLoop(il, key, inputSize);
return;
}
long vectorCount = GetVectorCount(key.InputType);
var clrType = GetClrType(key.InputType);
var vectorType = GetVectorType(clrType);
var locI = il.DeclareLocal(typeof(long)); // loop counter
var locUnrollEnd = il.DeclareLocal(typeof(long)); // totalSize - unrollStep
var locVectorEnd = il.DeclareLocal(typeof(long)); // totalSize - vectorCount
var locAcc = new LocalBuilder[8];
for (int k = 0; k < 8; k++) locAcc[k] = il.DeclareLocal(vectorType);
var locScalarAccum = il.DeclareLocal(GetClrType(key.AccumulatorType)); // scalar for tail
var lblUnrolledLoop = il.DefineLabel();
var lblUnrolledLoopEnd = il.DefineLabel();
var lblRemainderLoop = il.DefineLabel();
var lblRemainderLoopEnd = il.DefineLabel();
var lblTailLoop = il.DefineLabel();
var lblTailLoopEnd = il.DefineLabel();
long unrollStep = vectorCount * 8;
// Initialize 8 vector accumulators with the op's identity (0 for Sum/Mean,
// 1 for Prod, +Inf/-Inf for Min/Max) broadcast across all lanes.
for (int k = 0; k < 8; k++)
{
EmitVectorIdentity(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[k]);
}
// unrollEnd = totalSize - unrollStep
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.Emit(OpCodes.Ldc_I8, unrollStep);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Stloc, locUnrollEnd);
// vectorEnd = totalSize - vectorCount
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.Emit(OpCodes.Ldc_I8, vectorCount);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Stloc, locVectorEnd);
// i = 0
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locI);
// === 8x UNROLLED SIMD LOOP ===
il.MarkLabel(lblUnrolledLoop);
// if (i > unrollEnd) goto UnrolledLoopEnd
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldloc, locUnrollEnd);
il.Emit(OpCodes.Bgt, lblUnrolledLoopEnd);
for (int k = 0; k < 8; k++)
EmitAccumLoadCombine(il, key, locAcc[k], locI, inputSize, vectorCount * k);
// i += unrollStep
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, unrollStep);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locI);
il.Emit(OpCodes.Br, lblUnrolledLoop);
il.MarkLabel(lblUnrolledLoopEnd);
// === PAIRWISE TREE REDUCTION: 8 -> 4 -> 2 -> 1 ===
// Layer 1: (0,1)(2,3)(4,5)(6,7) → 4 accumulators in slots 0,2,4,6.
for (int k = 0; k < 8; k += 2)
{
il.Emit(OpCodes.Ldloc, locAcc[k]);
il.Emit(OpCodes.Ldloc, locAcc[k + 1]);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[k]);
}
// Layer 2: (0,2)(4,6) → slots 0,4.
il.Emit(OpCodes.Ldloc, locAcc[0]);
il.Emit(OpCodes.Ldloc, locAcc[2]);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[0]);
il.Emit(OpCodes.Ldloc, locAcc[4]);
il.Emit(OpCodes.Ldloc, locAcc[6]);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[4]);
// Layer 3: (0,4) → slot 0 (final reduced vector).
il.Emit(OpCodes.Ldloc, locAcc[0]);
il.Emit(OpCodes.Ldloc, locAcc[4]);
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locAcc[0]);
var locVecAccum0 = locAcc[0];
// === REMAINDER LOOP (0-3 vectors) ===
il.MarkLabel(lblRemainderLoop);
// if (i > vectorEnd) goto RemainderLoopEnd
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldloc, locVectorEnd);
il.Emit(OpCodes.Bgt, lblRemainderLoopEnd);
// Load vector accumulator
il.Emit(OpCodes.Ldloc, locVecAccum0);
// Load vector from input[i]
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, (long)inputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
EmitVectorLoad(il, key.InputType);
// vecAccum = vecAccum OP inputVec
EmitVectorBinaryReductionOp(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locVecAccum0);
// i += vectorCount
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, vectorCount);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locI);
il.Emit(OpCodes.Br, lblRemainderLoop);
il.MarkLabel(lblRemainderLoopEnd);
// === HORIZONTAL REDUCTION (once at end) ===
// Reduce vector accumulator to scalar
il.Emit(OpCodes.Ldloc, locVecAccum0);
EmitVectorHorizontalReduction(il, key.Op, key.InputType);
il.Emit(OpCodes.Stloc, locScalarAccum);
// === TAIL LOOP (scalar) ===
il.MarkLabel(lblTailLoop);
// if (i >= totalSize) goto end
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.Emit(OpCodes.Bge, lblTailLoopEnd);
// Load input[i], convert to accumulator type
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, (long)inputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
EmitLoadIndirect(il, key.InputType);
EmitConvertTo(il, key.InputType, key.AccumulatorType);
// Combine with scalar accumulator
il.Emit(OpCodes.Ldloc, locScalarAccum);
EmitReductionCombine(il, key.Op, key.AccumulatorType);
il.Emit(OpCodes.Stloc, locScalarAccum);
// i++
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, 1L);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locI);
il.Emit(OpCodes.Br, lblTailLoop);
il.MarkLabel(lblTailLoopEnd);
// Return scalar accumulator
il.Emit(OpCodes.Ldloc, locScalarAccum);
}
/// <summary>
/// Emit vector identity value (broadcast identity to all lanes).
/// </summary>
private static void EmitVectorIdentity(ILGenerator il, ReductionOp op, NPTypeCode type)
{
// Load scalar identity
EmitLoadIdentity(il, op, type);
// Broadcast to vector
EmitVectorCreate(il, type);
}
/// <summary>
/// Emit vector-vector binary reduction operation.
/// Stack has [vec1, vec2], result is combined vector.
/// </summary>
private static void EmitVectorBinaryReductionOp(ILGenerator il, ReductionOp op, NPTypeCode type)
{
var clrType = GetClrType(type);
// NaN-propagating Min/Max for floating point. Hardware MIN/MAX (Vector.Min/Max, MINPS/
// MAXPS) drop a NaN operand and return the other lane — but NumPy's (non-nan*) min/max
// PROPAGATE NaN. Emit ConditionalSelect(Equals(acc,acc) & Equals(v,v), Min(acc,v), acc+v):
// where both lanes are ordered (non-NaN) keep the hardware min/max; where either is NaN
// fall back to acc+v, which is NaN. The self-equality mask is the standard SIMD NaN test
// (NaN != NaN). Integer Min/Max have no NaN domain and keep the single-instruction path.
if ((op == ReductionOp.Min || op == ReductionOp.Max)
&& (type == NPTypeCode.Single || type == NPTypeCode.Double))
{
EmitVectorNaNPropagatingMinMax(il, op, VectorBits, clrType);
return;
}
string methodName = op switch
{
ReductionOp.Sum => "Add",
ReductionOp.Prod => "Multiply",
ReductionOp.Max => "Max",
ReductionOp.Min => "Min",
ReductionOp.Mean => "Add", // Mean uses Sum internally
_ => throw new NotSupportedException($"Vector binary op for {op} not supported")
};
// x86 fast path: Avx/Avx2 intrinsic when available (1.8-2x faster JIT codegen
// than Vector256.* on .NET 10). BinaryX86 returns null for ops/types without an
// x86 vector instruction (int64 Min/Max/Mul on Avx2), falling through to V256.
var x86 = VectorMethodCache.BinaryX86(VectorBits, methodName, clrType);
if (x86 != null)
{
il.EmitCall(OpCodes.Call, x86, null);
return;
}
// Multiply has a (V, T) scalar overload as well as (V, V); use the vector-vector
// variant explicitly. The other ops here only have the (V, V) overload.
var method = methodName == "Multiply"
? VectorMethodCache.MultiplyVectorVector(VectorBits, clrType)
: VectorMethodCache.Generic(VectorBits, methodName, clrType, paramCount: 2);
il.EmitCall(OpCodes.Call, method, null);
}
/// <summary>
/// Emit a NaN-propagating vector Min/Max for floating point (NumPy's non-nan* semantics).
/// Stack on entry: [acc, v] (two Vector{N}). Computes
/// <c>ConditionalSelect(Equals(acc,acc) & Equals(v,v), MinMax(acc,v), acc + v)</c> — the
/// hardware min/max where both lanes are ordered, and <c>acc + v</c> (which is NaN) where
/// either lane is NaN. Used by every reduction stage (unrolled body and horizontal merge),
/// so a NaN anywhere in the array propagates to the scalar result.
/// </summary>
private static void EmitVectorNaNPropagatingMinMax(ILGenerator il, ReductionOp op, int simdBits, Type clrType)
{
#if NET8_0
// net8.0: the BCL Vector{N}.Min/Max lower to raw MINPS/MAXPS, which DROP a NaN
// operand (return the other lane) — so NaN must be re-introduced explicitly.
// Stack on entry: [acc, v].
var vecType = VectorMethodCache.V(simdBits, clrType);
var locV = il.DeclareLocal(vecType);
var locAcc = il.DeclareLocal(vecType);
il.Emit(OpCodes.Stloc, locV); // pop v
il.Emit(OpCodes.Stloc, locAcc); // pop acc
// ordered = Equals(acc, acc) & Equals(v, v) (AllBitsSet lanes where both are non-NaN)
il.Emit(OpCodes.Ldloc, locAcc);
il.Emit(OpCodes.Ldloc, locAcc);
il.EmitCall(OpCodes.Call, VectorMethodCache.Equals(simdBits, clrType), null);
il.Emit(OpCodes.Ldloc, locV);
il.Emit(OpCodes.Ldloc, locV);
il.EmitCall(OpCodes.Call, VectorMethodCache.Equals(simdBits, clrType), null);
il.EmitCall(OpCodes.Call, VectorMethodCache.Generic(simdBits, "BitwiseAnd", clrType, paramCount: 2), null);
// MinMax(acc, v) — the ordered-lane result
il.Emit(OpCodes.Ldloc, locAcc);
il.Emit(OpCodes.Ldloc, locV);
il.EmitCall(OpCodes.Call,
VectorMethodCache.Generic(simdBits, op == ReductionOp.Min ? "Min" : "Max", clrType, paramCount: 2), null);
// acc + v — the NaN-propagating fallback for lanes where either operand is NaN
il.Emit(OpCodes.Ldloc, locAcc);
il.Emit(OpCodes.Ldloc, locV);
il.EmitCall(OpCodes.Call, VectorMethodCache.Generic(simdBits, "Add", clrType, paramCount: 2), null);
// ConditionalSelect(ordered, MinMax, acc+v)
il.EmitCall(OpCodes.Call, VectorMethodCache.ConditionalSelect(simdBits, clrType), null);
#else
// net9.0+: Vector{N}.Min/Max PROPAGATE NaN (the JIT lowers them to vminp{s,d}/
// vmaxp{s,d} PLUS the IEEE-754 NaN fixup — verified: Vector256.Min(<.,NaN,.>) keeps
// the NaN). The whole self-equality + acc+v + ConditionalSelect wrapper the net8.0
// path needs is pure overhead here (it ~tripled the per-combine op count and made
// float axis min/max ~2x slower than NumPy). Emit the single intrinsic call: stack
// is already [acc, v], so Min/Max consumes both. Matches NaNAwareMinMax256's #if.
il.EmitCall(OpCodes.Call,
VectorMethodCache.Generic(simdBits, op == ReductionOp.Min ? "Min" : "Max", clrType, paramCount: 2), null);
#endif
}
/// <summary>
/// Emit a scalar reduction loop for contiguous arrays (no SIMD).
/// </summary>
private static void EmitReductionScalarLoop(ILGenerator il, ElementReductionKernelKey key, int inputSize)
{
// Args: void* input (0), long* strides (1), long* shape (2), int ndim (3), long totalSize (4)
// For Half/Complex ArgMax/ArgMin, use helper method (comparison via IL doesn't work correctly)
if ((key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin) &&
(key.InputType == NPTypeCode.Half || key.InputType == NPTypeCode.Complex))
{
EmitArgMaxMinSimdLoop(il, key, inputSize);
return;
}
var locI = il.DeclareLocal(typeof(long)); // loop counter
var locAccum = il.DeclareLocal(GetClrType(key.AccumulatorType)); // accumulator
var locIdx = il.DeclareLocal(typeof(long)); // index for ArgMax/ArgMin
var lblLoop = il.DefineLabel();
var lblLoopEnd = il.DefineLabel();
// Initialize accumulator with identity value
EmitLoadIdentity(il, key.Op, key.AccumulatorType);
il.Emit(OpCodes.Stloc, locAccum);
// For ArgMax/ArgMin, initialize index to 0
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locIdx);
}
// i = 0
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locI);
il.MarkLabel(lblLoop);
// if (i >= totalSize) goto end
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.Emit(OpCodes.Bge, lblLoopEnd);
// Load input[i], convert to accumulator type
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, (long)inputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
EmitLoadIndirect(il, key.InputType);
EmitConvertTo(il, key.InputType, key.AccumulatorType);
// Combine with accumulator (and track index for ArgMax/ArgMin)
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
EmitArgReductionStep(il, key.Op, key.AccumulatorType, locAccum, locIdx, locI);
}
else
{
il.Emit(OpCodes.Ldloc, locAccum);
EmitReductionCombine(il, key.Op, key.AccumulatorType);
il.Emit(OpCodes.Stloc, locAccum);
}
// i++
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, 1L);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locI);
il.Emit(OpCodes.Br, lblLoop);
il.MarkLabel(lblLoopEnd);
// Return accumulator or index
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
il.Emit(OpCodes.Ldloc, locIdx);
}
else
{
il.Emit(OpCodes.Ldloc, locAccum);
}
}
/// <summary>
/// Emit a strided reduction loop for non-contiguous arrays.
/// </summary>
private static void EmitReductionStridedLoop(ILGenerator il, ElementReductionKernelKey key, int inputSize)
{
// Args: void* input (0), long* strides (1), long* shape (2), int ndim (3), long totalSize (4)
var locI = il.DeclareLocal(typeof(long)); // linear index
var locD = il.DeclareLocal(typeof(int)); // dimension counter
var locOffset = il.DeclareLocal(typeof(long)); // input offset
var locCoord = il.DeclareLocal(typeof(long)); // current coordinate (long for int64 shapes)
var locIdx = il.DeclareLocal(typeof(long)); // temp for coordinate calculation (long for int64 shapes)
var locAccum = il.DeclareLocal(GetClrType(key.AccumulatorType)); // accumulator
var locArgIdx = il.DeclareLocal(typeof(long)); // index for ArgMax/ArgMin
var locStride0 = il.DeclareLocal(typeof(long)); // cached strides[0] for the ndim==1 fast path
var lblLoop = il.DefineLabel();
var lblLoopEnd = il.DefineLabel();
var lblDimLoop = il.DefineLabel();
var lblDimLoopEnd = il.DefineLabel();
var lblGeneralPath = il.DefineLabel(); // ndim>1 coordinate-decode loop
var lblFastHead = il.DefineLabel(); // ndim==1 incremental loop head
// Initialize accumulator
EmitLoadIdentity(il, key.Op, key.AccumulatorType);
il.Emit(OpCodes.Stloc, locAccum);
// For ArgMax/ArgMin, initialize index to 0
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locArgIdx);
}
// i = 0
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locI);
// ===== ndim == 1 incremental fast path =====
// A single strided dimension needs no flat->coordinate decode: the offset of
// element i+1 is just offset(i) + strides[0]. This replaces a per-element
// div + mod + mul (the general loop below) with a single add — numpy's
// incremental-advance. 1-D sliced/strided views are the dominant non-contig
// reduction case and were ~14x slower than NumPy purely from that div/mod.
// The accumulate/compare logic is identical to the general path; only the
// address walk differs.
il.Emit(OpCodes.Ldarg_3); // ndim
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Bne_Un, lblGeneralPath);
{
// offset = 0
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locOffset);
// stride0 = strides[0] (element stride; multiplied by inputSize at load)
il.Emit(OpCodes.Ldarg_1); // strides
il.Emit(OpCodes.Ldind_I8);
il.Emit(OpCodes.Stloc, locStride0);
// ── AVX2 hardware-gather SIMD section (Phase 2a) ─────────────
// Bulk of a 1-D strided reduction runs as gathered vectors
// into 4 independent accumulators (NumPy has NO simd here —
// its strided pairwise_sum is a scalar 8-accumulator loop).
// Leaves locI/locOffset positioned so the scalar loop below
// finishes the tail. Emitted only for gather-capable dtypes
// with same-type accumulation; combine/identity/horizontal
// helpers are shared with the contiguous SIMD path so the
// semantics (incl. float min/max NaN behavior) are identical.
if (CanUseGatherReduction(key) && TryGetGatherSupport(key.InputType, out var gsup))
{
EmitGatherReductionSection(il, key, inputSize, gsup, locI, locOffset, locStride0, locAccum);
}
il.MarkLabel(lblFastHead);
// if (i >= totalSize) goto end
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.Emit(OpCodes.Bge, lblLoopEnd);
// load input[offset * inputSize]
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldloc, locOffset);
il.Emit(OpCodes.Ldc_I8, (long)inputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
EmitLoadIndirect(il, key.InputType);
EmitConvertTo(il, key.InputType, key.AccumulatorType);
// combine into accumulator (or arg-step using the linear index locI)
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
EmitArgReductionStep(il, key.Op, key.AccumulatorType, locAccum, locArgIdx, locI);
}
else
{
il.Emit(OpCodes.Ldloc, locAccum);
EmitReductionCombine(il, key.Op, key.AccumulatorType);
il.Emit(OpCodes.Stloc, locAccum);
}
// offset += stride0
il.Emit(OpCodes.Ldloc, locOffset);
il.Emit(OpCodes.Ldloc, locStride0);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locOffset);
// i++
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, 1L);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locI);
il.Emit(OpCodes.Br, lblFastHead);
}
// ===== general ndim>1 coordinate-decode path =====
il.MarkLabel(lblGeneralPath);
// Main loop
il.MarkLabel(lblLoop);
// if (i >= totalSize) goto end
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.Emit(OpCodes.Bge, lblLoopEnd);
// Calculate offset from linear index
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locOffset);
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Stloc, locIdx);
// d = ndim - 1
il.Emit(OpCodes.Ldarg_3); // ndim
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Stloc, locD);
il.MarkLabel(lblDimLoop);
// if (d < 0) goto DimLoopEnd
il.Emit(OpCodes.Ldloc, locD);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Blt, lblDimLoopEnd);
// coord = idx % shape[d]
il.Emit(OpCodes.Ldloc, locIdx);
il.Emit(OpCodes.Ldarg_2); // shape
il.Emit(OpCodes.Ldloc, locD);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Ldc_I4_8); // sizeof(long)
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldind_I8);
il.Emit(OpCodes.Rem);
il.Emit(OpCodes.Stloc, locCoord);
// idx /= shape[d]
il.Emit(OpCodes.Ldloc, locIdx);
il.Emit(OpCodes.Ldarg_2); // shape
il.Emit(OpCodes.Ldloc, locD);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Ldc_I4_8);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldind_I8);
il.Emit(OpCodes.Div);
il.Emit(OpCodes.Stloc, locIdx);
// offset += coord * strides[d]
il.Emit(OpCodes.Ldloc, locOffset);
il.Emit(OpCodes.Ldloc, locCoord);
il.Emit(OpCodes.Ldarg_1); // strides
il.Emit(OpCodes.Ldloc, locD);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Ldc_I4_8);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldind_I8);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locOffset);
// d--
il.Emit(OpCodes.Ldloc, locD);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Stloc, locD);
il.Emit(OpCodes.Br, lblDimLoop);
il.MarkLabel(lblDimLoopEnd);
// Load input[offset]
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldloc, locOffset);
il.Emit(OpCodes.Ldc_I8, (long)inputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
EmitLoadIndirect(il, key.InputType);
EmitConvertTo(il, key.InputType, key.AccumulatorType);
// Combine with accumulator
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
EmitArgReductionStep(il, key.Op, key.AccumulatorType, locAccum, locArgIdx, locI);
}
else
{
il.Emit(OpCodes.Ldloc, locAccum);
EmitReductionCombine(il, key.Op, key.AccumulatorType);
il.Emit(OpCodes.Stloc, locAccum);
}
// i++
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, 1L);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc, locI);
il.Emit(OpCodes.Br, lblLoop);
il.MarkLabel(lblLoopEnd);
// Return accumulator or index (ArgMax/ArgMin returns int64 per NumPy 2.x)
if (key.Op == ReductionOp.ArgMax || key.Op == ReductionOp.ArgMin)
{
il.Emit(OpCodes.Ldloc, locArgIdx);
// locArgIdx is already long (int64), return as-is for >2GB array support
}
else
{
il.Emit(OpCodes.Ldloc, locAccum);
}
}
#region Reduction IL Helpers
/// <summary>
/// Load the identity value for a reduction operation.
/// </summary>
private static void EmitLoadIdentity(ILGenerator il, ReductionOp op, NPTypeCode type)
{
switch (op)
{
case ReductionOp.Sum:
case ReductionOp.Mean:
case ReductionOp.CumSum:
// Identity is 0
EmitLoadZero(il, type);
break;
case ReductionOp.Prod:
// Identity is 1
EmitLoadOne(il, type);
break;
case ReductionOp.Max:
// Identity is minimum value (so first element becomes max)
EmitLoadMinValue(il, type);
break;
case ReductionOp.Min:
// Identity is maximum value (so first element becomes min)
EmitLoadMaxValue(il, type);
break;