Repository navigation
Expand file tree
/
Copy pathDirectILKernelGenerator.Scan.cs
More file actions
2520 lines (2308 loc) · 100 KB
/
Copy pathDirectILKernelGenerator.Scan.cs
File metadata and controls
2520 lines (2308 loc) · 100 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.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Intrinsics;
using NumSharp.Utilities;
// =============================================================================
// DirectILKernelGenerator.Scan.cs - Scan (prefix sum) kernel generation
// =============================================================================
//
// ARCHITECTURE OVERVIEW
// ---------------------
// Scan operations (cumsum, cumprod) are fundamentally different from reductions:
// - Reduction: N inputs -> 1 output (scalar)
// - Scan: N inputs -> N outputs (each output depends on all previous inputs)
//
// This makes SIMD optimization challenging for scans because each element
// depends on the previous element (sequential dependency). However, we can
// still optimize:
// 1. Contiguous same-type: Direct pointer access without iterator overhead
// 2. Type conversion: Efficient widening during accumulation
// 3. Memory access: Sequential writes are cache-friendly
//
// For contiguous arrays where input and output types match, we use a simple
// scalar loop with direct pointer access. For non-contiguous arrays, we fall
// back to coordinate-based iteration.
//
// =============================================================================
// PARTIAL CLASS FILE OWNERSHIP
// =============================================================================
//
// DirectILKernelGenerator.Scan.cs (THIS FILE)
// OWNERSHIP: Scan (cumulative) operations
// RESPONSIBILITY:
// - CumSum: cumulative sum (running total)
// - CumProd: cumulative product (future)
// DEPENDENCIES: Uses core emit helpers from DirectILKernelGenerator.cs
// FLOW: Called by DefaultEngine for np.cumsum, np.cumprod
// KEY MEMBERS:
// - CumulativeKernel delegate (defined in ReductionKernel.cs)
// - CumulativeKernelKey record struct (defined in ReductionKernel.cs)
// - _scanCache - caches by CumulativeKernelKey
// - GetCumulativeKernel(), TryGetCumulativeKernel()
// - CumSumHelper<TIn, TOut>() - optimized same-type cumsum
//
// =============================================================================
namespace NumSharp.Backends.Kernels
{
public static partial class DirectILKernelGenerator
{
#region Scan Kernel Generation
/// <summary>
/// Cache for cumulative (scan) kernels.
/// Key: CumulativeKernelKey (InputType, OutputType, Op, IsContiguous)
/// </summary>
internal static readonly ConcurrentDictionary<CumulativeKernelKey, Delegate> _scanCache = new();
/// <summary>
/// Get or generate a cumulative (scan) kernel.
/// Returns a delegate that computes running accumulation over all elements.
/// </summary>
public static CumulativeKernel GetCumulativeKernel(CumulativeKernelKey key)
{
if (!Enabled)
throw new InvalidOperationException("IL generation is disabled");
var kernel = _scanCache.GetOrAdd(key, GenerateCumulativeKernel);
return (CumulativeKernel)kernel;
}
/// <summary>
/// Try to get or generate a cumulative kernel.
/// </summary>
public static CumulativeKernel? TryGetCumulativeKernel(CumulativeKernelKey key)
{
if (!Enabled)
return null;
try
{
var kernel = _scanCache.GetOrAdd(key, GenerateCumulativeKernel);
return (CumulativeKernel)kernel;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[ILKernel] GetCumulativeKernel({key}): {ex.GetType().Name}: {ex.Message}");
return null;
}
}
/// <summary>
/// Generate a cumulative (scan) kernel.
/// </summary>
private static Delegate GenerateCumulativeKernel(CumulativeKernelKey key)
{
// CumulativeKernel signature:
// void(void* input, void* output, long* strides, long* shape, int ndim, long totalSize)
var dm = new DynamicMethod(
name: $"Scan_{key}",
returnType: typeof(void),
parameterTypes: new[]
{
typeof(void*), // input
typeof(void*), // output
typeof(long*), // strides
typeof(long*), // shape
typeof(int), // ndim
typeof(long) // totalSize
},
owner: typeof(DirectILKernelGenerator),
skipVisibility: true
);
var il = dm.GetILGenerator();
int inputSize = GetTypeSize(key.InputType);
int outputSize = GetTypeSize(key.OutputType);
if (key.IsContiguous && key.IsSameType)
{
// Fast path: contiguous array with same input/output type
// Use helper method for cleaner implementation
EmitScanHelperCall(il, key);
}
else if (key.IsContiguous)
{
// Contiguous but needs type conversion
EmitScanContiguousWithConversion(il, key, inputSize, outputSize);
}
else
{
// Non-contiguous: use coordinate-based iteration
EmitScanStridedLoop(il, key, inputSize, outputSize);
}
il.Emit(OpCodes.Ret);
return dm.CreateDelegate<CumulativeKernel>();
}
/// <summary>
/// Emit a call to the appropriate scan helper method.
/// Used for contiguous same-type arrays.
/// </summary>
private static void EmitScanHelperCall(ILGenerator il, CumulativeKernelKey key)
{
// Find the appropriate helper method based on operation
string helperName = key.Op switch
{
ReductionOp.CumSum => nameof(CumSumHelperSameType),
ReductionOp.CumProd => nameof(CumProdHelperSameType),
_ => throw new NotSupportedException($"Scan operation {key.Op} not supported")
};
var genericHelper = GetGenericHelper(helperName, GetClrType(key.InputType));
// Call helper: CumSumHelperSameType<T>(input, output, totalSize)
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldarg_1); // output
il.Emit(OpCodes.Ldarg_S, (byte)5); // totalSize
il.EmitCall(OpCodes.Call, genericHelper, null);
}
/// <summary>
/// SIMD-optimized cumulative sum helper for same-type contiguous arrays.
/// While scan is inherently sequential, we optimize memory access patterns.
/// </summary>
internal static unsafe void CumSumHelperSameType<T>(void* input, void* output, long totalSize)
where T : unmanaged, IAdditionOperators<T, T, T>
{
if (totalSize == 0)
return;
T* src = (T*)input;
T* dst = (T*)output;
// Scan is inherently sequential - each output depends on previous sum
// We use direct pointer access for optimal performance
T sum = default;
for (long i = 0; i < totalSize; i++)
{
sum += src[i];
dst[i] = sum;
}
}
/// <summary>
/// Cumulative product helper for same-type contiguous arrays. Scan is inherently
/// sequential; we use direct pointer access for optimal memory throughput. Mirrors
/// <see cref="CumSumHelperSameType{T}"/> with a multiplicative identity / combine.
/// </summary>
internal static unsafe void CumProdHelperSameType<T>(void* input, void* output, long totalSize)
where T : unmanaged, IMultiplyOperators<T, T, T>, IMultiplicativeIdentity<T, T>
{
if (totalSize == 0)
return;
T* src = (T*)input;
T* dst = (T*)output;
T product = T.MultiplicativeIdentity;
for (long i = 0; i < totalSize; i++)
{
product *= src[i];
dst[i] = product;
}
}
/// <summary>
/// Emit contiguous scan loop with type conversion.
/// </summary>
private static void EmitScanContiguousWithConversion(ILGenerator il, CumulativeKernelKey key, int inputSize, int outputSize)
{
// Args: void* input (0), void* output (1), long* strides (2), long* shape (3), int ndim (4), long totalSize (5)
var locI = il.DeclareLocal(typeof(long)); // loop counter
var locAccum = il.DeclareLocal(GetClrType(key.OutputType)); // accumulator
var lblLoop = il.DefineLabel();
var lblLoopEnd = il.DefineLabel();
// Initialize accumulator to identity value (0 for sum, 1 for prod)
EmitScanIdentity(il, key.Op, key.OutputType);
il.Emit(OpCodes.Stloc, locAccum);
// 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)5); // totalSize
il.Emit(OpCodes.Bge, lblLoopEnd);
// Load input[i], convert to output type, add to accumulator
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.OutputType);
// Add to accumulator
il.Emit(OpCodes.Ldloc, locAccum);
EmitScanCombine(il, key.Op, key.OutputType);
il.Emit(OpCodes.Stloc, locAccum);
// Store accumulator to output[i]
il.Emit(OpCodes.Ldarg_1); // output
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, (long)outputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldloc, locAccum);
EmitStoreIndirect(il, key.OutputType);
// 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);
}
/// <summary>
/// Emit a strided scan loop for non-contiguous arrays.
/// </summary>
private static void EmitScanStridedLoop(ILGenerator il, CumulativeKernelKey key, int inputSize, int outputSize)
{
// Args: void* input (0), void* output (1), long* strides (2), long* shape (3), int ndim (4), long totalSize (5)
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
var locAccum = il.DeclareLocal(GetClrType(key.OutputType)); // accumulator
var lblLoop = il.DefineLabel();
var lblLoopEnd = il.DefineLabel();
var lblDimLoop = il.DefineLabel();
var lblDimLoopEnd = il.DefineLabel();
// Initialize accumulator to identity value (0 for sum, 1 for prod)
EmitScanIdentity(il, key.Op, key.OutputType);
il.Emit(OpCodes.Stloc, locAccum);
// i = 0
il.Emit(OpCodes.Ldc_I8, 0L);
il.Emit(OpCodes.Stloc, locI);
// Main loop
il.MarkLabel(lblLoop);
// if (i >= totalSize) goto end
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldarg_S, (byte)5); // 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_S, (byte)4); // 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_3); // 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_3); // 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_2); // 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.OutputType);
// Add to accumulator
il.Emit(OpCodes.Ldloc, locAccum);
EmitScanCombine(il, key.Op, key.OutputType);
il.Emit(OpCodes.Stloc, locAccum);
// Store accumulator to output[i] (output is always contiguous)
il.Emit(OpCodes.Ldarg_1); // output
il.Emit(OpCodes.Ldloc, locI);
il.Emit(OpCodes.Ldc_I8, (long)outputSize);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldloc, locAccum);
EmitStoreIndirect(il, key.OutputType);
// 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);
}
/// <summary>
/// Emit scan combine operation.
/// Stack has [value, accumulator], result is combined value.
/// </summary>
private static void EmitScanCombine(ILGenerator il, ReductionOp op, NPTypeCode type)
{
// Special handling for decimal — only CumSum is supported (CumProd overflows quickly
// on decimal, so we don't expose it).
if (type == NPTypeCode.Decimal)
{
string opName = op switch
{
ReductionOp.CumSum => "op_Addition",
_ => throw new NotSupportedException($"Scan operation {op} not supported for decimal")
};
il.EmitCall(OpCodes.Call, ScalarMethodCache.BinaryOp(typeof(decimal), opName), null);
return;
}
switch (op)
{
case ReductionOp.CumSum:
il.Emit(OpCodes.Add);
break;
case ReductionOp.CumProd:
il.Emit(OpCodes.Mul);
break;
default:
throw new NotSupportedException($"Scan operation {op} not supported");
}
}
/// <summary>
/// Emit identity value for scan operations.
/// CumSum uses 0 (additive identity), CumProd uses 1 (multiplicative identity).
/// </summary>
private static void EmitScanIdentity(ILGenerator il, ReductionOp op, NPTypeCode type)
{
switch (op)
{
case ReductionOp.CumSum:
EmitLoadZero(il, type);
break;
case ReductionOp.CumProd:
EmitLoadOne(il, type);
break;
default:
throw new NotSupportedException($"Scan operation {op} has no identity");
}
}
// Note: EmitLoadZero and EmitLoadOne are defined in DirectILKernelGenerator.Reduction.cs
#endregion
#region Axis Scan Kernel Generation
/// <summary>
/// Cache for cumulative axis (scan along axis) kernels.
/// Key: CumulativeAxisKernelKey (InputType, OutputType, Op, InnerAxisContiguous)
/// </summary>
internal static readonly ConcurrentDictionary<CumulativeAxisKernelKey, Delegate> _axisScanCache = new();
/// <summary>
/// Try to get or generate a cumulative axis kernel.
/// </summary>
public static CumulativeAxisKernel? TryGetCumulativeAxisKernel(CumulativeAxisKernelKey key)
{
if (!Enabled)
return null;
try
{
var kernel = _axisScanCache.GetOrAdd(key, GenerateCumulativeAxisKernel);
return (CumulativeAxisKernel)kernel;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[ILKernel] TryGetCumulativeAxisKernel({key}): {ex.GetType().Name}: {ex.Message}");
return null;
}
}
/// <summary>
/// Generate a cumulative axis (scan along axis) kernel.
/// </summary>
private static Delegate GenerateCumulativeAxisKernel(CumulativeAxisKernelKey key)
{
// CumulativeAxisKernel signature:
// void(void* input, void* output, long* inputStrides, long* shape, int axis, int ndim, long totalSize)
var dm = new DynamicMethod(
name: $"AxisScan_{key}",
returnType: typeof(void),
parameterTypes: new[]
{
typeof(void*), // input
typeof(void*), // output
typeof(long*), // inputStrides
typeof(long*), // shape
typeof(int), // axis
typeof(int), // ndim
typeof(long) // totalSize
},
owner: typeof(DirectILKernelGenerator),
skipVisibility: true
);
var il = dm.GetILGenerator();
// For axis cumsum, we call a helper method that handles the iteration
// The IL kernel just dispatches to the right helper based on types
EmitAxisScanHelperCall(il, key);
il.Emit(OpCodes.Ret);
return dm.CreateDelegate<CumulativeAxisKernel>();
}
/// <summary>
/// Emit a call to the appropriate axis scan helper method.
/// </summary>
private static void EmitAxisScanHelperCall(ILGenerator il, CumulativeAxisKernelKey key)
{
// Find the appropriate helper method based on operation
string helperName = key.Op switch
{
ReductionOp.CumSum => nameof(AxisCumSumHelper),
// ReductionOp.CumProd => nameof(AxisCumProdHelper), // Future
_ => throw new NotSupportedException($"Axis scan operation {key.Op} not supported")
};
var genericHelper = GetHelper(helperName).MakeGenericMethod(
GetClrType(key.InputType),
GetClrType(key.OutputType));
// Call helper: AxisCumSumHelper<TIn, TOut>(input, output, inputStrides, shape, axis, ndim, totalSize)
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldarg_1); // output
il.Emit(OpCodes.Ldarg_2); // inputStrides
il.Emit(OpCodes.Ldarg_3); // shape
il.Emit(OpCodes.Ldarg_S, (byte)4); // axis
il.Emit(OpCodes.Ldarg_S, (byte)5); // ndim
il.Emit(OpCodes.Ldarg_S, (byte)6); // totalSize
il.EmitCall(OpCodes.Call, genericHelper, null);
}
/// <summary>
/// Axis cumulative sum helper. Computes cumsum along a specific axis.
/// Uses optimized iteration pattern based on axis position.
/// </summary>
internal static unsafe void AxisCumSumHelper<TIn, TOut>(
void* input, void* output, long* inputStrides, long* shape,
int axis, int ndim, long totalSize)
where TIn : unmanaged
where TOut : unmanaged
{
if (totalSize == 0)
return;
TIn* src = (TIn*)input;
TOut* dst = (TOut*)output;
long axisSize = shape[axis];
long axisStride = inputStrides[axis];
// Calculate outer size (product of dimensions before axis)
// and inner size (product of dimensions after axis)
long outerSize = 1;
long innerSize = 1;
for (int d = 0; d < axis; d++)
outerSize *= shape[d];
for (int d = axis + 1; d < ndim; d++)
innerSize *= shape[d];
// Calculate output strides (output is always contiguous)
long outputAxisStride = innerSize;
long outputOuterStride = axisSize * innerSize;
// Dispatch to specialized helper based on types
if (typeof(TIn) == typeof(TOut))
{
// When TIn == TOut, we can cast safely and use same-type optimized path
AxisCumSumSameType<TIn>((TIn*)src, (TIn*)(void*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else
{
AxisCumSumWithConversion<TIn, TOut>(src, dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
}
/// <summary>
/// Same-type axis cumprod implementation.
/// </summary>
private static unsafe void AxisCumProdSameType<T>(
T* src, T* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
where T : unmanaged
{
// General case: iterate using coordinate-based access with multiplication
AxisCumProdGeneral(src, dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
/// <summary>
/// General axis cumprod using coordinate-based iteration.
/// </summary>
private static unsafe void AxisCumProdGeneral<T>(
T* src, T* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
where T : unmanaged
{
// Type-specific dispatch for common types
if (typeof(T) == typeof(double))
{
AxisCumProdGeneralDouble((double*)src, (double*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(float))
{
AxisCumProdGeneralFloat((float*)src, (float*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(long))
{
AxisCumProdGeneralInt64((long*)src, (long*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(int))
{
AxisCumProdGeneralInt32((int*)src, (int*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(byte))
{
AxisCumProdGeneralByte((byte*)src, (byte*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(short))
{
AxisCumProdGeneralInt16((short*)src, (short*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(ushort))
{
AxisCumProdGeneralUInt16((ushort*)src, (ushort*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(uint))
{
AxisCumProdGeneralUInt32((uint*)src, (uint*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(ulong))
{
AxisCumProdGeneralUInt64((ulong*)src, (ulong*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else if (typeof(T) == typeof(decimal))
{
AxisCumProdGeneralDecimal((decimal*)src, (decimal*)dst, inputStrides, shape, axis, ndim,
axisSize, axisStride, outerSize, innerSize, outputAxisStride, outputOuterStride);
}
else
{
throw new NotSupportedException($"AxisCumProd not supported for type {typeof(T).Name}");
}
}
/// <summary>
/// General axis cumprod for double type.
/// </summary>
private static unsafe void AxisCumProdGeneralDouble(
double* src, double* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
// Calculate input base offset for this (outer, inner) combination
long inputOffset = 0;
long outerIdx = outer;
for (int d = axis - 1; d >= 0; d--)
{
long coord = outerIdx % shape[d];
outerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
long innerIdx = inner;
for (int d = ndim - 1; d > axis; d--)
{
long coord = innerIdx % shape[d];
innerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
// Calculate output base offset
long outputOffset = outer * outputOuterStride + inner;
// Cumprod along axis
double product = 1.0;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for float type.
/// </summary>
private static unsafe void AxisCumProdGeneralFloat(
float* src, float* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = 0;
long outerIdx = outer;
for (int d = axis - 1; d >= 0; d--)
{
long coord = outerIdx % shape[d];
outerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
long innerIdx = inner;
for (int d = ndim - 1; d > axis; d--)
{
long coord = innerIdx % shape[d];
innerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
long outputOffset = outer * outputOuterStride + inner;
float product = 1f;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for long type.
/// </summary>
private static unsafe void AxisCumProdGeneralInt64(
long* src, long* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = 0;
long outerIdx = outer;
for (int d = axis - 1; d >= 0; d--)
{
long coord = outerIdx % shape[d];
outerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
long innerIdx = inner;
for (int d = ndim - 1; d > axis; d--)
{
long coord = innerIdx % shape[d];
innerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
long outputOffset = outer * outputOuterStride + inner;
long product = 1L;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for int type.
/// </summary>
private static unsafe void AxisCumProdGeneralInt32(
int* src, int* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = 0;
long outerIdx = outer;
for (int d = axis - 1; d >= 0; d--)
{
long coord = outerIdx % shape[d];
outerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
long innerIdx = inner;
for (int d = ndim - 1; d > axis; d--)
{
long coord = innerIdx % shape[d];
innerIdx /= shape[d];
inputOffset += coord * inputStrides[d];
}
long outputOffset = outer * outputOuterStride + inner;
int product = 1;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for byte type.
/// </summary>
private static unsafe void AxisCumProdGeneralByte(
byte* src, byte* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = CalculateInputOffset(inputStrides, shape, axis, ndim, outer, inner);
long outputOffset = outer * outputOuterStride + inner;
byte product = 1;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for short type.
/// </summary>
private static unsafe void AxisCumProdGeneralInt16(
short* src, short* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = CalculateInputOffset(inputStrides, shape, axis, ndim, outer, inner);
long outputOffset = outer * outputOuterStride + inner;
short product = 1;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for ushort type.
/// </summary>
private static unsafe void AxisCumProdGeneralUInt16(
ushort* src, ushort* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = CalculateInputOffset(inputStrides, shape, axis, ndim, outer, inner);
long outputOffset = outer * outputOuterStride + inner;
ushort product = 1;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for uint type.
/// </summary>
private static unsafe void AxisCumProdGeneralUInt32(
uint* src, uint* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = CalculateInputOffset(inputStrides, shape, axis, ndim, outer, inner);
long outputOffset = outer * outputOuterStride + inner;
uint product = 1;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for ulong type.
/// </summary>
private static unsafe void AxisCumProdGeneralUInt64(
ulong* src, ulong* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = CalculateInputOffset(inputStrides, shape, axis, ndim, outer, inner);
long outputOffset = outer * outputOuterStride + inner;
ulong product = 1;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// General axis cumprod for decimal type.
/// </summary>
private static unsafe void AxisCumProdGeneralDecimal(
decimal* src, decimal* dst, long* inputStrides, long* shape, int axis, int ndim,
long axisSize, long axisStride, long outerSize, long innerSize,
long outputAxisStride, long outputOuterStride)
{
for (long outer = 0; outer < outerSize; outer++)
{
for (long inner = 0; inner < innerSize; inner++)
{
long inputOffset = CalculateInputOffset(inputStrides, shape, axis, ndim, outer, inner);
long outputOffset = outer * outputOuterStride + inner;
decimal product = 1m;
for (long i = 0; i < axisSize; i++)
{
product *= src[inputOffset + i * axisStride];
dst[outputOffset + i * outputAxisStride] = product;
}
}
}
}
/// <summary>
/// Helper to calculate input offset for general axis operations.