-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathonnxruntime.cc
3080 lines (2772 loc) · 118 KB
/
onnxruntime.cc
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 2019-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdint.h>
#include <mutex>
#include <vector>
#include "onnxruntime_loader.h"
#include "onnxruntime_utils.h"
#include "triton/backend/backend_common.h"
#include "triton/backend/backend_input_collector.h"
#include "triton/backend/backend_memory.h"
#include "triton/backend/backend_model.h"
#include "triton/backend/backend_model_instance.h"
#include "triton/backend/backend_output_responder.h"
#include "triton/backend/device_memory_tracker.h"
#ifdef TRITON_ENABLE_GPU
#include <cuda_runtime_api.h>
#endif // TRITON_ENABLE_GPU
//
// ONNX Runtime Backend that implements the TRITONBACKEND API.
//
namespace triton { namespace backend { namespace onnxruntime {
/// Deleter for OrtSession.
struct SessionDeleter {
void operator()(OrtSession* f) { OnnxLoader::UnloadSession(f); }
};
// BackendConfiguration
struct BackendConfiguration {
static const BackendConfiguration& RetrieveFrom(
TRITONBACKEND_Backend* backend)
{
void* state = nullptr;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_BackendState(backend, &state));
return *reinterpret_cast<BackendConfiguration*>(state);
}
static const BackendConfiguration& RetrieveFrom(TRITONBACKEND_Model* model)
{
TRITONBACKEND_Backend* backend = nullptr;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_ModelBackend(model, &backend));
return RetrieveFrom(backend);
}
static const BackendConfiguration& RetrieveFrom(
TRITONBACKEND_ModelInstance* instance)
{
TRITONBACKEND_Model* model = nullptr;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_ModelInstanceModel(instance, &model));
return RetrieveFrom(model);
}
bool enable_memory_tracker_{false};
int default_max_batch_size_{0};
};
//
// ModelState
//
// State associated with a model that is using this backend. An object
// of this class is created and associated with each
// TRITONBACKEND_Model.
//
class ModelState : public BackendModel {
public:
static TRITONSERVER_Error* Create(
TRITONBACKEND_Model* triton_model, ModelState** state);
virtual ~ModelState() = default;
// Load an ONNX model using 'artifact_name' as the name for the ONNX
// file/directory. If 'instance_group_kind' is not
// TRITONSERVER_INSTANCEGROUPKIND_AUTO then use it and
// 'instance_group_device_id' to initialize the appropriate
// execution providers. Return in 'model_path' the full path to the
// onnx file, return in 'session' and 'allocator' the ORT session
// and allocator.
TRITONSERVER_Error* LoadModel(
const std::string& artifact_name,
const TRITONSERVER_InstanceGroupKind instance_group_kind,
const int32_t instance_group_device_id, std::string* model_path,
OrtSession** session, OrtAllocator** default_allocator,
cudaStream_t stream);
const std::map<std::string, std::pair<int64_t, int64_t>>& ModelOutputs()
{
return model_outputs_;
}
private:
ModelState(TRITONBACKEND_Model* triton_model);
TRITONSERVER_Error* AutoCompleteConfig();
TRITONSERVER_Error* AutoCompleteMaxBatch(
const OnnxTensorInfoMap& input_tensor_infos,
const OnnxTensorInfoMap& output_tensor_infos);
TRITONSERVER_Error* AutoCompleteIO(
const char* key, const OnnxTensorInfoMap& io_infos);
// Session options used when creating a ORT session.
std::unique_ptr<OrtSessionOptions, SessionOptionsDeleter> session_options_;
// model_outputs is a map that contains unique outputs that the model must
// provide. In the model configuration, the output in the state configuration
// can have intersection with the outputs section of the model. If an output
// is specified both in the output section and state section, it indicates
// that the backend must return the output state to the client too.
std::map<std::string, std::pair<int64_t, int64_t>> model_outputs_;
};
TRITONSERVER_Error*
ModelState::Create(TRITONBACKEND_Model* triton_model, ModelState** state)
{
try {
*state = new ModelState(triton_model);
}
catch (const BackendModelException& ex) {
RETURN_ERROR_IF_TRUE(
ex.err_ == nullptr, TRITONSERVER_ERROR_INTERNAL,
std::string("unexpected nullptr in BackendModelException"));
RETURN_IF_ERROR(ex.err_);
}
// Auto-complete the configuration if requested...
bool auto_complete_config = false;
RETURN_IF_ERROR(TRITONBACKEND_ModelAutoCompleteConfig(
triton_model, &auto_complete_config));
if (auto_complete_config) {
RETURN_IF_ERROR((*state)->AutoCompleteConfig());
RETURN_IF_ERROR((*state)->SetModelConfig());
}
auto& model_outputs = (*state)->model_outputs_;
// Parse the output states in the model configuration
triton::common::TritonJson::Value sequence_batching;
if ((*state)->ModelConfig().Find("sequence_batching", &sequence_batching)) {
triton::common::TritonJson::Value states;
if (sequence_batching.Find("state", &states)) {
for (size_t i = 0; i < states.ArraySize(); i++) {
triton::common::TritonJson::Value state;
RETURN_IF_ERROR(states.IndexAsObject(i, &state));
std::string output_state_name;
RETURN_IF_ERROR(
state.MemberAsString("output_name", &output_state_name));
auto it = model_outputs.find(output_state_name);
if (it == model_outputs.end()) {
model_outputs.insert({output_state_name, std::make_pair(-1, i)});
} else {
it->second.second = i;
}
}
}
}
// Parse the output names in the model configuration
triton::common::TritonJson::Value outputs;
RETURN_IF_ERROR((*state)->ModelConfig().MemberAsArray("output", &outputs));
for (size_t i = 0; i < outputs.ArraySize(); i++) {
triton::common::TritonJson::Value output;
RETURN_IF_ERROR(outputs.IndexAsObject(i, &output));
std::string output_name_str;
RETURN_IF_ERROR(output.MemberAsString("name", &output_name_str));
auto it = model_outputs.find(output_name_str);
if (it == model_outputs.end()) {
model_outputs.insert({output_name_str, {i, -1}});
} else {
it->second.first = i;
}
}
return nullptr; // success
}
ModelState::ModelState(TRITONBACKEND_Model* triton_model)
: BackendModel(triton_model, true /* allow_optional */)
{
// Create session options that will be cloned and used for each
// instance when creating that instance's session.
OrtSessionOptions* soptions;
THROW_IF_BACKEND_MODEL_ORT_ERROR(ort_api->CreateSessionOptions(&soptions));
session_options_.reset(soptions);
GraphOptimizationLevel optimization_level =
GraphOptimizationLevel::ORT_ENABLE_ALL;
{
triton::common::TritonJson::Value optimization;
if (ModelConfig().Find("optimization", &optimization)) {
triton::common::TritonJson::Value graph;
if (optimization.Find("graph", &graph)) {
int64_t graph_level = 0;
THROW_IF_BACKEND_MODEL_ERROR(graph.MemberAsInt("level", &graph_level));
if (graph_level == -1) {
optimization_level = GraphOptimizationLevel::ORT_ENABLE_BASIC;
} else if (graph_level == 1) {
optimization_level = GraphOptimizationLevel::ORT_ENABLE_EXTENDED;
} else if (graph_level == 2) {
optimization_level = GraphOptimizationLevel::ORT_DISABLE_ALL;
}
}
}
}
THROW_IF_BACKEND_MODEL_ORT_ERROR(
ort_api->SetSessionGraphOptimizationLevel(soptions, optimization_level));
{
// Controls whether you want to execute operators in your graph sequentially
// or in parallel. Usually when the model has many branches, setting this
// option to ExecutionMode::ORT_PARALLEL will give you better performance.
int execution_mode = 0;
triton::common::TritonJson::Value params;
if (ModelConfig().Find("parameters", ¶ms)) {
THROW_IF_BACKEND_MODEL_ERROR(TryParseModelStringParameter(
params, "execution_mode", &execution_mode, 0));
}
// 0 and 1 are the only valid values.
if (execution_mode != 0 && execution_mode != 1) {
throw BackendModelException(TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string(
"Invalid configuration value provided. Expected values for "
" execution_mode are 0 or 1 but got " +
std::to_string(execution_mode) + " .")
.c_str())));
} else {
THROW_IF_BACKEND_MODEL_ORT_ERROR(ort_api->SetSessionExecutionMode(
soptions, execution_mode == 0 ? ExecutionMode::ORT_SEQUENTIAL
: ExecutionMode::ORT_PARALLEL));
}
}
// If global threadpool is enabled, disable per session threads.
// If it is not enabled then try to read the configs for intra and inter
// op num threads and set them for session.
if (OnnxLoader::IsGlobalThreadPoolEnabled()) {
THROW_IF_BACKEND_MODEL_ORT_ERROR(
ort_api->DisablePerSessionThreads(soptions));
} else {
{
// Sets the number of threads used to parallelize the execution within
// nodes A value of 0 means ORT will pick a default
int intra_op_thread_count = 0;
triton::common::TritonJson::Value params;
if (ModelConfig().Find("parameters", ¶ms)) {
THROW_IF_BACKEND_MODEL_ERROR(TryParseModelStringParameter(
params, "intra_op_thread_count", &intra_op_thread_count, 0));
}
if (intra_op_thread_count > 0) {
THROW_IF_BACKEND_MODEL_ORT_ERROR(
ort_api->SetIntraOpNumThreads(soptions, intra_op_thread_count));
}
}
{
// Sets the number of threads used to parallelize the execution of the
// graph (across nodes) If sequential execution is enabled this value is
// ignored A value of 0 means ORT will pick a default
int inter_op_thread_count = 0;
triton::common::TritonJson::Value params;
if (ModelConfig().Find("parameters", ¶ms)) {
THROW_IF_BACKEND_MODEL_ERROR(TryParseModelStringParameter(
params, "inter_op_thread_count", &inter_op_thread_count, 0));
}
if (inter_op_thread_count > 0) {
THROW_IF_BACKEND_MODEL_ORT_ERROR(
ort_api->SetInterOpNumThreads(soptions, inter_op_thread_count));
}
}
}
// memory configs
// enable/disable mem arena
{
triton::common::TritonJson::Value params;
if (ModelConfig().Find("parameters", ¶ms)) {
triton::common::TritonJson::Value json_value;
if (params.Find("enable_mem_arena", &json_value)) {
std::string string_value;
THROW_IF_BACKEND_MODEL_ERROR(
json_value.MemberAsString("string_value", &string_value));
bool enable_cpu_mem_arena = false;
THROW_IF_BACKEND_MODEL_ERROR(
ParseBoolValue(string_value, &enable_cpu_mem_arena));
OrtStatus* ort_status = nullptr;
if (enable_cpu_mem_arena) {
ort_status = ort_api->EnableCpuMemArena(soptions);
} else {
ort_status = ort_api->DisableCpuMemArena(soptions);
}
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("Configuring enable_mem_arena to ") + string_value)
.c_str());
THROW_IF_BACKEND_MODEL_ORT_ERROR(ort_status);
}
}
}
// enable/disable mem pattern
{
triton::common::TritonJson::Value params;
if (ModelConfig().Find("parameters", ¶ms)) {
triton::common::TritonJson::Value json_value;
if (params.Find("enable_mem_pattern", &json_value)) {
std::string string_value;
THROW_IF_BACKEND_MODEL_ERROR(
json_value.MemberAsString("string_value", &string_value));
bool enable_mem_pattern = false;
auto err = ParseBoolValue(string_value, &enable_mem_pattern);
THROW_IF_BACKEND_MODEL_ERROR(err);
OrtStatus* ort_status = nullptr;
if (enable_mem_pattern) {
ort_status = ort_api->EnableMemPattern(soptions);
} else {
ort_status = ort_api->DisableMemPattern(soptions);
}
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("Configuring enable_mem_pattern to ") + string_value)
.c_str());
THROW_IF_BACKEND_MODEL_ORT_ERROR(ort_status);
}
}
}
// FIXME. Is it possible to share a single OrtSession across
// multiple instances? If so then should move loading and validation
// of the session to here instead of creating a session for each
// instance in ModelStateInstance::Create().
}
TRITONSERVER_Error*
ModelState::LoadModel(
const std::string& artifact_name,
const TRITONSERVER_InstanceGroupKind instance_group_kind,
const int32_t instance_group_device_id, std::string* model_path,
OrtSession** session, OrtAllocator** default_allocator, cudaStream_t stream)
{
// Find the ONNX file that describes the model itself. If the model
// configuration doesn't have an explicit model file specified then
// use the default name ("model.onnx").
std::string cc_model_filename = artifact_name;
if (cc_model_filename.empty()) {
cc_model_filename = "model.onnx";
}
*model_path = JoinPath(
{RepositoryPath(), std::to_string(Version()), cc_model_filename});
// If the model path is a directory then the actual model is
// <dir>/model.onnx.
{
bool is_dir;
RETURN_IF_ERROR(IsDirectory(*model_path, &is_dir));
if (is_dir) {
*model_path = JoinPath({*model_path, "model.onnx"});
}
}
{
bool exists;
RETURN_IF_ERROR(FileExists(*model_path, &exists));
RETURN_ERROR_IF_FALSE(
exists, TRITONSERVER_ERROR_UNAVAILABLE,
std::string("unable to find '") + *model_path +
"' for model instance '" + Name() + "'");
}
// Make a clone for the session options for this instance...
OrtSessionOptions* soptions;
RETURN_IF_ORT_ERROR(
ort_api->CloneSessionOptions(session_options_.get(), &soptions));
std::unique_ptr<OrtSessionOptions, SessionOptionsDeleter> soptions_wrapper(
soptions);
bool need_lock = false;
// Add execution providers if they are requested.
// Don't need to ensure uniqueness of the providers, ONNX Runtime
// will check it.
// GPU execution providers
#ifdef TRITON_ENABLE_GPU
if ((instance_group_kind == TRITONSERVER_INSTANCEGROUPKIND_GPU) ||
(instance_group_kind == TRITONSERVER_INSTANCEGROUPKIND_AUTO)) {
triton::common::TritonJson::Value optimization;
if (model_config_.Find("optimization", &optimization)) {
triton::common::TritonJson::Value eas;
if (optimization.Find("execution_accelerators", &eas)) {
triton::common::TritonJson::Value gpu_eas;
if (eas.Find("gpu_execution_accelerator", &gpu_eas)) {
for (size_t ea_idx = 0; ea_idx < gpu_eas.ArraySize(); ea_idx++) {
triton::common::TritonJson::Value ea;
RETURN_IF_ERROR(gpu_eas.IndexAsObject(ea_idx, &ea));
std::string name;
RETURN_IF_ERROR(ea.MemberAsString("name", &name));
#ifdef TRITON_ENABLE_ONNXRUNTIME_TENSORRT
if (name == kTensorRTExecutionAccelerator) {
// create tensorrt options with default values
OrtTensorRTProviderOptionsV2* trt_options;
THROW_IF_BACKEND_MODEL_ORT_ERROR(
ort_api->CreateTensorRTProviderOptions(&trt_options));
std::unique_ptr<
OrtTensorRTProviderOptionsV2,
decltype(ort_api->ReleaseTensorRTProviderOptions)>
rel_trt_options(
trt_options, ort_api->ReleaseTensorRTProviderOptions);
std::string int8_calibration_table_name;
std::string trt_engine_cache_path;
// Validate and set parameters
triton::common::TritonJson::Value params;
if (ea.Find("parameters", ¶ms)) {
std::vector<std::string> param_keys, keys, values;
RETURN_IF_ERROR(params.Members(¶m_keys));
for (const auto& param_key : param_keys) {
std::string value_string, key, value;
if (param_key == "precision_mode") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
if (value_string == "FP16") {
key = "trt_fp16_enable";
value = "1";
} else if (value_string == "INT8") {
key = "trt_int8_enable";
value = "1";
} else if (value_string != "FP32") {
RETURN_ERROR_IF_FALSE(
false, TRITONSERVER_ERROR_INVALID_ARG,
std::string("unsupported precision mode '") +
value_string + "' is requested");
}
} else if (param_key == "max_workspace_size_bytes") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
size_t max_workspace_size_bytes;
RETURN_IF_ERROR(ParseUnsignedLongLongValue(
value_string, &max_workspace_size_bytes));
key = "trt_max_workspace_size";
value = value_string;
} else if (param_key == "trt_max_partition_iterations") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
int trt_max_partition_iterations;
RETURN_IF_ERROR(ParseIntValue(
value_string, &trt_max_partition_iterations));
key = "trt_max_partition_iterations";
value = value_string;
} else if (param_key == "trt_min_subgraph_size") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
int trt_min_subgraph_size;
RETURN_IF_ERROR(
ParseIntValue(value_string, &trt_min_subgraph_size));
key = "trt_min_subgraph_size";
value = value_string;
} else if (param_key == "int8_calibration_table_name") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_int8_calibration_table_name";
} else if (param_key == "int8_use_native_calibration_table") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool use_native_calibration_table;
RETURN_IF_ERROR(ParseBoolValue(
value_string, &use_native_calibration_table));
key = "trt_int8_use_native_calibration_table";
value = value_string;
} else if (param_key == "trt_dla_enable") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_dla_enable;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &trt_dla_enable));
key = "trt_dla_enable";
value = value_string;
} else if (param_key == "trt_dla_core") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
int trt_dla_core;
RETURN_IF_ERROR(ParseIntValue(value_string, &trt_dla_core));
key = "trt_dla_core";
value = value_string;
} else if (param_key == "trt_engine_cache_enable") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool enable_cache;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &enable_cache));
key = "trt_engine_cache_enable";
value = value_string;
} else if (param_key == "trt_engine_cache_path") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_engine_cache_path";
} else if (param_key == "trt_engine_cache_prefix") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_engine_cache_prefix";
} else if (param_key == "trt_dump_subgraphs") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool dump_subgraphs;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &dump_subgraphs));
key = "trt_dump_subgraphs";
value = value_string;
} else if (param_key == "trt_force_sequential_engine_build") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_force_sequential_engine_build;
RETURN_IF_ERROR(ParseBoolValue(
value_string, &trt_force_sequential_engine_build));
key = "trt_force_sequential_engine_build";
value = value_string;
} else if (param_key == "trt_context_memory_sharing_enable") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_context_memory_sharing_enable;
RETURN_IF_ERROR(ParseBoolValue(
value_string, &trt_context_memory_sharing_enable));
key = "trt_context_memory_sharing_enable";
value = value_string;
} else if (param_key == "trt_layer_norm_fp32_fallback") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_layer_norm_fp32_fallback;
RETURN_IF_ERROR(ParseBoolValue(
value_string, &trt_layer_norm_fp32_fallback));
key = "trt_layer_norm_fp32_fallback";
value = value_string;
} else if (param_key == "trt_timing_cache_enable") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_timing_cache_enable;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &trt_timing_cache_enable));
key = "trt_timing_cache_enable";
value = value_string;
} else if (param_key == "trt_timing_cache_path") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_timing_cache_path";
} else if (param_key == "trt_force_timing_cache") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_force_timing_cache;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &trt_force_timing_cache));
key = "trt_force_timing_cache";
value = value_string;
} else if (param_key == "trt_detailed_build_log") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_detailed_build_log;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &trt_detailed_build_log));
key = "trt_detailed_build_log";
value = value_string;
} else if (param_key == "trt_build_heuristics_enable") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_build_heuristics_enable;
RETURN_IF_ERROR(ParseBoolValue(
value_string, &trt_build_heuristics_enable));
key = "trt_build_heuristics_enable";
value = value_string;
} else if (param_key == "trt_sparsity_enable") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_sparsity_enable;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &trt_sparsity_enable));
key = "trt_sparsity_enable";
value = value_string;
} else if (param_key == "trt_builder_optimization_level") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
int trt_builder_optimization_level;
RETURN_IF_ERROR(ParseIntValue(
value_string, &trt_builder_optimization_level));
key = "trt_builder_optimization_level";
value = value_string;
} else if (param_key == "trt_auxiliary_streams") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
int trt_auxiliary_streams;
RETURN_IF_ERROR(
ParseIntValue(value_string, &trt_auxiliary_streams));
key = "trt_auxiliary_streams";
value = value_string;
} else if (param_key == "trt_tactic_sources") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_tactic_sources";
} else if (param_key == "trt_extra_plugin_lib_paths") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_extra_plugin_lib_paths";
} else if (param_key == "trt_profile_min_shapes") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_profile_min_shapes";
} else if (param_key == "trt_profile_max_shapes") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_profile_max_shapes";
} else if (param_key == "trt_profile_opt_shapes") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_profile_opt_shapes";
} else if (param_key == "trt_cuda_graph_enable") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_cuda_graph_enable;
RETURN_IF_ERROR(
ParseBoolValue(value_string, &trt_cuda_graph_enable));
key = "trt_cuda_graph_enable";
value = value_string;
} else if (param_key == "trt_dump_ep_context_model") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
bool trt_dump_ep_context_model;
RETURN_IF_ERROR(ParseBoolValue(
value_string, &trt_dump_ep_context_model));
key = "trt_dump_ep_context_model";
value = value_string;
} else if (param_key == "trt_ep_context_file_path") {
RETURN_IF_ERROR(
params.MemberAsString(param_key.c_str(), &value));
key = "trt_ep_context_file_path";
} else if (param_key == "trt_ep_context_embed_mode") {
RETURN_IF_ERROR(params.MemberAsString(
param_key.c_str(), &value_string));
int trt_ep_context_embed_mode;
RETURN_IF_ERROR(ParseIntValue(
value_string, &trt_ep_context_embed_mode));
key = "trt_ep_context_embed_mode";
value = value_string;
} else {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
std::string(
"unknown parameter '" + param_key +
"' is provided for TensorRT Execution "
"Accelerator")
.c_str());
}
if (!key.empty() && !value.empty()) {
keys.push_back(key);
values.push_back(value);
}
}
std::vector<const char*> c_keys, c_values;
if (!keys.empty() && !values.empty()) {
for (size_t i = 0; i < keys.size(); ++i) {
c_keys.push_back(keys[i].c_str());
c_values.push_back(values[i].c_str());
}
RETURN_IF_ORT_ERROR(ort_api->UpdateTensorRTProviderOptions(
rel_trt_options.get(), c_keys.data(), c_values.data(),
keys.size()));
}
}
RETURN_IF_ORT_ERROR(
ort_api->SessionOptionsAppendExecutionProvider_TensorRT_V2(
static_cast<OrtSessionOptions*>(soptions),
rel_trt_options.get()));
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("TensorRT Execution Accelerator is set for '") +
Name() + "' on device " +
std::to_string(instance_group_device_id))
.c_str());
continue;
}
#endif // TRITON_ENABLE_ONNXRUNTIME_TENSORRT
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("unknown Execution Accelerator '") + name +
"' is requested")
.c_str());
}
}
}
}
// Default GPU execution provider.
// Using default values for everything other than device id and cuda
// stream
OrtCUDAProviderOptions cuda_options;
cuda_options.device_id = instance_group_device_id;
cuda_options.has_user_compute_stream = stream != nullptr ? 1 : 0;
cuda_options.user_compute_stream =
stream != nullptr ? (void*)stream : nullptr,
cuda_options.default_memory_arena_cfg = nullptr;
{
// Parse CUDA EP configurations
triton::common::TritonJson::Value params;
if (model_config_.Find("parameters", ¶ms)) {
int cudnn_conv_algo_search = 0;
RETURN_IF_ERROR(TryParseModelStringParameter(
params, "cudnn_conv_algo_search", &cudnn_conv_algo_search, 0));
cuda_options.cudnn_conv_algo_search =
static_cast<OrtCudnnConvAlgoSearch>(cudnn_conv_algo_search);
RETURN_IF_ERROR(TryParseModelStringParameter(
params, "gpu_mem_limit", &cuda_options.gpu_mem_limit,
std::numeric_limits<size_t>::max()));
RETURN_IF_ERROR(TryParseModelStringParameter(
params, "arena_extend_strategy",
&cuda_options.arena_extend_strategy, 0));
RETURN_IF_ERROR(TryParseModelStringParameter(
params, "do_copy_in_default_stream",
&cuda_options.do_copy_in_default_stream, true));
}
}
RETURN_IF_ORT_ERROR(ort_api->SessionOptionsAppendExecutionProvider_CUDA(
soptions, &cuda_options));
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("CUDA Execution Accelerator is set for '") + Name() +
"' on device " + std::to_string(instance_group_device_id))
.c_str());
}
#endif // TRITON_ENABLE_GPU
// CPU execution providers
{
triton::common::TritonJson::Value optimization;
if (model_config_.Find("optimization", &optimization)) {
triton::common::TritonJson::Value eas;
if (optimization.Find("execution_accelerators", &eas)) {
triton::common::TritonJson::Value cpu_eas;
if (eas.Find("cpu_execution_accelerator", &cpu_eas)) {
for (size_t ea_idx = 0; ea_idx < cpu_eas.ArraySize(); ea_idx++) {
triton::common::TritonJson::Value ea;
RETURN_IF_ERROR(cpu_eas.IndexAsObject(ea_idx, &ea));
std::string name;
RETURN_IF_ERROR(ea.MemberAsString("name", &name));
#ifdef TRITON_ENABLE_ONNXRUNTIME_OPENVINO
if (name == kOpenVINOExecutionAccelerator) {
need_lock = true;
OrtOpenVINOProviderOptions openvino_options;
openvino_options.device_type =
"CPU_FP32"; // device_type default is CPU_FP32
RETURN_IF_ORT_ERROR(
ort_api->SessionOptionsAppendExecutionProvider_OpenVINO(
soptions, &openvino_options));
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("OpenVINO Execution Accelerator is set for '") +
Name() + "' on CPU")
.c_str());
continue;
}
#endif // TRITON_ENABLE_ONNXRUNTIME_OPENVINO
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("unknown Execution Accelerator '") + name +
"' is requested")
.c_str());
}
}
}
}
}
// Register all op libraries that contain custom operations.
{
triton::common::TritonJson::Value model_ops;
if (model_config_.Find("model_operations", &model_ops)) {
triton::common::TritonJson::Value op_library_filenames;
if (model_ops.Find("op_library_filename", &op_library_filenames)) {
for (size_t op_idx = 0; op_idx < op_library_filenames.ArraySize();
op_idx++) {
std::string op_filename;
RETURN_IF_ERROR(
op_library_filenames.IndexAsString(op_idx, &op_filename));
void* library_handle = nullptr;
RETURN_IF_ORT_ERROR(ort_api->RegisterCustomOpsLibrary(
soptions, op_filename.c_str(), &library_handle));
}
}
}
}
// ONNX session creation with OpenVINO is not thread-safe,
// so multiple creations are serialized with a global lock.
static std::mutex global_context_mu;
std::unique_lock<std::mutex> glock(global_context_mu, std::defer_lock);
if (need_lock) {
glock.lock();
}
RETURN_IF_ERROR(OnnxLoader::LoadSession(
true /* is_path */, *model_path, soptions, session));
// get default cpu allocator
RETURN_IF_ORT_ERROR(
ort_api->GetAllocatorWithDefaultOptions(default_allocator));
return nullptr; // success
}
TRITONSERVER_Error*
ModelState::AutoCompleteConfig()
{
// If the model configuration already specifies inputs and outputs
// then don't perform any auto-completion.
size_t input_cnt = 0;
size_t output_cnt = 0;
{
triton::common::TritonJson::Value inputs;
if (ModelConfig().Find("input", &inputs)) {
input_cnt = inputs.ArraySize();
}
triton::common::TritonJson::Value config_batch_inputs;
if (ModelConfig().Find("batch_input", &config_batch_inputs)) {
input_cnt += config_batch_inputs.ArraySize();
}
triton::common::TritonJson::Value outputs;
if (ModelConfig().Find("output", &outputs)) {
output_cnt = outputs.ArraySize();
}
}
if ((input_cnt > 0) && (output_cnt > 0)) {
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("skipping model configuration auto-complete for '") +
Name() + "': inputs and outputs already specified")
.c_str());
return nullptr; // success
}
std::string artifact_name;
RETURN_IF_ERROR(
ModelConfig().MemberAsString("default_model_filename", &artifact_name));
// Must cleanup 'session'. 'allocator' is default allocator which
// is managed by ONNX Runtime so don't need to free/release
std::unique_ptr<OrtSession, SessionDeleter> session;
OrtAllocator* default_allocator;
std::string model_path;
{
TRITONSERVER_InstanceGroupKind kind = TRITONSERVER_INSTANCEGROUPKIND_CPU;
#ifdef TRITON_ENABLE_GPU
triton::common::TritonJson::Value instance_group;
ModelConfig().Find("instance_group", &instance_group);
// Earlier in the model lifecycle, device checks for the instance group
// have already occurred. If at least one instance group with
// "kind" = "KIND_GPU" then allow model to use GPU else autocomplete to
// "KIND_CPU"
for (size_t i = 0; i < instance_group.ArraySize(); ++i) {
triton::common::TritonJson::Value instance_obj;
RETURN_IF_ERROR(instance_group.IndexAsObject(i, &instance_obj));
triton::common::TritonJson::Value instance_group_kind;
instance_obj.Find("kind", &instance_group_kind);
std::string kind_str;
RETURN_IF_ERROR(instance_group_kind.AsString(&kind_str));
if (kind_str == "KIND_GPU") {
kind = TRITONSERVER_INSTANCEGROUPKIND_GPU;
break;
}
}
#endif // TRITON_ENABLE_GPU
OrtSession* sptr = nullptr;
RETURN_IF_ERROR(LoadModel(
artifact_name, kind, 0, &model_path, &sptr, &default_allocator,
nullptr));
session.reset(sptr);
}
OnnxTensorInfoMap input_tensor_infos;
RETURN_IF_ERROR(
InputInfos(session.get(), default_allocator, input_tensor_infos));
OnnxTensorInfoMap output_tensor_infos;
RETURN_IF_ERROR(
OutputInfos(session.get(), default_allocator, output_tensor_infos));
RETURN_IF_ERROR(
AutoCompleteMaxBatch(input_tensor_infos, output_tensor_infos));
if (input_cnt == 0) {
RETURN_IF_ERROR(AutoCompleteIO("input", input_tensor_infos));
}
if (output_cnt == 0) {
RETURN_IF_ERROR(AutoCompleteIO("output", output_tensor_infos));
}
if (TRITONSERVER_LogIsEnabled(TRITONSERVER_LOG_VERBOSE)) {
LOG_JSON_VALUE(
TRITONSERVER_LOG_VERBOSE, "post auto-complete:", ModelConfig());
}
return nullptr; // success
}
TRITONSERVER_Error*
ModelState::AutoCompleteMaxBatch(
const OnnxTensorInfoMap& input_tensor_infos,
const OnnxTensorInfoMap& output_tensor_infos)
{
// Determine if the model can potentially support batching. All
// input and output tensors must have a variable first dimension.
bool can_support_batching = true;
for (const auto& io_info : input_tensor_infos) {
const auto& dims = io_info.second.dims_;
if ((dims.size() == 0) || (dims[0] != -1)) {
can_support_batching = false;
}
}
for (const auto& io_info : output_tensor_infos) {
const auto& dims = io_info.second.dims_;
if ((dims.size() == 0) || (dims[0] != -1)) {
can_support_batching = false;
}
}
// Set max-batch-size to 1 if we have determined that batching is
// supported and max-batch-size is not specified. We need to update
// the configuration itself as well as the cached value we have already
// initialized in the model state.
if (can_support_batching) {
if (MaxBatchSize() == 0) {
int default_max_batch_size = 0;
{
TRITONBACKEND_Backend* backend;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_ModelBackend(TritonModel(), &backend));
void* state;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_BackendState(backend, &state));
default_max_batch_size = reinterpret_cast<BackendConfiguration*>(state)
->default_max_batch_size_;
}
int max_batch_size = std::max(default_max_batch_size, 0);
triton::common::TritonJson::Value mbs_value;
ModelConfig().Find("max_batch_size", &mbs_value);
mbs_value.SetInt(max_batch_size);
SetMaxBatchSize(max_batch_size);
LOG_MESSAGE(
TRITONSERVER_LOG_WARN,
(std::string(
"autofilled max_batch_size to " +
std::to_string(max_batch_size) + " for model '") +
Name() +
"' since batching is supporrted but no max_batch_size is "
"specified "
"in model configuration. Must specify max_batch_size to utilize "
"autofill with a larger max batch size")