forked from microsoft/onnxruntime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrtValue.shared.cs
1463 lines (1327 loc) · 64 KB
/
OrtValue.shared.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.ML.OnnxRuntime.Tensors;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
#if NET8_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using SystemNumericsTensors = System.Numerics.Tensors;
using TensorPrimitives = System.Numerics.Tensors.TensorPrimitives;
#endif
namespace Microsoft.ML.OnnxRuntime
{
/// <summary>
/// A type of data that OrtValue encapsulates.
/// </summary>
public enum OnnxValueType
{
ONNX_TYPE_UNKNOWN = 0, // Not set
ONNX_TYPE_TENSOR = 1, // It's a Tensor
ONNX_TYPE_SEQUENCE = 2, // It's an Onnx sequence which may be a sequence of Tensors/Maps/Sequences
ONNX_TYPE_MAP = 3, // It's a map
ONNX_TYPE_OPAQUE = 4, // It's an experimental Opaque object
ONNX_TYPE_SPARSETENSOR = 5, // It's a Sparse Tensor
ONNX_TYPE_OPTIONAL = 6, // It's an optional type that designates anything above (except UNKNOWN)
}
/// <summary>
/// Represents a disposable OrtValue.
/// This class exposes a native instance of OrtValue.
/// The class implements IDisposable and must
/// be disposed of, otherwise native resources will leak
/// and will eventually cause the application to slow down or crash.
///
/// If the OrtValue instance is constructed over a managed memory, and it is not
/// disposed properly, the pinned memory will continue to be pinned and interfere
/// with GC operation.
/// </summary>
public class OrtValue : IOrtValueOwner, IDisposable
{
// OrtValues that are members of Sequences or Maps that map. They potentially map managed memory and we need to keep them around.
// this exists only when we deal with compose ML types.
private DisposableList<OrtValue> _compositeMembers;
private IntPtr _handle;
private MemoryHandle? _memHandle; // Present when the OrtValue is created on top of managed memory
private bool _disposed;
internal OrtValue(IntPtr handle)
{
_handle = handle;
InitOnnxType();
}
/// <summary>
/// Constructor. The newly constructed OrtValue takes ownership of the native OrtValue instance
/// </summary>
/// <param name="handle"></param>
/// <param name="onnxValueType"></param>
/// <exception cref="ArgumentException">thrown when onnxValue type is not known</exception>
internal OrtValue(IntPtr handle, OnnxValueType onnxValueType)
{
if (onnxValueType == OnnxValueType.ONNX_TYPE_UNKNOWN)
{
throw new ArgumentException("onnxValueType argument is passed as unknown");
}
_handle = handle;
OnnxType = onnxValueType;
}
/// <summary>
/// Constructor. The newly constructed OrtValue takes ownership of the native OrtValue instance
/// and disposes of it when the OrtValue instance is disposed. The instance will take ownership and will
/// dispose of compositeMembers instances.
///
/// This constructor can only throw if OnnxType is not specified.
/// </summary>
/// <param name="handle">native ortValue handle</param>
/// <param name="onnxValueType">must one of the valid types</param>
/// <param name="compositeMembers">For composite types this contains dependent ortValues such as members of a sequence
/// or keys/values for the map, that may have been created on top of the managed memory and must be disposed
/// with the new ortValue. This container will be taken the ownership of and the argument will be set to null.</param>
/// <exception cref="ArgumentException">throws when onnxValueType is not specified</exception>
internal OrtValue(IntPtr handle, OnnxValueType onnxValueType, ref DisposableList<OrtValue> compositeMembers)
{
if (onnxValueType == OnnxValueType.ONNX_TYPE_UNKNOWN)
{
throw new ArgumentException("onnxValueType argument is passed as unknown");
}
_handle = handle;
OnnxType = onnxValueType;
_compositeMembers = compositeMembers;
compositeMembers = null;
}
/// <summary>
/// Constructor to construct OrtValue over managed memory.
/// We pin the memory and unpin it at the disposal time.
/// The newly constructed OrtValue takes ownership of the native OrtValue instance
/// and disposes of it when the OrtValue instance is disposed.
/// </summary>
/// <param name="handle">Pointer to a native instance of OrtValue</param>
/// <param name="memHandle">memory handle to a pinned user supplied (usually managed) memory
/// It is disposed of (unpinned) when OrtValue is disposed.
/// </param>
private OrtValue(IntPtr handle, MemoryHandle memHandle)
{
_handle = handle;
_memHandle = memHandle;
// OrtValue on top of the pinned memory is always a tensor
OnnxType = OnnxValueType.ONNX_TYPE_TENSOR;
}
/// <summary>
/// Native handle to OrtValue for internal use.
/// </summary>
internal IntPtr Handle { get { return _handle; } }
/// <summary>
/// Implement IOrtValueOwner interface
/// </summary>
/// <value>returns this</value>
public OrtValue Value => this;
/// <summary>
/// Fetches OrtValue type if it has one.
/// </summary>
/// <value>OnnxValueType</value>
public OnnxValueType OnnxType { get; private set; }
private void InitOnnxType()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetValueType(Handle, out IntPtr onnxType));
OnnxType = (OnnxValueType)onnxType;
}
/// <summary>
/// Returns true if OrtValue contains a tensor
/// </summary>
/// <returns>true if tensor</returns>
public bool IsTensor
{
get
{
return OnnxType == OnnxValueType.ONNX_TYPE_TENSOR;
}
}
/// <summary>
/// Returns true if OrtValue contains a sparse tensor
/// </summary>
/// <returns>true if sparse tensor</returns>
public bool IsSparseTensor
{
get
{
return OnnxType == OnnxValueType.ONNX_TYPE_SPARSETENSOR;
}
}
/// <summary>
/// Valid for composite ML types like map, sequence.
/// Returns 2 for map (keys, values) and N for sequence, where N is the number of elements
/// in the sequence.
/// </summary>
/// <returns>Element count</returns>
public int GetValueCount()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetValueCount(Handle, out IntPtr count));
return (int)count;
}
/// <summary>
/// For non tensors return OrtValue element at the specified index.
/// For maps only indices 0 and 1 are valid. For sequences, [0..N) are valid.
/// See GetValueCount() to determine the valid range.
/// </summary>
/// <param name="index"></param>
/// <param name="allocator">allocator to use</param>
/// <returns>OrtValue disposable instance that points to the corresponding element of the composite type</returns>
public OrtValue GetValue(int index, OrtAllocator allocator)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetValue(Handle, index,
allocator.Pointer, out IntPtr ortValueHandle));
return new OrtValue(ortValueHandle);
}
/// <summary>
/// Returns a ReadOnlySpan<typeparamref name="T"/> over tensor native buffer that
/// provides a read-only view.
///
/// Note, that the memory may be device allocated and, therefore, not accessible from the CPU.
/// To get memory descriptor use GetTensorMemoryInfo().
///
/// OrtValue must contain a non-string tensor.
/// The span is valid as long as the OrtValue instance is alive (not disposed).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>ReadOnlySpan<typeparamref name="T"/></returns>
/// <exception cref="OnnxRuntimeException"></exception>
public ReadOnlySpan<T> GetTensorDataAsSpan<T>() where T : unmanaged
{
var byteSpan = GetTensorBufferRawData(typeof(T));
return MemoryMarshal.Cast<byte, T>(byteSpan);
}
#if NET8_0_OR_GREATER
/// <summary>
/// Returns a ReadOnlyTensorSpan<typeparamref name="T"/> over tensor native buffer that
/// provides a read-only view.
///
/// Note, that the memory may be device allocated and, therefore, not accessible from the CPU.
/// To get memory descriptor use GetTensorMemoryInfo().
///
/// OrtValue must contain a non-string tensor.
/// The span is valid as long as the OrtValue instance is alive (not disposed).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>ReadOnlySpan<typeparamref name="T"/></returns>
/// <exception cref="OnnxRuntimeException"></exception>
[Experimental("SYSLIB5001")]
public SystemNumericsTensors.ReadOnlyTensorSpan<T> GetTensorDataAsTensorSpan<T>() where T : unmanaged
{
var byteSpan = GetTensorBufferRawData(typeof(T));
var typeSpan = MemoryMarshal.Cast<byte, T>(byteSpan);
var shape = GetTypeInfo().TensorTypeAndShapeInfo.Shape;
nint[] nArray = Array.ConvertAll(shape, new Converter<long, nint>(x => (nint)x));
return new SystemNumericsTensors.ReadOnlyTensorSpan<T>(typeSpan, nArray, []);
}
#endif
/// <summary>
/// Returns a Span<typeparamref name="T"/> over tensor native buffer.
/// This enables you to safely and efficiently modify the underlying
/// native buffer in a type-safe manner. This is useful for example in IOBinding scenarios
/// where you want to modify results of the inference and feed it back as input.
///
/// Note, that the memory may be device allocated.
/// To get memory descriptor use GetTensorMemoryInfo().
///
/// OrtValue must contain a non-string tensor.
/// The span is valid as long as the OrtValue instance is alive (not disposed).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>Typed Span over the native buffer</returns>
public Span<T> GetTensorMutableDataAsSpan<T>() where T : unmanaged
{
var byteSpan = GetTensorBufferRawData(typeof(T));
return MemoryMarshal.Cast<byte, T>(byteSpan);
}
#if NET8_0_OR_GREATER
/// <summary>
/// Returns a TensorSpan<typeparamref name="T"/> over tensor native buffer.
///
/// Note, that the memory may be device allocated and, therefore, not accessible from the CPU.
/// To get memory descriptor use GetTensorMemoryInfo().
///
/// OrtValue must contain a non-string tensor.
/// The span is valid as long as the OrtValue instance is alive (not disposed).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>ReadOnlySpan<typeparamref name="T"/></returns>
/// <exception cref="OnnxRuntimeException"></exception>
[Experimental("SYSLIB5001")]
public SystemNumericsTensors.TensorSpan<T> GetTensorMutableDataAsTensorSpan<T>() where T : unmanaged
{
var byteSpan = GetTensorBufferRawData(typeof(T));
var typeSpan = MemoryMarshal.Cast<byte, T>(byteSpan);
var shape = GetTypeInfo().TensorTypeAndShapeInfo.Shape;
nint[] nArray = Array.ConvertAll(shape, new Converter<long, nint>(x => (nint)x));
return new SystemNumericsTensors.TensorSpan<T>(typeSpan, nArray, []);
}
#endif
/// <summary>
/// Provides mutable raw native buffer access.
/// </summary>
/// <returns>Span over the native buffer bytes</returns>
public Span<byte> GetTensorMutableRawData()
{
return GetTensorBufferRawData(typeof(byte));
}
#if NET8_0_OR_GREATER
/// <summary>
/// Provides mutable raw native buffer access.
/// </summary>
/// <returns>TensorSpan over the native buffer bytes</returns>
[Experimental("SYSLIB5001")]
public SystemNumericsTensors.TensorSpan<byte> GetTensorSpanMutableRawData<T>() where T : unmanaged
{
var byteSpan = GetTensorBufferRawData(typeof(T));
var shape = GetTypeInfo().TensorTypeAndShapeInfo.Shape;
nint[] nArray = Array.ConvertAll(shape, new Converter<long, nint>(x => (nint)x));
return new SystemNumericsTensors.TensorSpan<byte>(byteSpan, nArray, []);
}
#endif
/// <summary>
/// Fetch string tensor element buffer pointer at the specified index,
/// convert/copy to UTF-16 char[] and return a ReadOnlyMemory{char} instance.
///
/// Obtain TensorTypeAndShape to get shape and element count.
/// </summary>
/// <param name="index">flat string tensor element index</param>
/// <returns>ReadOnlyMemory{char} backed by a managed char[]. Its lifespan is not
/// tied to the native buffer of OrtValue.</returns>
public ReadOnlyMemory<char> GetStringElementAsMemory(int index)
{
var chars = GetStringTensorElementChars(index);
if (chars.Length == 0)
{
return ReadOnlyMemory<char>.Empty;
}
return new ReadOnlyMemory<char>(chars);
}
/// <summary>
/// Fetch string tensor element buffer pointer at the specified index,
/// copy/convert UTF-8 into a UTF-16 string and return it.
///
/// Obtain TensorTypeAndShape to get shape and element count.
/// </summary>
/// <param name="index">flat string tensor element index</param>
/// <returns>UTF-16 string instance</returns>
public string GetStringElement(int index)
{
GetStringTensorElementBuffer((UIntPtr)index, out uint bytesLen, out IntPtr bufferPtr);
if (bytesLen == 0)
{
return string.Empty;
}
unsafe
{
return Encoding.UTF8.GetString((byte*)bufferPtr.ToPointer(), (int)bytesLen);
}
}
/// <summary>
/// Get a span over the native memory of the string tensor element.
/// The span is valid as long as the OrtValue is valid.
///
/// This is useful if you want to perform your own UTF-8 decoding or
/// you do not care about decoding.
/// Obtain TensorTypeAndShape to get shape and element count.
/// </summary>
/// <param name="index">flat element index</param>
/// <returns>ReadOnlySpan over UTF-8 bytes of the string tensor element</returns>
public ReadOnlySpan<byte> GetStringElementAsSpan(int index)
{
GetStringTensorElementBuffer((UIntPtr)index, out uint bytesLen, out IntPtr bufferPtr);
if (bytesLen == 0)
{
return ReadOnlySpan<byte>.Empty;
}
unsafe
{
return new ReadOnlySpan<byte>((bufferPtr).ToPointer(), (int)bytesLen);
}
}
/// <summary>
/// Convenience method to obtain all string tensor elements as a string array.
/// </summary>
/// <returns>string[]</returns>
/// <exception cref="OnnxRuntimeException"></exception>
public string[] GetStringTensorAsArray()
{
GetTensorElementTypeAndCount(out long count, out TensorElementType elementType);
if (elementType != TensorElementType.String)
{
throw new OnnxRuntimeException(
ErrorCode.Fail,
$"GetStringTensorAsArray() is only supported for string tensors. This OrtValue contains a {elementType} tensor.");
}
var strings = new string[count];
for (int i = 0; i < count; i++)
{
strings[i] = GetStringElement(i);
}
return strings;
}
/// <summary>
/// Creates and fetches Type information about the contained OnnxValue.
/// </summary>
/// <returns>a disposable instance of OrtTypeInfo</returns>
public OrtTypeInfo GetTypeInfo()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetTypeInfo(Handle, out IntPtr typeInfo));
try
{
return new OrtTypeInfo(typeInfo);
}
finally
{
NativeMethods.OrtReleaseTypeInfo(typeInfo);
}
}
/// <summary>
/// Obtains Tensor And Type Information from the OrtValue iff it contains a tensor.
/// Valid only for OrtValues that contain a tensor.
/// </summary>
/// <returns>A disposable instance of OrtTensorTypeAndShapeInfo</returns>
public OrtTensorTypeAndShapeInfo GetTensorTypeAndShape()
{
var onnxType = OnnxType;
if (onnxType != OnnxValueType.ONNX_TYPE_TENSOR &&
onnxType != OnnxValueType.ONNX_TYPE_SPARSETENSOR)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
$"This OrtValue type contains: {onnxType}, not a tensor or sparse tensor");
}
NativeMethods.OrtGetTensorTypeAndShape(Handle, out IntPtr typeAndShapeInfo);
try
{
return new OrtTensorTypeAndShapeInfo(typeAndShapeInfo);
}
finally
{
NativeMethods.OrtReleaseTensorTypeAndShapeInfo(typeAndShapeInfo);
}
}
/// <summary>
/// Returns OrtMemoryInfo iff this OrtValue contains a tensor or a sparse tensor.
/// </summary>
/// <returns>OrtMemoryInfo that describes the underlying memory allocation</returns>
/// <exception cref="OnnxRuntimeException"></exception>
public OrtMemoryInfo GetTensorMemoryInfo()
{
var onnxType = OnnxType;
if (onnxType != OnnxValueType.ONNX_TYPE_TENSOR &&
onnxType != OnnxValueType.ONNX_TYPE_SPARSETENSOR)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
$"This OrtValue type contains: {onnxType}, not a tensor or sparse tensor");
}
NativeMethods.OrtGetTensorMemoryInfo(Handle, out IntPtr memoryInfo);
return new OrtMemoryInfo(memoryInfo, false);
}
private void GetTensorElementTypeAndCount(out long count, out TensorElementType elementType)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetTensorTypeAndShape(Handle, out IntPtr typeAndShapeInfo));
try
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetTensorElementType(typeAndShapeInfo, out IntPtr elType));
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetTensorShapeElementCount(typeAndShapeInfo, out UIntPtr cnt));
elementType = (TensorElementType)elType;
count = (long)cnt;
}
finally
{
NativeMethods.OrtReleaseTensorTypeAndShapeInfo(typeAndShapeInfo);
}
}
private char[] GetStringTensorElementChars(int index)
{
GetStringTensorElementBuffer((UIntPtr)index, out uint bytesLen, out IntPtr bufferPtr);
if (bytesLen == 0)
{
return Array.Empty<char>();
}
unsafe
{
int charCount = Encoding.UTF8.GetCharCount((byte*)(bufferPtr).ToPointer(), (int)bytesLen);
var chars = new char[charCount];
fixed (char* ch = chars)
{
Encoding.UTF8.GetChars((byte*)(bufferPtr).ToPointer(), (int)bytesLen, (char*)ch, charCount);
}
return chars;
}
}
private void GetStringTensorElementBuffer(UIntPtr index, out uint bytesLen, out IntPtr bufferPtr)
{
// Length is in UTF-8 bytes. Strings are not zero terminated, so length is required.
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetStringTensorElementLength(Handle, index, out UIntPtr bufferLen));
bytesLen = (uint)bufferLen;
if (bytesLen == 0)
{
bufferPtr = IntPtr.Zero;
return;
}
// XXX: We lack the API (at the moment) that simply gives access to string element buffer. So we get the resized one
// to the same length which leaves it unchanged.
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetResizedStringTensorElementBuffer(Handle,
(UIntPtr)index, bufferLen, out bufferPtr));
}
private Span<byte> GetTensorBufferRawData(Type requestedType)
{
if (OnnxType != OnnxValueType.ONNX_TYPE_TENSOR)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
$"This OrtValue type contains: {OnnxType}, not a tensor");
}
GetTensorElementTypeAndCount(out long count, out TensorElementType elementType);
if (elementType == TensorElementType.String)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Strings are not supported by this API");
}
var typeInfo = TensorBase.GetElementTypeInfo(elementType) ??
throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Element type: {elementType} is not registered type.");
// We are always Ok with byte
if (requestedType != typeof(byte) && requestedType != typeInfo.TensorType)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
$"Requested type: {requestedType} does not match the actual type: {typeInfo.TensorType}");
}
if (count == 0)
{
return Span<byte>.Empty;
}
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetTensorMutableData(Handle, out IntPtr tensorData));
var bufferLenInBytes = count * typeInfo.TypeSize;
unsafe
{
return new Span<byte>(tensorData.ToPointer(), (int)bufferLenInBytes);
}
}
/// <summary>
/// Factory method to construct an OrtValue of Tensor type on top of pre-allocated memory.
/// This can be a piece of arbitrary memory that may be allocated by OrtAllocator (possibly on a device),
/// a chunk of managed memory (must be pinned for the duration of OrtValue lifetime) or a memory that is allocated
/// natively allocated using Marshal.AllocHGlobal(), stackalloc or other means (may be on a device).
///
/// The resulting OrtValue does not own the underlying memory buffer and will not attempt to
/// deallocate it. The caller must make sure that the memory remains valid for the duration of OrtValue lifetime.
/// </summary>
/// <param name="memInfo">Memory Info. For managed memory its default is cpu.
/// For other kinds of memory, one must construct as appropriate.</param>
/// <param name="elementType">DataType for the Tensor</param>
/// <param name="shape">shape of the tensor to create. The size required by the shape
/// must be less of equal of the memory.Length</param>
/// <param name="dataBufferPtr">Pointer to a raw memory buffer which may reside on a device</param>
/// <param name="bufferLengthInBytes">Buffer length in bytes</param>
/// <returns>A disposable instance of OrtValue</returns>
public static OrtValue CreateTensorValueWithData(OrtMemoryInfo memInfo, TensorElementType elementType,
long[] shape,
IntPtr dataBufferPtr,
long bufferLengthInBytes)
{
var typeInfo = TensorBase.GetElementTypeInfo(elementType) ?? throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
$"Tensor element type: {elementType} is not supported");
if (typeInfo.IsString)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
"Cannot map managed strings buffer to native OrtValue. Use string specific interfaces");
}
var shapeSize = ShapeUtils.GetSizeForShape(shape);
var requiredBufferSizeInBytes = shapeSize * typeInfo.TypeSize;
// We allow creating a tensor over part of the buffer
if (requiredBufferSizeInBytes > bufferLengthInBytes)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
$"Shape: {shape} has: {shapeSize} elements requires a buffer of at least {requiredBufferSizeInBytes} bytes. Provided: {bufferLengthInBytes} bytes");
}
NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorWithDataAsOrtValue(
memInfo.Pointer,
dataBufferPtr,
(UIntPtr)bufferLengthInBytes,
shape,
(UIntPtr)shape.Length,
elementType,
out IntPtr ortValueHandle
));
return new OrtValue(ortValueHandle, OnnxValueType.ONNX_TYPE_TENSOR);
}
/// <summary>
/// This is a factory method that creates an OrtValue of Tensor type on top of Memory<typeparamref name="T"/> memory.
/// The API pins the memory for the duration of the OrtValue lifetime.
/// It is unpinned at disposal time.
/// </summary>
/// <typeparam name="T">T must be one of the supported types</typeparam>
/// <param name="memoryInfo">Memory information that describes memory location</param>
/// <param name="memory">contiguous region of memory</param>
/// <param name="shape">shape of the tensor to create. The size required by the shape
/// must be less of equal of the memory.Length</param>
/// <returns>A disposable OrtValue instance</returns>
/// <exception cref="OnnxRuntimeException"></exception>
public static OrtValue CreateTensorValueFromMemory<T>(OrtMemoryInfo memoryInfo, Memory<T> memory, long[] shape)
where T : unmanaged
{
var typeInfo = TensorBase.GetTypeInfo(typeof(T)) ??
throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Tensor of type: {typeof(T)} is not supported");
if (typeInfo.IsString)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
"Cannot map managed strings buffer to native OrtValue. Use string specific interfaces.");
}
var shapeSize = ShapeUtils.GetSizeForShape(shape);
// We allow creating a tensor over part of the buffer
if (shapeSize > memory.Length)
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument,
$"Managed memory size: {memory.Length} elements is less than shape size: {shapeSize} elements");
}
var bufferLengthInBytes = memory.Length * typeInfo.TypeSize;
var memoryHandle = memory.Pin();
try
{
IntPtr bufferPtr;
unsafe
{
bufferPtr = new IntPtr(memoryHandle.Pointer);
}
NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorWithDataAsOrtValue(
memoryInfo.Pointer,
bufferPtr,
(UIntPtr)bufferLengthInBytes,
shape,
(UIntPtr)shape.Length,
typeInfo.ElementType,
out IntPtr ortValueHandle
));
return new OrtValue(ortValueHandle, memoryHandle);
}
catch (Exception)
{
memoryHandle.Dispose();
throw;
}
}
/// <summary>
/// This is a factory method that creates an OrtValue of Tensor type on top managed data array.
/// The API pins the memory for the duration of the OrtValue lifetime.
/// It is unpinned at disposal time.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">managed data buffer</param>
/// <param name="shape">shape that describes the buffer</param>
/// <returns>A disposable OrtValue instance</returns>
public static OrtValue CreateTensorValueFromMemory<T>(T[] data, long[] shape) where T : unmanaged
{
return OrtValue.CreateTensorValueFromMemory(OrtMemoryInfo.DefaultInstance, new Memory<T>(data), shape);
}
#if NET8_0_OR_GREATER
/// <summary>
/// This is a factory method creates a native Onnxruntime OrtValue containing a tensor on top of the existing tensor managed memory.
/// The method will attempt to pin managed memory so no copying occurs when data is passed down
/// to native code.
/// </summary>
/// <param name="value">Tensor object</param>
/// <param name="elementType">discovered tensor element type</param>
/// <returns>And instance of OrtValue constructed on top of the object</returns>
[Experimental("SYSLIB5001")]
public static OrtValue CreateTensorValueFromSystemNumericsTensorObject<T>(SystemNumericsTensors.Tensor<T> tensor) where T : unmanaged
{
if (!IsContiguousAndDense(tensor))
{
var newTensor = SystemNumericsTensors.Tensor.Create<T>(tensor.Lengths);
tensor.CopyTo(newTensor);
tensor = newTensor;
}
unsafe
{
var backingData = (T[])tensor.GetType().GetField("_values", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tensor);
GCHandle handle = GCHandle.Alloc(backingData, GCHandleType.Pinned);
var memHandle = new MemoryHandle(Unsafe.AsPointer(ref tensor.GetPinnableReference()), handle);
try
{
IntPtr dataBufferPointer = IntPtr.Zero;
unsafe
{
dataBufferPointer = (IntPtr)memHandle.Pointer;
}
var bufferLengthInBytes = tensor.FlattenedLength * sizeof(T);
long[] shape = Array.ConvertAll(tensor.Lengths.ToArray(), new Converter<nint, long>(x => (long)x));
var typeInfo = TensorBase.GetTypeInfo(typeof(T)) ??
throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Tensor of type: {typeof(T)} is not supported");
NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorWithDataAsOrtValue(
OrtMemoryInfo.DefaultInstance.Pointer,
dataBufferPointer,
(UIntPtr)(bufferLengthInBytes),
shape,
(UIntPtr)tensor.Rank,
typeInfo.ElementType,
out IntPtr nativeValue));
return new OrtValue(nativeValue, memHandle);
}
catch (Exception)
{
memHandle.Dispose();
throw;
}
}
}
[Experimental("SYSLIB5001")]
private static bool IsContiguousAndDense<T>(SystemNumericsTensors.Tensor<T> tensor) where T : unmanaged
{
// Right most dimension must be 1 for a dense tensor.
if (tensor.Strides[^1] != 1)
return false;
// For other dimensions, the stride must be equal to the product of the dimensions to the right.
for (int i = tensor.Rank - 2; i >= 0; i--)
{
if (tensor.Strides[i] != TensorPrimitives.Product(tensor.Lengths.Slice(i + 1, tensor.Lengths.Length - i - 1)))
return false;
}
return true;
}
#endif
/// <summary>
/// The factory API creates an OrtValue with memory allocated using the given allocator
/// according to the specified shape and element type. The memory will be released when OrtValue
/// is disposed. Use GetTensorMutableDataAsSpan<T>() API to fill in the data.
/// </summary>
/// <param name="allocator"></param>
/// <param name="elementType"></param>
/// <param name="shape"></param>
/// <returns>A disposable OrtValue</returns>
public static OrtValue CreateAllocatedTensorValue(OrtAllocator allocator, TensorElementType elementType,
long[] shape)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorAsOrtValue(allocator.Pointer, shape,
(UIntPtr)shape.Length, elementType, out IntPtr ortValueHandle));
return new OrtValue(ortValueHandle, OnnxValueType.ONNX_TYPE_TENSOR);
}
/// <summary>
/// This is a factory method creates a native Onnxruntime OrtValue containing a tensor.
/// The method will attempt to pin managed memory so no copying occurs when data is passed down
/// to native code.
/// </summary>
/// <param name="value">Tensor object</param>
/// <param name="elementType">discovered tensor element type</param>
/// <returns>And instance of OrtValue constructed on top of the object</returns>
internal static OrtValue CreateFromTensorObject(TensorBase value, out TensorElementType elementType)
{
var typeInfo = value.GetTypeInfo();
OrtValue ortValue = null;
TensorElementType elType = typeInfo.ElementType;
var typeSize = typeInfo.TypeSize;
if (typeInfo.IsString)
{
ortValue = CreateFromStringTensor(value as Tensor<string>);
}
else
{
int dataBufferLength;
long[] shape;
int rank;
MemoryHandle memHandle;
switch (elType)
{
case TensorElementType.Float:
PinAsTensor(value as Tensor<float>, typeSize, out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.Double:
PinAsTensor(value as Tensor<double>, typeSize, out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.Int32:
PinAsTensor(value as Tensor<int>, typeSize, out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.UInt32:
PinAsTensor(value as Tensor<uint>, typeSize, out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.Int64:
PinAsTensor(value as Tensor<long>, typeSize, out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.UInt64:
PinAsTensor(value as Tensor<ulong>, typeSize, out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.Int16:
PinAsTensor(value as Tensor<short>, typeSize, out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.UInt16:
PinAsTensor(value as Tensor<ushort>, typeSize,
out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.UInt8:
PinAsTensor(value as Tensor<byte>, typeSize,
out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.Int8:
PinAsTensor(value as Tensor<sbyte>, typeSize,
out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.Bool:
PinAsTensor(value as Tensor<bool>, typeSize,
out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.Float16:
PinAsTensor(value as Tensor<Float16>, typeSize,
out memHandle, out dataBufferLength,
out shape, out rank);
break;
case TensorElementType.BFloat16:
PinAsTensor(value as Tensor<BFloat16>, typeSize,
out memHandle, out dataBufferLength,
out shape, out rank);
break;
default:
throw new NotSupportedException("Element type: " + elType + " is not of a supported type");
}
try
{
IntPtr dataBufferPointer = IntPtr.Zero;
unsafe
{
dataBufferPointer = (IntPtr)memHandle.Pointer;
}
NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorWithDataAsOrtValue(
OrtMemoryInfo.DefaultInstance.Pointer,
dataBufferPointer,
(UIntPtr)(dataBufferLength),
shape,
(UIntPtr)rank,
elType,
out IntPtr nativeValue));
ortValue = new OrtValue(nativeValue, memHandle);
}
catch (Exception)
{
memHandle.Dispose();
throw;
}
}
elementType = elType;
return ortValue;
}
/// <summary>
/// Creates an OrtValue that contains a string tensor of specified shape, and
/// containing empty strings. String tensors are always on CPU.
/// Use StringTensorSetElementAt to assign individual elements values.
/// </summary>
/// <param name="allocator"></param>
/// <returns>disposable OrtValue</returns>
/// <param name="shape">tensor shape</param>
public static OrtValue CreateTensorWithEmptyStrings(OrtAllocator allocator, long[] shape)
{
// allocate the native tensor
NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorAsOrtValue(
allocator.Pointer,
shape,
(UIntPtr)(shape.Length),
TensorElementType.String,
out IntPtr valueHandle
));
return new OrtValue(valueHandle, OnnxValueType.ONNX_TYPE_TENSOR);
}
/// <summary>
/// Converts the string argument represented by ReadOnlySpan to UTF-8,
/// allocates space in the native tensor and copies it into the native tensor memory.
/// Typically, this is used to populate a new empty string tensor element.
///
/// The number of elements is according to the shape supplied to CreateTensorWithEmptyStrings().
/// However, this API can also be used to overwrite any existing element within the string tensor.
///
/// In general, to obtain the number of elements for any tensor, use GetTensorTypeAndShape() which
/// would return a disposable instance of TensorTypeAndShapeInfo.
/// Then call GetElementCount() or GetShape().
/// </summary>
/// <param name="str">ReadOnlySpan over chars</param>
/// <param name="index">index of the string element within the tensor
/// must be within bounds of [0, N)</param>
public void StringTensorSetElementAt(ReadOnlySpan<char> str, int index)
{
unsafe
{
fixed (char* strPtr = str)
{
FillStringTensorElement(strPtr, str.Length, index);
}
}
}
/// <summary>
/// Converts the string argument represented by ReadOnlyMemory to UTF-8,
/// allocates space in the native tensor and copies it into the native tensor memory.
/// Typically, this is used to populate a new empty string tensor element.
///
/// The number of elements is according to the shape supplied to CreateTensorWithEmptyStrings().
/// However, this API can also be used to overwrite any existing element within the string tensor.
///
/// In general, to obtain the number of elements for any tensor, use GetTensorTypeAndShape() which
/// would return a disposable instance of TensorTypeAndShapeInfo.
/// Then call GetElementCount() or GetShape().
///
/// </summary>
/// <param name="rom">ReadOnlyMemory instance over an array of chars</param>
/// <param name="index">index of the string element within the tensor
/// must be within bounds of [0, N)</param>
public void StringTensorSetElementAt(ReadOnlyMemory<char> rom, int index)
{
StringTensorSetElementAt(rom.Span, index);
}
/// <summary>
/// This API resizes String Tensor element to the requested amount of bytes (UTF-8)
/// and copies the bytes from the supplied ReadOnlySpan into the native tensor memory (resized buffer).
///
/// The API is useful for quick loading of utf8 data into the native tensor memory.
/// </summary>
/// <param name="utf8Bytes">read only span of bytes</param>
/// <param name="index">flat index of the element in the string tensor</param>
public void StringTensorSetElementAt(ReadOnlySpan<byte> utf8Bytes, int index)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtGetResizedStringTensorElementBuffer(Handle,
(UIntPtr)index, (UIntPtr)utf8Bytes.Length, out IntPtr buffer));
if (utf8Bytes.Length == 0)
{
return;
}
unsafe
{
var destSpan = new Span<byte>(buffer.ToPointer(), utf8Bytes.Length);
utf8Bytes.CopyTo(destSpan);
}
}
/// <summary>
/// Creates an OrtValue that contains a string tensor.
/// String tensors are always allocated on CPU.
/// String data will be converted to UTF-8 and copied to native memory.
///
/// Note, this is different from creating an OrtValue from other primitive data types
/// where memory is pinned (if necessary) and the OrtValue points to that chunk of memory.
/// </summary>
/// <param name="tensor">Tensor{string}</param>