forked from migueldeicaza/TensorFlowSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTensor.cs
More file actions
1418 lines (1297 loc) · 52.1 KB
/
Tensor.cs
File metadata and controls
1418 lines (1297 loc) · 52.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// TensorFlow.cs; Bindings to the TensorFlow C API for .NET
//
// Authors:
// Miguel de Icaza ([email protected])
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using size_t = System.UIntPtr;
using TF_Tensor = System.IntPtr;
namespace TensorFlow
{
/// <summary>
/// TFTensor holds a multi-dimensional array of elements of a single data type.
/// </summary>
/// <remarks>
/// <para>
/// You can create tensors with the various constructors in this class, or using
/// the implicit conversions from various data types into a TFTensor, including
/// the creation of tensors from simple constants (returning a tensor that reprensets
/// a scalar, that is, it is a 0D tensor), arrays (returning a tensor of a single
/// dimension, 1D) or arbitrary multidimensional arrays.
///</para>
/// <para>
/// Given a tensor, you can retrieve the number of dimensions in it via the
/// NumDims property, or you can retrieve the shape of a tensor, that is how many
/// elements on each dimension the tensor has, by fetching the Shape property.
/// </para>
/// <para>
/// The implicit conversions for basic types produce tensors of one dimesion with
/// a single element, while the implicit conversion from an array, expects a multi-dimensional
/// array that is converted into a tensor of the right dimensions.
/// </para>
/// <para>
/// The special "String" tensor data type that you will find in TensorFlow documentation
/// really represents a byte array. You can create string tensors by using the <see cref="M:TensorFlow.TFTensor.CreateString"/>
/// method that takes a byte array buffer as input.
/// </para>
/// <example>
/// <code>
/// TFTensor scalar = 1; // Creates a 0D tensor, for the integer value 1
/// int d = scalar.NumDims; // d will be equal to zero, as it is a 0D tensor
/// long [] shape = scalar.Shape // returns an empty array, as it is a 0D tensor
///
/// TFTensor list = new [] {1,2,3} // Creates a 1D tensor, or vector, for the values 1, 2, 3
/// d = list.NumDims; // d will be one
/// shape = list.Shape; // shape will be an array with a single value 3, representing that the dimension 0 has 3 elements
///
/// // Creates a 3D tensor,
/// TFTensor cube = new [,,] { {{1,2,3},{4,5,6}}}
/// d = cube.NumDims // d will be 3
/// shape = list.Shape // shape will be [1,2,3] which is the shape of the above 3D array
/// </code>
/// </example>
/// </remarks>
public class TFTensor : TFDisposableThreadSafe
{
/// <summary>
/// Signature that methods must conform to to be used to release memory that was passed to a manually allocated TFTensor
/// </summary>
public delegate void Deallocator (IntPtr data, IntPtr size, IntPtr deallocatorData);
// extern TF_Tensor * TF_NewTensor (TF_DataType, const int64_t *dims, int num_dims, void *data, size_t len, void (* deallocator)(void *, size_t, void *), void *deallocator_arg);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Tensor TF_NewTensor (TFDataType dataType, long [] dims, int num_dims, IntPtr data, size_t len, Deallocator deallocator, IntPtr deallocator_arg);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Tensor TF_NewTensor (TFDataType dataType, IntPtr zeroDims, int num_dims, IntPtr data, size_t len, Deallocator deallocator, IntPtr deallocator_arg);
internal TFTensor (IntPtr handle) : base (handle) { }
static Deallocator FreeTensorDataDelegate = FreeTensorData;
static Deallocator FreeTensorHandleDelegate = FreeTensorHandle;
[MonoPInvokeCallback (typeof (Deallocator))]
internal static void FreeTensorData (IntPtr data, IntPtr len, IntPtr closure)
{
Marshal.FreeHGlobal (data);
}
[MonoPInvokeCallback (typeof (Deallocator))]
internal static void FreeTensorHandle (IntPtr data, IntPtr len, IntPtr closure)
{
var gch = GCHandle.FromIntPtr (closure);
gch.Free ();
}
// TODO: Other overloads we could add: String, Complex (float), Bool, QInt8, QUInt8, QInt32, Bfloat16,
// QInt16, QUint16, Half, Resource
// TODO: not clear that this is very useful (the dims versions), perhaps to reduce the surface of
// construcors these rarer blobs should be "FromSpec" or something like that
/// <summary>
/// Creates a new tensor from a portion of an array of sbytes
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, sbyte [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.Int8, shape, data, start, count, size: 2));
}
/// <summary>
/// Creates a new tensor from a portion of an array of bytes
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, byte [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.UInt8, shape, data, start, count, size: 1));
}
/// <summary>
/// Creates a new tensor from a portion of an array of shorts
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, short [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.Int16, shape, data, start, count, size: 2));
}
/// <summary>
/// Creates a new tensor from a portion of an array of ushorts
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, ushort [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.UInt16, shape, data, start, count, size: 2));
}
/// <summary>
/// Creates a new tensor from a portion of an array of ints
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, int [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.Int32, shape, data, start, count, size: 4));
}
/// <summary>
/// Creates a new tensor from a portion of an array of floats
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, float [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.Float, shape, data, start, count, size: 4));
}
/// <summary>
/// Creates a new tensor from a portion of an array of doubles
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, double [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.Double, shape, data, start, count, size: 8));
}
/// <summary>
/// Creates a new tensor from a portion of an array of longs
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, long [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.Int64, shape, data, start, count, size: 8));
}
/// <summary>
/// Creates a new tensor from a portion of an array of Complex numbers
/// </summary>
/// <param name="shape">Represents the tensor shape.</param>
/// <param name="data">The linear array of data, the data is shuffled to fit in the tensor with the specified dimensions.</param>
/// <param name="start">The offset into the provided data array where the data resides.</param>
/// <param name="count">The number of bytes to copy from count into the tensor.</param>
/// <remarks>
/// Use the FromBuffer method to create a tensor that has the specified dimensions
/// and is initialized with data from the data array. The data is copied starting
/// at the start offset, for count bytes and is laid out into the tensor following the
/// specified dimensions.
/// </remarks>
public static TFTensor FromBuffer (TFShape shape, Complex [] data, int start, int count)
{
return new TFTensor (SetupTensor (TFDataType.Complex128, shape, data, start, count, size: 16));
}
/// <summary>
/// Creates a constant tensor from an array, the shape reflects the shape of the C# array and the underlying type reflects the C# type.
/// </summary>
public unsafe TFTensor (Array array)
{
if (array == null)
throw new ArgumentNullException (nameof (array));
// Ensure that, if we have arrays of arrays, we can handle them accordingly:
if (isJagged (array.GetType ())) {
Type elementType = getInnerMostType (array);
int [] length = getLength (array);
Array multidimensional = Array.CreateInstance (elementType, length);
Array flatten = deepFlatten (array);
Buffer.BlockCopy (flatten, 0, multidimensional, 0, flatten.Length * Marshal.SizeOf (elementType));
createFromMultidimensionalArrays (multidimensional);
} else {
createFromMultidimensionalArrays (array);
}
}
private unsafe void createFromMultidimensionalArrays (Array array)
{
var t = array.GetType ().GetElementType ();
var tc = Type.GetTypeCode (t);
TFDataType dt;
long size = 0;
switch (tc) {
case TypeCode.Boolean:
dt = TFDataType.Bool;
size = 1;
break;
case TypeCode.SByte:
dt = TFDataType.Int8;
size = 1;
break;
case TypeCode.Byte:
dt = TFDataType.UInt8;
size = 1;
break;
case TypeCode.Int16:
dt = TFDataType.Int16;
size = 2;
break;
case TypeCode.UInt16:
dt = TFDataType.UInt16;
size = 2;
break;
case TypeCode.Int32:
dt = TFDataType.Int32;
size = 4;
break;
case TypeCode.Int64:
dt = TFDataType.Int64;
size = 8;
break;
case TypeCode.Single:
dt = TFDataType.Float;
size = 4;
break;
case TypeCode.Double:
dt = TFDataType.Double;
size = 8;
break;
default:
// Check types that are not handled by the typecode
if (t.IsAssignableFrom (typeof (Complex))) {
size = 16;
dt = TFDataType.Complex128;
} else
throw new ArgumentException ($"The data type {t} is not supported");
break;
}
var dims = new long [array.Rank];
for (int i = 0; i < array.Rank; i++) {
dims [i] = array.GetLength (i);
size *= (int)dims [i];
}
handle = SetupMulti (dt, dims, array, size);
}
/// <summary>
/// Creates a constant tensor with a single dimension from an integer value.
/// </summary>
public unsafe TFTensor (int value)
{
var v = (int*)Marshal.AllocHGlobal (sizeof (int));
*v = value;
handle = TF_NewTensor (TFDataType.Int32, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (int), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from a boolean value.
/// </summary>
public unsafe TFTensor (bool value)
{
var v = (bool*)Marshal.AllocHGlobal (sizeof (bool));
*v = value;
handle = TF_NewTensor (TFDataType.Bool, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (int), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from an sbyte value.
/// </summary>
public unsafe TFTensor (sbyte value)
{
var v = (sbyte*)Marshal.AllocHGlobal (sizeof (sbyte));
*v = value;
handle = TF_NewTensor (TFDataType.Int8, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (sbyte), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from a short value.
/// </summary>
public unsafe TFTensor (short value)
{
var v = (short*)Marshal.AllocHGlobal (sizeof (short));
*v = value;
handle = TF_NewTensor (TFDataType.Int16, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (short), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from an ushort value.
/// </summary>
public unsafe TFTensor (ushort value)
{
var v = (ushort*)Marshal.AllocHGlobal (sizeof (ushort));
*v = value;
handle = TF_NewTensor (TFDataType.Int16, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (ushort), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from an byte value.
/// </summary>
public unsafe TFTensor (byte value)
{
var v = (int*)Marshal.AllocHGlobal (sizeof (byte));
*v = value;
handle = TF_NewTensor (TFDataType.UInt8, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (byte), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from a Complex value.
/// </summary>
public unsafe TFTensor (Complex value)
{
var v = (Complex*)Marshal.AllocHGlobal (sizeof (Complex));
*v = value;
handle = TF_NewTensor (TFDataType.Complex128, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (Complex), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from a float value.
/// </summary>
public unsafe TFTensor (float value)
{
var v = (float*)Marshal.AllocHGlobal (sizeof (float));
*v = value;
handle = TF_NewTensor (TFDataType.Float, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (float), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from a double value.
/// </summary>
public unsafe TFTensor (double value)
{
var v = (double*)Marshal.AllocHGlobal (sizeof (double));
*v = value;
handle = TF_NewTensor (TFDataType.Double, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (double), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
/// <summary>
/// Creates a constant tensor with a single dimension from a long value.
/// </summary>
public unsafe TFTensor (long value)
{
var v = (long*)Marshal.AllocHGlobal (sizeof (long));
*v = value;
handle = TF_NewTensor (TFDataType.Int64, zeroDims: IntPtr.Zero, num_dims: 0, data: (IntPtr)v, len: (UIntPtr)sizeof (long), deallocator: FreeTensorDataDelegate, deallocator_arg: IntPtr.Zero);
}
// Convenience, should I add T[,] and T[,,] as more convenience ones?
/// <summary>
/// Creates a 1 dimensional tensor from an array of booleans.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (bool [] data) : base (SetupTensor (TFDataType.Bool, data, size: 1)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of sbytes.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (sbyte [] data) : base (SetupTensor (TFDataType.Int8, data, size: 1)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of bytes.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (byte [] data) : base (SetupTensor (TFDataType.UInt8, data, size: 1)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of shorts.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (short [] data) : base (SetupTensor (TFDataType.Int16, data, size: 2)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of ushorts
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (ushort [] data) : base (SetupTensor (TFDataType.UInt16, data, size: 2)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of ints.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (int [] data) : base (SetupTensor (TFDataType.Int32, data, size: 4)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of floats.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (float [] data) : base (SetupTensor (TFDataType.Float, data, size: 4)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of doubles.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (double [] data) : base (SetupTensor (TFDataType.Double, data, size: 8)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of longs.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (long [] data) : base (SetupTensor (TFDataType.Int64, data, size: 8)) { }
/// <summary>
/// Creates a 1 dimensional tensor from an array of complex numbers.
/// </summary>
/// <param name="data">Data.</param>
public TFTensor (Complex [] data) : base (SetupTensor (TFDataType.Complex128, data, size: 16)) { }
/// <summary>
/// Creates a single-dimension tensor from a byte buffer. This is different than creating a tensor from a byte array that produces a tensor with as many elements as the byte array.
/// </summary>
public unsafe static TFTensor CreateString (byte [] buffer)
{
if (buffer == null)
throw new ArgumentNullException (nameof (buffer));
//
// TF_STRING tensors are encoded with a table of 8-byte offsets followed by
// TF_StringEncode-encoded bytes.
//
var size = TFString.TF_StringEncodedSize ((UIntPtr)buffer.Length);
IntPtr handle = TF_AllocateTensor (TFDataType.String, IntPtr.Zero, 0, (UIntPtr)((ulong)size + 8));
// Clear offset table
IntPtr dst = TF_TensorData (handle);
Marshal.WriteInt64 (dst, 0);
var status = TFStatus.TF_NewStatus ();
fixed (byte* src = &buffer [0])
{
TFString.TF_StringEncode (src, (UIntPtr)buffer.Length, (sbyte*)(dst + 8), size, status);
var ok = TFStatus.TF_GetCode (status) == TFCode.Ok;
TFStatus.TF_DeleteStatus (status);
if (!ok)
return null;
}
return new TFTensor (handle);
}
// Convenience function to factor out the setup of a new tensor from an array
static IntPtr SetupTensor (TFDataType dt, long [] dims, Array data, int size)
{
return SetupTensor (dt, dims, data, start: 0, count: data.Length, size: size);
}
// Convenience function to factor out the setup of a new tensor from an array
static IntPtr SetupTensor (TFDataType dt, Array data, int size)
{
long [] dims = new long [data.Rank];
for (int i = 0; i < dims.Length; i++)
dims [i] = data.GetLength (i);
return SetupTensor (dt, dims, data, start: 0, count: data.Length, size: size);
}
// Use for single dimension arrays
static IntPtr SetupTensor (TFDataType dt, TFShape shape, Array data, int start, int count, int size)
{
if (shape == null)
throw new ArgumentNullException (nameof (shape));
return SetupTensor (dt, shape.dims, data, start, count, size);
}
// Use for single dimension arrays
static IntPtr SetupTensor (TFDataType dt, long [] dims, Array data, int start, int count, int size)
{
if (start < 0 || start > data.Length - count)
throw new ArgumentException ("start + count > Array size");
var dataHandle = GCHandle.Alloc (data, GCHandleType.Pinned);
if (dims == null)
return TF_NewTensor (dt, IntPtr.Zero, 0, dataHandle.AddrOfPinnedObject () + start * size, (UIntPtr)(count * size), FreeTensorHandleDelegate, GCHandle.ToIntPtr (dataHandle));
else
return TF_NewTensor (dt, dims, dims.Length, dataHandle.AddrOfPinnedObject () + start * size, (UIntPtr)(count * size), FreeTensorHandleDelegate, GCHandle.ToIntPtr (dataHandle));
}
// Use for multiple dimension arrays
static IntPtr SetupMulti (TFDataType dt, long [] dims, Array data, long bytes)
{
var dataHandle = GCHandle.Alloc (data, GCHandleType.Pinned);
if (dims == null)
return TF_NewTensor (dt, IntPtr.Zero, 0, dataHandle.AddrOfPinnedObject (), (UIntPtr)bytes, FreeTensorHandleDelegate, GCHandle.ToIntPtr (dataHandle));
else
return TF_NewTensor (dt, dims, dims.Length, dataHandle.AddrOfPinnedObject (), (UIntPtr)bytes, FreeTensorHandleDelegate, GCHandle.ToIntPtr (dataHandle));
}
//
// Factory methods to create tensors from a constant
//
/// <summary>
/// Converts an integer into a 1-dimensional, 1-valued tensor.
/// </summary>
/// <returns>The tensor representing the integer value.</returns>
/// <param name="value">Value to initialize the tensor with.</param>
public static implicit operator TFTensor (int value)
{
return new TFTensor (value);
}
/// <summary>
/// Converts a boolean into a 1-dimensional, 1-valued tensor.
/// </summary>
/// <returns>The tensor representing the integer value.</returns>
/// <param name="value">Value to initialize the tensor with.</param>
public static implicit operator TFTensor (bool value)
{
return new TFTensor (value);
}
/// <summary>
/// Converts a long into a 1-dimensional, 1-valued tensor.
/// </summary>
/// <returns>The tensor representing the long value.</returns>
/// <param name="value">Value to initialize the tensor with.</param>
public static implicit operator TFTensor (long value)
{
return new TFTensor (value);
}
/// <summary>
/// Converts a double into a 1-dimensional, 1-valued tensor.
/// </summary>
/// <returns>The tensor representing the double value.</returns>
/// <param name="value">Value to initialize the tensor with.</param>
unsafe public static implicit operator TFTensor (double value)
{
return new TFTensor (value);
}
/// <summary>
/// Converts a float into a 1-dimensional, 1-valued tensor.
/// </summary>
/// <returns>The tensor representing the float value.</returns>
/// <param name="value">Value to initialize the tensor with.</param>
unsafe public static implicit operator TFTensor (float value)
{
return new TFTensor (value);
}
/// <summary>
/// Converts a Complex number into a 1-dimensional, 1-valued tensor.
/// </summary>
/// <returns>The tensor representing the complex value.</returns>
/// <param name="value">Value to initialize the tensor with.</param>
unsafe public static implicit operator TFTensor (Complex value)
{
return new TFTensor (value);
}
/// <summary>
/// Converts a byte into a 1-dimensional, 1-valued tensor.
/// </summary>
/// <returns>The tensor representing the byte value.</returns>
/// <param name="value">Value to initialize the tensor with.</param>
unsafe public static implicit operator TFTensor (byte value)
{
return new TFTensor (value);
}
/// <summary>
/// Converts a C# array into a tensor.
/// </summary>
/// <returns>The tensor containing the data.</returns>
/// <param name="array">single dimension, or multi-dimensional array.</param>
/// <remarks>
/// This implicit conversion can convert single or multidimensional arrays of
/// booleans, sbytes, byte, shorts, ushorts, ints, longs, doubles, floats and
/// complex numbers into a tensor with the same dimensional shape as the provided
/// array.
/// </remarks>
unsafe public static implicit operator TFTensor (Array array)
{
return new TFTensor (array);
}
// General purpose constructor, specifies data type and gets pointer to buffer
// Is the default good, one where we let the user provide their own deallocator, or should we make a copy in that case?
/// <summary>
/// Low-level tensor constructor that creates a tensor from a buffer pointed to by an IntPtr.
/// </summary>
/// <param name="dataType">Specifies the data type held by the tensor, as well as how to interpret the provided data.</param>
/// <param name="dims">Describes the tensor shape, an array that indicates .</param>
/// <param name="data">Pointer to the raw data that will be used to initialize the tensor.</param>
/// <param name="dataSize">The size of the data being passed in.</param>
/// <param name="deallocator">Deallocator method, it is invoked when the tensor is destroyed to release the data pointed to by <paramref name="data"/>. On platforms like iOS (or other static compilation platforms), yiou must annotate the method specified in the deallocator with a <see cref="T:TensorFlow.MonoPInvokeCallbackAttribute"/>.</param>
/// <param name="deallocatorData">An optional argument of data that is passed to the deallocator method when the tensor is destroyed, you can use this to pass context information.</param>
public TFTensor (TFDataType dataType, long [] dims, IntPtr data, size_t dataSize, Deallocator deallocator, IntPtr deallocatorData) : base (IntPtr.Zero)
{
if (dims == null)
throw new ArgumentNullException ("dims");
handle = TF_NewTensor (dataType, dims, dims.Length, data, dataSize, deallocator, deallocatorData);
}
internal override void NativeDispose (IntPtr handle)
{
TF_DeleteTensor (handle);
}
// extern TF_Tensor * TF_AllocateTensor (TF_DataType, const int64_t *dims, int num_dims, size_t len);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Tensor TF_AllocateTensor (TFDataType dataType, long [] dims, int num_dims, size_t len);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Tensor TF_AllocateTensor (TFDataType dataType, IntPtr zeroDim, int num_dims, size_t len);
/// <summary>
/// Low-level: Creates an empty tensor of the specified type and shape, with the specified number of elements
/// </summary>
/// <param name="dataType">Data type.</param>
/// <param name="dims">Tensor shape.</param>
/// <param name="size">Size in bytes of the tensor, this will be the actual memory allocated.</param>
/// <remarks>
/// It is the responsibility of the caller to ensure that the size is correct given the data type size
/// and the tensor dimension specified in dims.
/// </remarks>
public TFTensor (TFDataType dataType, long [] dims, int size) : base (IntPtr.Zero)
{
if (dims == null)
throw new ArgumentNullException ("dims");
handle = TF_AllocateTensor (dataType, dims, dims.Length, (size_t)size);
}
// extern void TF_DeleteTensor (TF_Tensor *);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_DeleteTensor (TF_Tensor tensor);
// extern TF_DataType TF_TensorType (const TF_Tensor *);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe TFDataType TF_TensorType (TF_Tensor tensor);
/// <summary>
/// Returns the data type for the tensor.
/// </summary>
/// <value>The type of the tensor.</value>
public TFDataType TensorType => TF_TensorType (handle);
// extern int TF_NumDims (const TF_Tensor *);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_NumDims (TF_Tensor tensor);
/// <summary>
/// Returns the number of dimensions in the tensor.
/// </summary>
/// <remarks>
/// For single-dimension tensors the return is 1, 2 dimensions is 2 and so on.
/// </remarks>
public int NumDims => TF_NumDims (handle);
// extern int64_t TF_Dim (const TF_Tensor *tensor, int dim_index);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe long TF_Dim (TF_Tensor tensor, int dim_index);
/// <summary>
/// Returns the number of elements on a specific dimension in the tensor.
/// </summary>
/// <returns>The tensor dimension.</returns>
/// <param name="dimIndex">Dimension that you are querying.</param>
/// <remarks>
/// If you have a tensor of 3 elements by 5, represented by [3 5],
/// the GetTensorDimension(0) will return 3, the GetTensorDimension(1)
/// will return 5.
/// </remarks>
public long GetTensorDimension (int dimIndex)
{
return TF_Dim (handle, dimIndex);
}
// extern size_t TF_TensorByteSize (const TF_Tensor *);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe size_t TF_TensorByteSize (TF_Tensor tensor);
public size_t TensorByteSize => TF_TensorByteSize (handle);
// extern void * TF_TensorData (const TF_Tensor *);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe IntPtr TF_TensorData (TF_Tensor tensor);
/// <summary>
/// Returns a pointer to the raw data in the tensor.
/// </summary>
/// <remarks>
/// The contents of the Data must be interpreted according to the type of the
/// data as described by the DataType property. The amount of data
/// is given by the the TensorByteSize property.
/// </remarks>
public IntPtr Data => TF_TensorData (handle);
/// <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 {
var dims = new long [TF_NumDims (handle)];
for (int i = 0; i < dims.Length; i++)
dims [i] = (int)TF_Dim (handle, i);
return dims;
}
}
/// <summary>
/// Converts a <see cref="TFDataType"/> to a system type.
/// </summary>
/// <param name="type">The <see cref="TFDataType"/> to be converted.</param>
/// <returns>The system type corresponding to the given <paramref name="type"/>.</returns>
public static Type TypeFromTensorType (TFDataType type)
{
switch (type) {
case TFDataType.Float:
return typeof (float);
case TFDataType.Double:
return typeof (double);
case TFDataType.Int32:
return typeof (int);
case TFDataType.UInt8:
return typeof (byte);
case TFDataType.Int16:
return typeof (short);
case TFDataType.Int8:
return typeof (sbyte);
case TFDataType.String:
return typeof (TFString);
case TFDataType.Int64:
return typeof (long);
case TFDataType.Bool:
return typeof (bool);
case TFDataType.UInt16:
return typeof (ushort);
case TFDataType.Complex128:
return typeof (Complex);
default:
return null;
}
}
/// <summary>
/// Converts a system type to a <see cref="TFDataType"/>.
/// </summary>
/// <param name="type">The system type to be converted.</param>
/// <returns>The <see cref="TFDataType"/> corresponding to the given type.</returns>
public static TFDataType TensorTypeFromType (Type type)
{
if (type == typeof (float))
return TFDataType.Float;
if (type == typeof (double))
return TFDataType.Double;
if (type == typeof (int))
return TFDataType.Int32;
if (type == typeof (byte))
return TFDataType.UInt8;
if (type == typeof (short))
return TFDataType.Int16;
if (type == typeof (sbyte))
return TFDataType.Int8;
if (type == typeof (string))
return TFDataType.String;
if (type == typeof (long))
return TFDataType.Int64;
if (type == typeof (bool))
return TFDataType.Bool;
if (type == typeof (ushort))
return TFDataType.UInt16;
if (type == typeof (Complex))
return TFDataType.Complex128;
throw new ArgumentOutOfRangeException (nameof(type), $"The given type could not be mapped to an existing {nameof(TFDataType)}.");
}
internal static (TFDataType dt, long size) TensorTypeAndSizeFromType (Type t)
{
var tc = Type.GetTypeCode (t);
TFDataType dt;
long size = 0;
switch (tc) {
case TypeCode.Boolean:
dt = TFDataType.Bool;
size = 1;
break;
case TypeCode.SByte:
dt = TFDataType.Int8;
size = 1;
break;
case TypeCode.Byte:
dt = TFDataType.UInt8;
size = 1;
break;
case TypeCode.Int16:
dt = TFDataType.Int16;
size = 2;
break;
case TypeCode.UInt16:
dt = TFDataType.UInt16;
size = 2;
break;
case TypeCode.Int32:
dt = TFDataType.Int32;
size = 4;
break;
case TypeCode.Int64:
dt = TFDataType.Int64;
size = 8;
break;
case TypeCode.Single:
dt = TFDataType.Float;
size = 4;
break;
case TypeCode.Double:
dt = TFDataType.Double;
size = 8;
break;
default:
// Check types that are not handled by the typecode
if (t.IsAssignableFrom (typeof (Complex))) {
size = 16;
dt = TFDataType.Complex128;
} else
throw new ArgumentException ($"The data type {t} is not supported");
break;
}
return (dt, size);
}
internal static unsafe object FetchSimple (TFDataType dt, object data)
{
switch (dt) {
case TFDataType.Float:
return Convert.ToSingle (data);
case TFDataType.Double:
return Convert.ToDouble (data);
case TFDataType.Int32:
return Convert.ToInt32 (data);
case TFDataType.UInt8:
return Convert.ToByte (data);
case TFDataType.Int16:
return Convert.ToInt16 (data);
case TFDataType.Int8:
return Convert.ToSByte (data);
case TFDataType.String:
throw new NotImplementedException ();
case TFDataType.Int64:
return Convert.ToInt64 (data);
case TFDataType.Bool:
return Convert.ToBoolean (data);
case TFDataType.UInt16:
return Convert.ToUInt16 (data);
case TFDataType.Complex128:
return (Complex)data;
default:
return null;
}
}
static unsafe object FetchSimple (TFDataType dt, IntPtr data)
{
switch (dt) {
case TFDataType.Float:
return *(float*)data;
case TFDataType.Double:
return *(double*)data;
case TFDataType.Int32:
return *(int*)data;
case TFDataType.UInt8:
return *(byte*)data;
case TFDataType.Int16:
return *(short*)data;
case TFDataType.Int8:
return *(sbyte*)data;
case TFDataType.String:
throw new NotImplementedException ();
case TFDataType.Int64:
return *(long*)data;
case TFDataType.Bool:
return *(bool*)data;
case TFDataType.UInt16:
return *(ushort*)data;
case TFDataType.Complex128:
return *(Complex*)data;
default:
return null;
}
}
//used to create multidementional arrays / tensor with a constant value
internal static unsafe void Set (Array target, TFDataType dt, long [] shape, int [] idx, int level, object value)
{
if (level < shape.Length - 1) {
for (idx [level] = 0; idx [level] < shape [level]; idx [level]++)
Set (target, dt, shape, idx, level + 1, value);
} else {
for (idx [level] = 0; idx [level] < shape [level]; idx [level]++) {
switch (dt) {
case TFDataType.Float:
case TFDataType.Double:
case TFDataType.Int32:
case TFDataType.UInt8:
case TFDataType.Int16:
case TFDataType.Int8:
case TFDataType.Int64:
case TFDataType.Bool:
case TFDataType.Complex128:
target.SetValue (value, idx);
break;
case TFDataType.String:
throw new NotImplementedException ("String decoding not implemented for tensor vecotrs yet");