-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathTensor.cs
More file actions
7499 lines (6585 loc) · 342 KB
/
Tensor.cs
File metadata and controls
7499 lines (6585 loc) · 342 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) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using TorchSharp.PInvoke;
#nullable enable
namespace TorchSharp
{
public static partial class torch
{
/// <summary>
/// Represents a TorchSharp tensor.
/// </summary>
[TorchSharp.Utils.TypeFormatterSource(typeof(TorchSharp.Utils.TypeFormatterSource))]
public partial class Tensor : IDisposable
{
/// <summary>
/// A handle to the underlying native tensor.
/// This field should only be used in rare circumstances. Instead, use the 'Handle' property, which
/// validates that the handle is not zero.
/// </summary>
internal IntPtr handle;
static long _totalCount = 0;
static long _peakCount = 0;
internal DisposeScope? OwningDisposeScope { get; set; }
internal Tensor(IntPtr handle, bool register = true)
{
this.handle = handle;
System.Threading.Interlocked.Increment(ref _totalCount);
_peakCount = Math.Max(_totalCount, _peakCount);
if (register) {
OwningDisposeScope = DisposeScopeManager.ThreadSingleton.RegisterOnCurrentDisposeScope(this);
}
}
/// <summary>
/// Allows external packages to create tensors from the same native pointers that TorchSharp uses.
/// </summary>
/// <param name="handle">A pointer to a native at::Tensor.</param>
/// <returns>A Tensor reference</returns>
public static Tensor UnsafeCreateTensor(IntPtr handle) => new Tensor(handle);
/// <summary>
/// TODO
/// </summary>
/// <param name="obj"></param>
public override bool Equals(object? obj)
{
return (obj is Tensor) && this.Equals((obj as Tensor)!);
}
/// <summary>
/// TODO
/// </summary>
public override int GetHashCode() => base.GetHashCode();
/// <summary>
/// A friendly name for the tensor. This is useful for debugging purposes.
/// </summary>
public string? name { get; set; }
/// <summary>
/// Finalize the tensor. Releases the tensor and its associated data.
/// </summary>
~Tensor() => Dispose(false);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Implements the .NET Dispose pattern.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (handle != IntPtr.Zero) {
DisposeScopeManager.ThreadSingleton.DisposingOnCurrentScope(this);
OwningDisposeScope?.MarkAsDisposed(this);
System.Threading.Interlocked.Decrement(ref _totalCount);
NativeMethods.THSTensor_dispose(handle);
handle = IntPtr.Zero;
}
}
/// <summary>
/// Is true if the tensor has been disposed, false otherwise.
/// </summary>
public bool IsInvalid => handle == IntPtr.Zero;
/// <summary>
/// Moves tensor to the outer DisposeScope. If there is no outer DisposeScope, it's detached from the
/// DisposeScope system.
/// </summary>
/// <returns>The same tensor that the method was called on</returns>
public torch.Tensor MoveToOuterDisposeScope()
{
OwningDisposeScope?.MoveToOuter(this);
return this;
}
/// <summary>
/// Detaches the tensor completely from the DisposeScope system.
/// </summary>
/// <returns>The same tensor that the method was called on</returns>
public torch.Tensor DetachFromDisposeScope()
{
OwningDisposeScope?.Detach(this);
return this;
}
public torch.Tensor MoveToOtherDisposeScope(torch.Tensor other)
{
return MoveToOtherDisposeScope(other.OwningDisposeScope);
}
public torch.Tensor MoveToOtherDisposeScope(DisposeScope? other)
{
if (OwningDisposeScope == null && other != null) {
other.Attach(this);
}
else {
OwningDisposeScope?.MoveToOther(other, this);
}
return this;
}
/// <summary>
/// Detaches the tensor completely from the DisposeScope system.
/// </summary>
/// <returns>The same tensor that the method was called on</returns>
/// <remarks>
/// This was a misspelling of 'Detach'. Keeping it to avoid making a
/// breaking change, but it is deprecated and will be removed in a future
/// release.
/// </remarks>
[Obsolete("The method name misspells 'Detach.' Use 'DetachFromDisposeScope' instead.", false)]
public torch.Tensor DetatchFromDisposeScope() => DetachFromDisposeScope();
/// <summary>
/// Decouple the managed tensor from its underlying native tensor.
///
/// This is primarily useful when returning a tensor to native code in a callback,
/// or when having created a managed tensor from a passed-in native handle.
///
/// See the torch.nn.Module.Module(string name) constructor for an example of its use.
/// </summary>
public IntPtr DecoupleFromNativeHandle()
{
GC.SuppressFinalize(this);
if (handle == IntPtr.Zero)
throw new InvalidOperationException("Tensor invalid -- empty handle.");
System.Threading.Interlocked.Decrement(ref _totalCount);
var h = handle;
handle = IntPtr.Zero;
return h;
}
/// <summary>
/// The total number of allocated tensors.
/// </summary>
/// <remarks>
/// Only tensors that are realized in managed code will be counted, so tensors
/// resulting from computations that remain in native code will not be counted
/// in this property.
///
/// Further, two tensors may alias each other, pointing at the same underlying data.
///
/// Therefore, this property is mostly useful for diagnostic purposes, to
/// make sure that there is no drift in tensor count from epoch to epoch,
/// for example.
/// </remarks>
public static long TotalCount => _totalCount;
/// <summary>
/// The peak number of allocated tensors.
/// </summary>
/// <remarks>
/// Only tensors that are realized in managed code will be counted, so tensors
/// resulting from computations that remain in native code will not be counted
/// in this property.
///
/// Further, two tensors may alias each other, pointing at the same underlying data.
///
/// Therefore, this property is mostly useful for diagnostic purposes.
/// </remarks>
public static long PeakCount => _peakCount;
/// <summary>
/// Get the handle for the tensor, validating that it's not null.
/// </summary>
/// <remarks>
/// This property validates the handle. If you **aboslutely** need to get the handle without validation,
/// use the 'handle' field.
/// </remarks>
public IntPtr Handle {
get {
if (handle == IntPtr.Zero)
throw new InvalidOperationException("Tensor invalid -- empty handle.");
return handle;
}
}
/// <summary>
/// Disassociates the native tensor handle from the managed Tensor.
/// </summary>
/// <remarks>Used to create a Parameter instance.</remarks>
/// <returns>The handle to the underlying native tensor.</returns>
internal IntPtr MoveHandle()
{
var h = handle;
handle = IntPtr.Zero;
return h;
}
/// <summary>
/// Returns the number of dimensions for this tensor
/// </summary>
public long Dimensions => NativeMethods.THSTensor_ndimension(Handle);
/// <summary>
/// Returns the number of dimensions for this tensor
/// </summary>
public long dim() => Dimensions;
/// <summary>
/// Returns the number of dimensions for this tensor
/// </summary>
public long ndim => Dimensions;
/// <summary>
/// Get the number of elements in the tensor.
/// </summary>
public long NumberOfElements => NativeMethods.THSTensor_numel(Handle);
/// <summary>
/// Get the number of elements in the tensor.
/// </summary>
public long numel() => NumberOfElements;
/// <summary>
/// Get the size of each element in the tensor.
/// </summary>
public long ElementSize => NativeMethods.THSTensor_element_size(Handle);
public long element_size() => NativeMethods.THSTensor_element_size(Handle);
public bool is_integral() => torch.is_integral(dtype);
/// <summary>
/// Returns True if the data type of input is a floating point data type.
/// </summary>
public bool is_floating_point() => torch.is_floating_point(dtype);
/// <summary>
/// Returns True if the data type of input is a complex data type i.e., one of torch.complex64, and torch.complex128.
/// </summary>
public bool is_complex() => torch.is_complex(dtype);
/// <summary>
/// Returns True if the input is a single element tensor which is not equal to zero after type conversions,
/// i.e. not equal to torch.tensor([0.]) or torch.tensor([0]) or torch.tensor([False]).
/// Throws an InvalidOperationException if torch.numel() != 1.
/// </summary>
public bool is_nonzero()
{
if (numel() != 1)
throw new InvalidOperationException("is_nonzero() called on non-singleton tensor");
var res = NativeMethods.THSTensor_is_nonzero(Handle);
CheckForErrors();
return res != 0;
}
public bool is_cuda => device.type == DeviceType.CUDA;
public bool is_meta => device.type == DeviceType.META;
/// <summary>
/// All Tensors that have requires_grad which is true will be leaf Tensors by convention.
/// For Tensors that have requires_grad which is true, they will be leaf Tensors if they were created by the user.This means that they are not the result of an operation and so grad_fn is None.
/// Only leaf Tensors will have their grad populated during a call to backward(). To get grad populated for non-leaf Tensors, you can use retain_grad().
/// </summary>
public bool is_leaf { get => NativeMethods.THSTensor_is_leaf(Handle) != 0; }
/// <summary>
/// Create a new reference to the same underlying native tensor.
/// </summary>
/// <returns>A fresh reference to the underlying native tensor.</returns>
/// <remkars>
/// This is useful for function implementations where a caller may expect the input and output to be
/// distinct; in such situations, there's a risk that the tensor is disposed twice, with bad consequences.
/// With 'alias(),' the reference count to the underlying native tensor is increased, meaning that the
/// input and output can (and should) be disposed or finalized independently of each other.
/// </remkars>
public Tensor alias()
{
var res = NativeMethods.THSTensor_alias(Handle);
if (res == IntPtr.Zero) { CheckForErrors(); }
return new Tensor(res);
}
/// <summary>
/// Returns the underlying storage.
/// </summary>
/// <returns></returns>
public Storage<T> storage<T>() where T : unmanaged
{
return Storage.Create<T>(this);
}
/// <summary>
/// Returns the tensor’s offset in the underlying storage in terms of number of storage elements (not bytes).
/// </summary>
/// <returns></returns>
public long storage_offset()
{
var res = NativeMethods.THSTensor_storage_offset(Handle);
CheckForErrors();
return res;
}
/// <summary>
/// Returns a pointer to the unmanaged data managed by this tensor.
/// </summary>
public Utils.TensorAccessor<T> data<T>() where T : unmanaged
{
ValidateType(typeof(T));
return device_type != DeviceType.CPU
? new Utils.TensorAccessor<T>(cpu())
: new Utils.TensorAccessor<T>(this);
}
/// <summary>
/// Returns the singleton value of a scalar tensor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>The scalar held in the tensor</returns>
public T item<T>() where T : unmanaged
{
if (NumberOfElements != 1) throw new ArgumentException("Number of elements in the tensor must be 1");
return data<T>()[0];
}
internal void ValidateType(Type dotnetType)
{
switch (dtype) {
case ScalarType.Byte:
if (dotnetType != typeof(byte))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.Int8:
if (dotnetType != typeof(sbyte))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.Int16:
if (dotnetType != typeof(short))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.Int32:
if (dotnetType != typeof(int))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.Int64:
if (dotnetType != typeof(long))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.Bool:
if (dotnetType != typeof(bool))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.BFloat16:
throw new ArgumentException($"No support for {dtype.ToString()} in TorchSharp");
case ScalarType.Float16:
#if NET6_0_OR_GREATER
if (dotnetType != typeof(Half))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
#endif
case ScalarType.Float32:
if (dotnetType != typeof(float))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.Float64:
if (dotnetType != typeof(double))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.ComplexFloat32:
if (dotnetType != typeof((float, float)))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
case ScalarType.ComplexFloat64:
if (dotnetType != typeof(System.Numerics.Complex))
throw new ArgumentException($"{dotnetType.Name} is not compatible with {dtype.ToString()}");
break;
}
}
/// <summary>
/// Writes the bytes of the tensor to a stream. Useful for when tensors are >2GB.
/// </summary>
/// <param name="stream">Stream to write the bytes to</param>
/// <param name="bufferSize">The buffer size to use when writing to the stream</param>
public void WriteBytesToStream(Stream stream, int bufferSize = 1024)
{
// Validate, but passing 0 as the total size, since we don't need to validate the size
_validate(0);
long totalSize = NumberOfElements * ElementSize;
unsafe {
var ptr = NativeMethods.THSTensor_data(handle);
if (ptr == IntPtr.Zero) { CheckForErrors(); }
// NOTE: there is no safety here in this loop.
// Read in the buffer N bytes at a time, and write them out
byte[] buffer = new byte[bufferSize];
while (totalSize > 0) {
// Read in the current buffer size
int curBufferSize = (int)Math.Min(totalSize, bufferSize);
var span = new Span<byte>((void*)ptr, curBufferSize);
span.CopyTo(buffer);
// Write it out
stream.Write(buffer, 0, curBufferSize);
// Increment our pointer and decrease the total size of elements we have to write
ptr += curBufferSize;
totalSize -= curBufferSize;
}
}
}
/// <summary>
/// Reads the bytes of the tensor from a stream.
/// </summary>
/// <param name="stream">Stream to read the bytes from</param>
/// <param name="bufferSize">The buffer size to use when reading from the stream</param>
public void ReadBytesFromStream(Stream stream, int bufferSize = 1024)
{
long totalSize = NumberOfElements * ElementSize;
// Validate that this tensor matches the conditions for reading the bytes - pass 0 as total size
// since we don't need to check that condition.
_validate(0);
unsafe {
var ptr = NativeMethods.THSTensor_data(handle);
if (ptr == IntPtr.Zero) { CheckForErrors(); }
// NOTE: there is no safety here in this loop.
// Read in the buffer N bytes at a time, and write them out
byte[] buffer = new byte[bufferSize];
while (totalSize > 0) {
// Read in the current buffer size
int bytesRead = stream.Read(buffer, 0, (int)Math.Min(totalSize, bufferSize));
if (bytesRead == 0)
throw new EndOfStreamException();
// Copy the contents over to the span
var span = new Span<byte>((void*)ptr, bytesRead);
buffer.AsSpan(0, bytesRead).CopyTo(span);
// Increment our pointer and decrease the total size of elements we have to write
ptr += bytesRead;
totalSize -= bytesRead;
}
}
}
/// <summary>
/// Get or set the contents of a tensor as raw bytes.
/// </summary>
public Span<byte> bytes {
get {
long totalSize = NumberOfElements * ElementSize;
_validate(totalSize);
unsafe {
var res = NativeMethods.THSTensor_data(handle);
if (res == IntPtr.Zero) { CheckForErrors(); }
// NOTE: there is no safety here.
return new Span<byte>((void*)res, (int)totalSize);
}
}
set {
long totalSize = NumberOfElements * ElementSize;
if (!is_contiguous()) throw new InvalidOperationException("SetBytes() called on non-contiguous tensor.");
if (totalSize != value.Length) {
throw new ArgumentException("Mismatched data sizes in SetBytes().");
}
unsafe {
var res = NativeMethods.THSTensor_data(handle);
if (res == IntPtr.Zero) { CheckForErrors(); }
// NOTE: there is no safety here.
var data = new Span<byte>((void*)res, value.Length);
value.CopyTo(data);
}
}
}
private void _validate(long totalSize)
{
if (!is_contiguous()) throw new InvalidOperationException("Bytes() called on non-contiguous tensor.");
if (totalSize > int.MaxValue) {
throw new ArgumentException("Span only supports up to int.MaxValue elements.");
}
if (device_type != DeviceType.CPU) {
throw new InvalidOperationException("Reading data from non-CPU memory is not supported. Move or copy the tensor to the cpu before reading.");
}
}
public Tensor real {
get {
var res = NativeMethods.THSTensor_real(Handle);
if (res == IntPtr.Zero) { CheckForErrors(); }
return new Tensor(res);
}
}
public Tensor imag {
get {
var res = NativeMethods.THSTensor_imag(Handle);
if (res == IntPtr.Zero) { CheckForErrors(); }
return new Tensor(res);
}
}
/// <summary>
/// Read the double-precision value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public double ReadCpuDouble(long i) => Utils.TensorAccessor<double>.ReadItemAt(this, i);
/// <summary>
/// Read the single-precision float value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public float ReadCpuSingle(long i) => Utils.TensorAccessor<float>.ReadItemAt(this, i);
/// <summary>
/// Read the 32-bit integer float value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public int ReadCpuInt32(long i) => Utils.TensorAccessor<int>.ReadItemAt(this, i);
/// <summary>
/// Read the 64-bit integer value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public long ReadCpuInt64(long i) => Utils.TensorAccessor<long>.ReadItemAt(this, i);
/// <summary>
/// Read the byte value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public byte ReadCpuByte(long i) => Utils.TensorAccessor<byte>.ReadItemAt(this, i);
/// <summary>
/// Read the short value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public sbyte ReadCpuSByte(long i) => Utils.TensorAccessor<sbyte>.ReadItemAt(this, i);
/// <summary>
/// Read the int16 value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public short ReadCpuInt16(long i) => Utils.TensorAccessor<short>.ReadItemAt(this, i);
/// <summary>
/// Read the Boolean value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public bool ReadCpuBool(long i) => Utils.TensorAccessor<bool>.ReadItemAt(this, i);
/// <summary>
/// Read the value at the given index.
/// </summary>
/// <typeparam name="T">The type of the element to read.</typeparam>
/// <param name="i">The index.</param>
public T ReadCpuValue<T>(long i) where T : unmanaged => Utils.TensorAccessor<T>.ReadItemAt(this, i);
/// <summary>
/// Read the Float16 value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public float ReadCpuFloat16(long i)
{
if (i >= NumberOfElements) {
throw new IndexOutOfRangeException("The index is greater than the number of elements in the tensor");
}
return NativeMethods.THSTensor_data_idx_float16(handle, i);
}
/// <summary>
/// Read the BFloat16 value at the given index.
/// </summary>
/// <param name="i">The index.</param>
public float ReadCpuBFloat16(long i)
{
if (i >= NumberOfElements) {
throw new IndexOutOfRangeException("The index is greater than the number of elements in the tensor");
}
return NativeMethods.THSTensor_data_idx_bfloat16(handle, i);
}
/// <summary>
/// Convert to a scalar.
/// </summary>
public Scalar ToScalar()
{
var res = NativeMethods.THSTensor_item(Handle);
if (res == IntPtr.Zero) { CheckForErrors(); }
return new Scalar(res);
}
/// <summary>
/// Fill the tensor with the provided scalar value.
/// </summary>
/// <param name="value">A scalar value</param>
public Tensor fill_(Scalar value)
{
NativeMethods.THSTensor_fill_(Handle, value is null ? IntPtr.Zero : value.Handle);
CheckForErrors();
return this;
}
/// <summary>
/// Gets the type of the tensor elements.
/// </summary>
public ScalarType dtype => (ScalarType)NativeMethods.THSTensor_type(Handle);
/// <summary>
/// Gets a string representing the device where the tensor is stored.
/// </summary>
public torch.Device device {
get {
var dev_type = device_type;
if (dev_type == DeviceType.CPU) {
return new torch.Device(DeviceType.CPU);
} else {
return new torch.Device(dev_type, device_index);
}
}
}
/// <summary>
/// Gets a index of the device where the tensor is stored.
/// </summary>
public int device_index {
get {
var res = NativeMethods.THSTensor_device_index(Handle);
CheckForErrors();
return res;
}
}
/// <summary>
/// Gets the type ('CPU', 'CUDA', etc.) of the device where the tensor is stored.
/// </summary>
public DeviceType device_type {
get {
var res = NativeMethods.THSTensor_device_type(Handle);
CheckForErrors();
return (DeviceType)res;
}
}
/// <summary>
/// Is the tensor a sparse tensor?
/// </summary>
public bool is_sparse {
get {
var res = NativeMethods.THSTensor_is_sparse(Handle);
CheckForErrors();
return res;
}
}
public void backward(IList<Tensor>? grad_tensors = null, bool retain_graph = false, bool create_graph = false, IList<Tensor>? inputs = null) =>
torch.autograd.backward(new[] { this }, grad_tensors, retain_graph, create_graph, inputs);
/// <summary>
/// Creates a tensor by loading it from a file.
/// </summary>
/// <param name="location">The file path where tensor values are stored.</param>
public static Tensor load(string location)
{
var res = NativeMethods.THSTensor_load(location);
if (res == IntPtr.Zero)
CheckForErrors();
return new Tensor(res);
}
/// <summary>
/// Save the contents of a tensor to a file.
/// </summary>
/// <param name="location">The file path where tensor values are to be stored.</param>
public void save(string location)
{
NativeMethods.THSTensor_save(Handle, location);
CheckForErrors();
}
/// <summary>
/// Is the tensor tracking gradients?
/// </summary>
/// <remarks>Typically, gradients are tracked when the tensor is used as parameters of a module.</remarks>
public bool requires_grad {
get { return NativeMethods.THSTensor_requires_grad(Handle); }
set {
NativeMethods.THSTensor_set_requires_grad(Handle, value);
CheckForErrors();
}
}
public Tensor requires_grad_(bool requires_grad = true)
{
this.requires_grad = requires_grad;
return this;
}
/// <summary>
/// Enables this Tensor to have their grad populated during backward(). This is a no-op for leaf tensors.
/// </summary>
public void retain_grad()
{
NativeMethods.THSTensor_retain_grad(Handle);
CheckForErrors();
}
/// <summary>
/// Adds gradient tracking.
/// </summary>
public Tensor with_requires_grad(bool requires_grad = true)
{
this.requires_grad = requires_grad;
return this;
}
/// <summary>
/// Returns true if the tensor is on the CPU
/// </summary>
public bool is_cpu()
{
var res = NativeMethods.THSTensor_is_cpu(Handle);
torch.CheckForErrors();
return res;
}
/// <summary>
/// Moves the tensor data to the CPU device
/// </summary>
public Tensor cpu()
{
var res = NativeMethods.THSTensor_cpu(Handle);
if (res == IntPtr.Zero)
CheckForErrors();
return new Tensor(res);
}
/// <summary>
/// Moves the tensor data to the MPS device
/// </summary>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor mps(bool non_blocking = false)
{
var res = NativeMethods.THSTensor_to_device(Handle, (int)DeviceType.MPS, -1, true, non_blocking);
if (res == IntPtr.Zero)
CheckForErrors();
return new Tensor(res);
}
/// <summary>
/// Returns a copy of this object in CUDA memory.
/// If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.
/// </summary>
/// <param name="device">The target device</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor cuda(Device? device = null, bool non_blocking = false)
{
if (device is not null && device.type != DeviceType.CUDA) {
throw new ArgumentException("Not a CUDA device.", "device");
}
torch.InitializeDeviceType(DeviceType.CUDA);
var res = device is null
? NativeMethods.THSTensor_cuda(Handle)
: NativeMethods.THSTensor_to_device(Handle, (int)DeviceType.CUDA, device_index, false, non_blocking);
if (res == IntPtr.Zero)
CheckForErrors();
return new Tensor(res);
}
/// <summary>
/// Cast the tensor to the given element type.
/// </summary>
/// <param name="type">The target type</param>
/// <param name="copy">When copy is set, a new Tensor is created even when the Tensor already matches the desired conversion.</param>
/// <param name="disposeAfter">When disposeAfter is set, the current Tensor will be disposed after creating the new one</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor to_type(ScalarType type, bool copy = false, bool disposeAfter = false, bool non_blocking = false)
{
var res = NativeMethods.THSTensor_to_type(Handle, (sbyte)type, copy, non_blocking);
if (res == IntPtr.Zero)
CheckForErrors();
if (disposeAfter)
this.Dispose();
return new Tensor(res);
}
/// <summary>
/// Returns this tensor cast to the type of the given tensor.
/// </summary>
public Tensor type_as(Tensor tensor) => to_type(tensor.dtype);
/// <summary>
/// Overwrite an existing tensor with the contents of another tensor.
/// </summary>
/// <param name="source">The source tensor</param>
public Tensor set_(Tensor source)
{
NativeMethods.THSTensor_set_(Handle, source.Handle);
CheckForErrors();
return this;
}
/// <summary>
/// Moves the tensor data to a specific device.
/// </summary>
/// <param name="deviceType">The device type, e.g. 'CPU' or 'CUDA'.</param>
/// <param name="deviceIndex">The optional device index.</param>
/// <param name="copy">When copy is set, a new Tensor is created even when the Tensor already matches the desired conversion.</param>
/// <param name="disposeAfter">When disposeAfter is set, the current Tensor will be disposed after creating the new one</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor to(DeviceType deviceType, int deviceIndex = -1, bool copy = false, bool disposeAfter = false, bool non_blocking = false)
{
torch.InitializeDeviceType(deviceType);
var res = NativeMethods.THSTensor_to_device(Handle, (int)deviceType, deviceIndex, copy, non_blocking);
if (res == IntPtr.Zero)
CheckForErrors();
if (disposeAfter)
this.Dispose();
return new Tensor(res);
}
/// <summary>
/// Moves the tensor data and casts it to the given element type.
/// </summary>
/// <param name="type">The target type</param>
/// <param name="device">The target device</param>
/// <param name="copy">When copy is set, a new Tensor is created even when the Tensor already matches the desired conversion.</param>
/// <param name="disposeAfter">When disposeAfter is set, the current Tensor will be disposed after creating the new one</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor to(ScalarType type, torch.Device device, bool copy = false, bool disposeAfter = false, bool non_blocking = false)
{
device = torch.InitializeDevice(device);
var res = NativeMethods.THSTensor_to_type_and_device(Handle, (sbyte)type, (int)device.type, device.index, copy, non_blocking);
if (res == IntPtr.Zero)
CheckForErrors();
if (disposeAfter)
this.Dispose();
return new Tensor(res);
}
/// <summary>
/// Cast the tensor to the given element type.
/// </summary>
/// <param name="type">The target type</param>
/// <param name="copy">When copy is set, a new Tensor is created even when the Tensor already matches the desired conversion.</param>
/// <param name="disposeAfter">When disposeAfter is set, the current Tensor will be disposed after creating the new one</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
/// <remarks>Alias for to_type</remarks>
public Tensor to(ScalarType type, bool copy = false, bool disposeAfter = false, bool non_blocking = false) => to_type(type, copy, disposeAfter, non_blocking);
/// <summary>
/// Moves the tensor data.
/// </summary>
/// <param name="device">A string denoting the target device.</param>
/// <param name="copy">When copy is set, a new Tensor is created even when the Tensor already matches the desired conversion.</param>
/// <param name="disposeAfter">When disposeAfter is set, the current Tensor will be disposed after creating the new one</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor to(string device, bool copy = false, bool disposeAfter = false, bool non_blocking = false) => to(new torch.Device(device), copy, disposeAfter, non_blocking);
/// <summary>
/// Moves the tensor data.
/// </summary>
/// <param name="device">The target device</param>
/// <param name="copy">When copy is set, a new Tensor is created even when the Tensor already matches the desired conversion.</param>
/// <param name="disposeAfter">When disposeAfter is set, the current Tensor will be disposed after creating the new one</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor to(torch.Device device, bool copy = false, bool disposeAfter = false, bool non_blocking = false) => to(device.type, device.index, copy, disposeAfter, non_blocking);
/// <summary>
/// Moves the tensor data.
/// </summary>
/// <param name="other">The tensor serving as a template.</param>
/// <param name="non_blocking">Try to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor.</param>
public Tensor to(Tensor other, bool non_blocking = false) => to(other.dtype, other.device, non_blocking);
public Tensor type(Func<Tensor, Tensor> typeFunc) => typeFunc(this);
public Tensor type(ScalarType dtype) => this.to(dtype);
/// <summary>
/// Retrieves the size of the specified dimension in the tensor.
/// </summary>
/// <param name="dim">The dimension for which to retrieve the size.</param>
public long size(int dim)
{
var res = NativeMethods.THSTensor_size(Handle, dim);
CheckForErrors();
return res;
}
/// <summary>
/// Retrieves the sizes of all dimensions of the tensor.
/// </summary>
public long[] size()
{
long[] ptrArray;
using (var pa = new PinnedArray<long>()) {
NativeMethods.THSTensor_sizes(Handle, pa.CreateArray);
CheckForErrors();
ptrArray = pa.Array;
}
return ptrArray;
}
/// <summary>
/// Returns the tensor shape, this is an array whose size determines the number of dimensions on the tensor,
/// and each element is the size of the dimension
/// </summary>
/// <remarks>
/// An array of size 0 is used for constants, an array of size 1 is used
/// for single-dimension arrays, where the dimension is the value of the
/// first element. And so on.
/// </remarks>
public long[] shape {
get {
return size();
}
}
public bool has_names()
{
var res = NativeMethods.THSTensor_has_names(Handle);
CheckForErrors();
return res;
}
/// <summary>
/// Stores names for each of this tensor’s dimensions.
///
/// names[idx] corresponds to the name of tensor dimension idx.Names are either a string if the dimension is named or None if the dimension is unnamed.
/// Dimension names may contain characters or underscore.Furthermore, a dimension name must be a valid Python variable name(i.e., does not start with underscore).
/// Tensors may not have two named dimensions with the same name.
/// </summary>
/// <remarks>The named tensor API is experimental and subject to change.</remarks>
public string[] names {
get {
// It should be safe to cache the names, since only rename_() can change them in place.
if (_names != null) return _names!;