-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
TensorPrimitives.netcore.cs
11607 lines (9483 loc) · 610 KB
/
TensorPrimitives.netcore.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86;
namespace System.Numerics.Tensors
{
public static unsafe partial class TensorPrimitives
{
/// <summary>Defines the threshold, in bytes, at which non-temporal stores will be used.</summary>
/// <remarks>
/// A non-temporal store is one that allows the CPU to bypass the cache when writing to memory.
///
/// This can be beneficial when working with large amounts of memory where the writes would otherwise
/// cause large amounts of repeated updates and evictions. The hardware optimization manuals recommend
/// the threshold to be roughly half the size of the last level of on-die cache -- that is, if you have approximately
/// 4MB of L3 cache per core, you'd want this to be approx. 1-2MB, depending on if hyperthreading was enabled.
///
/// However, actually computing the amount of L3 cache per core can be tricky or error prone. Native memcpy
/// algorithms use a constant threshold that is typically around 256KB and we match that here for simplicity. This
/// threshold accounts for most processors in the last 10-15 years that had approx. 1MB L3 per core and support
/// hyperthreading, giving a per core last level cache of approx. 512KB.
/// </remarks>
private const nuint NonTemporalByteThreshold = 256 * 1024;
/// <summary>
/// Copies <paramref name="source"/> to <paramref name="destination"/>, converting each <see cref="float" />
/// value to its nearest representable half-precision floating-point value.
/// </summary>
/// <param name="source">The source span from which to copy values.</param>
/// <param name="destination">The destination span into which the converted values should be written.</param>
/// <exception cref="ArgumentException">Destination is too short.</exception>
/// <remarks>
/// <para>
/// This method effectively computes <c><paramref name="destination" />[i] = (Half)<paramref name="source" />[i]</c>.
/// </para>
/// <para>
/// <paramref name="source"/> and <paramref name="destination"/> must not overlap. If they do, behavior is undefined.
/// </para>
/// </remarks>
public static void ConvertToHalf(ReadOnlySpan<float> source, Span<Half> destination)
{
if (source.Length > destination.Length)
{
ThrowHelper.ThrowArgument_DestinationTooShort();
}
ref float sourceRef = ref MemoryMarshal.GetReference(source);
ref ushort destinationRef = ref Unsafe.As<Half, ushort>(ref MemoryMarshal.GetReference(destination));
int i = 0, twoVectorsFromEnd;
#if NET8_0_OR_GREATER
if (Vector512.IsHardwareAccelerated)
{
twoVectorsFromEnd = source.Length - (Vector512<float>.Count * 2);
if (i <= twoVectorsFromEnd)
{
// Loop handling two input vectors / one output vector at a time.
do
{
Vector512<uint> lower = SingleToHalfAsWidenedUInt32_Vector512(Vector512.LoadUnsafe(ref sourceRef, (uint)i));
Vector512<uint> upper = SingleToHalfAsWidenedUInt32_Vector512(Vector512.LoadUnsafe(ref sourceRef, (uint)(i + Vector512<float>.Count)));
Vector512.Narrow(lower, upper).StoreUnsafe(ref destinationRef, (uint)i);
i += Vector512<float>.Count * 2;
}
while (i <= twoVectorsFromEnd);
// Handle any remaining elements with final vectors.
if (i != source.Length)
{
i = source.Length - (Vector512<float>.Count * 2);
Vector512<uint> lower = SingleToHalfAsWidenedUInt32_Vector512(Vector512.LoadUnsafe(ref sourceRef, (uint)i));
Vector512<uint> upper = SingleToHalfAsWidenedUInt32_Vector512(Vector512.LoadUnsafe(ref sourceRef, (uint)(i + Vector512<float>.Count)));
Vector512.Narrow(lower, upper).StoreUnsafe(ref destinationRef, (uint)i);
}
return;
}
}
#endif
if (Vector256.IsHardwareAccelerated)
{
twoVectorsFromEnd = source.Length - (Vector256<float>.Count * 2);
if (i <= twoVectorsFromEnd)
{
// Loop handling two input vectors / one output vector at a time.
do
{
Vector256<uint> lower = SingleToHalfAsWidenedUInt32_Vector256(Vector256.LoadUnsafe(ref sourceRef, (uint)i));
Vector256<uint> upper = SingleToHalfAsWidenedUInt32_Vector256(Vector256.LoadUnsafe(ref sourceRef, (uint)(i + Vector256<float>.Count)));
Vector256<ushort> halfs = Vector256.Narrow(lower, upper);
halfs.StoreUnsafe(ref destinationRef, (uint)i);
i += Vector256<float>.Count * 2;
}
while (i <= twoVectorsFromEnd);
// Handle any remaining elements with final vectors.
if (i != source.Length)
{
i = source.Length - (Vector256<float>.Count * 2);
Vector256<uint> lower = SingleToHalfAsWidenedUInt32_Vector256(Vector256.LoadUnsafe(ref sourceRef, (uint)i));
Vector256<uint> upper = SingleToHalfAsWidenedUInt32_Vector256(Vector256.LoadUnsafe(ref sourceRef, (uint)(i + Vector256<float>.Count)));
Vector256.Narrow(lower, upper).StoreUnsafe(ref destinationRef, (uint)i);
}
return;
}
}
if (Vector128.IsHardwareAccelerated)
{
twoVectorsFromEnd = source.Length - (Vector128<float>.Count * 2);
if (i <= twoVectorsFromEnd)
{
// Loop handling two input vectors / one output vector at a time.
do
{
Vector128<uint> lower = SingleToHalfAsWidenedUInt32_Vector128(Vector128.LoadUnsafe(ref sourceRef, (uint)i));
Vector128<uint> upper = SingleToHalfAsWidenedUInt32_Vector128(Vector128.LoadUnsafe(ref sourceRef, (uint)(i + Vector128<float>.Count)));
Vector128.Narrow(lower, upper).StoreUnsafe(ref destinationRef, (uint)i);
i += Vector128<float>.Count * 2;
}
while (i <= twoVectorsFromEnd);
// Handle any remaining elements with final vectors.
if (i != source.Length)
{
i = source.Length - (Vector128<float>.Count * 2);
Vector128<uint> lower = SingleToHalfAsWidenedUInt32_Vector128(Vector128.LoadUnsafe(ref sourceRef, (uint)i));
Vector128<uint> upper = SingleToHalfAsWidenedUInt32_Vector128(Vector128.LoadUnsafe(ref sourceRef, (uint)(i + Vector128<float>.Count)));
Vector128.Narrow(lower, upper).StoreUnsafe(ref destinationRef, (uint)i);
}
return;
}
}
while (i < source.Length)
{
Unsafe.Add(ref destinationRef, i) = BitConverter.HalfToUInt16Bits((Half)Unsafe.Add(ref sourceRef, i));
i++;
}
// This implements a vectorized version of the `explicit operator Half(float value) operator`.
// See detailed description of the algorithm used here:
// https://github.com/dotnet/runtime/blob/ca8d6f0420096831766ec11c7d400e4f7ccc7a34/src/libraries/System.Private.CoreLib/src/System/Half.cs#L606-L714
// The cast operator converts a float to a Half represented as a UInt32, then narrows to a UInt16, and reinterpret casts to Half.
// This does the same, with an input VectorXx<float> and an output VectorXx<uint>.
// Loop handling two input vectors at a time; each input float is double the size of each output Half,
// so we need two vectors of floats to produce one vector of Halfs. Half isn't supported in VectorXx<T>,
// so we convert the VectorXx<float> to a VectorXx<uint>, and the caller then uses this twice, narrows the combination
// into a VectorXx<ushort>, and then saves that out to the destination `ref Half` reinterpreted as `ref ushort`.
#pragma warning disable IDE0059 // https://github.com/dotnet/roslyn/issues/44948
const uint MinExp = 0x3880_0000u; // Minimum exponent for rounding
const uint Exponent126 = 0x3f00_0000u; // Exponent displacement #1
const uint SingleBiasedExponentMask = 0x7F80_0000; // float.BiasedExponentMask; // Exponent mask
const uint Exponent13 = 0x0680_0000u; // Exponent displacement #2
const float MaxHalfValueBelowInfinity = 65520.0f; // Maximum value that is not Infinity in Half
const uint ExponentMask = 0x7C00; // Mask for exponent bits in Half
const uint SingleSignMask = 0x8000_0000u; // float.SignMask; // Mask for sign bit in float
#pragma warning restore IDE0059
static Vector128<uint> SingleToHalfAsWidenedUInt32_Vector128(Vector128<float> value)
{
Vector128<uint> bitValue = value.AsUInt32();
// Extract sign bit
Vector128<uint> sign = Vector128.ShiftRightLogical(bitValue & Vector128.Create(SingleSignMask), 16);
// Detecting NaN (0u if value is NaN; otherwise, ~0u)
Vector128<uint> realMask = Vector128.Equals(value, value).AsUInt32();
// Clear sign bit
value = Vector128.Abs(value);
// Rectify values that are Infinity in Half.
value = Vector128.Min(Vector128.Create(MaxHalfValueBelowInfinity), value);
// Rectify lower exponent
Vector128<uint> exponentOffset0 = Vector128.Max(value, Vector128.Create(MinExp).AsSingle()).AsUInt32();
// Extract exponent
exponentOffset0 &= Vector128.Create(SingleBiasedExponentMask);
// Add exponent by 13
exponentOffset0 += Vector128.Create(Exponent13);
// Round Single into Half's precision (NaN also gets modified here, just setting the MSB of fraction)
value += exponentOffset0.AsSingle();
bitValue = value.AsUInt32();
// Only exponent bits will be modified if NaN
Vector128<uint> maskedHalfExponentForNaN = ~realMask & Vector128.Create(ExponentMask);
// Subtract exponent by 126
bitValue -= Vector128.Create(Exponent126);
// Shift bitValue right by 13 bits to match the boundary of exponent part and fraction part.
Vector128<uint> newExponent = Vector128.ShiftRightLogical(bitValue, 13);
// Clear the fraction parts if the value was NaN.
bitValue &= realMask;
// Merge the exponent part with fraction part, and add the exponent part and fraction part's overflow.
bitValue += newExponent;
// Clear exponents if value is NaN
bitValue &= ~maskedHalfExponentForNaN;
// Merge sign bit with possible NaN exponent
Vector128<uint> signAndMaskedExponent = maskedHalfExponentForNaN | sign;
// Merge sign bit and possible NaN exponent
bitValue |= signAndMaskedExponent;
// The final result
return bitValue;
}
static Vector256<uint> SingleToHalfAsWidenedUInt32_Vector256(Vector256<float> value)
{
Vector256<uint> bitValue = value.AsUInt32();
// Extract sign bit
Vector256<uint> sign = Vector256.ShiftRightLogical(bitValue & Vector256.Create(SingleSignMask), 16);
// Detecting NaN (0u if value is NaN; otherwise, ~0u)
Vector256<uint> realMask = Vector256.Equals(value, value).AsUInt32();
// Clear sign bit
value = Vector256.Abs(value);
// Rectify values that are Infinity in Half.
value = Vector256.Min(Vector256.Create(MaxHalfValueBelowInfinity), value);
// Rectify lower exponent
Vector256<uint> exponentOffset0 = Vector256.Max(value, Vector256.Create(MinExp).AsSingle()).AsUInt32();
// Extract exponent
exponentOffset0 &= Vector256.Create(SingleBiasedExponentMask);
// Add exponent by 13
exponentOffset0 += Vector256.Create(Exponent13);
// Round Single into Half's precision (NaN also gets modified here, just setting the MSB of fraction)
value += exponentOffset0.AsSingle();
bitValue = value.AsUInt32();
// Only exponent bits will be modified if NaN
Vector256<uint> maskedHalfExponentForNaN = ~realMask & Vector256.Create(ExponentMask);
// Subtract exponent by 126
bitValue -= Vector256.Create(Exponent126);
// Shift bitValue right by 13 bits to match the boundary of exponent part and fraction part.
Vector256<uint> newExponent = Vector256.ShiftRightLogical(bitValue, 13);
// Clear the fraction parts if the value was NaN.
bitValue &= realMask;
// Merge the exponent part with fraction part, and add the exponent part and fraction part's overflow.
bitValue += newExponent;
// Clear exponents if value is NaN
bitValue &= ~maskedHalfExponentForNaN;
// Merge sign bit with possible NaN exponent
Vector256<uint> signAndMaskedExponent = maskedHalfExponentForNaN | sign;
// Merge sign bit and possible NaN exponent
bitValue |= signAndMaskedExponent;
// The final result
return bitValue;
}
#if NET8_0_OR_GREATER
static Vector512<uint> SingleToHalfAsWidenedUInt32_Vector512(Vector512<float> value)
{
Vector512<uint> bitValue = value.AsUInt32();
// Extract sign bit
Vector512<uint> sign = Vector512.ShiftRightLogical(bitValue & Vector512.Create(SingleSignMask), 16);
// Detecting NaN (0u if value is NaN; otherwise, ~0u)
Vector512<uint> realMask = Vector512.Equals(value, value).AsUInt32();
// Clear sign bit
value = Vector512.Abs(value);
// Rectify values that are Infinity in Half.
value = Vector512.Min(Vector512.Create(MaxHalfValueBelowInfinity), value);
// Rectify lower exponent
Vector512<uint> exponentOffset0 = Vector512.Max(value, Vector512.Create(MinExp).AsSingle()).AsUInt32();
// Extract exponent
exponentOffset0 &= Vector512.Create(SingleBiasedExponentMask);
// Add exponent by 13
exponentOffset0 += Vector512.Create(Exponent13);
// Round Single into Half's precision (NaN also gets modified here, just setting the MSB of fraction)
value += exponentOffset0.AsSingle();
bitValue = value.AsUInt32();
// Only exponent bits will be modified if NaN
Vector512<uint> maskedHalfExponentForNaN = ~realMask & Vector512.Create(ExponentMask);
// Subtract exponent by 126
bitValue -= Vector512.Create(Exponent126);
// Shift bitValue right by 13 bits to match the boundary of exponent part and fraction part.
Vector512<uint> newExponent = Vector512.ShiftRightLogical(bitValue, 13);
// Clear the fraction parts if the value was NaN.
bitValue &= realMask;
// Merge the exponent part with fraction part, and add the exponent part and fraction part's overflow.
bitValue += newExponent;
// Clear exponents if value is NaN
bitValue &= ~maskedHalfExponentForNaN;
// Merge sign bit with possible NaN exponent
Vector512<uint> signAndMaskedExponent = maskedHalfExponentForNaN | sign;
// Merge sign bit and possible NaN exponent
bitValue |= signAndMaskedExponent;
// The final result
return bitValue;
}
#endif
}
/// <summary>
/// Copies <paramref name="source"/> to <paramref name="destination"/>, converting each half-precision
/// floating-point value to its nearest representable <see cref="float"/> value.
/// </summary>
/// <param name="source">The source span from which to copy values.</param>
/// <param name="destination">The destination span into which the converted values should be written.</param>
/// <exception cref="ArgumentException">Destination is too short.</exception>
/// <remarks>
/// <para>
/// This method effectively computes <c><paramref name="destination" />[i] = (float)<paramref name="source" />[i]</c>.
/// </para>
/// <para>
/// <paramref name="source"/> and <paramref name="destination"/> must not overlap. If they do, behavior is undefined.
/// </para>
/// </remarks>
public static void ConvertToSingle(ReadOnlySpan<Half> source, Span<float> destination)
{
if (source.Length > destination.Length)
{
ThrowHelper.ThrowArgument_DestinationTooShort();
}
ref short sourceRef = ref Unsafe.As<Half, short>(ref MemoryMarshal.GetReference(source));
ref float destinationRef = ref MemoryMarshal.GetReference(destination);
int i = 0, oneVectorFromEnd;
#if NET8_0_OR_GREATER
if (Vector512.IsHardwareAccelerated)
{
oneVectorFromEnd = source.Length - Vector512<short>.Count;
if (i <= oneVectorFromEnd)
{
// Loop handling one input vector / two output vectors at a time.
do
{
(Vector512<int> lower, Vector512<int> upper) = Vector512.Widen(Vector512.LoadUnsafe(ref sourceRef, (uint)i));
HalfAsWidenedUInt32ToSingle_Vector512(lower.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)i);
HalfAsWidenedUInt32ToSingle_Vector512(upper.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)(i + Vector512<float>.Count));
i += Vector512<short>.Count;
}
while (i <= oneVectorFromEnd);
// Handle any remaining elements with a final input vector.
if (i != source.Length)
{
i = source.Length - Vector512<short>.Count;
(Vector512<int> lower, Vector512<int> upper) = Vector512.Widen(Vector512.LoadUnsafe(ref sourceRef, (uint)i));
HalfAsWidenedUInt32ToSingle_Vector512(lower.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)i);
HalfAsWidenedUInt32ToSingle_Vector512(upper.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)(i + Vector512<float>.Count));
}
return;
}
}
#endif
if (Vector256.IsHardwareAccelerated)
{
oneVectorFromEnd = source.Length - Vector256<short>.Count;
if (i <= oneVectorFromEnd)
{
// Loop handling one input vector / two output vectors at a time.
do
{
(Vector256<int> lower, Vector256<int> upper) = Vector256.Widen(Vector256.LoadUnsafe(ref sourceRef, (uint)i));
HalfAsWidenedUInt32ToSingle_Vector256(lower.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)i);
HalfAsWidenedUInt32ToSingle_Vector256(upper.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)(i + Vector256<float>.Count));
i += Vector256<short>.Count;
}
while (i <= oneVectorFromEnd);
// Handle any remaining elements with a final input vector.
if (i != source.Length)
{
i = source.Length - Vector256<short>.Count;
(Vector256<int> lower, Vector256<int> upper) = Vector256.Widen(Vector256.LoadUnsafe(ref sourceRef, (uint)i));
HalfAsWidenedUInt32ToSingle_Vector256(lower.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)i);
HalfAsWidenedUInt32ToSingle_Vector256(upper.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)(i + Vector256<float>.Count));
}
return;
}
}
if (Vector128.IsHardwareAccelerated)
{
oneVectorFromEnd = source.Length - Vector128<short>.Count;
if (i <= oneVectorFromEnd)
{
// Loop handling one input vector / two output vectors at a time.
do
{
(Vector128<int> lower, Vector128<int> upper) = Vector128.Widen(Vector128.LoadUnsafe(ref sourceRef, (uint)i));
HalfAsWidenedUInt32ToSingle_Vector128(lower.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)i);
HalfAsWidenedUInt32ToSingle_Vector128(upper.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)(i + Vector128<float>.Count));
i += Vector128<short>.Count;
}
while (i <= oneVectorFromEnd);
// Handle any remaining elements with a final input vector.
if (i != source.Length)
{
i = source.Length - Vector128<short>.Count;
(Vector128<int> lower, Vector128<int> upper) = Vector128.Widen(Vector128.LoadUnsafe(ref sourceRef, (uint)i));
HalfAsWidenedUInt32ToSingle_Vector128(lower.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)i);
HalfAsWidenedUInt32ToSingle_Vector128(upper.AsUInt32()).StoreUnsafe(ref destinationRef, (uint)(i + Vector128<float>.Count));
}
return;
}
}
while (i < source.Length)
{
Unsafe.Add(ref destinationRef, i) = (float)Unsafe.As<short, Half>(ref Unsafe.Add(ref sourceRef, i));
i++;
}
// This implements a vectorized version of the `explicit operator float(Half value) operator`.
// See detailed description of the algorithm used here:
// https://github.com/dotnet/runtime/blob/3bf40a378f00cb5bf18ff62796bc7097719b974c/src/libraries/System.Private.CoreLib/src/System/Half.cs#L1010-L1040
// The cast operator converts a Half represented as uint to a float. This does the same, with an input VectorXx<uint> and an output VectorXx<float>.
// The VectorXx<uint> is created by reading a vector of Halfs as a VectorXx<short> then widened to two VectorXx<int>s and cast to VectorXx<uint>s.
// We loop handling one input vector at a time, producing two output float vectors.
#pragma warning disable IDE0059 // https://github.com/dotnet/roslyn/issues/44948
const uint ExponentLowerBound = 0x3880_0000u; // The smallest positive normal number in Half, converted to Single
const uint ExponentOffset = 0x3800_0000u; // BitConverter.SingleToUInt32Bits(1.0f) - ((uint)BitConverter.HalfToUInt16Bits((Half)1.0f) << 13)
const uint SingleSignMask = 0x8000_0000; // float.SignMask; // Mask for sign bit in Single
const uint HalfExponentMask = 0x7C00; // Mask for exponent bits in Half
const uint HalfToSingleBitsMask = 0x0FFF_E000; // Mask for bits in Single converted from Half
#pragma warning restore IDE0059
static Vector128<float> HalfAsWidenedUInt32ToSingle_Vector128(Vector128<uint> value)
{
// Extract sign bit of value
Vector128<uint> sign = value & Vector128.Create(SingleSignMask);
// Copy sign bit to upper bits
Vector128<uint> bitValueInProcess = value;
// Extract exponent bits of value (BiasedExponent is not for here as it performs unnecessary shift)
Vector128<uint> offsetExponent = bitValueInProcess & Vector128.Create(HalfExponentMask);
// ~0u when value is subnormal, 0 otherwise
Vector128<uint> subnormalMask = Vector128.Equals(offsetExponent, Vector128<uint>.Zero);
// ~0u when value is either Infinity or NaN, 0 otherwise
Vector128<uint> infinityOrNaNMask = Vector128.Equals(offsetExponent, Vector128.Create(HalfExponentMask));
// 0x3880_0000u if value is subnormal, 0 otherwise
Vector128<uint> maskedExponentLowerBound = subnormalMask & Vector128.Create(ExponentLowerBound);
// 0x3880_0000u if value is subnormal, 0x3800_0000u otherwise
Vector128<uint> offsetMaskedExponentLowerBound = Vector128.Create(ExponentOffset) | maskedExponentLowerBound;
// Match the position of the boundary of exponent bits and fraction bits with IEEE 754 Binary32(Single)
bitValueInProcess = Vector128.ShiftLeft(bitValueInProcess, 13);
// Double the offsetMaskedExponentLowerBound if value is either Infinity or NaN
offsetMaskedExponentLowerBound = Vector128.ConditionalSelect(Vector128.Equals(infinityOrNaNMask, Vector128<uint>.Zero),
offsetMaskedExponentLowerBound,
Vector128.ShiftLeft(offsetMaskedExponentLowerBound, 1));
// Extract exponent bits and fraction bits of value
bitValueInProcess &= Vector128.Create(HalfToSingleBitsMask);
// Adjust exponent to match the range of exponent
bitValueInProcess += offsetMaskedExponentLowerBound;
// If value is subnormal, remove unnecessary 1 on top of fraction bits.
Vector128<uint> absoluteValue = (bitValueInProcess.AsSingle() - maskedExponentLowerBound.AsSingle()).AsUInt32();
// Merge sign bit with rest
return (absoluteValue | sign).AsSingle();
}
static Vector256<float> HalfAsWidenedUInt32ToSingle_Vector256(Vector256<uint> value)
{
// Extract sign bit of value
Vector256<uint> sign = value & Vector256.Create(SingleSignMask);
// Copy sign bit to upper bits
Vector256<uint> bitValueInProcess = value;
// Extract exponent bits of value (BiasedExponent is not for here as it performs unnecessary shift)
Vector256<uint> offsetExponent = bitValueInProcess & Vector256.Create(HalfExponentMask);
// ~0u when value is subnormal, 0 otherwise
Vector256<uint> subnormalMask = Vector256.Equals(offsetExponent, Vector256<uint>.Zero);
// ~0u when value is either Infinity or NaN, 0 otherwise
Vector256<uint> infinityOrNaNMask = Vector256.Equals(offsetExponent, Vector256.Create(HalfExponentMask));
// 0x3880_0000u if value is subnormal, 0 otherwise
Vector256<uint> maskedExponentLowerBound = subnormalMask & Vector256.Create(ExponentLowerBound);
// 0x3880_0000u if value is subnormal, 0x3800_0000u otherwise
Vector256<uint> offsetMaskedExponentLowerBound = Vector256.Create(ExponentOffset) | maskedExponentLowerBound;
// Match the position of the boundary of exponent bits and fraction bits with IEEE 754 Binary32(Single)
bitValueInProcess = Vector256.ShiftLeft(bitValueInProcess, 13);
// Double the offsetMaskedExponentLowerBound if value is either Infinity or NaN
offsetMaskedExponentLowerBound = Vector256.ConditionalSelect(Vector256.Equals(infinityOrNaNMask, Vector256<uint>.Zero),
offsetMaskedExponentLowerBound,
Vector256.ShiftLeft(offsetMaskedExponentLowerBound, 1));
// Extract exponent bits and fraction bits of value
bitValueInProcess &= Vector256.Create(HalfToSingleBitsMask);
// Adjust exponent to match the range of exponent
bitValueInProcess += offsetMaskedExponentLowerBound;
// If value is subnormal, remove unnecessary 1 on top of fraction bits.
Vector256<uint> absoluteValue = (bitValueInProcess.AsSingle() - maskedExponentLowerBound.AsSingle()).AsUInt32();
// Merge sign bit with rest
return (absoluteValue | sign).AsSingle();
}
#if NET8_0_OR_GREATER
static Vector512<float> HalfAsWidenedUInt32ToSingle_Vector512(Vector512<uint> value)
{
// Extract sign bit of value
Vector512<uint> sign = value & Vector512.Create(SingleSignMask);
// Copy sign bit to upper bits
Vector512<uint> bitValueInProcess = value;
// Extract exponent bits of value (BiasedExponent is not for here as it performs unnecessary shift)
Vector512<uint> offsetExponent = bitValueInProcess & Vector512.Create(HalfExponentMask);
// ~0u when value is subnormal, 0 otherwise
Vector512<uint> subnormalMask = Vector512.Equals(offsetExponent, Vector512<uint>.Zero);
// ~0u when value is either Infinity or NaN, 0 otherwise
Vector512<uint> infinityOrNaNMask = Vector512.Equals(offsetExponent, Vector512.Create(HalfExponentMask));
// 0x3880_0000u if value is subnormal, 0 otherwise
Vector512<uint> maskedExponentLowerBound = subnormalMask & Vector512.Create(ExponentLowerBound);
// 0x3880_0000u if value is subnormal, 0x3800_0000u otherwise
Vector512<uint> offsetMaskedExponentLowerBound = Vector512.Create(ExponentOffset) | maskedExponentLowerBound;
// Match the position of the boundary of exponent bits and fraction bits with IEEE 754 Binary32(Single)
bitValueInProcess = Vector512.ShiftLeft(bitValueInProcess, 13);
// Double the offsetMaskedExponentLowerBound if value is either Infinity or NaN
offsetMaskedExponentLowerBound = Vector512.ConditionalSelect(Vector512.Equals(infinityOrNaNMask, Vector512<uint>.Zero),
offsetMaskedExponentLowerBound,
Vector512.ShiftLeft(offsetMaskedExponentLowerBound, 1));
// Extract exponent bits and fraction bits of value
bitValueInProcess &= Vector512.Create(HalfToSingleBitsMask);
// Adjust exponent to match the range of exponent
bitValueInProcess += offsetMaskedExponentLowerBound;
// If value is subnormal, remove unnecessary 1 on top of fraction bits.
Vector512<uint> absoluteValue = (bitValueInProcess.AsSingle() - maskedExponentLowerBound.AsSingle()).AsUInt32();
// Merge sign bit with rest
return (absoluteValue | sign).AsSingle();
}
#endif
}
/// <summary>Computes the cosine similarity between the two specified non-empty, equal-length tensors of single-precision floating-point numbers.</summary>
/// <remarks>Assumes arguments have already been validated to be non-empty and equal length.</remarks>
private static float CosineSimilarityCore(ReadOnlySpan<float> x, ReadOnlySpan<float> y)
{
// Compute the same as:
// TensorPrimitives.Dot(x, y) / (Math.Sqrt(TensorPrimitives.SumOfSquares(x)) * Math.Sqrt(TensorPrimitives.SumOfSquares(y)))
// but only looping over each span once.
#if NET8_0_OR_GREATER
if (Vector512.IsHardwareAccelerated && x.Length >= Vector512<float>.Count)
{
ref float xRef = ref MemoryMarshal.GetReference(x);
ref float yRef = ref MemoryMarshal.GetReference(y);
Vector512<float> dotProductVector = Vector512<float>.Zero;
Vector512<float> xSumOfSquaresVector = Vector512<float>.Zero;
Vector512<float> ySumOfSquaresVector = Vector512<float>.Zero;
// Process vectors, summing their dot products and squares, as long as there's a vector's worth remaining.
int oneVectorFromEnd = x.Length - Vector512<float>.Count;
int i = 0;
do
{
Vector512<float> xVec = Vector512.LoadUnsafe(ref xRef, (uint)i);
Vector512<float> yVec = Vector512.LoadUnsafe(ref yRef, (uint)i);
dotProductVector = FusedMultiplyAdd(xVec, yVec, dotProductVector);
xSumOfSquaresVector = FusedMultiplyAdd(xVec, xVec, xSumOfSquaresVector);
ySumOfSquaresVector = FusedMultiplyAdd(yVec, yVec, ySumOfSquaresVector);
i += Vector512<float>.Count;
}
while (i <= oneVectorFromEnd);
// Process the last vector in the span, masking off elements already processed.
if (i != x.Length)
{
Vector512<float> xVec = Vector512.LoadUnsafe(ref xRef, (uint)(x.Length - Vector512<float>.Count));
Vector512<float> yVec = Vector512.LoadUnsafe(ref yRef, (uint)(x.Length - Vector512<float>.Count));
Vector512<float> remainderMask = CreateRemainderMaskSingleVector512(x.Length - i);
xVec &= remainderMask;
yVec &= remainderMask;
dotProductVector = FusedMultiplyAdd(xVec, yVec, dotProductVector);
xSumOfSquaresVector = FusedMultiplyAdd(xVec, xVec, xSumOfSquaresVector);
ySumOfSquaresVector = FusedMultiplyAdd(yVec, yVec, ySumOfSquaresVector);
}
// Sum(X * Y) / (|X| * |Y|)
return
Vector512.Sum(dotProductVector) /
(MathF.Sqrt(Vector512.Sum(xSumOfSquaresVector)) * MathF.Sqrt(Vector512.Sum(ySumOfSquaresVector)));
}
#endif
if (Vector256.IsHardwareAccelerated && x.Length >= Vector256<float>.Count)
{
ref float xRef = ref MemoryMarshal.GetReference(x);
ref float yRef = ref MemoryMarshal.GetReference(y);
Vector256<float> dotProductVector = Vector256<float>.Zero;
Vector256<float> xSumOfSquaresVector = Vector256<float>.Zero;
Vector256<float> ySumOfSquaresVector = Vector256<float>.Zero;
// Process vectors, summing their dot products and squares, as long as there's a vector's worth remaining.
int oneVectorFromEnd = x.Length - Vector256<float>.Count;
int i = 0;
do
{
Vector256<float> xVec = Vector256.LoadUnsafe(ref xRef, (uint)i);
Vector256<float> yVec = Vector256.LoadUnsafe(ref yRef, (uint)i);
dotProductVector = FusedMultiplyAdd(xVec, yVec, dotProductVector);
xSumOfSquaresVector = FusedMultiplyAdd(xVec, xVec, xSumOfSquaresVector);
ySumOfSquaresVector = FusedMultiplyAdd(yVec, yVec, ySumOfSquaresVector);
i += Vector256<float>.Count;
}
while (i <= oneVectorFromEnd);
// Process the last vector in the span, masking off elements already processed.
if (i != x.Length)
{
Vector256<float> xVec = Vector256.LoadUnsafe(ref xRef, (uint)(x.Length - Vector256<float>.Count));
Vector256<float> yVec = Vector256.LoadUnsafe(ref yRef, (uint)(x.Length - Vector256<float>.Count));
Vector256<float> remainderMask = CreateRemainderMaskSingleVector256(x.Length - i);
xVec &= remainderMask;
yVec &= remainderMask;
dotProductVector = FusedMultiplyAdd(xVec, yVec, dotProductVector);
xSumOfSquaresVector = FusedMultiplyAdd(xVec, xVec, xSumOfSquaresVector);
ySumOfSquaresVector = FusedMultiplyAdd(yVec, yVec, ySumOfSquaresVector);
}
// Sum(X * Y) / (|X| * |Y|)
return
Vector256.Sum(dotProductVector) /
(MathF.Sqrt(Vector256.Sum(xSumOfSquaresVector)) * MathF.Sqrt(Vector256.Sum(ySumOfSquaresVector)));
}
if (Vector128.IsHardwareAccelerated && x.Length >= Vector128<float>.Count)
{
ref float xRef = ref MemoryMarshal.GetReference(x);
ref float yRef = ref MemoryMarshal.GetReference(y);
Vector128<float> dotProductVector = Vector128<float>.Zero;
Vector128<float> xSumOfSquaresVector = Vector128<float>.Zero;
Vector128<float> ySumOfSquaresVector = Vector128<float>.Zero;
// Process vectors, summing their dot products and squares, as long as there's a vector's worth remaining.
int oneVectorFromEnd = x.Length - Vector128<float>.Count;
int i = 0;
do
{
Vector128<float> xVec = Vector128.LoadUnsafe(ref xRef, (uint)i);
Vector128<float> yVec = Vector128.LoadUnsafe(ref yRef, (uint)i);
dotProductVector = FusedMultiplyAdd(xVec, yVec, dotProductVector);
xSumOfSquaresVector = FusedMultiplyAdd(xVec, xVec, xSumOfSquaresVector);
ySumOfSquaresVector = FusedMultiplyAdd(yVec, yVec, ySumOfSquaresVector);
i += Vector128<float>.Count;
}
while (i <= oneVectorFromEnd);
// Process the last vector in the span, masking off elements already processed.
if (i != x.Length)
{
Vector128<float> xVec = Vector128.LoadUnsafe(ref xRef, (uint)(x.Length - Vector128<float>.Count));
Vector128<float> yVec = Vector128.LoadUnsafe(ref yRef, (uint)(x.Length - Vector128<float>.Count));
Vector128<float> remainderMask = CreateRemainderMaskSingleVector128(x.Length - i);
xVec &= remainderMask;
yVec &= remainderMask;
dotProductVector = FusedMultiplyAdd(xVec, yVec, dotProductVector);
xSumOfSquaresVector = FusedMultiplyAdd(xVec, xVec, xSumOfSquaresVector);
ySumOfSquaresVector = FusedMultiplyAdd(yVec, yVec, ySumOfSquaresVector);
}
// Sum(X * Y) / (|X| * |Y|)
return
Vector128.Sum(dotProductVector) /
(MathF.Sqrt(Vector128.Sum(xSumOfSquaresVector)) * MathF.Sqrt(Vector128.Sum(ySumOfSquaresVector)));
}
// Vectorization isn't supported or there are too few elements to vectorize.
// Use a scalar implementation.
float dotProduct = 0f, xSumOfSquares = 0f, ySumOfSquares = 0f;
for (int i = 0; i < x.Length; i++)
{
dotProduct = MathF.FusedMultiplyAdd(x[i], y[i], dotProduct);
xSumOfSquares = MathF.FusedMultiplyAdd(x[i], x[i], xSumOfSquares);
ySumOfSquares = MathF.FusedMultiplyAdd(y[i], y[i], ySumOfSquares);
}
// Sum(X * Y) / (|X| * |Y|)
return
dotProduct /
(MathF.Sqrt(xSumOfSquares) * MathF.Sqrt(ySumOfSquares));
}
/// <summary>Performs an aggregation over all elements in <paramref name="x"/> to produce a single-precision floating-point value.</summary>
/// <typeparam name="TTransformOperator">Specifies the transform operation that should be applied to each element loaded from <paramref name="x"/>.</typeparam>
/// <typeparam name="TAggregationOperator">
/// Specifies the aggregation binary operation that should be applied to multiple values to aggregate them into a single value.
/// The aggregation is applied after the transform is applied to each element.
/// </typeparam>
private static float Aggregate<TTransformOperator, TAggregationOperator>(
ReadOnlySpan<float> x)
where TTransformOperator : struct, IUnaryOperator
where TAggregationOperator : struct, IAggregationOperator
{
// Since every branch has a cost and since that cost is
// essentially lost for larger inputs, we do branches
// in a way that allows us to have the minimum possible
// for small sizes
ref float xRef = ref MemoryMarshal.GetReference(x);
nuint remainder = (uint)(x.Length);
#if NET8_0_OR_GREATER
if (Vector512.IsHardwareAccelerated)
{
float result;
if (remainder >= (uint)(Vector512<float>.Count))
{
result = Vectorized512(ref xRef, remainder);
}
else
{
// We have less than a vector and so we can only handle this as scalar. To do this
// efficiently, we simply have a small jump table and fallthrough. So we get a simple
// length check, single jump, and then linear execution.
result = Vectorized512Small(ref xRef, remainder);
}
return result;
}
#endif
if (Vector256.IsHardwareAccelerated)
{
float result;
if (remainder >= (uint)(Vector256<float>.Count))
{
result = Vectorized256(ref xRef, remainder);
}
else
{
// We have less than a vector and so we can only handle this as scalar. To do this
// efficiently, we simply have a small jump table and fallthrough. So we get a simple
// length check, single jump, and then linear execution.
result = Vectorized256Small(ref xRef, remainder);
}
return result;
}
if (Vector128.IsHardwareAccelerated)
{
float result;
if (remainder >= (uint)(Vector128<float>.Count))
{
result = Vectorized128(ref xRef, remainder);
}
else
{
// We have less than a vector and so we can only handle this as scalar. To do this
// efficiently, we simply have a small jump table and fallthrough. So we get a simple
// length check, single jump, and then linear execution.
result = Vectorized128Small(ref xRef, remainder);
}
return result;
}
// This is the software fallback when no acceleration is available.
// It requires no branches to hit.
return SoftwareFallback(ref xRef, remainder);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static float SoftwareFallback(ref float xRef, nuint length)
{
float result = TAggregationOperator.IdentityValue;
for (nuint i = 0; i < length; i++)
{
result = TAggregationOperator.Invoke(result, TTransformOperator.Invoke(Unsafe.Add(ref xRef, i)));
}
return result;
}
static float Vectorized128(ref float xRef, nuint remainder)
{
Vector128<float> vresult = Vector128.Create(TAggregationOperator.IdentityValue);
// Preload the beginning and end so that overlapping accesses don't negatively impact the data
Vector128<float> beg = TTransformOperator.Invoke(Vector128.LoadUnsafe(ref xRef));
Vector128<float> end = TTransformOperator.Invoke(Vector128.LoadUnsafe(ref xRef, remainder - (uint)(Vector128<float>.Count)));
nuint misalignment = 0;
if (remainder > (uint)(Vector128<float>.Count * 8))
{
// Pinning is cheap and will be short lived for small inputs and unlikely to be impactful
// for large inputs (> 85KB) which are on the LOH and unlikely to be compacted.
fixed (float* px = &xRef)
{
float* xPtr = px;
// We need to the ensure the underlying data can be aligned and only align
// it if it can. It is possible we have an unaligned ref, in which case we
// can never achieve the required SIMD alignment.
bool canAlign = ((nuint)(xPtr) % sizeof(float)) == 0;
if (canAlign)
{
// Compute by how many elements we're misaligned and adjust the pointers accordingly
//
// Noting that we are only actually aligning dPtr. This is because unaligned stores
// are more expensive than unaligned loads and aligning both is significantly more
// complex.
misalignment = ((uint)(sizeof(Vector128<float>)) - ((nuint)(xPtr) % (uint)(sizeof(Vector128<float>)))) / sizeof(float);
xPtr += misalignment;
Debug.Assert(((nuint)(xPtr) % (uint)(sizeof(Vector128<float>))) == 0);
remainder -= misalignment;
}
Vector128<float> vector1;
Vector128<float> vector2;
Vector128<float> vector3;
Vector128<float> vector4;
// We only need to load, so there isn't a lot of benefit to doing non-temporal operations
while (remainder >= (uint)(Vector128<float>.Count * 8))
{
// We load, process, and store the first four vectors
vector1 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 0)));
vector2 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 1)));
vector3 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 2)));
vector4 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 3)));
vresult = TAggregationOperator.Invoke(vresult, vector1);
vresult = TAggregationOperator.Invoke(vresult, vector2);
vresult = TAggregationOperator.Invoke(vresult, vector3);
vresult = TAggregationOperator.Invoke(vresult, vector4);
// We load, process, and store the next four vectors
vector1 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 4)));
vector2 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 5)));
vector3 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 6)));
vector4 = TTransformOperator.Invoke(Vector128.Load(xPtr + (uint)(Vector128<float>.Count * 7)));
vresult = TAggregationOperator.Invoke(vresult, vector1);
vresult = TAggregationOperator.Invoke(vresult, vector2);
vresult = TAggregationOperator.Invoke(vresult, vector3);
vresult = TAggregationOperator.Invoke(vresult, vector4);
// We adjust the source and destination references, then update
// the count of remaining elements to process.
xPtr += (uint)(Vector128<float>.Count * 8);
remainder -= (uint)(Vector128<float>.Count * 8);
}
// Adjusting the refs here allows us to avoid pinning for very small inputs
xRef = ref *xPtr;
}
}
// Store the first block. Handling this separately simplifies the latter code as we know
// they come after and so we can relegate it to full blocks or the trailing elements
beg = Vector128.ConditionalSelect(CreateAlignmentMaskSingleVector128((int)(misalignment)), beg, Vector128.Create(TAggregationOperator.IdentityValue));
vresult = TAggregationOperator.Invoke(vresult, beg);
// Process the remaining [0, Count * 7] elements via a jump table
//
// We end up handling any trailing elements in case 0 and in the
// worst case end up just doing the identity operation here if there
// were no trailing elements.
(nuint blocks, nuint trailing) = Math.DivRem(remainder, (nuint)(Vector128<float>.Count));
blocks -= (misalignment == 0) ? 1u : 0u;
remainder -= trailing;
switch (blocks)
{
case 7:
{
Vector128<float> vector = TTransformOperator.Invoke(Vector128.LoadUnsafe(ref xRef, remainder - (uint)(Vector128<float>.Count * 7)));
vresult = TAggregationOperator.Invoke(vresult, vector);
goto case 6;