Repository navigation
Expand file tree
/
Copy pathNDIterBufferManager.cs
More file actions
1239 lines (1096 loc) · 49.1 KB
/
Copy pathNDIterBufferManager.cs
File metadata and controls
1239 lines (1096 loc) · 49.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using NumSharp.Backends.Kernels;
using NumSharp.Utilities;
namespace NumSharp.Backends.Iteration
{
/// <summary>
/// Buffer management for NDIter.
/// Handles allocation, copy-in, and copy-out of iteration buffers.
/// </summary>
public static unsafe class NDIterBufferManager
{
/// <summary>
/// Built-in default buffer size (number of elements) — NumPy's <c>NPY_BUFSIZE</c>.
/// Used whenever neither an explicit nditer <c>buffersize</c> nor a per-thread
/// override (<see cref="NumSharp.np.setbufsize(long)"/>) applies.
/// </summary>
public const long DefaultBufferSize = 8192;
/// <summary>
/// Smallest valid ufunc buffer size (NumPy: must be ≥ 5 AND a multiple of 16, so the
/// effective minimum is 16). See <c>extobj.c</c>'s <c>extobj_make_extobj</c>.
/// </summary>
internal const long MinBufferSize = 16;
/// <summary>
/// Largest valid ufunc buffer size (NumPy's <c>10e6</c>, inclusive).
/// </summary>
internal const long MaxBufferSize = 10_000_000;
/// <summary>
/// Per-thread override for the ufunc/NDIter default buffer size, set through
/// <see cref="NumSharp.np.setbufsize(long)"/>. Zero means "unset" — the thread then
/// falls back to <see cref="DefaultBufferSize"/>. Thread-local to mirror NumPy 2.x's
/// context-local extobj (a <c>setbufsize</c> on one thread never leaks into another).
/// </summary>
[ThreadStatic] private static long _userBufferSize;
/// <summary>
/// The current default NDIter/ufunc buffer size for the calling thread — exactly the
/// value <see cref="NumSharp.np.getbufsize"/> returns. Equals the last
/// <see cref="NumSharp.np.setbufsize(long)"/> value on this thread, or
/// <see cref="DefaultBufferSize"/> (8192) when none was set. Changing it alters only the
/// buffer/chunk size of buffered iteration, never any computed result.
/// </summary>
public static long CurrentBufferSize
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { long v = _userBufferSize; return v > 0 ? v : DefaultBufferSize; }
internal set => _userBufferSize = value; // validated by np.setbufsize before it reaches here
}
/// <summary>
/// Required alignment for SIMD operations.
/// </summary>
public const int Alignment = 64; // Cache line size, good for AVX-512
/// <summary>
/// Allocate aligned buffer for an operand.
/// </summary>
public static void* AllocateAligned(long elements, NPTypeCode dtype)
{
long bytes = elements * InfoOf.GetSize(dtype);
return NativeMemory.AlignedAlloc((nuint)bytes, Alignment);
}
/// <summary>
/// Free aligned buffer.
/// </summary>
public static void FreeAligned(void* buffer)
{
if (buffer != null)
NativeMemory.AlignedFree(buffer);
}
/// <summary>
/// Determine optimal buffer size based on array sizes and cache.
/// </summary>
public static long DetermineBufferSize(ref NDIterState state, long requestedSize)
{
if (requestedSize > 0)
return requestedSize;
// Use L2 cache size heuristic
const long L2CacheSize = 256 * 1024; // 256 KB
long totalElementSize = 0;
for (int op = 0; op < state.NOp; op++)
{
totalElementSize += state.GetElementSize(op);
}
if (totalElementSize == 0)
return DefaultBufferSize;
// Target: buffers fit in L2 cache
long maxElements = L2CacheSize / totalElementSize;
// Round down to SIMD vector multiple
int vectorSize = 32; // AVX2
maxElements = (maxElements / vectorSize) * vectorSize;
return Math.Max(vectorSize, Math.Min(maxElements, DefaultBufferSize));
}
/// <summary>
/// Allocate buffers for all operands that need buffering.
///
/// Buffering criterion (NumPy nditer parity): an operand is buffered when
/// it needs a CAST, when the user requested CONTIG, or when its memory is
/// not a single linear walk across the whole (coalesced) iteration space
/// (<see cref="IsOperandIterLinear"/>). Linear operands — contiguous OR
/// constant-stride 1-D views OR fully-broadcast scalars — stay unbuffered
/// (BUFNEVER-style) and the kernel reads/writes the array directly through
/// its true stride, which the Tier-3B kernels handle (incl. AVX2 gather).
///
/// For unbuffered operands, <see cref="NDIterState.BufStrides"/> is set to
/// the operand's TRUE inner-axis byte stride so that
/// <c>GetInnerLoopByteStrides()</c> exposes one consistent stride array to
/// kernels under BUFFER. (Buffered operands get the tight element size.)
/// </summary>
public static bool AllocateBuffers(ref NDIterState state, long bufferSize)
{
if (bufferSize <= 0)
bufferSize = DetermineBufferSize(ref state, 0);
state.BufferSize = bufferSize;
for (int op = 0; op < state.NOp; op++)
{
var opFlags = state.GetOpFlags(op);
var dtype = state.GetOpDType(op);
// Skip if operand doesn't need buffering
if ((opFlags & NDIterOpFlags.BUFNEVER) != 0)
{
SetUnbufferedBufStride(ref state, op);
continue;
}
// Buffered REDUCE keeps the historical criterion (its double-loop
// machinery owns BufStrides/DataPtr swapping for every operand,
// incl. the stride-0 accumulator slot). The windowed non-reduce
// path uses the linearity criterion so linear strided operands
// stay unbuffered and keep their true strides.
bool reduceIter = (state.ItFlags & (uint)NDIterFlags.REDUCE) != 0;
bool needsBuffer =
state.NeedsCast(op) ||
(opFlags & (NDIterOpFlags.CAST | NDIterOpFlags.CONTIG | NDIterOpFlags.REDUCE)) != 0 ||
(reduceIter ? !IsOperandContiguous(ref state, op)
: !IsOperandIterLinear(ref state, op));
if (needsBuffer)
{
// A buffered WRITEMASKED write means the flush will be a
// MASKED copy-back reading the ARRAYMASK operand byte-wise.
// NumPy validates the mask dtype when it builds that masked
// transfer function (nditer_constr.c:3470-3494 →
// dtype_transfer.c, TypeError) — same here, same text. Both
// the mask's array dtype and its buffer dtype must be a
// 1-byte nonzero-test type or the byte-wise reads are junk.
if ((opFlags & NDIterOpFlags.WRITEMASKED) != 0 &&
(opFlags & NDIterOpFlags.WRITE) != 0 &&
state.MaskOp >= 0)
{
var maskSrcType = state.GetOpSrcDType(state.MaskOp);
var maskBufType = state.GetOpDType(state.MaskOp);
if ((maskSrcType != NPTypeCode.Boolean && maskSrcType != NPTypeCode.Byte) ||
(maskBufType != NPTypeCode.Boolean && maskBufType != NPTypeCode.Byte))
{
throw new NotSupportedException(
"Only bool and uint8 masks are supported.");
}
}
var buffer = AllocateAligned(bufferSize, dtype);
if (buffer == null)
{
// Cleanup already allocated buffers
FreeBuffers(ref state);
return false;
}
state.SetBuffer(op, buffer);
state.BufStrides[op] = state.GetElementSize(op);
}
else
{
SetUnbufferedBufStride(ref state, op);
}
}
return true;
}
/// <summary>
/// Record the true inner-axis byte stride for an operand that is NOT
/// buffered, so kernels see correct strides via BufStrides under BUFFER.
/// </summary>
private static void SetUnbufferedBufStride(ref NDIterState state, int op)
{
if (state.NDim == 0)
{
state.BufStrides[op] = 0;
return;
}
long innerElemStride = state.GetStride(state.NDim - 1, op);
state.BufStrides[op] = innerElemStride * state.GetSrcElementSize(op);
}
/// <summary>
/// True when the operand's memory positions form one arithmetic
/// progression over the entire (coalesced) iteration space — i.e. a
/// single 1-D walk at the inner stride covers every element in order.
/// Contiguous operands, constant-stride 1-D views, and fully-broadcast
/// (all-stride-0) operands qualify; genuinely multi-dimensional strided
/// operands do not.
/// </summary>
public static bool IsOperandIterLinear(ref NDIterState state, int op)
{
if (state.NDim <= 1)
return true;
long inner = state.GetStride(state.NDim - 1, op);
long expected = inner * state.Shape[state.NDim - 1];
for (int d = state.NDim - 2; d >= 0; d--)
{
long dim = state.Shape[d];
if (dim == 0)
return true; // empty iteration — trivially linear
if (dim != 1)
{
if (state.GetStride(d, op) != expected)
return false;
}
expected *= dim;
}
return true;
}
/// <summary>
/// Free all allocated buffers.
/// </summary>
public static void FreeBuffers(ref NDIterState state)
{
for (int op = 0; op < state.NOp; op++)
{
var buffer = state.GetBuffer(op);
if (buffer != null)
{
FreeAligned(buffer);
state.SetBuffer(op, null);
}
}
}
/// <summary>
/// Check if an operand is contiguous in the current iteration space.
/// </summary>
private static bool IsOperandContiguous(ref NDIterState state, int op)
{
if (state.NDim == 0)
return true;
long expected = 1;
// Access dynamically allocated arrays directly (not fixed arrays)
var shape = state.Shape;
var strides = state.Strides;
int stridesNDim = state.StridesNDim;
for (int axis = state.NDim - 1; axis >= 0; axis--)
{
long dim = shape[axis];
if (dim == 0)
return true;
long stride = strides[op * stridesNDim + axis];
if (dim != 1)
{
if (stride != expected)
return false;
expected *= dim;
}
}
return true;
}
/// <summary>
/// Copy data from operand to buffer (strided to contiguous).
/// If operand needs casting, performs type conversion during copy.
/// Runtime dtype dispatch version - handles any NumSharp dtype.
/// </summary>
public static void CopyToBuffer(ref NDIterState state, int op, long count)
{
// Check if casting is needed
if (state.NeedsCast(op))
{
CopyToBufferWithCast(ref state, op, count);
return;
}
// No casting - use same-type copy
var dtype = state.GetOpDType(op);
switch (dtype)
{
case NPTypeCode.Boolean: CopyToBuffer<bool>(ref state, op, count); break;
case NPTypeCode.Byte: CopyToBuffer<byte>(ref state, op, count); break;
case NPTypeCode.SByte: CopyToBuffer<sbyte>(ref state, op, count); break;
case NPTypeCode.Int16: CopyToBuffer<short>(ref state, op, count); break;
case NPTypeCode.UInt16: CopyToBuffer<ushort>(ref state, op, count); break;
case NPTypeCode.Int32: CopyToBuffer<int>(ref state, op, count); break;
case NPTypeCode.UInt32: CopyToBuffer<uint>(ref state, op, count); break;
case NPTypeCode.Int64: CopyToBuffer<long>(ref state, op, count); break;
case NPTypeCode.UInt64: CopyToBuffer<ulong>(ref state, op, count); break;
case NPTypeCode.Half: CopyToBuffer<Half>(ref state, op, count); break;
case NPTypeCode.Single: CopyToBuffer<float>(ref state, op, count); break;
case NPTypeCode.Double: CopyToBuffer<double>(ref state, op, count); break;
case NPTypeCode.Decimal: CopyToBuffer<decimal>(ref state, op, count); break;
case NPTypeCode.Complex: CopyToBuffer<System.Numerics.Complex>(ref state, op, count); break;
case NPTypeCode.Char: CopyToBuffer<char>(ref state, op, count); break;
default: throw new NotSupportedException($"Buffer copy not supported for dtype {dtype}");
}
}
/// <summary>
/// Copy data from buffer to operand (contiguous to strided).
/// If operand needs casting, performs type conversion during copy.
/// Runtime dtype dispatch version - handles any NumSharp dtype.
/// </summary>
public static void CopyFromBuffer(ref NDIterState state, int op, long count)
{
// Check if casting is needed
if (state.NeedsCast(op))
{
CopyFromBufferWithCast(ref state, op, count);
return;
}
// No casting - use same-type copy
var dtype = state.GetOpDType(op);
switch (dtype)
{
case NPTypeCode.Boolean: CopyFromBuffer<bool>(ref state, op, count); break;
case NPTypeCode.Byte: CopyFromBuffer<byte>(ref state, op, count); break;
case NPTypeCode.SByte: CopyFromBuffer<sbyte>(ref state, op, count); break;
case NPTypeCode.Int16: CopyFromBuffer<short>(ref state, op, count); break;
case NPTypeCode.UInt16: CopyFromBuffer<ushort>(ref state, op, count); break;
case NPTypeCode.Int32: CopyFromBuffer<int>(ref state, op, count); break;
case NPTypeCode.UInt32: CopyFromBuffer<uint>(ref state, op, count); break;
case NPTypeCode.Int64: CopyFromBuffer<long>(ref state, op, count); break;
case NPTypeCode.UInt64: CopyFromBuffer<ulong>(ref state, op, count); break;
case NPTypeCode.Half: CopyFromBuffer<Half>(ref state, op, count); break;
case NPTypeCode.Single: CopyFromBuffer<float>(ref state, op, count); break;
case NPTypeCode.Double: CopyFromBuffer<double>(ref state, op, count); break;
case NPTypeCode.Decimal: CopyFromBuffer<decimal>(ref state, op, count); break;
case NPTypeCode.Complex: CopyFromBuffer<System.Numerics.Complex>(ref state, op, count); break;
case NPTypeCode.Char: CopyFromBuffer<char>(ref state, op, count); break;
default: throw new NotSupportedException($"Buffer copy not supported for dtype {dtype}");
}
}
/// <summary>
/// Copy data from operand to buffer with type conversion.
/// </summary>
public static void CopyToBufferWithCast(ref NDIterState state, int op, long count)
{
var buffer = state.GetBuffer(op);
if (buffer == null || count <= 0)
return;
var srcType = state.GetOpSrcDType(op);
var dstType = state.GetOpDType(op);
var src = state.GetDataPtr(op);
if (src == null)
return;
if (state.NDim == 0)
{
// Scalar - just convert one value
NDIterCasting.ConvertValue(src, buffer, srcType, dstType);
return;
}
var stridePtr = state.GetStridesPointer(op);
if (state.NDim == 1)
{
// Simple 1D copy with cast
long stride = stridePtr[0];
NDIterCasting.CopyWithCast(src, stride, srcType, buffer, 1, dstType, count);
}
else
{
// Multi-dimensional strided copy with cast
NDIterCasting.CopyStridedToContiguousWithCast(
src, stridePtr, srcType,
buffer, dstType,
state.GetShapePointer(), state.NDim, count);
}
}
/// <summary>
/// Copy data from buffer to operand with type conversion.
/// </summary>
public static void CopyFromBufferWithCast(ref NDIterState state, int op, long count)
{
var buffer = state.GetBuffer(op);
if (buffer == null)
return;
var opFlags = state.GetOpFlags(op);
if ((opFlags & NDIterOpFlags.WRITE) == 0)
return; // Read-only operand
var srcType = state.GetOpDType(op); // Buffer dtype
var dstType = state.GetOpSrcDType(op); // Array dtype
var dst = state.GetDataPtr(op);
var stridePtr = state.GetStridesPointer(op);
if (state.NDim == 1)
{
// Simple 1D copy with cast
long stride = stridePtr[0];
NDIterCasting.CopyWithCast(buffer, 1, srcType, dst, stride, dstType, count);
}
else
{
// Multi-dimensional strided copy with cast
NDIterCasting.CopyContiguousToStridedWithCast(
buffer, srcType,
dst, stridePtr, dstType,
state.GetShapePointer(), state.NDim, count);
}
}
/// <summary>
/// Copy data from operand to buffer (strided to contiguous).
/// </summary>
public static void CopyToBuffer<T>(
ref NDIterState state,
int op,
long count)
where T : unmanaged
{
var buffer = (T*)state.GetBuffer(op);
if (buffer == null)
return;
var src = (T*)state.GetDataPtr(op);
var stridePtr = state.GetStridesPointer(op);
if (state.NDim == 1)
{
// Simple 1D copy
long stride = stridePtr[0];
if (stride == 1)
{
// Contiguous
Unsafe.CopyBlock(buffer, src, (uint)(count * sizeof(T)));
}
else
{
// Strided
for (long i = 0; i < count; i++)
{
buffer[i] = src[i * stride];
}
}
}
else
{
// Multi-dimensional strided copy
CopyStridedToContiguous<T>(src, buffer, state.GetShapePointer(), stridePtr, state.NDim, count);
}
}
/// <summary>
/// Copy data from buffer to operand (contiguous to strided).
/// </summary>
public static void CopyFromBuffer<T>(
ref NDIterState state,
int op,
long count)
where T : unmanaged
{
var buffer = (T*)state.GetBuffer(op);
if (buffer == null)
return;
var opFlags = state.GetOpFlags(op);
if ((opFlags & NDIterOpFlags.WRITE) == 0)
return; // Read-only operand
var dst = (T*)state.GetDataPtr(op);
var stridePtr = state.GetStridesPointer(op);
if (state.NDim == 1)
{
long stride = stridePtr[0];
if (stride == 1)
{
Unsafe.CopyBlock(dst, buffer, (uint)(count * sizeof(T)));
}
else
{
for (long i = 0; i < count; i++)
{
dst[i * stride] = buffer[i];
}
}
}
else
{
CopyContiguousToStrided<T>(buffer, dst, state.GetShapePointer(), stridePtr, state.NDim, count);
}
}
/// <summary>
/// Copy strided data to contiguous buffer.
/// </summary>
private static void CopyStridedToContiguous<T>(
T* src,
T* dst,
long* shape,
long* strides,
int ndim,
long count)
where T : unmanaged
{
// Use coordinate-based iteration
var coords = stackalloc long[ndim];
for (int d = 0; d < ndim; d++)
coords[d] = 0;
for (long i = 0; i < count; i++)
{
// Calculate source offset
long srcOffset = 0;
for (int d = 0; d < ndim; d++)
{
srcOffset += coords[d] * strides[d];
}
dst[i] = src[srcOffset];
// Advance coordinates (ripple carry)
for (int d = ndim - 1; d >= 0; d--)
{
coords[d]++;
if (coords[d] < shape[d])
break;
coords[d] = 0;
}
}
}
/// <summary>
/// Copy contiguous buffer to strided destination.
/// </summary>
private static void CopyContiguousToStrided<T>(
T* src,
T* dst,
long* shape,
long* strides,
int ndim,
long count)
where T : unmanaged
{
var coords = stackalloc long[ndim];
for (int d = 0; d < ndim; d++)
coords[d] = 0;
for (long i = 0; i < count; i++)
{
long dstOffset = 0;
for (int d = 0; d < ndim; d++)
{
dstOffset += coords[d] * strides[d];
}
dst[dstOffset] = src[i];
for (int d = ndim - 1; d >= 0; d--)
{
coords[d]++;
if (coords[d] < shape[d])
break;
coords[d] = 0;
}
}
}
// =========================================================================
// Windowed buffered iteration (NumPy npyiter_copy_to_buffers /
// npyiter_copy_from_buffers / npyiter_buffered_iternext equivalents)
// =========================================================================
// A "window" is one buffer fill: BufTransferSize elements starting at the
// iterator's current position (IterIndex/Coords — which stay parked at the
// fill start while the kernel consumes the window; BufferedNext flushes,
// jumps, and refills).
//
// Per-operand semantics per fill (matching NumPy):
// • buffered + READ → strided/casting copy into the buffer
// • buffered + WRITEONLY → no copy-in; kernel produces the contents
// • buffered + WRITE → flushed back to the array on iternext/Dispose
// • unbuffered (linear) → DataPtr stays in the array; BufStrides holds
// its true inner byte stride
//
// Fills are capped at BufferSize and, for NDim > 1, row-aligned (end on an
// inner-dimension boundary) — observed NumPy behavior: a (100,100) strided
// source with buffersize=4096 fills in chunks of 4000/4000/2000, with and
// without GROWINNER.
// =========================================================================
/// <summary>
/// Number of elements the next buffer fill should cover, from the
/// iterator's current position. Capped at <see cref="NDIterState.BufferSize"/>;
/// for multi-dim iterations the window ends on an inner-row boundary
/// unless a single row exceeds the buffer (then a partial row is used).
/// </summary>
public static long ComputeTransferSize(ref NDIterState state)
{
long remaining = state.IterEnd - state.IterIndex;
if (remaining <= 0)
return 0;
long cap = Math.Min(remaining, state.BufferSize);
if (state.NDim <= 1 || cap == remaining)
return cap;
long inner = state.Shape[state.NDim - 1];
if (inner <= 0)
return cap;
long posInRow = state.Coords[state.NDim - 1];
long firstRun = inner - posInRow;
if (cap <= firstRun)
return cap; // can't finish the current row — partial-row fill
long wholeRows = (cap - firstRun) / inner;
return firstRun + wholeRows * inner;
}
/// <summary>
/// Fill all buffered READ operands from the iterator's current position
/// for <paramref name="count"/> elements, record the array write-back
/// positions, swap buffered operands' DataPtrs to their buffers, and set
/// the window bookkeeping (BufTransferSize / BufIterEnd / BufFlushed).
/// </summary>
public static void FillBufferWindow(ref NDIterState state, long count)
{
// Save the array positions of the fill start: flush targets, and the
// restore points for unbuffered operands are simply unchanged.
for (int op = 0; op < state.NOp; op++)
state.SetArrayWritebackPtr(op, state.GetDataPtr(op));
for (int op = 0; op < state.NOp; op++)
{
var buffer = state.GetBuffer(op);
if (buffer == null)
continue;
if ((state.GetOpFlags(op) & NDIterOpFlags.READ) != 0 && count > 0)
CopyWindowToBuffer(ref state, op, count);
state.SetDataPtr(op, buffer);
}
state.BufTransferSize = count;
state.BufIterEnd = state.IterIndex + count;
state.BufFlushed = 0;
}
/// <summary>
/// Write the current window's buffered WRITE operands back to their
/// arrays. Idempotent (BufFlushed) so iternext, the single-inner-loop
/// fast paths, and Dispose can all call it.
/// </summary>
public static void FlushBufferWindow(ref NDIterState state)
{
if (state.BufFlushed != 0)
return;
state.BufFlushed = 1;
long count = state.BufTransferSize;
if (count <= 0)
return;
for (int op = 0; op < state.NOp; op++)
{
var buffer = state.GetBuffer(op);
if (buffer == null)
continue;
var opFlags = state.GetOpFlags(op);
if ((opFlags & NDIterOpFlags.WRITE) != 0)
{
// WRITEMASKED: only elements whose ARRAYMASK byte is true
// reach the array; everything else in the buffer is
// discarded. This is the ONLY place masking is enforced —
// an unbuffered WRITEMASKED operand writes the array
// directly and the mask is the kernel's contract, exactly
// like NumPy (verified 2.4.2: 'buffered' + contiguous
// same-dtype operands write unmasked slots too).
// NumPy npyiter_copy_from_buffers (nditer_api.c:2001-2026).
if ((opFlags & NDIterOpFlags.WRITEMASKED) != 0 && state.MaskOp >= 0)
CopyWindowFromBufferMasked(ref state, op, count);
else
CopyWindowFromBuffer(ref state, op, count);
}
}
}
/// <summary>
/// Strided/casting gather of <paramref name="count"/> elements from the
/// operand's array (starting at the fill-start position recorded in
/// ArrayWritebackPtrs, walking the iteration space from the current
/// Coords) into its tight contiguous buffer. Decomposes the window into
/// inner-axis runs and uses the SIMD IL cast kernels per run.
/// </summary>
private static void CopyWindowToBuffer(ref NDIterState state, int op, long count)
{
var srcType = state.GetOpSrcDType(op);
var dstType = state.GetOpDType(op);
int srcSize = state.GetSrcElementSize(op);
int dstSize = state.GetElementSize(op);
byte* src = (byte*)state.GetArrayWritebackPtr(op);
byte* dst = (byte*)state.GetBuffer(op);
if (state.NDim <= 1)
{
long stride = state.NDim == 0 ? 0 : state.GetStride(0, op);
CopyRunToBuffer(src, stride, srcType, srcSize, dst, dstType, count);
return;
}
int ndim = state.NDim;
int innerAxis = ndim - 1;
long innerLen = state.Shape[innerAxis];
long innerStride = state.GetStride(innerAxis, op);
// Local walk state — must NOT mutate the iterator's Coords.
long* coords;
long* coordsHeap = null;
if (ndim <= NDIterState.StackAllocThreshold)
{
long* coordsStack = stackalloc long[ndim];
coords = coordsStack;
}
else
{
coordsHeap = (long*)NativeMemory.Alloc((nuint)(ndim * sizeof(long)));
coords = coordsHeap;
}
try
{
for (int d = 0; d < ndim; d++)
coords[d] = state.Coords[d];
long remaining = count;
while (remaining > 0)
{
long run = Math.Min(remaining, innerLen - coords[innerAxis]);
CopyRunToBuffer(src, innerStride, srcType, srcSize, dst, dstType, run);
dst += run * dstSize;
remaining -= run;
if (remaining <= 0)
break;
// Row finished — ripple-carry to the next position, adjusting
// the source pointer incrementally (same math as Advance()).
src += run * innerStride * srcSize;
coords[innerAxis] += run;
for (int d = innerAxis; d >= 0; d--)
{
if (coords[d] < state.Shape[d])
break;
coords[d] = 0;
src -= state.GetStride(d, op) * state.Shape[d] * srcSize;
if (d == 0)
break;
coords[d - 1]++;
src += state.GetStride(d - 1, op) * srcSize;
}
}
}
finally
{
if (coordsHeap != null)
NativeMemory.Free(coordsHeap);
}
}
/// <summary>
/// Scatter of <paramref name="count"/> elements from the operand's tight
/// contiguous buffer back into its array — the mirror of
/// <see cref="CopyWindowToBuffer"/> (same window: ArrayWritebackPtrs +
/// current Coords, which still describe the fill start).
/// </summary>
private static void CopyWindowFromBuffer(ref NDIterState state, int op, long count)
{
var bufType = state.GetOpDType(op);
var arrType = state.GetOpSrcDType(op);
int bufSize = state.GetElementSize(op);
int arrSize = state.GetSrcElementSize(op);
byte* buf = (byte*)state.GetBuffer(op);
byte* dst = (byte*)state.GetArrayWritebackPtr(op);
if (state.NDim <= 1)
{
long stride = state.NDim == 0 ? 0 : state.GetStride(0, op);
CopyRunFromBuffer(buf, bufType, bufSize, dst, stride, arrType, count);
return;
}
int ndim = state.NDim;
int innerAxis = ndim - 1;
long innerLen = state.Shape[innerAxis];
long innerStride = state.GetStride(innerAxis, op);
long* coords;
long* coordsHeap = null;
if (ndim <= NDIterState.StackAllocThreshold)
{
long* coordsStack = stackalloc long[ndim];
coords = coordsStack;
}
else
{
coordsHeap = (long*)NativeMemory.Alloc((nuint)(ndim * sizeof(long)));
coords = coordsHeap;
}
try
{
for (int d = 0; d < ndim; d++)
coords[d] = state.Coords[d];
long remaining = count;
while (remaining > 0)
{
long run = Math.Min(remaining, innerLen - coords[innerAxis]);
CopyRunFromBuffer(buf, bufType, bufSize, dst, innerStride, arrType, run);
buf += run * bufSize;
remaining -= run;
if (remaining <= 0)
break;
dst += run * innerStride * arrSize;
coords[innerAxis] += run;
for (int d = innerAxis; d >= 0; d--)
{
if (coords[d] < state.Shape[d])
break;
coords[d] = 0;
dst -= state.GetStride(d, op) * state.Shape[d] * arrSize;
if (d == 0)
break;
coords[d - 1]++;
dst += state.GetStride(d - 1, op) * arrSize;
}
}
}
finally
{
if (coordsHeap != null)
NativeMemory.Free(coordsHeap);
}
}
/// <summary>
/// Masked mirror of <see cref="CopyWindowFromBuffer"/> for WRITEMASKED
/// operands: scatters the window back to the array but ONLY where the
/// ARRAYMASK operand's byte is nonzero. The mask is read from its
/// buffer when it was buffered, else from its array at the window's
/// fill-start position (ArrayWritebackPtrs — saved for every operand
/// by <see cref="FillBufferWindow"/>) — NumPy chooses the same way by
/// BUFNEVER (nditer_api.c:2002-2014). The mask byte stride is
/// <see cref="NDIterState.BufStrides"/>: the tight element size for a
/// buffered mask, the TRUE single linear byte stride for an unbuffered
/// one (unbuffered ⇒ IsOperandIterLinear, so window element k sits at
/// exactly k strides from the window start — incl. stride 0 for a
/// fully-broadcast mask).
/// </summary>
private static void CopyWindowFromBufferMasked(ref NDIterState state, int op, long count)
{
int maskOp = state.MaskOp;
byte* maskBuffer = (byte*)state.GetBuffer(maskOp);
byte* mask = maskBuffer != null ? maskBuffer : (byte*)state.GetArrayWritebackPtr(maskOp);
long maskStride = maskBuffer != null
? state.GetElementSize(maskOp)
: state.BufStrides[maskOp];
var bufType = state.GetOpDType(op);
var arrType = state.GetOpSrcDType(op);
int bufSize = state.GetElementSize(op);
int arrSize = state.GetSrcElementSize(op);
byte* buf = (byte*)state.GetBuffer(op);
byte* dst = (byte*)state.GetArrayWritebackPtr(op);
if (state.NDim <= 1)
{
long stride = state.NDim == 0 ? 0 : state.GetStride(0, op);
CopyRunFromBufferMasked(buf, bufType, bufSize, dst, stride, arrType, arrSize,
count, mask, maskStride);
return;
}
int ndim = state.NDim;
int innerAxis = ndim - 1;
long innerLen = state.Shape[innerAxis];
long innerStride = state.GetStride(innerAxis, op);
long* coords;
long* coordsHeap = null;
if (ndim <= NDIterState.StackAllocThreshold)
{
long* coordsStack = stackalloc long[ndim];
coords = coordsStack;
}
else
{
coordsHeap = (long*)NativeMemory.Alloc((nuint)(ndim * sizeof(long)));
coords = coordsHeap;
}
try
{
for (int d = 0; d < ndim; d++)
coords[d] = state.Coords[d];
long remaining = count;
while (remaining > 0)
{
long run = Math.Min(remaining, innerLen - coords[innerAxis]);
CopyRunFromBufferMasked(buf, bufType, bufSize, dst, innerStride, arrType, arrSize,
run, mask, maskStride);
buf += run * bufSize;
mask += run * maskStride;
remaining -= run;
if (remaining <= 0)
break;
dst += run * innerStride * arrSize;
coords[innerAxis] += run;
for (int d = innerAxis; d >= 0; d--)
{
if (coords[d] < state.Shape[d])
break;
coords[d] = 0;
dst -= state.GetStride(d, op) * state.Shape[d] * arrSize;
if (d == 0)
break;
coords[d - 1]++;
dst += state.GetStride(d - 1, op) * arrSize;
}
}
}
finally
{
if (coordsHeap != null)
NativeMemory.Free(coordsHeap);
}
}
/// <summary>
/// One masked inner-axis run: tight buffer → array, writing only where
/// the mask byte is nonzero. Decomposes the run into contiguous TRUE
/// stretches and hands each to the unmasked <see cref="CopyRunFromBuffer"/>
/// (memcpy / SIMD cast kernels stay effective for dense masks) — the
/// same structure as NumPy's _strided_masked_wrapper
/// (dtype_transfer.c: skip false runs via mask scan, transfer true runs).
/// The mask reads are 1-byte nonzero tests, guaranteed by the
/// bool/uint8 mask validation in <see cref="AllocateBuffers"/>.
/// </summary>
private static void CopyRunFromBufferMasked(