/
InferenceSession.shared.cs
2089 lines (1878 loc) · 90.2 KB
/
InferenceSession.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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace Microsoft.ML.OnnxRuntime
{
/// <summary>
/// Represents an Inference Session on an ONNX Model.
/// This is a IDisposable class and it must be disposed of
/// using either a explicit call to Dispose() method or
/// a pattern of using() block. If this is a member of another
/// class that class must also become IDisposable and it must
/// dispose of InferenceSession in its Dispose() method.
/// </summary>
public class InferenceSession : IDisposable
{
/// <summary>
/// A pointer to a underlying native instance of OrtSession
/// </summary>
private IntPtr _nativeHandle;
/// <summary>
/// Dictionary that represents input metadata
/// </summary>
private Dictionary<string, NodeMetadata> _inputMetadata;
/// <summary>
/// Ordered list of input names
/// </summary>
private List<string> _inputNames;
/// <summary>
/// Dictionary that represent output metadata
/// </summary>
private Dictionary<string, NodeMetadata> _outputMetadata;
/// <summary>
/// Ordered list of output names
/// </summary>
private List<string> _outputNames;
/// <summary>
/// Dictionary that represents overridableInitializers metadata
/// </summary>
private Dictionary<string, NodeMetadata> _overridableInitializerMetadata;
/// <summary>
/// This list holds Utf-8 converted input/output names allocated from a native heap
/// and as such do not require pinning. It must be disposed of (freed).
///
/// Introduced to reduce the GC burden as the names are used in every Run() call.
/// </summary>
private List<IntPtr> _namesMemoryPtrs;
private SessionOptions _builtInSessionOptions = null;
private RunOptions _builtInRunOptions = null;
private ModelMetadata _modelMetadata = null;
private bool _disposed = false;
private ulong _profilingStartTimeNs = 0;
#region Public API
/// <summary>
/// Constructs an InferenceSession from a model file
/// </summary>
/// <param name="modelPath"></param>
public InferenceSession(string modelPath)
{
_builtInSessionOptions = new SessionOptions(); // need to be disposed
Init(modelPath, _builtInSessionOptions);
}
/// <summary>
/// Constructs an InferenceSession from a model file and it will use
/// the provided pre-packed weights container to store and share pre-packed buffers
/// of shared initializers across sessions if any.
/// </summary>
/// <param name="modelPath">Model path</param>
/// <param name="prepackedWeightsContainer">Instance of PrepackedWeightsContainer.
/// Lifetime of 'prepackedWeightsContainer' must be
/// managed by the user and it must outlive any sessions reliant on it</param>
public InferenceSession(string modelPath, PrePackedWeightsContainer prepackedWeightsContainer)
{
_builtInSessionOptions = new SessionOptions(); // need to be disposed
Init(modelPath, _builtInSessionOptions, prepackedWeightsContainer);
}
/// <summary>
/// Constructs an InferenceSession from a model file, with some additional session options
/// </summary>
/// <param name="modelPath"></param>
/// <param name="options"></param>
public InferenceSession(string modelPath, SessionOptions options)
{
Init(modelPath, options);
}
/// <summary>
/// Constructs an InferenceSession from a model file, with some additional session options
/// and it will use the provided pre-packed weights container to store and share pre-packed buffers
/// of shared initializers across sessions if any.
/// </summary>
/// <param name="modelPath">Model path</param>
/// <param name="options">Session options</param>
/// <param name="prepackedWeightsContainer">Instance of PrepackedWeightsContainer.
/// Lifetime of 'prepackedWeightsContainer' must be
/// managed by the user and it must outlive any sessions reliant on it</param>
public InferenceSession(string modelPath, SessionOptions options,
PrePackedWeightsContainer prepackedWeightsContainer)
{
Init(modelPath, options, prepackedWeightsContainer);
}
/// <summary>
/// Constructs an InferenceSession from a model data in byte array
/// </summary>
/// <param name="model"></param>
public InferenceSession(byte[] model)
{
_builtInSessionOptions = new SessionOptions(); // need to be disposed
Init(model, _builtInSessionOptions);
}
/// <summary>
/// Constructs an InferenceSession from a model data (in byte array) and it will use
/// the provided pre-packed weights container to store and share pre-packed buffers
/// of shared initializers across sessions if any.
/// </summary>
/// <param name="model">Model as byte array</param>
/// <param name="prepackedWeightsContainer">Instance of PrepackedWeightsContainer.
/// Lifetime of 'prepackedWeightsContainer' must be
/// managed by the user and it must outlive any sessions reliant on it</param>
public InferenceSession(byte[] model, PrePackedWeightsContainer prepackedWeightsContainer)
{
_builtInSessionOptions = new SessionOptions(); // need to be disposed
Init(model, _builtInSessionOptions, prepackedWeightsContainer);
}
/// <summary>
/// Constructs an InferenceSession from a model data in byte array, with some additional session options
/// </summary>
/// <param name="model"></param>
/// <param name="options"></param>
public InferenceSession(byte[] model, SessionOptions options)
{
Init(model, options);
}
/// <summary>
/// Constructs an InferenceSession from a model data (in byte array) with some additional
/// session options and it will use the provided pre-packed weights container to store
/// and share pre-packed buffers of shared initializers across sessions if any.
/// </summary>
/// <param name="model">Model as byte array</param>
/// <param name="options">Session Options</param>
/// <param name="prepackedWeightsContainer">Instance of PrepackedWeightsContainer.
/// Lifetime of 'prepackedWeightsContainer' must be
/// managed by the user and it must outlive any sessions reliant on it</param>
public InferenceSession(byte[] model, SessionOptions options,
PrePackedWeightsContainer prepackedWeightsContainer)
{
Init(model, options, prepackedWeightsContainer);
}
/// <summary>
/// Meta data regarding the input nodes, keyed by input names
/// </summary>
public IReadOnlyDictionary<string, NodeMetadata> InputMetadata
{
get
{
return _inputMetadata;
}
}
/// <summary>
/// Ordered list of input names that can be accessed by index;
/// </summary>
public IReadOnlyList<string> InputNames { get { return _inputNames; } }
/// <summary>
/// Metadata regarding the output nodes, keyed by output names
/// </summary>
public IReadOnlyDictionary<string, NodeMetadata> OutputMetadata
{
get
{
return _outputMetadata;
}
}
/// <summary>
/// Ordered list of output names that can be accessed by index.
/// </summary>
public IReadOnlyList<string> OutputNames { get { return _outputNames; } }
/// <summary>
/// Metadata regarding the overridable initializers, keyed by node names
/// </summary>
public IReadOnlyDictionary<string, NodeMetadata> OverridableInitializerMetadata
{
get
{
return _overridableInitializerMetadata;
}
}
/// <summary>
/// Runs the loaded model for the given inputs, and fetches all the outputs.
/// </summary>
/// <param name="inputs">specify a collection of <see cref="NamedOnnxValue"/> that indicates the input values.</param>
/// <returns>Output Tensors in a Collection of NamedOnnxValue. User must dispose the output.</returns>
public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs)
{
return Run(inputs, _outputNames);
}
/// <summary>
/// Runs the loaded model for the given inputs, and fetches the outputs specified in <paramref name="outputNames"/>.
/// </summary>
/// <param name="inputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names to fetch.</param>
/// <returns>Output Tensors in a Collection of NamedOnnxValue. User must dispose the output.</returns>
public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs,
IReadOnlyCollection<string> outputNames)
{
return Run(inputs, outputNames, _builtInRunOptions);
}
/// <summary>
/// Runs the loaded model for the given inputs, and fetches the specified outputs in <paramref name="outputNames"/>. Uses the given RunOptions for this run.
/// </summary>
/// <param name="inputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names to fetch.</param>
/// <param name="options"></param>
/// <returns>Output Tensors in a Collection of NamedOnnxValue. User must dispose the output.</returns>
public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs,
IReadOnlyCollection<string> outputNames,
RunOptions options)
{
var inputNamesArray = LookupUtf8Names(inputs, v => v.Name, LookupInputMetadata);
var outputNamesArray = LookupUtf8Names(outputNames, n => n, LookupOutputMetadata);
var inputValuesArray = GetOrtValuesHandles(inputs, LookupInputMetadata,
ExtractOrtValueHandleForInput, out DisposableArray<IDisposable> inputsDisposer);
try
{
var outputsDisposer = RunImpl(options, inputNamesArray, inputValuesArray, outputNamesArray);
try
{
return CreateDisposableResult(outputsDisposer.Span, outputNames);
}
finally
{
outputsDisposer.Dispose();
}
}
finally
{
inputsDisposer.Dispose();
}
}
/// <summary>
/// Runs the loaded model for the given inputs, and fetches all the outputs.
/// </summary>
/// <param name="inputNames">Specify a collection of string that indicates the input names. Should match <paramref name="inputValues"/>.</param>
/// <param name="inputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the input values.</param>
/// <returns>Output Tensors in a Collection of NamedOnnxValue. User must dispose the output.</returns>
public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(
IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<FixedBufferOnnxValue> inputValues)
{
return Run(inputNames, inputValues, _outputNames, _builtInRunOptions);
}
/// <summary>
/// Runs the loaded model for the given inputs, and fetches the outputs specified in <paramref name="outputNames"/>.
/// </summary>
/// <param name="inputNames">Specify a collection of string that indicates the input names. Should match <paramref name="inputValues"/>.</param>
/// <param name="inputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names to fetch.</param>
/// <returns>Output Tensors in a Collection of NamedOnnxValue. User must dispose the output.</returns>
public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(
IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<FixedBufferOnnxValue> inputValues,
IReadOnlyCollection<string> outputNames)
{
return Run(inputNames, inputValues, outputNames, _builtInRunOptions);
}
/// <summary>
/// Runs the loaded model for the given inputs, and fetches the specified outputs in <paramref name="outputNames"/>. Uses the given RunOptions for this run.
/// </summary>
/// <param name="inputNames">Specify a collection of string that indicates the input names. Should match <paramref name="inputValues"/>.</param>
/// <param name="inputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names to fetch.</param>
/// <param name="options"></param>
/// <returns>Output Tensors in a Collection of NamedOnnxValue. User must dispose the output.</returns>
public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(
IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<FixedBufferOnnxValue> inputValues,
IReadOnlyCollection<string> outputNames,
RunOptions options)
{
if (inputNames.Count != inputValues.Count)
{
throw new ArgumentException($"Length of {nameof(inputNames)} ({inputNames.Count}) must match that of {nameof(inputValues)} ({inputValues.Count}).");
}
var inputNamesArray = LookupUtf8Names(inputNames, n => n, LookupInputMetadata);
IntPtr[] inputValuesArray = GetOrtValuesHandles(inputValues, true);
var outputNamesArray = LookupUtf8Names(outputNames, n => n, LookupOutputMetadata);
var disposableHandles = RunImpl(options, inputNamesArray, inputValuesArray, outputNamesArray);
try
{
return CreateDisposableResult(disposableHandles.Span, outputNames);
}
finally
{
disposableHandles.Dispose();
}
}
/// <summary>
/// Runs the loaded model for the given inputs and outputs.
///
/// Outputs need to be created with correct type and dimension to accept the fetched data.
/// </summary>
/// <param name="inputNames">Specify a collection of string that indicates the input names. Should match <paramref name="inputValues"/>.</param>
/// <param name="inputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names. Should match <paramref name="outputValues"/>.</param>
/// <param name="outputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the output values.</param>
public void Run(
IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<FixedBufferOnnxValue> inputValues,
IReadOnlyCollection<string> outputNames,
IReadOnlyCollection<FixedBufferOnnxValue> outputValues)
{
Run(inputNames, inputValues, outputNames, outputValues, _builtInRunOptions);
}
/// <summary>
/// Runs the loaded model for the given inputs and outputs. Uses the given RunOptions for this run.
///
/// Outputs need to be created with correct type and dimension to accept the fetched data.
/// </summary>
/// <param name="inputNames">Specify a collection of string that indicates the input names. Should match <paramref name="inputValues"/>.</param>
/// <param name="inputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names. Should match <paramref name="outputValues"/>.</param>
/// <param name="outputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the output values.</param>
/// <param name="options"></param>
public void Run(
IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<FixedBufferOnnxValue> inputValues,
IReadOnlyCollection<string> outputNames,
IReadOnlyCollection<FixedBufferOnnxValue> outputValues,
RunOptions options)
{
if (inputNames.Count != inputValues.Count)
{
throw new ArgumentException($"Length of {nameof(inputNames)} ({inputNames.Count}) must match that of {nameof(inputValues)} ({inputValues.Count}).");
}
if (outputNames.Count != outputValues.Count)
{
throw new ArgumentException($"Length of {nameof(outputNames)} ({outputNames.Count}) must match that of {nameof(outputValues)} ({outputValues.Count}).");
}
// prepare inputs
var inputNamesArray = LookupUtf8Names(inputNames, n => n, LookupInputMetadata);
IntPtr[] inputValuesArray = GetOrtValuesHandles(inputValues, true);
// prepare outputs
var outputNamesArray = LookupUtf8Names(outputNames, n => n, LookupOutputMetadata);
IntPtr[] outputValuesArray = GetOrtValuesHandles(outputValues, false);
NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(
_nativeHandle,
options.Handle,
inputNamesArray,
inputValuesArray,
(UIntPtr)inputNames.Count,
outputNamesArray,
(UIntPtr)outputNames.Count,
outputValuesArray /* pointers to Pre-allocated OrtValue instances */
));
}
/// <summary>
/// Runs the loaded model for the given inputs and outputs.
///
/// Outputs need to be created with correct type and dimension to receive the fetched data.
/// </summary>
/// <param name="inputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the input values.</param>
/// <param name="outputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the output values.</param>
public void Run(
IReadOnlyCollection<NamedOnnxValue> inputs,
IReadOnlyCollection<NamedOnnxValue> outputs)
{
Run(inputs, outputs, _builtInRunOptions);
}
/// <summary>
///
/// Runs the loaded model for the given inputs and outputs. Uses the given RunOptions for this run.
///
/// Outputs need to be created with correct type and dimension to receive the fetched data.
/// </summary>
/// <param name="inputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the input values.</param>
/// <param name="outputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the output values.</param>
/// <param name="options"></param>
public void Run(
IReadOnlyCollection<NamedOnnxValue> inputs,
IReadOnlyCollection<NamedOnnxValue> outputs,
RunOptions options)
{
var inputNamesArray = LookupUtf8Names(inputs, i => i.Name, LookupInputMetadata);
var outputNamesArray = LookupUtf8Names(outputs, o => o.Name, LookupOutputMetadata);
var inputValuesArray = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput,
out DisposableArray<IDisposable> inputDisposer);
try
{
var outputValuesArray = GetOrtValuesHandles(outputs, LookupOutputMetadata, ExtractOrtValueHandleForOutput,
out DisposableArray<IDisposable> outputDisposer);
try
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(
_nativeHandle,
options.Handle,
inputNamesArray,
inputValuesArray,
(UIntPtr)inputs.Count,
outputNamesArray,
(UIntPtr)outputs.Count,
outputValuesArray /* pointers to Pre-allocated OrtValue instances */
));
}
finally
{
outputDisposer.Dispose();
}
}
finally
{
inputDisposer.Dispose();
}
}
/// <summary>
/// Runs the loaded model for the given inputs and outputs.
///
/// Outputs need to be created with correct type and dimension to receive the fetched data.
/// </summary>
/// <param name="inputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names. Should match <paramref name="outputValues"/>.</param>
/// <param name="outputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the output values.</param>
public void Run(
IReadOnlyCollection<NamedOnnxValue> inputs,
IReadOnlyCollection<string> outputNames,
IReadOnlyCollection<FixedBufferOnnxValue> outputValues)
{
Run(inputs, outputNames, outputValues, _builtInRunOptions);
}
/// <summary>
/// Runs the loaded model for the given inputs and outputs. Uses the given RunOptions for this run.
///
/// Outputs need to be created with correct type and dimension to receive the fetched data.
/// </summary>
/// <param name="inputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the input values.</param>
/// <param name="outputNames">Specify a collection of string that indicates the output names. Should match <paramref name="outputValues"/>.</param>
/// <param name="outputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the output values.</param>
/// <param name="options"></param>
public void Run(
IReadOnlyCollection<NamedOnnxValue> inputs,
IReadOnlyCollection<string> outputNames,
IReadOnlyCollection<FixedBufferOnnxValue> outputValues,
RunOptions options)
{
if (outputNames.Count != outputValues.Count)
{
throw new ArgumentException($"Length of {nameof(outputNames)} ({outputNames.Count}) must match that of {nameof(outputValues)} ({outputValues.Count}).");
}
var inputNamesArray = LookupUtf8Names(inputs, i => i.Name, LookupInputMetadata);
var outputNamesArray = LookupUtf8Names(outputNames, n => n, LookupOutputMetadata);
var outputValuesArray = GetOrtValuesHandles(outputValues, false);
var inputValuesArray = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput,
out DisposableArray<IDisposable> inputsDisposer);
try
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(
_nativeHandle,
options.Handle,
inputNamesArray,
inputValuesArray,
(UIntPtr)inputs.Count,
outputNamesArray,
(UIntPtr)outputNames.Count,
outputValuesArray /* pointers to Pre-allocated OrtValue instances */
));
}
finally
{
inputsDisposer.Dispose();
}
}
/// <summary>
///
/// Runs the loaded model for the given inputs and outputs.
///
/// Outputs need to be created with correct type and dimension to receive the fetched data.
/// </summary>
/// <param name="inputNames">Specify a collection of string that indicates the input names. Should match <paramref name="inputValues"/>.</param>
/// <param name="inputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the input values.</param>
/// <param name="outputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the output values.</param>
public void Run(
IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<FixedBufferOnnxValue> inputValues,
IReadOnlyCollection<NamedOnnxValue> outputs)
{
Run(inputNames, inputValues, outputs, _builtInRunOptions);
}
/// <summary>
///
/// Runs the loaded model for the given inputs and outputs. Uses the given RunOptions for this run.
///
/// Outputs need to be created with correct type and dimension to receive the fetched data.
/// </summary>
/// <param name="inputNames">Specify a collection of string that indicates the input names. Should match <paramref name="inputValues"/>.</param>
/// <param name="inputValues">Specify a collection of <see cref="FixedBufferOnnxValue"/> that indicates the input values.</param>
/// <param name="outputs">Specify a collection of <see cref="NamedOnnxValue"/> that indicates the output values.</param>
/// <param name="options"></param>
public void Run(
IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<FixedBufferOnnxValue> inputValues,
IReadOnlyCollection<NamedOnnxValue> outputs,
RunOptions options)
{
if (inputNames.Count != inputValues.Count)
{
throw new ArgumentException($"Length of {nameof(inputNames)} ({inputNames.Count}) must match that of {nameof(inputValues)} ({inputValues.Count}).");
}
// prepare inputs
var inputNamesArray = LookupUtf8Names(inputNames, n => n, LookupInputMetadata);
var inputValuesArray = GetOrtValuesHandles(inputValues, true);
// prepare outputs
var outputNamesArray = LookupUtf8Names(outputs, o => o.Name, LookupOutputMetadata);
var outputValuesArray = GetOrtValuesHandles(outputs, LookupOutputMetadata, ExtractOrtValueHandleForOutput,
out DisposableArray<IDisposable> outputsDisposer);
try
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(
_nativeHandle,
options.Handle,
inputNamesArray,
inputValuesArray,
(UIntPtr)inputNames.Count,
outputNamesArray,
(UIntPtr)outputs.Count,
outputValuesArray /* pointers to Pre-allocated OrtValue instances */
));
}
finally
{
outputsDisposer.Dispose();
}
}
/// <summary>
/// The API runs the inference taking a collection of OrtValues as input and
/// returning a collection of output OrtValues.
/// </summary>
/// <param name="runOptions">runOptions</param>
/// <param name="inputNames">A collection of input names.
/// To supply all names, use InputNames property</param>
/// <param name="inputValues">Input OrtValues. The size of the collection must match the size and the order of the inputNames</param>
/// <param name="outputNames">Output names requested. To supply all names, use OutputNames property.</param>
/// <returns>A disposable collection of disposable OrtValues</returns>
/// <exception cref="ArgumentException"></exception>
public IDisposableReadOnlyCollection<OrtValue> Run(RunOptions runOptions, IReadOnlyCollection<string> inputNames,
IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames)
{
if (inputNames.Count != inputValues.Count)
{
throw new ArgumentException($"Length of {nameof(inputNames)} ({inputNames.Count}) must match that of {nameof(inputValues)} ({inputValues.Count}).");
}
var inputNamesArray = LookupUtf8Names(inputNames, n => n, LookupInputMetadata);
var inputHandlesArray = inputValues.Select(v => v.Handle).ToArray();
var outputNamesArray = LookupUtf8Names(outputNames, n => n, LookupOutputMetadata);
var disposableHandles = RunImpl(runOptions, inputNamesArray, inputHandlesArray, outputNamesArray);
try
{
return CreateDisposableResult(disposableHandles);
}
finally
{
disposableHandles.Dispose();
}
}
/// <summary>
/// This API takes inputs as a dictionary of input names paired with input OrtValues
///
/// It returns a disposable collection of OrtValues for outputs that were designated by outputNames
/// </summary>
/// <param name="runOptions"></param>
/// <param name="inputs">Dictionary of name/value pairs</param>
/// <param name="outputNames">requested outputs. To request all outputs, use OutputNames property of this sessions</param>
/// <returns>A disposable collection of outputs</returns>
public IDisposableReadOnlyCollection<OrtValue> Run(RunOptions runOptions, IReadOnlyDictionary<string, OrtValue> inputs,
IReadOnlyCollection<string> outputNames)
{
IntPtr[] inputNamesArray = new IntPtr[inputs.Count];
IntPtr[] inputHandlesArray = new IntPtr[inputs.Count];
int count = 0;
foreach (var input in inputs)
{
inputNamesArray[count] = LookupInputMetadata(input.Key).ZeroTerminatedName;
inputHandlesArray[count] = input.Value.Handle;
++count;
}
var outputNamesArray = LookupUtf8Names(outputNames, n => n, LookupOutputMetadata);
var disposableHandles = RunImpl(runOptions, inputNamesArray, inputHandlesArray, outputNamesArray);
try
{
return CreateDisposableResult(disposableHandles);
}
finally
{
disposableHandles.Dispose();
}
}
private static IDisposableReadOnlyCollection<OrtValue> CreateDisposableResult(DisposableOrtValueHandleArray disposableHandles)
{
var outputValues = new DisposableList<OrtValue>(disposableHandles.Span.Length);
try
{
for (int i = 0; i < disposableHandles.Span.Length; i++)
{
outputValues.Add(new OrtValue(disposableHandles.Span[i]));
disposableHandles.Span[i] = IntPtr.Zero;
}
return outputValues;
}
catch (Exception)
{
outputValues.Dispose();
throw;
}
}
/// <summary>
/// The API takes collections of inputNames/inputValues and collections of outputNames/outputValues.
/// The sizes of the corresponding collections must match.
///
/// The output OrtValues are pre-allocated and the API will fill the data into the OrtValues.
/// These MUST be tensors. The API does not support non-tensor types for output values.
///
/// The API is useful when the output values are tensors and their shapes are known, and you
/// prefer the output to go to the pre-allocated memory. In such a case, you create
/// output OrtValues over those pre-allocated buffers and pass them to the API.
/// </summary>
/// <param name="runOptions">runOptions, if null the defaults are used</param>
/// <param name="inputNames">collection of input names.</param>
/// <param name="inputValues">collection of input OrtValues. Must match the order and the number of input names.</param>
/// <param name="outputNames">Requested output names.</param>
/// <param name="outputValues">Pre-allocated output values.
/// The order and the number must match the specified output names. Shapes must match actual output values.</param>
/// <exception cref="ArgumentException"></exception>
public void Run(RunOptions runOptions, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues,
IReadOnlyCollection<string> outputNames, IReadOnlyCollection<OrtValue> outputValues)
{
if (inputNames.Count != inputValues.Count)
{
throw new ArgumentException(
$"Length of {nameof(inputNames)} ({inputNames.Count}) must match that of {nameof(inputValues)} ({inputValues.Count}).");
}
if (outputNames.Count != outputValues.Count)
{
throw new ArgumentException(
$"Length of {nameof(outputNames)} ({outputNames.Count}) must match that of {nameof(outputValues)} ({outputValues.Count}).");
}
if (runOptions is null)
{
runOptions = _builtInRunOptions;
}
var inputNamesArray = LookupUtf8Names(inputNames, n => n, LookupInputMetadata);
var inputHandlesArray = inputValues.Select(v => v.Handle).ToArray();
var outputNamesArray = LookupUtf8Names(outputNames, n => n, LookupOutputMetadata);
var outputHandlesArray = outputValues.Select(v => v.Handle).ToArray();
NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(
_nativeHandle,
runOptions.Handle,
inputNamesArray,
inputHandlesArray,
(UIntPtr)inputNames.Count,
outputNamesArray,
(UIntPtr)outputNames.Count,
outputHandlesArray /* pointers to Pre-allocated OrtValue instances */
));
}
/// <summary>
/// Create OrtIoBinding instance to bind pre-allocated buffers
/// to input/output
/// </summary>
/// <returns>A new instance of OrtIoBinding</returns>
public OrtIoBinding CreateIoBinding()
{
return new OrtIoBinding(this);
}
/// <summary>
/// This method runs inference on the OrtIoBinding instance
/// The method does not return anything. This is a lightweight version of
/// RunWithBindingAndNames(). When you bind pre-allocated buffers to the output values
/// you may not want to fetch the outputs since you already have access to them so you can spare
/// the expense of fetching them and pairing with names.
/// You can still fetch the outputs by calling OrtIOBinding.GetOutputValues()
/// </summary>
/// <param name="runOptions">runOptions</param>
/// <param name="ioBinding">ioBinding instance to use</param>
public void RunWithBinding(RunOptions runOptions, OrtIoBinding ioBinding)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle));
}
/// <summary>
/// This method runs inference on the OrtIoBinding instance. It returns a collection of OrtValues.
/// This method is useful when it is impossible to bind outputs to pre-allocated buffers, because
/// the output shape is not known in advance. In this case, the OrtValues returned by this method
/// are allocated and owned by ORT. The caller is responsible for disposing the collection.
/// </summary>
/// <param name="runOptions">RunOptions</param>
/// <param name="ioBinding">Binding instance</param>
/// <returns>A disposable collection of OrtValues</returns>
public IDisposableReadOnlyCollection<OrtValue> RunWithBoundResults(RunOptions runOptions, OrtIoBinding ioBinding)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle));
return ioBinding.GetOutputValues();
}
/// <summary>
/// This method return a collection of DisposableNamedOnnxValue as in other interfaces
/// Query names from OrtIoBinding object and pair then with the array of OrtValues returned
/// from OrtIoBinding.GetOutputValues().
///
/// This API will be deprecated in favor of the API that returns a collection of OrtValues.
///
/// </summary>
/// <param name="runOptions">RunOptions</param>
/// <param name="ioBinding">OrtIoBinding instance with bindings</param>
/// <param name="names">optional parameter. If you already know the names of the outputs you can save a native
/// call to retrieve output names. They will be paired with the returned OrtValues and combined into DisposbleNamedOnnxValues.
/// Otherwise, the method will retrieve output names from the OrtIoBinding instance.
/// It is an error if you supply a different number of names than the returned outputs</param>
/// <returns>A disposable collection of DisposableNamedOnnxValue that encapsulate output OrtValues</returns>
public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> RunWithBindingAndNames(RunOptions runOptions, OrtIoBinding ioBinding, string[] names = null)
{
string[] outputNames = names;
if (outputNames == null || names.Length == 0)
{
outputNames = ioBinding.GetOutputNames();
}
NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle));
var ortValues = ioBinding.GetOutputOrtValues();
var dispValues = new DisposableArray<OrtValue>(ortValues);
try
{
var result = new DisposableList<DisposableNamedOnnxValue>(ortValues.Length);
try
{
for (int i = 0; i < outputNames.Length; ++i)
{
result.Add(DisposableNamedOnnxValue.CreateFromOrtValue(outputNames[i], ref ortValues[i]));
}
return result;
}
catch (Exception)
{
result.Dispose();
throw;
}
}
finally
{
// On success ortValues would contain nulls that will be
// ignored. On failure, ortValues would contain at least
// some valid OrtValue instances that need to be disposed.
dispValues.Dispose();
}
}
/// <summary>
/// Ends profiling for the session.
/// </summary>
/// <returns> Returns the profile file name.</returns>
public string EndProfiling()
{
var allocator = OrtAllocator.DefaultInstance;
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionEndProfiling(_nativeHandle,
allocator.Pointer,
out IntPtr nameHandle));
return NativeOnnxValueHelper.StringFromNativeUtf8(nameHandle, allocator);
}
// Delegate for string extraction from an arbitrary input/output object
private delegate string NameExtractor<in TInput>(TInput input);
// delegate to fetch input/output OrtValue
private delegate IntPtr OrtValueHandleExtractor(NamedOnnxValue value, NodeMetadata metadata, out IDisposable memOwner);
// Delegate to lookup metadata for input/initializers/output
private delegate NodeMetadata MetadataLookup(string nodeName);
/// <summary>
/// Checks if the name is a known input or overridable initializer name
/// and if so, returns metadata for it.
/// metadata
/// </summary>
/// <param name="nodeName"></param>
/// <returns>NodeMetadata for the nodeName</returns>
/// <exception cref="OnnxRuntimeException"></exception>
private NodeMetadata LookupInputMetadata(string nodeName)
{
if (!_inputMetadata.TryGetValue(nodeName, out NodeMetadata meta) &&
!_overridableInitializerMetadata.TryGetValue(nodeName, out meta))
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Input name: '{nodeName}' is not in the metadata");
}
return meta;
}
/// <summary>
/// Checks if the nodeName is a known output name and if so returns metadata for it.
/// </summary>
/// <param name="nodeName"></param>
/// <returns></returns>
/// <exception cref="OnnxRuntimeException"></exception>
private NodeMetadata LookupOutputMetadata(string nodeName)
{
if (!_outputMetadata.TryGetValue(nodeName, out NodeMetadata meta))
{
throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Output name: '{nodeName}' is not in the metadata");
}
return meta;
}
/// <summary>
/// Fetches/creates OrtValue for the content of the input
/// </summary>
/// <param name="input"></param>
/// <param name="metadata"></param>
/// <param name="memOwner"></param>
/// <returns></returns>
private static IntPtr ExtractOrtValueHandleForInput(NamedOnnxValue input, NodeMetadata metadata, out IDisposable memOwner)
{
return input.InputToOrtValueHandle(metadata, out memOwner);
}
/// <summary>
/// Fetches/Creates OrtValue for output
/// </summary>
/// <param name="output"></param>
/// <param name="metadata"></param>
/// <param name="memOwner"></param>
/// <returns>May return null if the onnx value type does not support pre-creation of output OrtValues</returns>
private static IntPtr ExtractOrtValueHandleForOutput(NamedOnnxValue output, NodeMetadata metadata, out IDisposable memOwner)
{
return output.OutputToOrtValueHandle(metadata, out memOwner);
}
/// <summary>
/// Run helper
/// </summary>
/// <param name="values">names to convert to zero terminated utf8 and pin</param>
/// <param name="nameExtractor">extractor functor that helps extracting names from inputs</param>
/// <param name="metaDict">inputs/outputs metadata</param>
/// <returns></returns>
private static IntPtr[] LookupUtf8Names<T>(IReadOnlyCollection<T> values, NameExtractor<T> nameExtractor,
MetadataLookup metaLookup)
{
var result = new IntPtr[values.Count];
for (int i = 0; i < values.Count; ++i)
{
var name = nameExtractor(values.ElementAt(i));
NodeMetadata meta = metaLookup(name);
result[i] = meta.ZeroTerminatedName;
}
return result;
}
/// <summary>
/// This function obtains ortValues for NamedOnnxValue.
/// The problem with NamedOnnxValue is that it is not disposable and can not contain any disposable items.
/// so calling InputToOrtValue creates a new instance of OrtValue that needs to be disposed.
/// The deriving object DisposableNamedValue actually contains and owns OrtValue and it returns
/// it.
/// </summary>
/// <param name="values">a collection of NamedOnnxValues</param>
/// <param name="metaLookup">Metadata lookup function (input/initializers/output)</param>
/// <returns></returns>
private static IntPtr[] GetOrtValuesHandles(IReadOnlyCollection<NamedOnnxValue> values, MetadataLookup metaLookup,
OrtValueHandleExtractor ortValueExtractor, out DisposableArray<IDisposable> disposer)
{
IDisposable[] memHolders = new IDisposable[values.Count];
var disp = new DisposableArray<IDisposable>(memHolders);
try
{
IntPtr[] result = new IntPtr[values.Count];
for (int valueIndex = 0; valueIndex < values.Count; ++valueIndex)
{
var value = values.ElementAt(valueIndex);
var meta = metaLookup(value.Name);
result[valueIndex] = ortValueExtractor(value, meta, out IDisposable memHolder);
if (memHolder != null)
{
memHolders[valueIndex] = memHolder;
}
}
disposer = disp;
return result;
}
catch (Exception)
{
disp.Dispose();
throw;
}
}
private static IntPtr[] GetOrtValuesHandles(IReadOnlyCollection<FixedBufferOnnxValue> values, bool input)
{
var valuesArray = new IntPtr[values.Count];
for (int index = 0; index < values.Count; ++index)
{
var v = values.ElementAt(index);
if (!input && v.ElementType == Tensors.TensorElementType.String)
{
throw new NotSupportedException("Using string type FixedBufferOnnxValue in outputs is not supported.");
}
valuesArray[index] = v.Value.Handle;
}
return valuesArray;
}
private DisposableOrtValueHandleArray RunImpl(RunOptions options, IntPtr[] inputNames, IntPtr[] inputValues, IntPtr[] outputNames)
{
IntPtr[] outputValuesArray = new IntPtr[outputNames.Length];
NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(
_nativeHandle,
options.Handle,
inputNames,
inputValues,
(UIntPtr)inputNames.Length,
outputNames,
(UIntPtr)outputNames.Length,
outputValuesArray /* Empty array is passed in to receive output OrtValue pointers */
));
return new DisposableOrtValueHandleArray(outputValuesArray);
}
private static IDisposableReadOnlyCollection<DisposableNamedOnnxValue> CreateDisposableResult(Span<IntPtr> valueHandles,
IReadOnlyCollection<string> outputNames)
{
Debug.Assert(valueHandles.Length == outputNames.Count, "Handles and names sizes must match");
var result = new DisposableList<DisposableNamedOnnxValue>(valueHandles.Length);
try