-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathlibtorch.cc
2681 lines (2380 loc) · 95.7 KB
/
libtorch.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-2024, 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 <cstdint>
#include <exception>
#include "libtorch_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/common/nvtx.h"
#include "triton/core/tritonbackend.h"
#ifdef TRITON_PYTORCH_ENABLE_TORCHVISION
// Suppress warnings in torch headers
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma warning(push, 0)
#include <torchvision/ops/ops.h>
#include <torchvision/vision.h> // Torchvision header
#pragma warning(pop)
#pragma GCC diagnostic pop
#endif // TRITON_PYTORCH_ENABLE_TORCHVISION
#ifdef TRITON_ENABLE_GPU
#include <c10/cuda/CUDACachingAllocator.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda_runtime_api.h>
#endif // TRITON_ENABLE_GPU
// for thread control
// https://pytorch.org/docs/stable/notes/cpu_threading_torchscript_inference.html#runtime-api
// https://github.com/pytorch/pytorch/blob/v2.2.1-rc3/aten/src/ATen/Parallel.h#L133
#include <ATen/Parallel.h>
//
// PyTorch C++ (LibTorch) Backend that implements the TRITONBACKEND API.
//
namespace triton { namespace backend { namespace pytorch {
//
// 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 a TorchScript model using 'artifact_name' as the name for the
// TorchScript file. Return in 'model_path' the full path to the
// TorchScript file, return in 'torch_model' the Torch Module
// representing the model.
TRITONSERVER_Error* LoadModel(
const std::string& artifact_name, const torch::Device device,
std::string* model_path, const TRITONSERVER_InstanceGroupKind& kind,
std::shared_ptr<torch::jit::script::Module>* torch_model);
bool EnabledOptimizedExecution() { return enable_optimized_execution_; }
const std::pair<bool, bool>& EnabledTensorExprFuser() const
{
return enable_tensor_fuser_pair_;
}
const std::pair<bool, bool>& EnabledJitProfiling() const
{
return enable_jit_profiling_pair_;
}
const std::pair<bool, bool>& EnabledJitExecutor() const
{
return enable_jit_executor_pair_;
}
bool EnabledInferenceMode() { return enable_inference_mode_; }
bool EnabledCudnn() { return enable_cudnn_; }
bool EnabledCacheCleaning() { return enable_cache_cleaning_; }
bool EnabledWeightSharing() { return enable_weight_sharing_; }
const std::map<std::string, std::pair<int64_t, int64_t>>& ModelOutputs()
{
return model_outputs_;
}
private:
ModelState(TRITONBACKEND_Model* triton_model);
TRITONSERVER_Error* AutoCompleteConfig();
// Parses and validates parameters in config
TRITONSERVER_Error* ParseParameters();
// Flag to indicate whether optimized execution is enabled. Defaults to true.
bool enable_optimized_execution_;
// Flag to indicate whether inference mode is enabled. Defaults to false.
bool enable_inference_mode_;
// Flag to indicate whether cudnn is enabled. Defaults to true.
bool enable_cudnn_;
// Flag to indicate whether cache cleaning after each run is enabled.
// Defaults to false.
bool enable_cache_cleaning_;
// Flag to indicate whether weight sharing is enabled. Defaults to false.
bool enable_weight_sharing_;
// Flag pairs to indicate if various JIT settings are set and
// enabled respectively. Defaults to (false, true). Default behavior
// is to do nothing if not explicitly set.
std::pair<bool, bool> enable_tensor_fuser_pair_;
std::pair<bool, bool> enable_jit_profiling_pair_;
std::pair<bool, bool> enable_jit_executor_pair_;
// Model mapping for shared TorchScript model across all instances on the
// same device. The key is a pair of isGPU and device index.
std::map<
std::pair<bool, int64_t>, std::shared_ptr<torch::jit::script::Module>>
torch_models_;
// model_outputs is a map that contains unique outputs that the model must
// provide. The first pair is the model output index and the second is
// the index in the model state, -1 is used if one is not required.
// 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;
THROW_IF_BACKEND_INSTANCE_ERROR(outputs.IndexAsObject(i, &output));
// Use names from ModelConfig by reference since the model
// config will persist longer than this inference execution.
std::string output_name;
THROW_IF_BACKEND_INSTANCE_ERROR(
output.MemberAsString("name", &output_name));
auto it = model_outputs.find(output_name);
if (it == model_outputs.end()) {
model_outputs.insert({output_name, std::make_pair(i, -1)});
} else {
it->second.first = i;
}
}
RETURN_IF_ERROR((*state)->ParseParameters());
return nullptr; // success
}
ModelState::ModelState(TRITONBACKEND_Model* triton_model)
: BackendModel(triton_model), enable_optimized_execution_(true),
enable_inference_mode_(true), enable_cudnn_(true),
enable_cache_cleaning_(false), enable_weight_sharing_(false),
enable_tensor_fuser_pair_({false, true}),
enable_jit_profiling_pair_({false, true}),
enable_jit_executor_pair_({false, true})
{
}
TRITONSERVER_Error*
ModelState::LoadModel(
const std::string& artifact_name, const torch::Device device,
std::string* model_path, const TRITONSERVER_InstanceGroupKind& kind,
std::shared_ptr<torch::jit::script::Module>* torch_model)
{
// Find the TorchScript file that describes the model. If the model
// configuration doesn't have an explicit model file specified then
// use the default name ("model.pt").
std::string cc_model_filename = artifact_name;
if (cc_model_filename.empty()) {
cc_model_filename = "model.pt";
}
*model_path = JoinPath(
{RepositoryPath(), std::to_string(Version()), cc_model_filename});
{
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() + "'");
}
// If weight sharing is enabled, skip loading model if
// it is already available on the target device
std::pair<bool, int> device_pair;
if (enable_weight_sharing_) {
device_pair = std::make_pair(!device.is_cpu(), device.index());
auto mit = torch_models_.find(device_pair);
if (mit != torch_models_.end()) {
*torch_model = mit->second;
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Reusing TorchScript model for instance '") + Name() +
"'")
.c_str());
return nullptr; // success
}
}
// Serialize the torch model to string
std::string model_data_str;
RETURN_IF_ERROR(ReadTextFile(*model_path, &model_data_str));
// InferenceMode should be used to guard all tensors operations including
// model loading: https://pytorch.org/cppdocs/notes/inference_mode.html
torch::InferenceMode infer_guard(EnabledInferenceMode());
try {
std::istringstream model_stream(model_data_str);
if (kind == TRITONSERVER_INSTANCEGROUPKIND_MODEL) {
// Load the model without selecting a device.
torch_model->reset(
new torch::jit::Module(torch::jit::load(model_stream)));
} else {
torch_model->reset(
new torch::jit::Module(torch::jit::load(model_stream, device)));
}
}
catch (const std::exception& ex) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
("failed to load model '" + Name() + "': " + ex.what()).c_str());
}
if (enable_weight_sharing_) {
if (!((torch_models_.emplace(device_pair, *torch_model)).second)) {
std::string type = device.is_cpu() ? "CPU" : "GPU";
LOG_MESSAGE(
TRITONSERVER_LOG_WARN,
(std::string("Model already found on target ") + type + " device " +
"(id " + std::to_string(device.index()) + ") for '" + Name() + "'")
.c_str());
}
}
return nullptr; // success
}
TRITONSERVER_Error*
ModelState::AutoCompleteConfig()
{
// Auto-complete configuration is not supported since PyTorch does not
// store/capture sufficient model metadata so just log error instead.
LOG_MESSAGE(
TRITONSERVER_LOG_WARN,
(std::string("skipping model configuration auto-complete for '") +
Name() + "': not supported for pytorch backend")
.c_str());
return nullptr; // success
}
TRITONSERVER_Error*
ModelState::ParseParameters()
{
triton::common::TritonJson::Value params;
bool status = model_config_.Find("parameters", ¶ms);
if (status) {
// If 'DISABLE_OPTIMIZED_EXECUTION' is not present in 'parameters' then no
// update is made to 'enable_optimized_execution_'.
bool disable_optimized_execution = false;
TRITONSERVER_Error* err = ParseParameter(
params, "DISABLE_OPTIMIZED_EXECUTION", &disable_optimized_execution);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
}
enable_optimized_execution_ = !disable_optimized_execution;
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Optimized execution is ") +
(enable_optimized_execution_ ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
// If 'ENABLE_CACHE_CLEANING' is not present in 'parameters' then
// no update is made to 'enable_cache_cleaning_'.
err = ParseParameter(
params, "ENABLE_CACHE_CLEANING", &enable_cache_cleaning_);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
}
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Cache Cleaning is ") +
(enable_cache_cleaning_ ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
// If 'INFERENCE_MODE' is not present in 'parameters' then no update is made
// to 'enable_inference_mode_'.
err = ParseParameter(params, "INFERENCE_MODE", &enable_inference_mode_);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
}
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Inference Mode is ") +
(enable_inference_mode_ ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
// If 'DISABLE_CUDNN' is not present in 'parameters' then no update is made
// to 'enable_cudnn_'.
bool disable_cudnn = false;
err = ParseParameter(params, "DISABLE_CUDNN", &disable_cudnn);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
}
enable_cudnn_ = !disable_cudnn;
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("cuDNN is ") + (enable_cudnn_ ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
// If 'ENABLE_TENSOR_FUSER' is not present in 'parameters' then no
// update is made to 'enable_tensor_fuser'.
bool enable_tensor_fuser = false;
err = ParseParameter(params, "ENABLE_TENSOR_FUSER", &enable_tensor_fuser);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
} else {
enable_tensor_fuser_pair_ = {true, enable_tensor_fuser};
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Tensor fuser is ") +
(enable_tensor_fuser ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
}
// If 'ENABLE_WEIGHT_SHARING' is not present in 'parameters' then no
// update is made to 'enable_weight_sharing'.
err = ParseParameter(
params, "ENABLE_WEIGHT_SHARING", &enable_weight_sharing_);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
} else {
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Weight sharing is ") +
(enable_weight_sharing_ ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
}
// If 'ENABLE_JIT_PROFILING' is not present in 'parameters' then no update
// is made to 'enable_jit_profiling'.
bool enable_jit_profiling = false;
err = ParseParameter(params, "ENABLE_JIT_PROFILING", &enable_jit_profiling);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
} else {
enable_jit_profiling_pair_ = {true, enable_jit_profiling};
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Jit profiling is ") +
(enable_jit_profiling ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
}
// If 'ENABLE_JIT_EXECUTOR' is not present in 'parameters' then no update is
// made to 'enable_jit_executor'.
bool enable_jit_executor = false;
err = ParseParameter(params, "ENABLE_JIT_EXECUTOR", &enable_jit_executor);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
} else {
enable_jit_executor_pair_ = {true, enable_jit_executor};
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Jit executor is ") +
(enable_jit_executor ? "enabled" : "disabled") +
" for model instance '" + Name() + "'")
.c_str());
}
// If 'INTRA_OP_THREAD_COUNT' is not present in 'parameters' then no update
// is made to 'intra_op_thread_count', which by default will take all
// threads
int intra_op_thread_count = -1;
err =
ParseParameter(params, "INTRA_OP_THREAD_COUNT", &intra_op_thread_count);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
} else {
if (intra_op_thread_count > 0) {
at::set_num_threads(intra_op_thread_count);
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Intra op thread count is set to ") +
std::to_string(intra_op_thread_count) + " for model instance '" +
Name() + "'")
.c_str());
}
}
// If 'INTER_OP_THREAD_COUNT' is not present in 'parameters' then no update
// is made to 'inter_op_thread_count', which by default will take all
// threads
int inter_op_thread_count = -1;
err =
ParseParameter(params, "INTER_OP_THREAD_COUNT", &inter_op_thread_count);
if (err != nullptr) {
if (TRITONSERVER_ErrorCode(err) != TRITONSERVER_ERROR_NOT_FOUND) {
return err;
} else {
TRITONSERVER_ErrorDelete(err);
}
} else {
if (inter_op_thread_count > 0) {
at::set_num_interop_threads(inter_op_thread_count);
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Inter op thread count is set to ") +
std::to_string(inter_op_thread_count) + " for model instance '" +
Name() + "'")
.c_str());
}
}
}
return nullptr;
}
// The naming convention followed for inputs/outputs in the model configuration.
// Outputs don't support FORWARD_ARGUMENT.
enum class NamingConvention {
NAMED_INDEX,
FORWARD_ARGUMENT,
STRICT_CONFIG_ORDERING
};
//
// ModelInstanceState
//
// State associated with a model instance. An object of this class is
// created and associated with each TRITONBACKEND_ModelInstance.
//
class ModelInstanceState : public BackendModelInstance {
public:
static TRITONSERVER_Error* Create(
ModelState* model_state,
TRITONBACKEND_ModelInstance* triton_model_instance,
ModelInstanceState** state);
virtual ~ModelInstanceState();
// Get the state of the model that corresponds to this instance.
ModelState* StateForModel() const { return model_state_; }
// Execute...
void ProcessRequests(
TRITONBACKEND_Request** requests, const uint32_t request_count);
// Clear CUDA cache
void ClearCache();
private:
ModelInstanceState(
ModelState* model_state,
TRITONBACKEND_ModelInstance* triton_model_instance);
TRITONSERVER_Error* ValidateBooleanSequenceControl(
triton::common::TritonJson::Value& sequence_batching,
const std::string& control_kind, bool required, bool* have_control);
TRITONSERVER_Error* ValidateTypedSequenceControl(
triton::common::TritonJson::Value& sequence_batching,
const std::string& control_kind, bool required, bool* have_control);
TRITONSERVER_Error* ValidateInputs(const size_t expected_input_cnt);
void AddInputToMap(
NamingConvention naming_convention,
const std::vector<std::string> allowed_inputs, const std::string& io_name,
const uint32_t index);
TRITONSERVER_Error* ValidateOutputs();
void Execute(
std::vector<TRITONBACKEND_Response*>* responses,
const uint32_t response_count,
std::vector<torch::jit::IValue>* input_tensors,
std::vector<torch::jit::IValue>* output_tensors);
TRITONSERVER_Error* SetInputTensors(
size_t total_batch_size, TRITONBACKEND_Request** requests,
const uint32_t request_count,
std::vector<TRITONBACKEND_Response*>* responses,
BackendInputCollector* collector, std::vector<const char*>* input_names,
std::vector<torch::jit::IValue>* input_tensors, bool* cuda_copy);
TRITONSERVER_Error* ReadOutputTensors(
size_t total_batch_size,
const std::vector<torch::jit::IValue>& output_tensors,
TRITONBACKEND_Request** requests, const uint32_t request_count,
std::vector<TRITONBACKEND_Response*>* responses);
TRITONSERVER_Error* RecordBackendTimestamp(
uint64_t* timestamp, void* cuda_event);
// Get the naming convention for inputs/outputs from the model configuration
TRITONSERVER_Error* GetNamingConvention(
NamingConvention* naming_convention,
const std::vector<std::string>& allowed_io);
// Create CUDA events for statistics collection.
void CreateCudaEvents(const int32_t& device_id);
// Get the appropriate CUDA stream for input and output handling based on the
// instance group type.
cudaStream_t GetCudaStreamByInstanceKind();
// Replace the default CUDA stream with the stream we created to ensure proper
// cuda stream synchronization.
void SetCurrentCudaStream(
const cudaStream_t& stream, const int32_t& device_id);
// Get the elapsed time between two CUDA events.
float GetCudaEventElapsedTime(
const cudaEvent_t& start_event, const cudaEvent_t& end_event);
ModelState* model_state_;
// The full path to the TorchScript model file.
std::string model_path_;
std::shared_ptr<torch::jit::script::Module> torch_model_;
torch::Device device_;
// Map from configuration name for an input to the index of
// that input in the model.
std::unordered_map<std::string, int> input_index_map_;
uint32_t batch_input_count_ = 0;
// Map from configuration name for an output to the index of
// that output in the model.
std::unordered_map<std::string, int> output_index_map_;
std::unordered_map<std::string, TRITONSERVER_DataType> output_dtype_map_;
// If the input to the tensor is a dictionary of tensors.
bool is_dict_input_;
// If the model supports batching.
bool supports_batching_;
cudaEvent_t compute_input_start_event_;
cudaEvent_t compute_infer_start_event_;
cudaEvent_t compute_output_start_event_;
// Store the cuda streams created for the 'KIND_MODEL' instance group.
std::vector<cudaStream_t> stream_vec_;
// The number of available devices.
int device_cnt_;
};
TRITONSERVER_Error*
ModelInstanceState::Create(
ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance,
ModelInstanceState** state)
{
try {
*state = new ModelInstanceState(model_state, triton_model_instance);
}
catch (const BackendModelInstanceException& ex) {
RETURN_ERROR_IF_TRUE(
ex.err_ == nullptr, TRITONSERVER_ERROR_INTERNAL,
std::string("unexpected nullptr in BackendModelInstanceException"));
RETURN_IF_ERROR(ex.err_);
}
return nullptr; // success
}
ModelInstanceState::ModelInstanceState(
ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance)
: BackendModelInstance(model_state, triton_model_instance),
model_state_(model_state), device_(torch::kCPU), is_dict_input_(false),
device_cnt_(0)
{
if (Kind() == TRITONSERVER_INSTANCEGROUPKIND_GPU) {
#ifdef TRITON_ENABLE_GPU
device_ = torch::Device(torch::kCUDA, DeviceId());
CreateCudaEvents(DeviceId());
#endif
}
#ifdef TRITON_ENABLE_GPU
device_cnt_ = torch::cuda::device_count();
#endif
THROW_IF_BACKEND_INSTANCE_ERROR(model_state->LoadModel(
ArtifactFilename(), device_, &model_path_, Kind(), &torch_model_));
if (Kind() == TRITONSERVER_INSTANCEGROUPKIND_MODEL) {
#ifdef TRITON_ENABLE_GPU
// Since we cannot determine the exact devices used by the model, we create
// a CUDA stream for every available device to ensure proper synchronization
// of CUDA streams. This approach may have implications when a timestamp is
// captured on a device that is not used by the model. Currently, this issue
// is addressed by synchronizing the CUDA streams before recording
// timestamps to prevent timestamp skewing. However, in the future, any
// modifications to the CUDA stream synchronization logic should be handled
// with caution.
for (int i = 0; i < device_cnt_; i++) {
cudaStream_t stream;
THROW_IF_BACKEND_INSTANCE_ERROR(
CreateCudaStream(i, 0 /* cuda_stream_priority */, &stream));
stream_vec_.push_back(stream);
}
if (!stream_vec_.empty()) {
// Create CUDA events on the first device that will be used for collecting
// inputs/outputs.
CreateCudaEvents(0);
}
#endif
}
size_t expected_input_cnt = 0;
{
triton::common::TritonJson::Value inputs;
if (model_state->ModelConfig().Find("input", &inputs)) {
expected_input_cnt = inputs.ArraySize();
}
triton::common::TritonJson::Value config_batch_inputs;
if (model_state->ModelConfig().Find("batch_input", &config_batch_inputs)) {
batch_input_count_ = config_batch_inputs.ArraySize();
expected_input_cnt += batch_input_count_;
}
}
// If this is a sequence model then make sure that the required
// inputs are present in the model and have the correct shape and
// datatype.
triton::common::TritonJson::Value sequence_batching;
if (model_state->ModelConfig().Find(
"sequence_batching", &sequence_batching)) {
bool have_start, have_end, have_ready, have_corrid;
THROW_IF_BACKEND_INSTANCE_ERROR(ValidateBooleanSequenceControl(
sequence_batching, "CONTROL_SEQUENCE_START", false /* required */,
&have_start));
THROW_IF_BACKEND_INSTANCE_ERROR(ValidateBooleanSequenceControl(
sequence_batching, "CONTROL_SEQUENCE_END", false /* required */,
&have_end));
THROW_IF_BACKEND_INSTANCE_ERROR(ValidateBooleanSequenceControl(
sequence_batching, "CONTROL_SEQUENCE_READY", false /* required */,
&have_ready));
THROW_IF_BACKEND_INSTANCE_ERROR(ValidateTypedSequenceControl(
sequence_batching, "CONTROL_SEQUENCE_CORRID", false /* required */,
&have_corrid));
if (have_start) {
expected_input_cnt += 1;
}
if (have_end) {
expected_input_cnt += 1;
}
if (have_ready) {
expected_input_cnt += 1;
}
if (have_corrid) {
expected_input_cnt += 1;
}
// Add the state inputs to the expected count
triton::common::TritonJson::Value states;
if (sequence_batching.Find("state", &states)) {
expected_input_cnt += states.ArraySize();
}
}
supports_batching_ = model_state_->MaxBatchSize() > 0;
THROW_IF_BACKEND_INSTANCE_ERROR(ValidateInputs(expected_input_cnt));
THROW_IF_BACKEND_INSTANCE_ERROR(ValidateOutputs());
}
void
ModelInstanceState::ClearCache()
{
#ifdef TRITON_ENABLE_GPU
if (device_.is_cuda() ||
((Kind() == TRITONSERVER_INSTANCEGROUPKIND_MODEL) && (device_cnt_ > 0))) {
c10::cuda::CUDACachingAllocator::emptyCache();
}
#endif // TRITON_ENABLE_GPU
}
ModelInstanceState::~ModelInstanceState()
{
torch_model_.reset();
ClearCache();
if (Kind() == TRITONSERVER_INSTANCEGROUPKIND_MODEL) {
#ifdef TRITON_ENABLE_GPU
for (size_t i = 0; i < stream_vec_.size(); i++) {
LOG_IF_ERROR(
ConvertCUDAStatusToTritonError(
cudaSetDevice(i), TRITONSERVER_ERROR_INTERNAL,
"Failed to set the device"),
"Failed to set the device");
LOG_IF_ERROR(
ConvertCUDAStatusToTritonError(
cudaStreamDestroy(stream_vec_[i]), TRITONSERVER_ERROR_INTERNAL,
"Failed to destroy cuda stream"),
"~ModelInstanceState error: ");
stream_vec_[i] = nullptr;
}
#endif
}
}
TRITONSERVER_Error*
ModelInstanceState::ValidateBooleanSequenceControl(
triton::common::TritonJson::Value& sequence_batching,
const std::string& control_kind, bool required, bool* have_control)
{
std::string tensor_name;
std::string tensor_datatype;
RETURN_IF_ERROR(GetBooleanSequenceControlProperties(
sequence_batching, model_state_->Name(), control_kind, required,
&tensor_name, &tensor_datatype, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr));
*have_control = !tensor_name.empty();
if (*have_control) {
std::string deliminator = "__";
int ip_index = 0;
int start_pos = tensor_name.find(deliminator);
if (start_pos == -1) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
("input '" + tensor_name +
"' does not follow <name>__<index> naming convention.")
.c_str());
}
// check if the index part of the name is not an integer
std::string index_str = tensor_name.substr(start_pos + 2);
for (auto itr = index_str.begin(); itr != index_str.end(); itr++) {
if (std::isdigit(*itr) == 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
("input '" + tensor_name +
"' does not follow <name>__<index> naming convention.")
.c_str());
}
}
ip_index = std::atoi(tensor_name.substr(start_pos + 2).c_str());
input_index_map_[tensor_name] = ip_index;
}
return nullptr; // success
}
TRITONSERVER_Error*
ModelInstanceState::ValidateTypedSequenceControl(
triton::common::TritonJson::Value& sequence_batching,
const std::string& control_kind, bool required, bool* have_control)
{
std::string tensor_name;
std::string tensor_datatype;
RETURN_IF_ERROR(GetTypedSequenceControlProperties(
sequence_batching, model_state_->Name(), control_kind, required,
&tensor_name, &tensor_datatype));
*have_control = !tensor_name.empty();
if (*have_control) {
std::string deliminator = "__";
int ip_index = 0;
int start_pos = tensor_name.find(deliminator);
if (start_pos == -1) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
("input '" + tensor_name +
"' does not follow <name>__<index> naming convention.")
.c_str());
}
// check if the index part of the name is not an integer
std::string index_str = tensor_name.substr(start_pos + 2);
for (auto itr = index_str.begin(); itr != index_str.end(); itr++) {
if (std::isdigit(*itr) == 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
("input '" + tensor_name +
"' does not follow <name>__<index> naming convention.")
.c_str());
}
}
// check if the data type is supported by PyTorch
if (!ModelConfigDataTypeToTorchType(tensor_datatype).first) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
("input '" + tensor_name + "' type '" + tensor_datatype +
"' is not supported by PyTorch.")
.c_str());
}
ip_index = std::atoi(tensor_name.substr(start_pos + 2).c_str());
input_index_map_[tensor_name] = ip_index;
}
return nullptr; // success
}
void
ModelInstanceState::AddInputToMap(
NamingConvention naming_convention,
const std::vector<std::string> allowed_inputs, const std::string& io_name,
const uint32_t index)
{
std::string deliminator = "__";
if (is_dict_input_) {
// If dictionary, index is irrelevant but we use the map to store the
// input names since they are the keys for the dictionary
input_index_map_[io_name] = index;
} else {
switch (naming_convention) {
case NamingConvention::FORWARD_ARGUMENT: {
auto itr =
std::find(allowed_inputs.begin(), allowed_inputs.end(), io_name);
if (itr != allowed_inputs.end()) {
input_index_map_[io_name] =
std::distance(allowed_inputs.begin(), itr);
}
return;
}
case NamingConvention::NAMED_INDEX: {
int start_pos = io_name.find(deliminator);
int ip_index = std::atoi(io_name.substr(start_pos + 2).c_str());
input_index_map_[io_name] = ip_index;
return;
}
case NamingConvention::STRICT_CONFIG_ORDERING: {
input_index_map_[io_name] = index;
return;
}
}
}
}
TRITONSERVER_Error*
ModelInstanceState::ValidateInputs(const size_t expected_input_cnt)
{
// Collect all the expected input tensor names and validate that the model
// configuration specifies only those.
std::vector<std::string> allowed_inputs;
const torch::jit::Method& method = torch_model_->get_method("forward");
const auto& schema = method.function().getSchema();
const std::vector<c10::Argument>& arguments = schema.arguments();
// Currently, only models with a single input of type Dict(str, Tensor) are
// supported. If the model expects more than one input then they must be all
// be of type Tensor.
//
// Ignore the argument at idx 0 if it is of Class type (self param in forward
// function)
size_t start_idx = 0;
if ((arguments.size() > 0) &&
(arguments.at(0).type()->kind() == c10::TypeKind::ClassType)) {
start_idx = 1;
}
if ((arguments.size() == (1 + start_idx)) &&
(arguments.at(start_idx).type()->kind() == c10::TypeKind::DictType)) {
is_dict_input_ = true;
} else if (arguments.size() > start_idx) {
// Return error if multiple inputs are of kind DictType
for (size_t i = start_idx + 1; i < arguments.size(); i++) {
if (arguments.at(i).type()->kind() == c10::TypeKind::DictType) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"Multiple inputs of kind DictType were detected. Only a single "
"input of type Dict(str, Tensor) is supported.");
}
}
// Return error if all inputs are not of type Tensor
for (size_t i = start_idx; i < arguments.size(); i++) {
if ((arguments.at(i).type()->kind() != c10::TypeKind::TensorType) &&
(arguments.at(i).type()->kind() != c10::TypeKind::ListType)) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,