forked from zhongkaifu/TensorSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTensorApplyCPU.cs
More file actions
3158 lines (2641 loc) · 100 KB
/
Copy pathTensorApplyCPU.cs
File metadata and controls
3158 lines (2641 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
// Copyright (c) Zhongkai Fu. All rights reserved.
// https://github.com/zhongkaifu/TensorSharp
//
// This file is part of TensorSharp.
//
// TensorSharp is licensed under the BSD-3-Clause license found in the LICENSE file in the root directory of this source tree.
//
// TensorSharp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD-3-Clause License for more details.
// Copyright (c) Zhongkai Fu. All rights reserved.
// https://github.com/zhongkaifu/Seq2SeqSharp
//
// This file is part of Seq2SeqSharp.
//
// Seq2SeqSharp is licensed under the BSD-3-Clause license found in the LICENSE file in the root directory of this source tree.
//
// Seq2SeqSharp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD-3-Clause License for more details.
using System;
using System.Buffers;
using System.Numerics;
using System.Numerics.Tensors;
using System.Runtime.CompilerServices;
using System.Xml;
using System.Threading.Tasks;
using TensorSharp.Cpu;
namespace TensorSharp
{
public class TensorApplyCPU
{
private const int ParallelWorkThreshold = 1 << 15;
#region Tensor iteration methods
unsafe public delegate void Apply1KernelFunction(float* x);
unsafe public delegate void Apply2KernelFunction(float* x, float* y);
unsafe public delegate void Apply3KernelFunction(float* x, float* y, float* z);
unsafe public delegate void Apply4KernelFunction(float* x, float* y, float* z, float* k);
unsafe public delegate void Apply5KernelFunction(float* x, float* y, float* z, float* k, float* l);
unsafe public delegate void ApplyDim2KernelFuncton(float* x, long sizeX, long stridesX, float* y, long sizeY, long stridesY);
unsafe public delegate void ApplyDim3KernelFuncton(float* x, long sizeX, long stridesX, float* y, long sizeY, long stridesY, float* z, long sizeZ, long stridesZ);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe private static bool TryGetContiguousFloat(Tensor tensor, out float* ptr, out int length)
{
if (tensor.ElementType == DType.Float32 && tensor.IsContiguous() && tensor.ElementCount() <= int.MaxValue)
{
ptr = (float*)CpuNativeHelpers.GetBufferStart(tensor);
length = (int)tensor.ElementCount();
return true;
}
ptr = null;
length = 0;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe private static bool TryGetContiguousRows(Tensor tensor, out float* ptr, out int rows, out int cols)
{
if (tensor.ElementType == DType.Float32 && tensor.IsContiguous() && tensor.ElementCount() <= int.MaxValue && tensor.Sizes[^1] <= int.MaxValue)
{
cols = (int)tensor.Sizes[^1];
int elementCount = (int)tensor.ElementCount();
if (cols > 0 && elementCount % cols == 0)
{
ptr = (float*)CpuNativeHelpers.GetBufferStart(tensor);
rows = elementCount / cols;
return true;
}
}
ptr = null;
rows = 0;
cols = 0;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool ShouldParallelize(int outerWork, int innerWork)
{
return outerWork > 1 && (long)outerWork * innerWork >= ParallelWorkThreshold;
}
unsafe private static void SiLUContiguous(float* resultPtr, float* srcPtr, int length)
{
ReadOnlySpan<float> input = new ReadOnlySpan<float>(srcPtr, length);
Span<float> output = new Span<float>(resultPtr, length);
if (resultPtr != srcPtr)
{
TensorPrimitives.Sigmoid(input, output);
TensorPrimitives.Multiply(input, output, output);
return;
}
float[] rented = ArrayPool<float>.Shared.Rent(length);
try
{
Span<float> sigmoid = rented.AsSpan(0, length);
TensorPrimitives.Sigmoid(input, sigmoid);
TensorPrimitives.Multiply(input, sigmoid, output);
}
finally
{
ArrayPool<float>.Shared.Return(rented);
}
}
unsafe private static void SiLUMulContiguous(float* resultPtr, float* gatePtr, float* upPtr, int length)
{
ReadOnlySpan<float> gate = new ReadOnlySpan<float>(gatePtr, length);
ReadOnlySpan<float> up = new ReadOnlySpan<float>(upPtr, length);
Span<float> output = new Span<float>(resultPtr, length);
if (resultPtr != gatePtr && resultPtr != upPtr)
{
TensorPrimitives.Sigmoid(gate, output);
MultiplySiLUGateUp(gate, up, output, output);
return;
}
float[] rented = ArrayPool<float>.Shared.Rent(length);
try
{
Span<float> tmp = rented.AsSpan(0, length);
TensorPrimitives.Sigmoid(gate, tmp);
MultiplySiLUGateUp(gate, up, tmp, output);
}
finally
{
ArrayPool<float>.Shared.Return(rented);
}
}
private static void MultiplySiLUGateUp(
ReadOnlySpan<float> gate,
ReadOnlySpan<float> up,
ReadOnlySpan<float> sigmoid,
Span<float> output)
{
int vectorSize = Vector<float>.Count;
int i = 0;
for (; i <= output.Length - vectorSize; i += vectorSize)
{
Vector<float> value =
new Vector<float>(gate.Slice(i)) *
new Vector<float>(sigmoid.Slice(i)) *
new Vector<float>(up.Slice(i));
value.CopyTo(output.Slice(i));
}
for (; i < output.Length; i++)
{
output[i] = gate[i] * sigmoid[i] * up[i];
}
}
unsafe private static void SigmoidMulContiguous(float* resultPtr, float* xPtr, float* gatePtr, int length)
{
ReadOnlySpan<float> x = new ReadOnlySpan<float>(xPtr, length);
ReadOnlySpan<float> gate = new ReadOnlySpan<float>(gatePtr, length);
Span<float> output = new Span<float>(resultPtr, length);
if (resultPtr != xPtr && resultPtr != gatePtr)
{
TensorPrimitives.Sigmoid(gate, output);
TensorPrimitives.Multiply(x, output, output);
return;
}
float[] rented = ArrayPool<float>.Shared.Rent(length);
try
{
Span<float> tmp = rented.AsSpan(0, length);
TensorPrimitives.Sigmoid(gate, tmp);
TensorPrimitives.Multiply(x, tmp, output);
}
finally
{
ArrayPool<float>.Shared.Return(rented);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe private static Vector<float> LoadVec(float* ptr)
{
return Unsafe.ReadUnaligned<Vector<float>>(ref *(byte*)ptr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe private static void StoreVec(float* ptr, Vector<float> value)
{
Unsafe.WriteUnaligned(ref *(byte*)ptr, value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe private static float DotContiguous(float* lhs, float* rhs, int length)
{
int vectorSize = Vector<float>.Count;
Vector<float> acc = Vector<float>.Zero;
int i = 0;
for (; i <= length - vectorSize; i += vectorSize)
{
acc += LoadVec(lhs + i) * LoadVec(rhs + i);
}
float sum = Vector.Sum(acc);
for (; i < length; i++)
{
sum += lhs[i] * rhs[i];
}
return sum;
}
unsafe static void Apply1(Tensor tensor1, Apply1KernelFunction func)
{
float* buffer1 = (float*)CpuNativeHelpers.GetBufferStart(tensor1);
TensorIterState tensor1Iter = new TensorIterState(buffer1, tensor1.DimensionCount, tensor1.SizesMemory, tensor1.StridesMemory);
do
{
for (; !tensor1Iter.ReachedBlockEnd(); tensor1Iter.BlockStep())
{
func(tensor1Iter.data);
}
} while (tensor1Iter.NextBlock());
}
unsafe static void Apply2(Tensor tensor1, Tensor tensor2, Apply2KernelFunction func, int step = 1)
{
float* buffer1 = (float*)CpuNativeHelpers.GetBufferStart(tensor1);
float* buffer2 = (float*)CpuNativeHelpers.GetBufferStart(tensor2);
TensorIterState tensor1Iter = new TensorIterState(buffer1, tensor1.DimensionCount, tensor1.SizesMemory, tensor1.StridesMemory, step);
TensorIterState tensor2Iter = new TensorIterState(buffer2, tensor2.DimensionCount, tensor2.SizesMemory, tensor2.StridesMemory, step);
do
{
for (; !tensor1Iter.ReachedBlockEnd() && !tensor2Iter.ReachedBlockEnd(); tensor1Iter.BlockStep(), tensor2Iter.BlockStep())
{
func(tensor1Iter.data, tensor2Iter.data);
}
} while (tensor1Iter.NextBlock() && tensor2Iter.NextBlock());
}
unsafe static void Apply3(Tensor tensor1, Tensor tensor2, Tensor tensor3, Apply3KernelFunction func, int step = 1)
{
float* buffer1 = (float*)CpuNativeHelpers.GetBufferStart(tensor1);
float* buffer2 = (float*)CpuNativeHelpers.GetBufferStart(tensor2);
float* buffer3 = (float*)CpuNativeHelpers.GetBufferStart(tensor3);
TensorIterState tensor1Iter = new TensorIterState(buffer1, tensor1.DimensionCount, tensor1.SizesMemory, tensor1.StridesMemory, step);
TensorIterState tensor2Iter = new TensorIterState(buffer2, tensor2.DimensionCount, tensor2.SizesMemory, tensor2.StridesMemory, step);
TensorIterState tensor3Iter = new TensorIterState(buffer3, tensor3.DimensionCount, tensor3.SizesMemory, tensor3.StridesMemory, step);
do
{
for (; !tensor1Iter.ReachedBlockEnd() && !tensor2Iter.ReachedBlockEnd() && !tensor3Iter.ReachedBlockEnd();
tensor1Iter.BlockStep(), tensor2Iter.BlockStep(), tensor3Iter.BlockStep())
{
func(tensor1Iter.data, tensor2Iter.data, tensor3Iter.data);
}
} while (tensor1Iter.NextBlock() && tensor2Iter.NextBlock() && tensor3Iter.NextBlock());
}
unsafe static void Apply4(Tensor tensor1, Tensor tensor2, Tensor tensor3, Tensor tensor4, Apply4KernelFunction func)
{
float* buffer1 = (float*)CpuNativeHelpers.GetBufferStart(tensor1);
float* buffer2 = (float*)CpuNativeHelpers.GetBufferStart(tensor2);
float* buffer3 = (float*)CpuNativeHelpers.GetBufferStart(tensor3);
float* buffer4 = (float*)CpuNativeHelpers.GetBufferStart(tensor4);
TensorIterState tensor1Iter = new TensorIterState(buffer1, tensor1.DimensionCount, tensor1.SizesMemory, tensor1.StridesMemory);
TensorIterState tensor2Iter = new TensorIterState(buffer2, tensor2.DimensionCount, tensor2.SizesMemory, tensor2.StridesMemory);
TensorIterState tensor3Iter = new TensorIterState(buffer3, tensor3.DimensionCount, tensor3.SizesMemory, tensor3.StridesMemory);
TensorIterState tensor4Iter = new TensorIterState(buffer4, tensor4.DimensionCount, tensor4.SizesMemory, tensor4.StridesMemory);
do
{
for (; !tensor1Iter.ReachedBlockEnd() && !tensor2Iter.ReachedBlockEnd() && !tensor3Iter.ReachedBlockEnd() && !tensor4Iter.ReachedBlockEnd();
tensor1Iter.BlockStep(), tensor2Iter.BlockStep(), tensor3Iter.BlockStep(), tensor4Iter.BlockStep())
{
func(tensor1Iter.data, tensor2Iter.data, tensor3Iter.data, tensor4Iter.data);
}
} while (tensor1Iter.NextBlock() && tensor2Iter.NextBlock() && tensor3Iter.NextBlock() && tensor4Iter.NextBlock());
}
unsafe static void Apply5(Tensor tensor1, Tensor tensor2, Tensor tensor3, Tensor tensor4, Tensor tensor5, Apply5KernelFunction func, int step = 1)
{
float* buffer1 = (float*)CpuNativeHelpers.GetBufferStart(tensor1);
float* buffer2 = (float*)CpuNativeHelpers.GetBufferStart(tensor2);
float* buffer3 = (float*)CpuNativeHelpers.GetBufferStart(tensor3);
float* buffer4 = (float*)CpuNativeHelpers.GetBufferStart(tensor4);
float* buffer5 = (float*)CpuNativeHelpers.GetBufferStart(tensor5);
TensorIterState tensor1Iter = new TensorIterState(buffer1, tensor1.DimensionCount, tensor1.SizesMemory, tensor1.StridesMemory, step);
TensorIterState tensor2Iter = new TensorIterState(buffer2, tensor2.DimensionCount, tensor2.SizesMemory, tensor2.StridesMemory, step);
TensorIterState tensor3Iter = new TensorIterState(buffer3, tensor3.DimensionCount, tensor3.SizesMemory, tensor3.StridesMemory, step);
TensorIterState tensor4Iter = new TensorIterState(buffer4, tensor4.DimensionCount, tensor4.SizesMemory, tensor4.StridesMemory, step);
TensorIterState tensor5Iter = new TensorIterState(buffer5, tensor5.DimensionCount, tensor5.SizesMemory, tensor5.StridesMemory, step);
do
{
for (; !tensor1Iter.ReachedBlockEnd() && !tensor2Iter.ReachedBlockEnd() && !tensor3Iter.ReachedBlockEnd() && !tensor4Iter.ReachedBlockEnd() && !tensor5Iter.ReachedBlockEnd();
tensor1Iter.BlockStep(), tensor2Iter.BlockStep(), tensor3Iter.BlockStep(), tensor4Iter.BlockStep(), tensor5Iter.BlockStep())
{
func(tensor1Iter.data, tensor2Iter.data, tensor3Iter.data, tensor4Iter.data, tensor5Iter.data);
}
} while (tensor1Iter.NextBlock() && tensor2Iter.NextBlock() && tensor3Iter.NextBlock() && tensor4Iter.NextBlock() && tensor5Iter.NextBlock());
}
unsafe static void ApplyDim2(Tensor tensor1, Tensor tensor2, int iterationDim, ApplyDim2KernelFuncton func)
{
float* buffer1 = (float*)CpuNativeHelpers.GetBufferStart(tensor1);
float* buffer2 = (float*)CpuNativeHelpers.GetBufferStart(tensor2);
TensorDimIterState tensor1Iter = new TensorDimIterState(buffer1, tensor1.DimensionCount, tensor1.SizesMemory, tensor1.StridesMemory, iterationDim);
TensorDimIterState tensor2Iter = new TensorDimIterState(buffer2, tensor2.DimensionCount, tensor2.SizesMemory, tensor2.StridesMemory, iterationDim);
do
{
func(tensor1Iter.data, tensor1Iter.size, tensor1Iter.stride,
tensor2Iter.data, tensor2Iter.size, tensor2Iter.stride);
} while (tensor1Iter.NextBlock() && tensor2Iter.NextBlock());
}
unsafe static void ApplyDim3(Tensor tensor1, Tensor tensor2, Tensor tensor3, int iterationDim, ApplyDim3KernelFuncton func)
{
float* buffer1 = (float*)CpuNativeHelpers.GetBufferStart(tensor1);
float* buffer2 = (float*)CpuNativeHelpers.GetBufferStart(tensor2);
float* buffer3 = (float*)CpuNativeHelpers.GetBufferStart(tensor3);
TensorDimIterState tensor1Iter = new TensorDimIterState(buffer1, tensor1.DimensionCount, tensor1.SizesMemory, tensor1.StridesMemory, iterationDim);
TensorDimIterState tensor2Iter = new TensorDimIterState(buffer2, tensor2.DimensionCount, tensor2.SizesMemory, tensor2.StridesMemory, iterationDim);
TensorDimIterState tensor3Iter = new TensorDimIterState(buffer3, tensor3.DimensionCount, tensor3.SizesMemory, tensor3.StridesMemory, iterationDim);
do
{
func(tensor1Iter.data, tensor1Iter.size, tensor1Iter.stride,
tensor2Iter.data, tensor2Iter.size, tensor2Iter.stride,
tensor3Iter.data, tensor3Iter.size, tensor3Iter.stride);
} while (tensor1Iter.NextBlock() && tensor2Iter.NextBlock() && tensor3Iter.NextBlock());
}
#endregion
// True iff all three tensors are 2D contiguous float32 with matching
// outer shape (i.e. a typical [N,D] gather/scatter layout). The fast
// paths below bypass the generic TensorDimIterState walk: they iterate
// rows in the outer loop (cache-friendly writes) and detect the
// embedding-style "all indices in a row equal" pattern to emit a
// single row memcpy instead of D scalar copies.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe bool TryGetGatherScatter2DFast(
Tensor result, Tensor src, Tensor indices, int dim,
out float* rPtr, out float* sPtr, out float* iPtr,
out long N, out long D, out long otherDim)
{
rPtr = sPtr = iPtr = null;
N = D = otherDim = 0;
if (result == null || src == null || indices == null) return false;
if (result.DimensionCount != 2 || src.DimensionCount != 2 || indices.DimensionCount != 2) return false;
if (dim != 0 && dim != 1) return false;
if (result.ElementType != DType.Float32 || src.ElementType != DType.Float32) return false;
if (indices.ElementType != DType.Float32) return false;
if (!result.IsContiguous() || !src.IsContiguous() || !indices.IsContiguous()) return false;
// Shape preconditions match the public API: result.shape == indices.shape,
// and src/result agree on every dim except `dim`.
if (result.Sizes[0] != indices.Sizes[0] || result.Sizes[1] != indices.Sizes[1]) return false;
int otherIdx = dim == 0 ? 1 : 0;
if (src.Sizes[otherIdx] != result.Sizes[otherIdx]) return false;
N = result.Sizes[0];
D = result.Sizes[1];
otherDim = src.Sizes[dim];
rPtr = (float*)CpuNativeHelpers.GetBufferStart(result);
sPtr = (float*)CpuNativeHelpers.GetBufferStart(src);
iPtr = (float*)CpuNativeHelpers.GetBufferStart(indices);
return true;
}
unsafe public static void Gather(Tensor result, Tensor src, int dim, Tensor indices)
{
if (TryGetGatherScatter2DFast(result, src, indices, dim,
out float* rPtr, out float* sPtr, out float* iPtr,
out long N, out long D, out long sSize))
{
if (dim == 0)
{
// result[i, j] = src[indices[i, j], j]
for (long i = 0; i < N; i++)
{
float* indRow = iPtr + i * D;
float* resRow = rPtr + i * D;
long firstIdx = (long)indRow[0];
if (firstIdx < 0 || firstIdx >= sSize)
throw new IndexOutOfRangeException($"Invalid index in gather. Idx = '{firstIdx}', sSize = '{sSize}'");
// Detect embedding-style uniform-row indices and emit
// a single row memcpy.
bool uniform = true;
for (long j = 1; j < D; j++)
{
if ((long)indRow[j] != firstIdx) { uniform = false; break; }
}
if (uniform)
{
long bytes = D * sizeof(float);
Buffer.MemoryCopy(sPtr + firstIdx * D, resRow, bytes, bytes);
}
else
{
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= sSize)
throw new IndexOutOfRangeException($"Invalid index in gather. Idx = '{idx}', sSize = '{sSize}'");
resRow[j] = sPtr[idx * D + j];
}
}
}
}
else // dim == 1: result[i, j] = src[i, indices[i, j]]
{
long srcCols = sSize;
for (long i = 0; i < N; i++)
{
float* srcRow = sPtr + i * srcCols;
float* indRow = iPtr + i * D;
float* resRow = rPtr + i * D;
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= srcCols)
throw new IndexOutOfRangeException($"Invalid index in gather. Idx = '{idx}', sSize = '{srcCols}'");
resRow[j] = srcRow[idx];
}
}
}
return;
}
unsafe void func(float* rData, long rSize, long rStride,
float* sData, long sSize2, long sStride,
float* iData, long iSize, long iStride)
{
for (int i = 0; i < iSize; ++i)
{
long idx = (long)*(iData + i * iStride);
if (idx < 0 || idx >= sSize2) { throw new IndexOutOfRangeException($"Invalid index in gather. Idx = '{idx}', sSize = '{sSize2}'"); }
*(rData + i * rStride) = sData[idx * sStride];
}
}
ApplyDim3(result, src, indices, dim, func);
}
unsafe public static void Scatter(Tensor result, Tensor src, int dim, Tensor indices)
{
if (TryGetGatherScatter2DFast(result, src, indices, dim,
out float* rPtr, out float* sPtr, out float* iPtr,
out long N, out long D, out long rSize))
{
if (dim == 0)
{
// result[indices[i, j], j] = src[i, j]
for (long i = 0; i < N; i++)
{
float* indRow = iPtr + i * D;
float* srcRow = sPtr + i * D;
long firstIdx = (long)indRow[0];
if (firstIdx < 0 || firstIdx >= rSize)
throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{firstIdx}', rSize = '{rSize}'");
bool uniform = true;
for (long j = 1; j < D; j++)
{
if ((long)indRow[j] != firstIdx) { uniform = false; break; }
}
if (uniform)
{
long bytes = D * sizeof(float);
Buffer.MemoryCopy(srcRow, rPtr + firstIdx * D, bytes, bytes);
}
else
{
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= rSize)
throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{idx}', rSize = '{rSize}'");
rPtr[idx * D + j] = srcRow[j];
}
}
}
}
else // dim == 1: result[i, indices[i, j]] = src[i, j]
{
long resCols = rSize;
for (long i = 0; i < N; i++)
{
float* resRow = rPtr + i * resCols;
float* indRow = iPtr + i * D;
float* srcRow = sPtr + i * D;
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= resCols)
throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{idx}', rSize = '{resCols}'");
resRow[idx] = srcRow[j];
}
}
}
return;
}
unsafe void func(float* rData, long rSize2, long rStride,
float* sData, long sSize, long sStride,
float* iData, long iSize, long iStride)
{
for (int i = 0; i < iSize; ++i)
{
long idx = (long)*(iData + i * iStride);
if (idx < 0 || idx >= rSize2) { throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{idx}', rSize = '{rSize2}'"); }
rData[idx * rStride] = *(sData + i * sStride);
}
}
ApplyDim3(result, src, indices, dim, func);
}
unsafe public static void ScatterAdd(Tensor result, Tensor src, int dim, Tensor indices)
{
if (TryGetGatherScatter2DFast(result, src, indices, dim,
out float* rPtr, out float* sPtr, out float* iPtr,
out long N, out long D, out long rSize))
{
if (dim == 0)
{
// result[indices[i, j], j] += src[i, j]
for (long i = 0; i < N; i++)
{
float* indRow = iPtr + i * D;
float* srcRow = sPtr + i * D;
long firstIdx = (long)indRow[0];
if (firstIdx < 0 || firstIdx >= rSize)
throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{firstIdx}', rSize = '{rSize}'");
bool uniform = true;
for (long j = 1; j < D; j++)
{
if ((long)indRow[j] != firstIdx) { uniform = false; break; }
}
if (uniform)
{
// Vectorized add for the destination row.
int vectorSize = Vector<float>.Count;
float* dst = rPtr + firstIdx * D;
long j = 0;
for (; j <= D - vectorSize; j += vectorSize)
{
Vector<float> a = LoadVec(dst + j);
Vector<float> b = LoadVec(srcRow + j);
StoreVec(dst + j, a + b);
}
for (; j < D; j++)
dst[j] += srcRow[j];
}
else
{
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= rSize)
throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{idx}', rSize = '{rSize}'");
rPtr[idx * D + j] += srcRow[j];
}
}
}
}
else // dim == 1: result[i, indices[i, j]] += src[i, j]
{
long resCols = rSize;
for (long i = 0; i < N; i++)
{
float* resRow = rPtr + i * resCols;
float* indRow = iPtr + i * D;
float* srcRow = sPtr + i * D;
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= resCols)
throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{idx}', rSize = '{resCols}'");
resRow[idx] += srcRow[j];
}
}
}
return;
}
unsafe void func(float* rData, long rSize2, long rStride,
float* sData, long sSize, long sStride,
float* iData, long iSize, long iStride)
{
for (int i = 0; i < iSize; ++i)
{
long idx = (long)*(iData + i * iStride);
if (idx < 0 || idx >= rSize2) { throw new IndexOutOfRangeException($"Invalid index in scatter. Idx = '{idx}', rSize = '{rSize2}'"); }
rData[idx * rStride] += *(sData + i * sStride);
}
}
ApplyDim3(result, src, indices, dim, func);
}
unsafe public static void ScatterFill(Tensor result, float value, int dim, Tensor indices)
{
// 2D-contig fast path for ScatterFill (no src tensor).
if (result != null && indices != null
&& result.DimensionCount == 2 && indices.DimensionCount == 2
&& (dim == 0 || dim == 1)
&& result.ElementType == DType.Float32 && indices.ElementType == DType.Float32
&& result.IsContiguous() && indices.IsContiguous()
&& indices.Sizes[1 - dim] == result.Sizes[1 - dim])
{
long N = indices.Sizes[0];
long D = indices.Sizes[1];
long otherDim = result.Sizes[dim];
float* rPtrFast = (float*)CpuNativeHelpers.GetBufferStart(result);
float* iPtrFast = (float*)CpuNativeHelpers.GetBufferStart(indices);
if (dim == 0)
{
long resCols = result.Sizes[1];
for (long i = 0; i < N; i++)
{
float* indRow = iPtrFast + i * D;
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= otherDim)
throw new IndexOutOfRangeException($"Invalid index in ScatterFill. Idx = '{idx}', rSize = '{otherDim}'");
rPtrFast[idx * resCols + j] = value;
}
}
}
else // dim == 1
{
long resCols = result.Sizes[1];
for (long i = 0; i < N; i++)
{
float* resRow = rPtrFast + i * resCols;
float* indRow = iPtrFast + i * D;
for (long j = 0; j < D; j++)
{
long idx = (long)indRow[j];
if (idx < 0 || idx >= resCols)
throw new IndexOutOfRangeException($"Invalid index in ScatterFill. Idx = '{idx}', rSize = '{resCols}'");
resRow[idx] = value;
}
}
}
return;
}
unsafe void func(float* rData, long rSize, long rStride, float* iData, long iSize, long iStride)
{
for (int i = 0; i < iSize; ++i)
{
long idx = (long)*(iData + i * iStride);
if (idx < 0 || idx >= rSize) { throw new IndexOutOfRangeException($"Invalid index in ScatterFill. Idx = '{idx}', rSize = '{rSize}'"); }
rData[idx * rStride] = value;
}
}
ApplyDim2(result, indices, dim, func);
}
unsafe public static void Fill(Tensor result, float value)
{
if (TryGetContiguousFloat(result, out float* resultPtr, out int length))
{
new Span<float>(resultPtr, length).Fill(value);
return;
}
// The generic Apply1 path treats every element as 4 bytes, so
// routing a Float16 (or block-quantized Q8_0) tensor through it
// walks past the storage buffer and surfaces as an
// AccessViolationException during KV-cache zero-init. Mirror the
// GGML backend's contiguous F16/Q8_0 fast paths so non-F32 caches
// can be filled safely on the managed CPU backend.
if (result.ElementType == DType.Float16 && IsContiguousNonNarrowed(result))
{
ushort halfBits = BitConverter.HalfToUInt16Bits((System.Half)value);
ushort* halfBuffer = (ushort*)CpuNativeHelpers.GetBufferStart(result);
long elementCount = result.ElementCount();
if (halfBits == 0)
{
long offset = 0;
while (offset < elementCount)
{
int slice = (int)Math.Min(elementCount - offset, int.MaxValue);
new Span<ushort>(halfBuffer + offset, slice).Clear();
offset += slice;
}
}
else
{
for (long i = 0; i < elementCount; i++)
halfBuffer[i] = halfBits;
}
return;
}
if (result.ElementType == DType.Q8_0 && IsContiguousNonNarrowed(result))
{
if (value != 0f)
throw new NotSupportedException("Fill on Q8_0 tensors only supports value=0 (cache reset).");
long byteLength = DTypeExtensions.Q8_0Bytes(result.ElementCount());
byte* byteBuffer = (byte*)CpuNativeHelpers.GetBufferStart(result);
long offset = 0;
while (offset < byteLength)
{
int slice = (int)Math.Min(byteLength - offset, int.MaxValue);
new Span<byte>(byteBuffer + offset, slice).Clear();
offset += slice;
}
return;
}
if (result.ElementType != DType.Float32)
throw new NotSupportedException(
$"Fill on {result.ElementType} tensors requires a contiguous, non-narrowed layout.");
unsafe void func(float* r)
{
*r = value;
}
Apply1(result, func);
}
private static bool IsContiguousNonNarrowed(Tensor t)
{
if (t.StorageOffset != 0) return false;
long expected = 1;
for (int d = t.DimensionCount - 1; d >= 0; d--)
{
if (t.Strides[d] != expected) return false;
expected *= t.Sizes[d];
}
return expected == t.ElementCount();
}
unsafe public static void Clamp(Tensor result, Tensor src, float min, float max)
{
unsafe void func(float* r, float* s)
{
*r = clamp(*s, min, max);
}
Apply2(result, src, func);
}
unsafe public static void Copy(Tensor result, Tensor src)
{
if (result.IsContiguous() && src.IsContiguous() &&
result.ElementType == src.ElementType &&
result.ElementCount() == src.ElementCount())
{
long byteCount = result.ElementCount() * result.ElementType.Size();
if (byteCount <= int.MaxValue)
{
byte* srcBytes = (byte*)CpuNativeHelpers.GetBufferStart(src);
byte* resultBytes = (byte*)CpuNativeHelpers.GetBufferStart(result);
new ReadOnlySpan<byte>(srcBytes, (int)byteCount).CopyTo(new Span<byte>(resultBytes, (int)byteCount));
}
else
{
Buffer.MemoryCopy(
CpuNativeHelpers.GetBufferStart(src).ToPointer(),
CpuNativeHelpers.GetBufferStart(result).ToPointer(),
byteCount,
byteCount);
}
return;
}
int vectorSize = Vector<float>.Count;
if (result.Strides[^1] == 1 && src.Strides[^1] == 1 && result.Sizes[^1] % vectorSize == 0)
{
unsafe void funcVec(float* r, float* s)
{
Span<float> spanR = new Span<float>(r, vectorSize);
Span<float> spanS = new Span<float>(s, vectorSize);
Vector<float> vecS = new Vector<float>(spanS);
vecS.CopyTo(spanR);
}
Apply2(result, src, funcVec, vectorSize);
}
else
{
unsafe void func(float* r, float* s)
{
*r = *s;
}
Apply2(result, src, func);
}
}
unsafe public static void Sum(Tensor result, Tensor src, int dimension)
{
unsafe void func(float* r, long rSize, long rStride, float* s, long sSize, long sStride)
{
float sum = 0.0f;
for (long i = 0; i < sSize; ++i)
{
sum += s[i * sStride];
}
*r = sum;
}
ApplyDim2(result, src, dimension, func);
}
unsafe public static void Mean(Tensor result, Tensor src, int dimension)
{
unsafe void func(float* r, long rSize, long rStride, float* s, long sSize, long sStride)
{
float sum = 0.0f;
for (long i = 0; i < sSize; ++i)
{
sum += s[i * sStride];
}
*r = sum / sSize;
}
ApplyDim2(result, src, dimension, func);
}
unsafe public static void Argmax(Tensor resultIndices, Tensor src, int dimension)
{
unsafe void func(float* rIndVal, long rIndSize, long rIndStride,
float* s, long sSize, long sStride)
{
float value = s[0];
float index = 0;
for (long i = 1; i < sSize; ++i)
{
float currentVal = s[i * sStride];
if (currentVal > value)
{
value = currentVal;
index = (float)i;
}
}
*rIndVal = index;
}
ApplyDim2(resultIndices, src, dimension, func);
}
unsafe public static void Max(Tensor result, Tensor src, int dimension)
{
unsafe void func(float* r, long rSize, long rStride, float* s, long sSize, long sStride)
{
float value = s[0];
for (long i = 1; i < sSize; ++i)
{
value = Math.Max(value, s[i * sStride]);
}
*r = value;
}
ApplyDim2(result, src, dimension, func);
}
unsafe public static void Add(Tensor result, Tensor lhs, Tensor rhs)
{
if (TryGetContiguousFloat(result, out float* resultPtr, out int length) &&
TryGetContiguousFloat(lhs, out float* lhsPtr, out int lhsLength) &&
TryGetContiguousFloat(rhs, out float* rhsPtr, out int rhsLength) &&
length == lhsLength && length == rhsLength)
{
int simdWidth = Vector<float>.Count;
int i = 0;
for (; i <= length - simdWidth; i += simdWidth)
{
StoreVec(resultPtr + i, LoadVec(lhsPtr + i) + LoadVec(rhsPtr + i));
}
for (; i < length; i++)
{
resultPtr[i] = lhsPtr[i] + rhsPtr[i];
}
return;
}
int vectorSize = Vector<float>.Count;
if (result.Strides[^1] == 1 && lhs.Strides[^1] == 1 && rhs.Strides[^1] == 1 && result.Sizes[^1] % vectorSize == 0)
{
unsafe void funcVec(float* r, float* left, float* right)
{
Span<float> spanR = new Span<float>(r, vectorSize);
Span<float> spanLeft = new Span<float>(left, vectorSize);
Span<float> spanRight = new Span<float>(right, vectorSize);
Vector<float> vecLeft = new Vector<float>(spanLeft);
Vector<float> vecRight = new Vector<float>(spanRight);
Vector<float> vecR = vecLeft + vecRight;
vecR.CopyTo(spanR);
}
Apply3(result, lhs, rhs, funcVec, vectorSize);
}
else
{
unsafe void func(float* r, float* left, float* right)
{
*r = add(*left, *right);
}
Apply3(result, lhs, rhs, func);
}
}
unsafe public static void Sub(Tensor result, Tensor lhs, Tensor rhs)
{
if (TryGetContiguousFloat(result, out float* resultPtr, out int length) &&
TryGetContiguousFloat(lhs, out float* lhsPtr, out int lhsLength) &&
TryGetContiguousFloat(rhs, out float* rhsPtr, out int rhsLength) &&
length == lhsLength && length == rhsLength)
{
int simdWidth = Vector<float>.Count;
int i = 0;
for (; i <= length - simdWidth; i += simdWidth)
{
StoreVec(resultPtr + i, LoadVec(lhsPtr + i) - LoadVec(rhsPtr + i));
}
for (; i < length; i++)
{
resultPtr[i] = lhsPtr[i] - rhsPtr[i];
}
return;
}
int vectorSize = Vector<float>.Count;
if (result.Strides[^1] == 1 && lhs.Strides[^1] == 1 && rhs.Strides[^1] == 1 && result.Sizes[^1] % vectorSize == 0)