-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
TensorExtensions.cs
2527 lines (2268 loc) · 126 KB
/
TensorExtensions.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;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.VisualBasic;
using System.Text;
using System.Buffers;
using System.Xml.Linq;
#pragma warning disable CS8601 // Possible null reference assignment.
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
#pragma warning disable 8500 // address / sizeof of managed types
namespace System.Numerics.Tensors
{
public static partial class Tensor
{
#region ToString
// REVIEW: WHAT SHOULD WE NAME THIS? WHERE DO WE WANT IT TO LIVE?
/// <summary>
/// Creates a <see cref="string"/> representation of the <see cref="TensorSpan{T}"/>."/>
/// </summary>
/// <param name="span">The <see cref="TensorSpan{T}"/> you want to represent as a string.</param>
/// <param name="maximumLengths">Maximum Length of each dimension</param>
/// <returns>A <see cref="string"/> representation of the <paramref name="span"/></returns>
public static string ToString<T>(this TensorSpan<T> span, params scoped ReadOnlySpan<nint> maximumLengths) => ((ReadOnlyTensorSpan<T>)span).ToString(maximumLengths);
/// <summary>
/// Creates a <see cref="string"/> representation of the <see cref="ReadOnlyTensorSpan{T}"/>."/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="span">The <see cref="ReadOnlyTensorSpan{T}"/> you want to represent as a string.</param>
/// <param name="maximumLengths">Maximum Length of each dimension</param>
public static string ToString<T>(this ReadOnlyTensorSpan<T> span, params scoped ReadOnlySpan<nint> maximumLengths)
{
var sb = new StringBuilder();
scoped Span<nint> curIndexes;
nint[]? curIndexesArray;
if (span.Rank > 6)
{
curIndexesArray = ArrayPool<nint>.Shared.Rent(span.Rank);
curIndexes = curIndexesArray;
}
else
{
curIndexesArray = null;
curIndexes = stackalloc nint[span.Rank];
}
nint copiedValues = 0;
T[] values = new T[span.Lengths[span.Rank - 1]];
while (copiedValues < span._flattenedLength)
{
var sp = new ReadOnlyTensorSpan<T>(ref Unsafe.Add(ref span._reference, TensorSpanHelpers.ComputeLinearIndex(curIndexes, span.Strides, span.Lengths)), [span.Lengths[span.Rank - 1]], [1], span.Lengths[span.Rank - 1]);
sb.Append('{');
sp.FlattenTo(values);
sb.Append(string.Join(",", values));
sb.AppendLine("}");
TensorSpanHelpers.AdjustIndexes(span.Rank - 2, 1, curIndexes, span._lengths);
copiedValues += span.Lengths[span.Rank - 1];
}
if (curIndexesArray != null)
ArrayPool<nint>.Shared.Return(curIndexesArray);
return sb.ToString();
}
#endregion
#region Resize
/// <summary>
/// Creates a new <see cref="Tensor{T}"/>, allocates new memory, and copies the data from <paramref name="input"/>. If the final shape is smaller all data after
/// that point is ignored.
/// </summary>
/// <param name="input">Input <see cref="Tensor{T}"/>.</param>
/// <param name="shape"><see cref="ReadOnlySpan{T}"/> of the desired new shape.</param>
public static Tensor<T> Resize<T>(Tensor<T> input, scoped ReadOnlySpan<nint> shape)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
nint newSize = TensorSpanHelpers.CalculateTotalLength(shape);
T[] values = input.IsPinned ? GC.AllocateArray<T>((int)newSize) : (new T[newSize]);
Tensor<T> output = new Tensor<T>(values, shape, false);
ReadOnlySpan<T> span = MemoryMarshal.CreateSpan(ref input.AsTensorSpan()._reference, (int)input.FlattenedLength);
Span<T> ospan = MemoryMarshal.CreateSpan(ref output.AsTensorSpan()._reference, (int)output.FlattenedLength);
if (newSize > input.FlattenedLength)
TensorSpanHelpers.Memmove(ospan, span, input.FlattenedLength);
else
TensorSpanHelpers.Memmove(ospan, span, newSize);
return output;
}
/// <summary>
/// Creates a new <see cref="TensorSpan{T}"/>, allocates new managed memory, and copies the data from <paramref name="input"/>. If the final shape is smaller all data after
/// </summary>
/// <param name="input">Input <see cref="TensorSpan{T}"/>.</param>
/// <param name="shape"><see cref="ReadOnlySpan{T}"/> of the desired new shape.</param>
public static TensorSpan<T> Resize<T>(TensorSpan<T> input, scoped ReadOnlySpan<nint> shape)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
nint newSize = TensorSpanHelpers.CalculateTotalLength(shape);
T[] values = new T[newSize];
TensorSpan<T> output = new TensorSpan<T>(values, 0, shape, default);
ReadOnlySpan<T> span = MemoryMarshal.CreateSpan(ref input._reference, (int)input.FlattenedLength);
Span<T> ospan = MemoryMarshal.CreateSpan(ref output._reference, (int)output.FlattenedLength);
if (newSize > input.FlattenedLength)
TensorSpanHelpers.Memmove(ospan, span, input.FlattenedLength);
else
TensorSpanHelpers.Memmove(ospan, span, newSize);
return output;
}
#endregion
#region Broadcast
/// <summary>
/// Broadcast the data from <paramref name="input"/> to the new shape <paramref name="shape"/>. Creates a new <see cref="Tensor{T}"/> and allocates new memory.
/// If the shape of the <paramref name="input"/> is not compatible with the new shape, an exception is thrown.
/// </summary>
/// <param name="input">Input <see cref="Tensor{T}"/>.</param>
/// <param name="shape"><see cref="ReadOnlySpan{T}"/> of the desired new shape.</param>
/// <exception cref="ArgumentException">Thrown when the shapes are not broadcast compatible.</exception>
public static Tensor<T> Broadcast<T>(Tensor<T> input, scoped ReadOnlySpan<nint> shape)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
Tensor<T> intermediate = BroadcastTo(input, shape);
return Tensor.Create(intermediate.ToArray(), intermediate.Lengths);
}
// Lazy/non-copy broadcasting, internal only for now.
/// <summary>
/// Broadcast the data from <paramref name="input"/> to the new shape <paramref name="shape"/>. Creates a new <see cref="Tensor{T}"/>
/// but no memory is allocated. It manipulates the strides to achieve this affect.
/// If the shape of the <paramref name="input"/> is not compatible with the new shape, an exception is thrown.
/// </summary>
/// <param name="input">Input <see cref="Tensor{T}"/>.</param>
/// <param name="shape"><see cref="ReadOnlySpan{T}"/> of the desired new shape.</param>
/// <exception cref="ArgumentException">Thrown when the shapes are not broadcast compatible.</exception>
internal static Tensor<T> BroadcastTo<T>(Tensor<T> input, ReadOnlySpan<nint> shape)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
if (input.Lengths.SequenceEqual(shape))
return new Tensor<T>(input._values, shape, false);
if (!TensorHelpers.AreShapesBroadcastCompatible(input.Lengths, shape))
ThrowHelper.ThrowArgument_ShapesNotBroadcastCompatible();
nint newSize = TensorSpanHelpers.CalculateTotalLength(shape);
if (newSize == input.FlattenedLength)
return Reshape(input, shape);
nint[] intermediateShape = TensorHelpers.GetIntermediateShape(input.Lengths, shape.Length);
nint[] strides = new nint[shape.Length];
nint stride = 1;
for (int i = strides.Length - 1; i >= 0; i--)
{
if ((intermediateShape[i] == 1 && shape[i] != 1) || (intermediateShape[i] == 1 && shape[i] == 1))
strides[i] = 0;
else
{
strides[i] = stride;
stride *= intermediateShape[i];
}
}
Tensor<T> output = new Tensor<T>(input._values, shape, strides);
return output;
}
// Lazy/non-copy broadcasting, internal only for now.
/// <summary>
/// Broadcast the data from <paramref name="input"/> to the new shape <paramref name="shape"/>. Creates a new <see cref="Tensor{T}"/>
/// but no memory is allocated. It manipulates the strides to achieve this affect.
/// If the shape of the <paramref name="input"/> is not compatible with the new shape, an exception is thrown.
/// </summary>
/// <param name="input">Input <see cref="TensorSpan{T}"/>.</param>
/// <param name="shape"><see cref="ReadOnlySpan{T}"/> of the desired new shape.</param>
/// <exception cref="ArgumentException">Thrown when the shapes are not broadcast compatible.</exception>
internal static TensorSpan<T> BroadcastTo<T>(TensorSpan<T> input, scoped ReadOnlySpan<nint> shape)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
if (input.Lengths.SequenceEqual(shape))
return new TensorSpan<T>(ref input._reference, shape, input.Strides, input._memoryLength);
if (!TensorHelpers.AreShapesBroadcastCompatible(input.Lengths, shape))
ThrowHelper.ThrowArgument_ShapesNotBroadcastCompatible();
nint newSize = TensorSpanHelpers.CalculateTotalLength(shape);
if (newSize == input.FlattenedLength)
return Reshape(input, shape);
nint[] intermediateShape = TensorHelpers.GetIntermediateShape(input.Lengths, shape.Length);
nint[] strides = new nint[shape.Length];
nint stride = 1;
for (int i = strides.Length - 1; i >= 0; i--)
{
if ((intermediateShape[i] == 1 && shape[i] != 1) || (intermediateShape[i] == 1 && shape[i] == 1))
strides[i] = 0;
else
{
strides[i] = stride;
stride *= intermediateShape[i];
}
}
TensorSpan<T> output = new TensorSpan<T>(ref input._reference, shape, strides, input._memoryLength);
return output;
}
#endregion
#region Reverse
/// <summary>
/// Reverse the order of elements in the <paramref name="input"/> along the given axis. The shape of the tensor is preserved, but the elements are reordered.
/// <paramref name="axis"/> defaults to -1 when not provided, which reverses the entire tensor.
/// </summary>
/// <param name="input">Input <see cref="Tensor{T}"/>.</param>
/// <param name="axis">Axis along which to reverse over. The default, -1, will reverse over all of the axes of the left tensor.</param>
public static Tensor<T> Reverse<T>(Tensor<T> input, nint axis = -1)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
T[] values = input.IsPinned ? GC.AllocateArray<T>((int)input._flattenedLength) : (new T[input._flattenedLength]);
Tensor<T> output = new Tensor<T>(values, input.Lengths.ToArray(), input.Strides.ToArray());
if (axis == -1)
{
int index = 0;
ReadOnlySpan<T> span = MemoryMarshal.CreateSpan(ref input._values[0], (int)input.FlattenedLength);
Span<T> ospan = MemoryMarshal.CreateSpan(ref output._values[0], (int)output.FlattenedLength);
for (int i = (int)input.FlattenedLength - 1; i >= 0; i--)
{
ospan[index++] = span[i];
}
}
else
{
nint copyLength = 1;
for (nint i = axis; i < input.Lengths.Length; i++)
{
copyLength *= input.Lengths[(int)i];
}
copyLength /= input.Lengths[(int)axis];
scoped Span<nint> oIndices;
nint[]? oIndicesArray;
scoped Span<nint> iIndices;
nint[]? iIndicesArray;
if (input.Rank > 6)
{
oIndicesArray = ArrayPool<nint>.Shared.Rent(input.Rank);
oIndices = oIndicesArray;
iIndicesArray = ArrayPool<nint>.Shared.Rent(input.Rank);
iIndices = iIndicesArray;
}
else
{
oIndicesArray = null;
oIndices = stackalloc nint[input.Rank];
iIndicesArray = null;
iIndices = stackalloc nint[input.Rank];
}
iIndices[(int)axis] = input.Lengths[(int)axis] - 1;
nint copiedValues = 0;
TensorSpan<T> islice = input.AsTensorSpan().Slice(input.Lengths);
TensorSpan<T> oslice = output.AsTensorSpan().Slice(output._lengths);
while (copiedValues < input._flattenedLength)
{
TensorSpanHelpers.Memmove(ref Unsafe.Add(ref oslice._reference, TensorSpanHelpers.ComputeLinearIndex(oIndices, input.Strides, input.Lengths)), ref Unsafe.Add(ref islice._reference, TensorSpanHelpers.ComputeLinearIndex(iIndices, islice.Strides, islice.Lengths)), copyLength);
TensorSpanHelpers.AdjustIndexes((int)axis, 1, oIndices, input._lengths);
TensorSpanHelpers.AdjustIndexesDown((int)axis, 1, iIndices, input._lengths);
copiedValues += copyLength;
}
if (oIndicesArray != null && iIndicesArray != null)
{
ArrayPool<nint>.Shared.Return(oIndicesArray);
ArrayPool<nint>.Shared.Return(iIndicesArray);
}
}
return output;
}
/// <summary>
/// Reverse the order of elements in the <paramref name="input"/> along the given axis. The shape of the tensor is preserved, but the elements are reordered.
/// <paramref name="axis"/> defaults to -1 when not provided, which reverses the entire span.
/// </summary>
/// <param name="input">Input <see cref="TensorSpan{T}"/>.</param>
/// <param name="axis">Axis along which to reverse over. The default, -1, will reverse over all of the axes of the left span.</param>
public static TensorSpan<T> Reverse<T>(TensorSpan<T> input, nint axis = -1)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
if (axis == -1)
{
nint index = input.FlattenedLength - 1;
Span<T> span = MemoryMarshal.CreateSpan(ref input._reference, (int)input.FlattenedLength);
T temp;
for (int i = 0; i <= input.FlattenedLength / 2; i++)
{
temp = span[(int)index];
span[(int)index] = span[i];
span[i] = temp;
}
}
else
{
T[] values = new T[input.FlattenedLength];
nint copyLength = 1;
for (nint i = axis; i < input.Lengths.Length; i++)
{
copyLength *= input.Lengths[(int)i];
}
copyLength /= input.Lengths[(int)axis];
scoped Span<nint> oIndices;
nint[]? oIndicesArray;
scoped Span<nint> iIndices;
nint[]? iIndicesArray;
if (input.Rank > 6)
{
oIndicesArray = ArrayPool<nint>.Shared.Rent(input.Rank);
oIndices = oIndicesArray;
iIndicesArray = ArrayPool<nint>.Shared.Rent(input.Rank);
iIndices = iIndicesArray;
}
else
{
oIndicesArray = null;
oIndices = stackalloc nint[input.Rank];
iIndicesArray = null;
iIndices = stackalloc nint[input.Rank];
}
iIndices[(int)axis] = input.Lengths[(int)axis] - 1;
nint copiedValues = 0;
TensorSpan<T> islice = input.Slice(input.Lengths);
while (copiedValues < input.FlattenedLength)
{
TensorSpanHelpers.Memmove(ref Unsafe.Add(ref values, TensorSpanHelpers.ComputeLinearIndex(oIndices, input.Strides, input.Lengths)), ref Unsafe.Add(ref islice._reference, TensorSpanHelpers.ComputeLinearIndex(iIndices, islice.Strides, islice.Lengths)), copyLength);
TensorSpanHelpers.AdjustIndexes((int)axis, 1, oIndices, input.Lengths);
TensorSpanHelpers.AdjustIndexesDown((int)axis, 1, iIndices, input.Lengths);
copiedValues += copyLength;
}
TensorSpanHelpers.Memmove(ref input._reference, ref values[0], input.FlattenedLength);
if (oIndicesArray != null && iIndicesArray != null)
{
ArrayPool<nint>.Shared.Return(oIndicesArray);
ArrayPool<nint>.Shared.Return(iIndicesArray);
}
}
return input;
}
#endregion
#region Split
/// <summary>
/// Split a <see cref="Tensor{T}"/> into <paramref name="numSplits"/> along the given <paramref name="axis"/>. If the tensor cannot be split
/// evenly on the given <paramref name="axis"/> an exception is thrown.
/// </summary>
/// <param name="input">Input <see cref="Tensor{T}"/>.</param>
/// <param name="numSplits">How many times to split the <paramref name="input"/></param>
/// <param name="axis">The axis to split on.</param>
public static Tensor<T>[] Split<T>(Tensor<T> input, nint numSplits, nint axis)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
if (input.Lengths[(int)axis] % numSplits != 0)
ThrowHelper.ThrowArgument_SplitNotSplitEvenly();
Tensor<T>[] outputs = new Tensor<T>[numSplits];
nint totalToCopy = input.FlattenedLength / numSplits;
nint copyLength = 1;
for (nint i = axis; i < input.Lengths.Length; i++)
{
copyLength *= input.Lengths[(int)i];
}
copyLength /= numSplits;
nint[] newShape = input.Lengths.ToArray();
newShape[(int)axis] = newShape[(int)axis] / numSplits;
scoped Span<nint> oIndices;
nint[]? oIndicesArray;
scoped Span<nint> iIndices;
nint[]? iIndicesArray;
if (input.Rank > 6)
{
oIndicesArray = ArrayPool<nint>.Shared.Rent(input.Rank);
oIndices = oIndicesArray;
iIndicesArray = ArrayPool<nint>.Shared.Rent(input.Rank);
iIndices = iIndicesArray;
}
else
{
oIndicesArray = null;
oIndices = stackalloc nint[input.Rank];
iIndicesArray = null;
iIndices = stackalloc nint[input.Rank];
}
for (int i = 0; i < outputs.Length; i++)
{
T[] values = input.IsPinned ? GC.AllocateArray<T>((int)totalToCopy) : (new T[(int)totalToCopy]);
outputs[i] = new Tensor<T>(values, newShape);
oIndices.Clear();
iIndices.Clear();
iIndices[(int)axis] = i;
TensorSpan<T> islice = input.AsTensorSpan().Slice(input.Lengths);
TensorSpan<T> oslice = outputs[i].AsTensorSpan().Slice(outputs[i]._lengths);
nint copiedValues = 0;
while (copiedValues < totalToCopy)
{
TensorSpanHelpers.Memmove(ref Unsafe.Add(ref oslice._reference, TensorSpanHelpers.ComputeLinearIndex(oIndices, outputs[0].Strides, outputs[0].Lengths)), ref Unsafe.Add(ref islice._reference, TensorSpanHelpers.ComputeLinearIndex(iIndices, islice.Strides, islice.Lengths)), copyLength);
TensorSpanHelpers.AdjustIndexes((int)axis, 1, oIndices, outputs[i]._lengths);
TensorSpanHelpers.AdjustIndexes((int)axis - 1, 1, iIndices, input._lengths);
copiedValues += copyLength;
}
}
if (oIndicesArray != null && iIndicesArray != null)
{
ArrayPool<nint>.Shared.Return(oIndicesArray);
ArrayPool<nint>.Shared.Return(iIndicesArray);
}
return outputs;
}
#endregion
#region SetSlice
// REVIEW: WHAT DO WE WANT TO CALL THIS? COPYTO? IT DOES FIT IN WITH THE EXISTING COPY TO CONVENTIONS FOR VECTOR (albeit backwards).
/// <summary>
/// Sets a slice of the given <paramref name="tensor"/> with the provided <paramref name="values"/> for the given <paramref name="ranges"/>
/// </summary>
/// <param name="tensor">Input <see cref="Tensor{T}"/>.</param>
/// <param name="values">The values you want to set in the <paramref name="tensor"/>.</param>
/// <param name="ranges">The ranges you want to set.</param>
public static Tensor<T> SetSlice<T>(this Tensor<T> tensor, Tensor<T> values, params scoped ReadOnlySpan<NRange> ranges)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
TensorSpan<T> srcSpan;
if (ranges == ReadOnlySpan<NRange>.Empty)
{
if (!tensor.Lengths.SequenceEqual(values.Lengths))
ThrowHelper.ThrowArgument_SetSliceNoRange(nameof(values));
srcSpan = tensor.AsTensorSpan().Slice(tensor.Lengths);
}
else
srcSpan = tensor.AsTensorSpan().Slice(ranges);
if (!srcSpan.Lengths.SequenceEqual(values.Lengths))
ThrowHelper.ThrowArgument_SetSliceInvalidShapes(nameof(values));
values.AsTensorSpan().CopyTo(srcSpan);
return tensor;
}
#endregion
#region FilteredUpdate
// REVIEW: PYTORCH/NUMPY DO THIS.
// t0[t0 < 2] = -1;
// OR SHOULD THIS BE AN OVERLOAD OF FILL THAT TAKES IN A FUNC TO KNOW WHICH ONE TO UPDATE?
/// <summary>
/// Updates the <paramref name="tensor"/> tensor with the <paramref name="value"/> where the <paramref name="filter"/> is true.
/// </summary>
/// <param name="tensor">Input <see cref="Tensor{T}"/>.</param>
/// <param name="filter">Input filter where if the index is true then it will update the <paramref name="tensor"/>.</param>
/// <param name="value">Value to update in the <paramref name="tensor"/>.</param>
public static Tensor<T> FilteredUpdate<T>(Tensor<T> tensor, Tensor<bool> filter, T value)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
if (filter.Lengths.Length != tensor.Lengths.Length)
ThrowHelper.ThrowArgument_DimensionsNotSame(nameof(filter));
Span<T> srcSpan = MemoryMarshal.CreateSpan(ref tensor._values[0], (int)tensor._flattenedLength);
Span<bool> filterSpan = MemoryMarshal.CreateSpan(ref filter._values[0], (int)tensor._flattenedLength);
for (int i = 0; i < filterSpan.Length; i++)
{
if (filterSpan[i])
{
srcSpan[i] = value;
}
}
return tensor;
}
/// <summary>
/// Updates the <paramref name="tensor"/> tensor with the <paramref name="values"/> where the <paramref name="filter"/> is true.
/// If dmesions are not the same an exception is thrown.
/// </summary>
/// <param name="tensor">Input <see cref="Tensor{T}"/>.</param>
/// <param name="filter">Input filter where if the index is true then it will update the <paramref name="tensor"/>.</param>
/// <param name="values">Values to update in the <paramref name="tensor"/>.</param>
public static Tensor<T> FilteredUpdate<T>(Tensor<T> tensor, Tensor<bool> filter, Tensor<T> values)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
if (filter.Lengths.Length != tensor.Lengths.Length)
ThrowHelper.ThrowArgument_DimensionsNotSame(nameof(filter));
if (values.Rank != 1)
ThrowHelper.ThrowArgument_1DTensorRequired(nameof(values));
nint numTrueElements = TensorHelpers.CountTrueElements(filter);
if (numTrueElements != values._flattenedLength)
ThrowHelper.ThrowArgument_IncorrectNumberOfFilterItems(nameof(values));
Span<T> dstSpan = MemoryMarshal.CreateSpan(ref tensor._values[0], (int)tensor._flattenedLength);
Span<bool> filterSpan = MemoryMarshal.CreateSpan(ref filter._values[0], (int)tensor._flattenedLength);
Span<T> valuesSpan = MemoryMarshal.CreateSpan(ref values._values[0], (int)values._flattenedLength);
int index = 0;
for (int i = 0; i < filterSpan.Length; i++)
{
if (filterSpan[i])
{
dstSpan[i] = valuesSpan[index++];
}
}
return tensor;
}
#endregion
#region SequenceEqual
/// <summary>
/// Compares the elements of two <see cref="Tensor{T}"/> for equality. If the shapes are not the same, the tensors are broadcasted to the smallest broadcastable size
/// before they are compared. It returns a <see cref="Tensor{Boolean}"/> where the value is true if the elements are equal and false if they are not."/>
/// </summary>
/// <param name="left">First <see cref="Tensor{T}"/> to compare.</param>
/// <param name="right">Second <see cref="Tensor{T}"/> to compare.</param>
/// <returns>A <see cref="Tensor{Boolean}"/> where the value is true if the elements are equal and false if they are not.</returns>
public static Tensor<bool> SequenceEqual<T>(Tensor<T> left, Tensor<T> right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
Tensor<bool> result;
if (TensorHelpers.AreShapesTheSame(left, right))
{
result = Tensor.Create<bool>(left.Lengths, false);
for (int i = 0; i < left.FlattenedLength; i++)
{
result._values[i] = left._values[i] == right._values[i];
}
}
else
{
nint[] newSize = TensorHelpers.GetSmallestBroadcastableSize(left.Lengths, right.Lengths);
result = Tensor.Create<bool>(newSize, false);
Tensor<T> broadcastedLeft = BroadcastTo(left, newSize);
Tensor<T> broadcastedRight = BroadcastTo(right, newSize);
scoped Span<nint> curIndex;
nint[]? curIndexArray;
if (broadcastedRight.Lengths.Length > 6)
{
curIndexArray = ArrayPool<nint>.Shared.Rent(broadcastedRight.Lengths.Length);
curIndex = curIndexArray;
}
else
{
curIndexArray = null;
curIndex = stackalloc nint[broadcastedRight.Lengths.Length];
}
for (int i = 0; i < broadcastedLeft.FlattenedLength; i++)
{
result._values[i] = broadcastedLeft[curIndex] == broadcastedRight[curIndex];
TensorSpanHelpers.AdjustIndexes(broadcastedRight.Rank - 1, 1, curIndex, broadcastedRight.Lengths);
}
if (curIndexArray != null)
ArrayPool<nint>.Shared.Return(curIndexArray);
}
return result;
}
#endregion
#region LessThan
/// <summary>
/// Compares the elements of two <see cref="Tensor{T}"/> to see which elements of <paramref name="left"/> are less than <paramref name="right"/>.
/// If the shapes are not the same, the tensors are broadcasted to the smallest broadcastable size before they are compared.
/// It returns a <see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are less than <paramref name="right"/>
/// and false if they are not."/>
/// </summary>
/// <param name="left">First <see cref="Tensor{T}"/> to compare.</param>
/// <param name="right">Second <see cref="Tensor{T}"/> to compare.</param>
/// <returns>A <see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are less than <paramref name="right"/> and
/// false if they are not.</returns>
public static Tensor<bool> LessThan<T>(Tensor<T> left, Tensor<T> right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
Tensor<bool> result;
if (TensorHelpers.AreShapesTheSame(left, right))
{
result = Tensor.Create<bool>(left.Lengths, false);
for (int i = 0; i < left.FlattenedLength; i++)
{
result._values[i] = left._values[i] < right._values[i];
}
}
else
{
nint[] newSize = TensorHelpers.GetSmallestBroadcastableSize(left.Lengths, right.Lengths);
result = Tensor.Create<bool>(newSize, false);
Tensor<T> broadcastedLeft = BroadcastTo(left, newSize);
Tensor<T> broadcastedRight = BroadcastTo(right, newSize);
scoped Span<nint> curIndex;
nint[]? curIndexArray;
if (broadcastedRight.Lengths.Length > 6)
{
curIndexArray = ArrayPool<nint>.Shared.Rent(broadcastedRight.Lengths.Length);
curIndex = curIndexArray;
}
else
{
curIndexArray = null;
curIndex = stackalloc nint[broadcastedRight.Lengths.Length];
}
for (int i = 0; i < broadcastedLeft.FlattenedLength; i++)
{
result._values[i] = broadcastedLeft[curIndex] < broadcastedRight[curIndex];
TensorSpanHelpers.AdjustIndexes(broadcastedRight.Rank - 1, 1, curIndex, broadcastedRight.Lengths);
}
if (curIndexArray != null)
ArrayPool<nint>.Shared.Return(curIndexArray);
}
return result;
}
/// <summary>
/// Compares the elements of a <see cref="Tensor{T}"/> to see which elements are less than <paramref name="right"/>.
/// It returns a <see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are less than <paramref name="right"/>
/// and false if they are not."/>
/// </summary>
/// <param name="left"><see cref="Tensor{T}"/> to compare.</param>
/// <param name="right"><typeparamref name="T"/> to compare against <paramref name="left"/>.</param>
/// <returns><see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are less than <paramref name="right"/>
/// and false if they are not.</returns>
public static Tensor<bool> LessThan<T>(Tensor<T> left, T right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
Tensor<bool> result = Tensor.Create<bool>(left.Lengths, false);
for (int i = 0; i < left.FlattenedLength; i++)
{
result._values[i] = left._values[i] < right;
}
return result;
}
/// <summary>
/// Compares the elements of two <see cref="Tensor{T}"/> to see if any elements of <paramref name="left"/> are less than <paramref name="right"/>.
/// If the shapes are not the same, the tensors are broadcasted to the smallest broadcastable size before they are compared.
/// It returns a <see cref="bool"/> where the value is true if any elements in <paramref name="left"/> are less than <paramref name="right"/>.
/// </summary>
/// <param name="left">First <see cref="Tensor{T}"/> to compare.</param>
/// <param name="right">Second <see cref="Tensor{T}"/> to compare against.</param>
/// <returns><see cref="bool"/> where the value is true if any elements in <paramref name="left"/> are less than <paramref name="right"/>.</returns>
public static bool LessThanAny<T>(Tensor<T> left, Tensor<T> right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
if (TensorHelpers.AreShapesTheSame(left, right))
{
for (int i = 0; i < left.FlattenedLength; i++)
{
if (left._values[i] < right._values[i])
return true;
}
}
else
{
nint[] newSize = TensorHelpers.GetSmallestBroadcastableSize(left.Lengths, right.Lengths);
Tensor<T> broadcastedLeft = BroadcastTo(left, newSize);
Tensor<T> broadcastedRight = BroadcastTo(right, newSize);
scoped Span<nint> curIndex;
nint[]? curIndexArray;
if (broadcastedRight.Lengths.Length > 6)
{
curIndexArray = ArrayPool<nint>.Shared.Rent(broadcastedRight.Lengths.Length);
curIndex = curIndexArray;
}
else
{
curIndexArray = null;
curIndex = stackalloc nint[broadcastedRight.Lengths.Length];
}
for (int i = 0; i < broadcastedLeft.FlattenedLength; i++)
{
if (broadcastedLeft[curIndex] < broadcastedRight[curIndex])
return true;
TensorSpanHelpers.AdjustIndexes(broadcastedRight.Rank - 1, 1, curIndex, broadcastedRight.Lengths);
}
if (curIndexArray != null)
ArrayPool<nint>.Shared.Return(curIndexArray);
}
return false;
}
/// <summary>
/// Compares the elements of two <see cref="Tensor{T}"/> to see if all elements of <paramref name="left"/> are less than <paramref name="right"/>.
/// If the shapes are not the same, the tensors are broadcasted to the smallest broadcastable size before they are compared.
/// It returns a <see cref="bool"/> where the value is true if all elements in <paramref name="left"/> are less than <paramref name="right"/>.
/// </summary>
/// <param name="left">First <see cref="Tensor{T}"/> to compare.</param>
/// <param name="right">Second <see cref="Tensor{T}"/> to compare against.</param>
/// <returns><see cref="bool"/> where the value is true if all elements in <paramref name="left"/> are less than <paramref name="right"/>.</returns>
public static bool LessThanAll<T>(Tensor<T> left, Tensor<T> right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
if (TensorHelpers.AreShapesTheSame(left, right))
{
for (int i = 0; i < left.FlattenedLength; i++)
{
if (left._values[i] > right._values[i])
return false;
}
}
else
{
nint[] newSize = TensorHelpers.GetSmallestBroadcastableSize(left.Lengths, right.Lengths);
Tensor<T> broadcastedLeft = BroadcastTo(left, newSize);
Tensor<T> broadcastedRight = BroadcastTo(right, newSize);
scoped Span<nint> curIndex;
nint[]? curIndexArray;
if (broadcastedRight.Lengths.Length > 6)
{
curIndexArray = ArrayPool<nint>.Shared.Rent(broadcastedRight.Lengths.Length);
curIndex = curIndexArray;
}
else
{
curIndexArray = null;
curIndex = stackalloc nint[broadcastedRight.Lengths.Length];
}
for (int i = 0; i < broadcastedLeft.FlattenedLength; i++)
{
if (broadcastedLeft[curIndex] > broadcastedRight[curIndex])
return false;
TensorSpanHelpers.AdjustIndexes(broadcastedRight.Rank - 1, 1, curIndex, broadcastedRight.Lengths);
}
if (curIndexArray != null)
ArrayPool<nint>.Shared.Return(curIndexArray);
}
return true;
}
#endregion
#region GreaterThan
/// <summary>
/// Compares the elements of two <see cref="Tensor{T}"/> to see which elements of <paramref name="left"/> are greater than <paramref name="right"/>.
/// If the shapes are not the same, the tensors are broadcasted to the smallest broadcastable size before they are compared.
/// It returns a <see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are greater than <paramref name="right"/>
/// and false if they are not."/>
/// </summary>
/// <param name="left">First <see cref="Tensor{T}"/> to compare.</param>
/// <param name="right">Second <see cref="Tensor{T}"/> to compare.</param>
/// <returns>A <see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are greater than <paramref name="right"/> and
/// false if they are not.</returns>
public static Tensor<bool> GreaterThan<T>(Tensor<T> left, Tensor<T> right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
Tensor<bool> result;
if (TensorHelpers.AreShapesTheSame(left, right))
{
result = Tensor.Create<bool>(left.Lengths, false);
for (int i = 0; i < left.FlattenedLength; i++)
{
result._values[i] = left._values[i] > right._values[i];
}
}
else
{
nint[] newSize = TensorHelpers.GetSmallestBroadcastableSize(left.Lengths, right.Lengths);
result = Tensor.Create<bool>(newSize, false);
Tensor<T> broadcastedLeft = BroadcastTo(left, newSize);
Tensor<T> broadcastedRight = BroadcastTo(right, newSize);
scoped Span<nint> curIndex;
nint[]? curIndexArray;
if (broadcastedRight.Lengths.Length > 6)
{
curIndexArray = ArrayPool<nint>.Shared.Rent(broadcastedRight.Lengths.Length);
curIndex = curIndexArray;
}
else
{
curIndexArray = null;
curIndex = stackalloc nint[broadcastedRight.Lengths.Length];
}
for (int i = 0; i < broadcastedLeft.FlattenedLength; i++)
{
result._values[i] = broadcastedLeft[curIndex] > broadcastedRight[curIndex];
TensorSpanHelpers.AdjustIndexes(broadcastedRight.Rank - 1, 1, curIndex, broadcastedRight.Lengths);
}
if (curIndexArray != null)
ArrayPool<nint>.Shared.Return(curIndexArray);
}
return result;
}
/// <summary>
/// Compares the elements of a <see cref="Tensor{T}"/> to see which elements are greater than <paramref name="right"/>.
/// It returns a <see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are greater than <paramref name="right"/>
/// and false if they are not."/>
/// </summary>
/// <param name="left"><see cref="Tensor{T}"/> to compare.</param>
/// <param name="right"><typeparamref name="T"/> to compare against <paramref name="left"/>.</param>
/// <returns><see cref="Tensor{Boolean}"/> where the value is true if the elements in <paramref name="left"/> are greater than <paramref name="right"/>
/// and false if they are not.</returns>
public static Tensor<bool> GreaterThan<T>(Tensor<T> left, T right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
Tensor<bool> result = Tensor.Create<bool>(left.Lengths, false);
for (int i = 0; i < left.FlattenedLength; i++)
{
result._values[i] = left._values[i] > right;
}
return result;
}
/// <summary>
/// Compares the elements of two <see cref="Tensor{T}"/> to see if any elements of <paramref name="left"/> are greater than <paramref name="right"/>.
/// If the shapes are not the same, the tensors are broadcasted to the smallest broadcastable size before they are compared.
/// It returns a <see cref="bool"/> where the value is true if any elements in <paramref name="left"/> are greater than <paramref name="right"/>.
/// </summary>
/// <param name="left">First <see cref="Tensor{T}"/> to compare.</param>
/// <param name="right">Second <see cref="Tensor{T}"/> to compare against.</param>
/// <returns><see cref="bool"/> where the value is true if any elements in <paramref name="left"/> are greater than <paramref name="right"/>.</returns>
public static bool GreaterThanAny<T>(Tensor<T> left, Tensor<T> right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
if (TensorHelpers.AreShapesTheSame(left, right))
{
for (int i = 0; i < left.FlattenedLength; i++)
{
if (left._values[i] > right._values[i])
return true;
}
}
else
{
nint[] newSize = TensorHelpers.GetSmallestBroadcastableSize(left.Lengths, right.Lengths);
Tensor<T> broadcastedLeft = BroadcastTo(left, newSize);
Tensor<T> broadcastedRight = BroadcastTo(right, newSize);
scoped Span<nint> curIndex;
nint[]? curIndexArray;
if (broadcastedRight.Lengths.Length > 6)
{
curIndexArray = ArrayPool<nint>.Shared.Rent(broadcastedRight.Lengths.Length);
curIndex = curIndexArray;
}
else
{
curIndexArray = null;
curIndex = stackalloc nint[broadcastedRight.Lengths.Length];
}
for (int i = 0; i < broadcastedLeft.FlattenedLength; i++)
{
if (broadcastedLeft[curIndex] > broadcastedRight[curIndex])
return true;
TensorSpanHelpers.AdjustIndexes(broadcastedRight.Rank - 1, 1, curIndex, broadcastedRight.Lengths);
}
if (curIndexArray != null)
ArrayPool<nint>.Shared.Return(curIndexArray);
}
return false;
}
/// <summary>
/// Compares the elements of two <see cref="Tensor{T}"/> to see if all elements of <paramref name="left"/> are greater than <paramref name="right"/>.
/// If the shapes are not the same, the tensors are broadcasted to the smallest broadcastable size before they are compared.
/// It returns a <see cref="bool"/> where the value is true if all elements in <paramref name="left"/> are greater than <paramref name="right"/>.
/// </summary>
/// <param name="left">First <see cref="Tensor{T}"/> to compare.</param>
/// <param name="right">Second <see cref="Tensor{T}"/> to compare against.</param>
/// <returns><see cref="bool"/> where the value is true if all elements in <paramref name="left"/> are greater than <paramref name="right"/>.</returns>
public static bool GreaterThanAll<T>(Tensor<T> left, Tensor<T> right)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>, IComparisonOperators<T, T, bool>
{
if (TensorHelpers.AreShapesTheSame(left, right))
{
for (int i = 0; i < left.FlattenedLength; i++)
{
if (left._values[i] < right._values[i])
return false;
}
}
else
{
nint[] newSize = TensorHelpers.GetSmallestBroadcastableSize(left.Lengths, right.Lengths);
Tensor<T> broadcastedLeft = BroadcastTo(left, newSize);
Tensor<T> broadcastedRight = BroadcastTo(right, newSize);
scoped Span<nint> curIndex;
nint[]? curIndexArray;
if (broadcastedRight.Lengths.Length > 6)
{
curIndexArray = ArrayPool<nint>.Shared.Rent(broadcastedRight.Lengths.Length);
curIndex = curIndexArray;
}
else
{
curIndexArray = null;
curIndex = stackalloc nint[broadcastedRight.Lengths.Length];
}
for (int i = 0; i < broadcastedLeft.FlattenedLength; i++)
{
if (broadcastedLeft[curIndex] < broadcastedRight[curIndex])
return false;
TensorSpanHelpers.AdjustIndexes(broadcastedRight.Rank - 1, 1, curIndex, broadcastedRight.Lengths);
}
if (curIndexArray != null)
ArrayPool<nint>.Shared.Return(curIndexArray);
}
return true;
}
#endregion
#region Stack
// REVIEW: NEEDS A DIFFERENT NAME?
// JUST AN OVERLOAD FOR CONCATENATE?
/// <summary>
/// Join an array of <see cref="Tensor{T}"/> along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result and
/// defaults to 0. All tensors must have the same shape.
/// </summary>
/// <param name="input">Array of <see cref="Tensor{T}"/>.</param>
/// <param name="axis">Index of where the new axis will be. Defaults to 0.</param>
public static Tensor<T> Stack<T>(Tensor<T>[] input, int axis = 0)
where T : IEquatable<T>, IEqualityOperators<T, T, bool>
{
if (input.Length < 2)
ThrowHelper.ThrowArgument_StackTooFewTensors();
if (axis < 0)
axis = input.Rank - axis;
Tensor<T>[] outputs = new Tensor<T>[input.Length];
for (int i = 0; i < input.Length; i++)
{
outputs[i] = Tensor.Unsqueeze(input[0], axis);
}
return Tensor.Concatenate<T>(outputs, axis);
}
#endregion
#region Reshape
// REVIEW: SENTINAL VALUE? CONSTANT VALUE FOR -1 WILDCARD?
/// <summary>
/// Reshapes the <paramref name="input"/> tensor to the specified <paramref name="lengths"/>. If one of the lengths is -1, it will be calculated automatically.