forked from triton-inference-server/tensorrt_backend
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstance_state.cc
More file actions
3867 lines (3529 loc) · 147 KB
/
instance_state.cc
File metadata and controls
3867 lines (3529 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022-2025, 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 "instance_state.h"
#include "tensorrt_utils.h"
#include "triton/common/nvtx.h"
namespace triton { namespace backend { namespace tensorrt {
namespace {
TRITONSERVER_Error*
CreateCudaEvent(
const std::string& event_name, unsigned int event_flags, cudaEvent_t* event)
{
// Not adding 'cudaEventBlockingSync' to reduce gaps between the
// time of event record and the time of signaling blocking thread.
// The busy waiting only happens when there is an inflight request.
auto cuerr = cudaEventCreateWithFlags(event, event_flags);
if (cuerr != cudaSuccess) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("unable to create CUDA event for ") + event_name + ": " +
cudaGetErrorString(cuerr))
.c_str());
}
return nullptr;
}
} // namespace
#ifdef TRITON_ENABLE_STATS
#define FAIL_ALL_AND_RETURN_IF_ERROR( \
REQUESTS, REQUEST_COUNT, RESPONSES, S, LOG_MSG) \
do { \
TRITONSERVER_Error* farie_err_ = (S); \
if (farie_err_ != nullptr) { \
for (uint32_t r = 0; r < REQUEST_COUNT; ++r) { \
if (RESPONSES[r] != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
RESPONSES[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
farie_err_), \
"failed to send TensorRT backend response"); \
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, (LOG_MSG)); \
} \
LOG_IF_ERROR( \
TRITONBACKEND_ModelInstanceReportStatistics( \
TritonModelInstance(), REQUESTS[r], false /* success */, 0, 0, \
0, 0), \
"failed reporting request statistics"); \
LOG_IF_ERROR( \
TRITONBACKEND_RequestRelease( \
REQUESTS[r], TRITONSERVER_REQUEST_RELEASE_ALL), \
"failed releasing request"); \
REQUESTS[r] = nullptr; \
} \
TRITONSERVER_ErrorDelete(farie_err_); \
return; \
} \
} while (false)
void CUDART_CB
TimestampCaptureCallback(void* data)
{
SET_TIMESTAMP(*(reinterpret_cast<uint64_t*>(data)));
}
#else
#define FAIL_ALL_AND_RETURN_IF_ERROR( \
REQUESTS, REQUEST_COUNT, RESPONSES, S, LOG_MSG) \
do { \
TRITONSERVER_Error* farie_err_ = (S); \
if (farie_err_ != nullptr) { \
for (uint32_t r = 0; r < REQUEST_COUNT; ++r) { \
if (RESPONSES[r] != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
RESPONSES[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
farie_err_), \
"failed to send TensorRT backend response"); \
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, (LOG_MSG)); \
} \
LOG_IF_ERROR( \
TRITONBACKEND_RequestRelease( \
REQUESTS[r], TRITONSERVER_REQUEST_RELEASE_ALL), \
"failed releasing request"); \
REQUESTS[r] = nullptr; \
} \
TRITONSERVER_ErrorDelete(farie_err_); \
return; \
} \
} while (false)
#endif // TRITON_ENABLE_STATS
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_);
}
// If the model configuration doesn't have an explicit model file
// specified then use the default name.
std::string cc_model_filename = (*state)->ArtifactFilename();
if (cc_model_filename.empty()) {
cc_model_filename = "model.plan";
}
auto model_path = JoinPath(
{model_state->RepositoryPath(), std::to_string(model_state->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 '" + (*state)->Name() + "'");
}
(*state)->InitSemaphore();
RETURN_IF_ERROR((*state)->InitStreamsAndEvents());
RETURN_IF_ERROR(model_state->CreateEngine(
(*state)->DeviceId(), (*state)->DLACoreId(), model_path,
(*state)->EnginePtr()));
// Create TRT API interface, all TRT operations must be done after the
// interface is instantiated.
(*state)->interface_.reset(new TRTv3Interface(*state));
RETURN_IF_ERROR((*state)->InitIOIndexMap());
RETURN_IF_ERROR((*state)->InitOptimizationProfiles());
RETURN_IF_ERROR((*state)->ValidateIO());
RETURN_IF_ERROR((*state)->InitIOBindingBuffers());
(*state)->completion_thread_ =
std::thread(&ModelInstanceState::ProcessResponse, *state);
// CUDA 10.1 starts to support CUDA graphs.
// If enabled, build CUDA graphs with a set of graph specs.
#ifdef TRITON_ENABLE_CUDA_GRAPH
if (model_state->UseCudaGraphs()) {
RETURN_IF_ERROR((*state)->InitializeCudaGraph());
}
#endif
model_state->RegisterInstance((*state)->DeviceId(), *state);
std::string profiles_desc;
(*state)->GetConfiguredProfiles(&profiles_desc);
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Created instance ") + (*state)->Name() + " on GPU " +
std::to_string((*state)->DeviceId()) + " with stream priority " +
std::to_string((*state)->CudaStreamPriority()) +
" and optimization profile" + profiles_desc)
.c_str());
return nullptr; // success
}
ModelInstanceState::ModelInstanceState(
ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance)
: TensorRTModelInstance(model_state, triton_model_instance),
total_io_tensors_(0), uses_implicit_state_(false),
model_state_(model_state)
{
// 'coalesce_request_input_' is set at backend level
{
TRITONBACKEND_Model* model;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_ModelInstanceModel(triton_model_instance, &model));
TRITONBACKEND_Backend* backend;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_ModelBackend(model, &backend));
void* state;
THROW_IF_BACKEND_INSTANCE_ERROR(
TRITONBACKEND_BackendState(backend, &state));
coalesce_request_input_ =
reinterpret_cast<BackendConfiguration*>(state)->coalesce_request_input_;
}
if (Kind() != TRITONSERVER_INSTANCEGROUPKIND_GPU) {
throw triton::backend::BackendModelInstanceException(TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("unable to load model '") + model_state_->Name() +
"', TensorRT backend supports only GPU device")
.c_str()));
}
signal_stream_ = nullptr;
input_copy_stream_ = nullptr;
output_copy_stream_ = nullptr;
num_copy_streams_ = (model_state_->SeparateOutputStream()) ? 2 : 1;
next_buffer_binding_set_ = 0;
next_set_ = 0;
for (size_t idx = 0; idx < EVENT_SET_COUNT; idx++) {
events_[idx].input_ready_ = nullptr;
events_[idx].ready_for_input_ = nullptr;
events_[idx].output_ready_ = nullptr;
events_[idx].ready_for_output_ = nullptr;
events_[idx].compute_input_start_ = nullptr;
events_[idx].compute_input_end_ = nullptr;
events_[idx].compute_output_start_ = nullptr;
}
support_batching_ = (model_state_->MaxBatchSize() > 0);
TRITONSERVER_Error* err =
SupportsIntegratedZeroCopy(DeviceId(), &zero_copy_support_);
if (err != nullptr) {
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, TRITONSERVER_ErrorMessage(err));
TRITONSERVER_ErrorDelete(err);
err = nullptr;
zero_copy_support_ = false;
} else if (zero_copy_support_) {
LOG_MESSAGE(TRITONSERVER_LOG_VERBOSE, "Zero copy optimization is enabled");
} else {
LOG_MESSAGE(TRITONSERVER_LOG_VERBOSE, "Zero copy optimization is disabled");
}
}
ModelInstanceState::~ModelInstanceState()
{
cudaSetDevice(DeviceId());
for (auto& io_binding_infos : io_binding_infos_) {
for (auto& io_binding_info : io_binding_infos) {
if (!io_binding_info.IsDynamicShapeOutput() &&
io_binding_info.GetBuffer() != nullptr) {
cudaError_t err = cudaSuccess;
if (io_binding_info.GetMemoryType() == TRITONSERVER_MEMORY_GPU) {
err = cudaFree(io_binding_info.GetBuffer());
} else {
err = cudaFreeHost(io_binding_info.GetBuffer());
}
if (err != cudaSuccess) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR,
(std::string("Failed to free allocated memory for '") + Name() +
"': " + cudaGetErrorString(err))
.c_str());
}
}
}
}
for (auto& trt_context : trt_contexts_) {
for (const auto& cuda_graph_execs : trt_context.second.cuda_graph_execs_) {
for (const auto& pr : cuda_graph_execs) {
cudaError_t err = cudaGraphExecDestroy(pr.second.cuda_graph_exec_);
if (err != cudaSuccess) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR,
(std::string("Failed to destroy cuda graph exec: ") +
+cudaGetErrorString(err))
.c_str());
}
}
}
trt_context.second.cuda_graph_execs_.clear();
}
if (stream_ != nullptr) {
cudaError_t err = cudaStreamDestroy(stream_);
if (err != cudaSuccess) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR,
(std::string("Failed to destroy cuda stream: ") +
+cudaGetErrorString(err))
.c_str());
}
stream_ = nullptr;
}
if (signal_stream_ != nullptr) {
cudaError_t err = cudaStreamDestroy(signal_stream_);
if (err != cudaSuccess) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR,
(std::string("Failed to destroy cuda signal stream: ") +
+cudaGetErrorString(err))
.c_str());
}
signal_stream_ = nullptr;
}
if (input_copy_stream_ != nullptr) {
cudaError_t err = cudaStreamDestroy(input_copy_stream_);
if (err != cudaSuccess) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR,
(std::string("Failed to destroy cuda input copy stream: ") +
+cudaGetErrorString(err))
.c_str());
}
input_copy_stream_ = nullptr;
}
if (output_copy_stream_ != nullptr) {
cudaError_t err = cudaStreamDestroy(output_copy_stream_);
if (err != cudaSuccess) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR,
(std::string("Failed to destroy cuda output copy stream: ") +
+cudaGetErrorString(err))
.c_str());
}
output_copy_stream_ = nullptr;
}
DestroyEventSet();
// Notify the completion thread to exit
completion_queue_.Put(std::move(std::unique_ptr<Payload>()));
if (completion_thread_.joinable()) {
completion_thread_.join();
}
}
void
ModelInstanceState::ProcessRequests(
TRITONBACKEND_Request** requests, const uint32_t request_count)
{
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("TRITONBACKEND_ModelExecute: Issuing ") + Name() + " with " +
std::to_string(request_count) + " requests")
.c_str());
Run(requests, request_count);
bool run_failed = true;
for (size_t i = 0; i < request_count; ++i) {
if (requests[i] != nullptr) {
run_failed = false;
break;
}
}
// On error, handle the response here instead of delegating to the
// completion thread as the completion thread will wait on CUDA
// events unconditionally, which can be ignored on error.
if (run_failed) {
// On inference error, place the slot back in the queue
// immediately, as all work for the slot should be ignored.
semaphore_->Release();
} else {
auto event_set_idx = next_set_;
next_set_ = (event_set_idx + 1) % EVENT_SET_COUNT;
payload_->requests_list_.reserve(payload_->request_count_);
for (uint32_t i = 0; i < payload_->request_count_; i++) {
payload_->requests_list_.push_back(payload_->requests_[i]);
}
payload_->requests_ = &payload_->requests_list_[0];
// Put the details needed by the ProcessResponse thread on the
// queue
completion_queue_.Put(std::move(payload_));
next_buffer_binding_set_ =
(next_buffer_binding_set_ + 1) % num_copy_streams_;
// Wait until the states are updated. Barrier is only
// engaged when model has an implicit state.
if (barrier_.get() != nullptr) {
barrier_->get_future().wait();
}
}
}
void
ModelInstanceState::Run(
TRITONBACKEND_Request** requests, const uint32_t request_count)
{
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("TRITONBACKEND_ModelExecute: Running ") + Name() + " with " +
std::to_string(request_count) + " requests")
.c_str());
NVTX_RANGE(nvtx_, "Run " + Name());
// Should set a barrier so that instance execution can be blocked until
// the state update is completed.
if (uses_implicit_state_) {
barrier_.reset(new std::promise<void>());
}
// Need to move the TRITONBACKEND_Request objects, as the lifetime
// must be extended until ProcessResponse completes.
payload_.reset(new Payload(next_set_, requests, request_count));
SET_TIMESTAMP(payload_->compute_start_ns_);
cudaSetDevice(DeviceId());
#ifdef TRITON_ENABLE_STATS
{
SET_TIMESTAMP(payload_->compute_start_ns_);
cudaEventRecord(events_[next_set_].compute_input_start_, signal_stream_);
}
#endif // TRITON_ENABLE_STATS
const int max_batch_size = StateForModel()->MaxBatchSize();
// For each request collect the total batch size for this inference
// execution. The batch-size, number of inputs, and size of each
// input has already been checked so don't need to do that here.
payload_->total_batch_size_ = 0;
for (size_t i = 0; i < payload_->request_count_; i++) {
// If we get a nullptr request then something is badly wrong. Fail
// and release all requests.
if (payload_->requests_[i] == nullptr) {
RequestsRespondWithError(
payload_->requests_, payload_->request_count_,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"null request given to TensorRT backend for '" + Name() + "'")
.c_str()));
return;
}
if (max_batch_size > 0) {
// Retrieve the batch size from one of the inputs,
// if the model support batching, the first dimension size is
// batch size
TRITONBACKEND_Input* input;
auto err =
TRITONBACKEND_RequestInputByIndex(requests[i], 0 /* index */, &input);
if (err == nullptr) {
const int64_t* shape;
err = TRITONBACKEND_InputProperties(
input, nullptr, nullptr, &shape, nullptr, nullptr, nullptr);
payload_->total_batch_size_ += shape[0];
}
if (err != nullptr) {
RequestsRespondWithError(requests, request_count, err);
return;
}
} else {
payload_->total_batch_size_ += 1;
}
}
// If there are no valid requests then no need to run the
// inference. This should never happen unless called with an empty
// 'requests' for some reason.
if (payload_->total_batch_size_ == 0) {
return;
}
// Make sure the maximum batch size is not exceeded. The
// total_batch_size must be 1 for models that don't support batching
// (i.e. max_batch_size == 0). If max_batch_size is exceeded then
// scheduler has done something badly wrong so fail and release all
// requests.
if ((payload_->total_batch_size_ != 1) &&
(payload_->total_batch_size_ > (size_t)max_batch_size)) {
RequestsRespondWithError(
payload_->requests_, payload_->request_count_,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"batch size " + std::to_string(payload_->total_batch_size_) +
" for '" + Name() + "', max allowed is " +
std::to_string(max_batch_size))
.c_str()));
return;
}
std::map<int32_t, ShapeTensor> request_shape_values;
// Scheduler ensures all the requests have identical shape values so
// use values from first shape tensor
TRITONSERVER_Error* err = GetRequestShapeValues(
payload_->total_batch_size_, payload_->requests_[0],
&request_shape_values);
if (err != nullptr) {
RequestsRespondWithError(
payload_->requests_, payload_->request_count_, err);
return;
}
std::map<int, TensorRTContext>::iterator citr;
err = GetMostOptimizedProfile(
payload_->total_batch_size_, payload_->requests_,
payload_->request_count_, request_shape_values, &citr);
if (err != nullptr) {
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, TRITONSERVER_ErrorMessage(err));
TRITONSERVER_ErrorDelete(err);
err = nullptr;
}
// At this point we are committed to running inference with all
// 'requests'. Create a response for each request. During input
// processing if there is an error with any request that error will
// be sent immediately with the corresponding response (and the
// response pointer will then be nullptr). The request object
// itself will not be released until after all inferencing is done
// (below) as we may need to access the request object when
// determine how to process outputs (for example, even if we don't
// need the outputs for a request that has an error, we do need to
// know the size of those outputs associated with the request so we
// can skip them in the output tensors).
payload_->responses_.reserve(payload_->request_count_);
for (size_t i = 0; i < payload_->request_count_; i++) {
TRITONBACKEND_Response* response;
auto err = TRITONBACKEND_ResponseNew(&response, requests[i]);
if (err == nullptr) {
payload_->responses_.emplace_back(response);
} else {
payload_->responses_.emplace_back(nullptr);
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, "Fail to create response");
TRITONSERVER_ErrorDelete(err);
}
}
// Calculate the set of event used with the current buffer set
// in previous execution
int prev_set = (EVENT_SET_COUNT -
(io_binding_infos_.size() % EVENT_SET_COUNT) + next_set_) %
EVENT_SET_COUNT;
auto prev_input_ready_event = model_state_->EagerBatching()
? events_[prev_set].ready_for_input_
: nullptr;
std::vector<int64_t> input_dims{(int64_t)payload_->total_batch_size_};
payload_->collector_.reset(new BackendInputCollector(
payload_->requests_, payload_->request_count_, &payload_->responses_,
model_state_->TritonMemoryManager(), model_state_->EnablePinnedInput(),
input_copy_stream_, events_[next_set_].input_ready_,
prev_input_ready_event, model_state_->GatherKernelBufferThreshold(),
HostPolicyName().c_str(), zero_copy_support_, coalesce_request_input_));
// For each input, concatenate input values from each request into
// the corresponding binding.
for (int io_index = 0; io_index < total_io_tensors_; ++io_index) {
auto& io_binding_info =
io_binding_infos_[next_buffer_binding_set_][io_index];
const std::string& name = tensor_names_[io_index];
if (io_binding_info.IsDynamicShapeOutput()) {
citr->second.context_->setOutputAllocator(
io_binding_info.GetName().c_str(), io_binding_info.GetAllocator());
}
if (!IsInput(engine_.get(), name)) {
continue;
}
TRITONSERVER_Error* err = nullptr;
// Set the shape binding if needed. If unable to set the shape
// binding then fail all requests.
if (engine_->isShapeInferenceIO(name.c_str())) {
auto it = request_shape_values.find(io_index);
if (it != request_shape_values.end()) {
err = ValidateShapeValues(
it->second, citr->second.min_shapes_[io_index],
citr->second.max_shapes_[io_index], citr->second.nb_shape_values_);
} else {
err = TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("unable to find shape values for shape input '") +
name + "' in request for " + Name())
.c_str());
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
err, "missing shape values for the shape tensor");
}
if (err != nullptr) {
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
err, "invalid shape values encountered for shape inputs");
} else {
// [FIXME] formalize it, the 'buffer_' may be set directly while forming
// the shape value
memcpy(
io_binding_info.GetBuffer(), it->second.GetData(),
it->second.GetSize());
citr->second.context_->setInputTensorAddress(
name.c_str(), io_binding_info.GetBuffer());
}
// Skip the upcoming section if it is a shape tensor
continue;
}
// FIXME inefficient as looping in this way may iterate the same
// source_input multiple times
if (io_binding_info.GetBatchInput() != nullptr) {
std::vector<int64_t> shape;
const auto& batch_input = io_binding_info.GetBatchInput()->first;
auto& allocated_memory = io_binding_info.GetBatchInput()->second;
TRITONSERVER_MemoryType mem_type = allocated_memory->MemoryType();
int64_t mem_type_id = allocated_memory->MemoryTypeId();
char* input_buffer = allocated_memory->MemoryPtr();
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
payload_->collector_->BatchInputShape(batch_input, &shape),
"error getting the batch input shape");
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
interface_->SetBindingDimensions(
name, shape, citr->second, io_index, &input_dims),
"error setting the binding dimension");
TRITONSERVER_DataType datatype = batch_input.DataType();
size_t total_byte_size = GetByteSize(datatype, shape);
const char* dst_buffer;
size_t dst_buffer_byte_size;
TRITONSERVER_MemoryType dst_memory_type;
int64_t dst_memory_type_id;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
payload_->collector_->ProcessBatchInput(
batch_input, input_buffer, total_byte_size,
{{mem_type, mem_type_id}}, &dst_buffer, &dst_buffer_byte_size,
&dst_memory_type, &dst_memory_type_id),
"error setting the batch input value");
if ((batch_input.BatchInputKind() !=
BatchInput::Kind::BATCH_MAX_ELEMENT_COUNT_AS_SHAPE) &&
(io_binding_info.GetMemoryType() == TRITONSERVER_MEMORY_GPU)) {
bool cuda_used = false;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
CopyBuffer(
name, mem_type, mem_type_id, io_binding_info.GetMemoryType(),
io_binding_info.GetMemoryTypeId(), total_byte_size,
input_buffer, io_binding_info.GetBuffer(), input_copy_stream_,
&cuda_used),
"error copying the batch input buffer");
if (cuda_used) {
cudaEventRecord(events_[next_set_].input_ready_, input_copy_stream_);
}
}
} else if (io_binding_info.IsBufferRagged()) {
std::vector<int64_t> ragged_shape{0};
TRITONSERVER_DataType datatype;
for (size_t req_idx = 0; req_idx < payload_->request_count_; req_idx++) {
TRITONBACKEND_Input* repr_input;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
TRITONBACKEND_RequestInput(
payload_->requests_[req_idx], name.c_str(), &repr_input),
(std::string("failed to obtain the input '") + name + "'").c_str());
TRITONSERVER_DataType temp_dt;
const int64_t* shape;
uint32_t dims_count;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
TRITONBACKEND_InputProperties(
repr_input, nullptr, &temp_dt, &shape, &dims_count, nullptr,
nullptr),
(std::string("failed to obtain the input properties for '") + name +
"'")
.c_str());
ragged_shape[0] += backend::GetElementCount(shape, dims_count);
if (req_idx == 0) {
datatype = temp_dt;
}
}
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
interface_->SetBindingDimensions(
name, ragged_shape, citr->second, io_index, &input_dims),
"error setting the binding dimension");
size_t total_byte_size = GetByteSize(datatype, ragged_shape);
payload_->collector_->ProcessTensor(
name.c_str(), static_cast<char*>(io_binding_info.GetBuffer()),
total_byte_size, io_binding_info.GetMemoryType(),
io_binding_info.GetMemoryTypeId());
} else {
TRITONBACKEND_Input* repr_input;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
TRITONBACKEND_RequestInput(
payload_->requests_[0], name.c_str(), &repr_input),
(std::string("failed to obtain the representative input '") + name +
"'")
.c_str());
// Get the shape of the input. The request has already checked
// that the request shape is valid so don't need to do it here.
TRITONSERVER_DataType datatype;
const int64_t* shape;
uint32_t dims_count;
size_t req_data_byte_size;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
TRITONBACKEND_InputProperties(
repr_input, nullptr, &datatype, &shape, &dims_count,
&req_data_byte_size, nullptr),
(std::string("failed to obtain the representative input "
"properties for '") +
name + "'")
.c_str());
// The shape for the entire input batch, [total_batch_size, ...]
std::vector<int64_t> batchn_shape;
uint64_t dim_idx = 0;
batchn_shape.reserve(dims_count);
if (support_batching_) {
if (!engine_->isShapeInferenceIO(name.c_str())) {
batchn_shape.push_back(payload_->total_batch_size_);
dim_idx = 1;
}
}
while (dim_idx < dims_count) {
batchn_shape.push_back(shape[dim_idx++]);
}
// Set the binding dimension so that output dimensions can be
// obtained
if (!engine_->isShapeInferenceIO(name.c_str())) {
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
interface_->SetBindingDimensions(
name, batchn_shape, citr->second, io_index, &input_dims),
"error setting the binding dimension");
}
size_t total_byte_size = 0;
if (io_binding_info.GetFormat().is_linear_format_) {
total_byte_size = GetByteSize(datatype, batchn_shape);
// For input tensors with a linear IO format, the request has already
// verified the byte size, so no further validation is needed here.
} else {
batchn_shape[io_binding_info.GetFormat().vectorized_dim_] +=
(io_binding_info.GetFormat().components_per_element_ -
(batchn_shape[io_binding_info.GetFormat().vectorized_dim_] %
io_binding_info.GetFormat().components_per_element_));
total_byte_size = GetByteSize(datatype, batchn_shape);
// Ensure the request data byte size matches the expected byte size for
// non-linear IO format tensors
if (req_data_byte_size != total_byte_size) {
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_,
payload_->responses_,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("input byte size mismatch for input '") + name +
"'" + " for model '" + model_state_->Name() +
"'. Expected " + std::to_string(total_byte_size) + ", got " +
std::to_string(req_data_byte_size))
.c_str()),
"failed to run TRT inference");
}
}
payload_->collector_->ProcessTensor(
name.c_str(), static_cast<char*>(io_binding_info.GetBuffer()),
total_byte_size, io_binding_info.GetMemoryType(),
io_binding_info.GetMemoryTypeId());
}
}
payload_->collector_->Finalize();
const TensorRTContext::CudaGraph* cuda_graph = nullptr;
bool found_exact = false;
// FIXME closest_cuda_graph
FindClosestCudaGraph(citr->second, input_dims, &cuda_graph, &found_exact);
// [DLIS-4283] should re-visit below...
// is below even necessary if we are going to launch a CUDA graph?
// regular input buffer has been filled and batch input buffer has been set,
// unless the below is something that must be changed based on selected graph
if ((cuda_graph != nullptr) && !found_exact) {
size_t input_idx = 0;
for (int io_index = 0; io_index < total_io_tensors_; ++io_index) {
auto& io_binding_info =
io_binding_infos_[next_buffer_binding_set_][io_index];
const std::string& tensor_name = tensor_names_[io_index];
if (!IsInput(engine_.get(), tensor_name) ||
engine_->isShapeInferenceIO(tensor_name.c_str())) {
continue;
}
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
interface_->SetBindingDimensions(
"CUDA graph input", cuda_graph->input_dims_[input_idx],
citr->second, io_index, nullptr),
"error setting the binding dimension");
// Initialize additional entries in batch input
if (io_binding_info.GetBatchInput() != nullptr) {
const auto& batch_input = io_binding_info.GetBatchInput()->first;
const size_t total_byte_size = GetByteSize(
batch_input.DataType(), cuda_graph->input_dims_[input_idx]);
auto& allocated_memory = io_binding_info.GetBatchInput()->second;
TRITONSERVER_MemoryType mem_type = allocated_memory->MemoryType();
int64_t mem_type_id = allocated_memory->MemoryTypeId();
char* input_buffer = allocated_memory->MemoryPtr();
const char* dst_buffer;
size_t dst_buffer_byte_size;
TRITONSERVER_MemoryType dst_memory_type;
int64_t dst_memory_type_id;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
payload_->collector_->ProcessBatchInput(
batch_input, input_buffer, total_byte_size,
{{mem_type, mem_type_id}}, &dst_buffer, &dst_buffer_byte_size,
&dst_memory_type, &dst_memory_type_id),
"error setting the bath input value");
if ((batch_input.BatchInputKind() !=
BatchInput::Kind::BATCH_MAX_ELEMENT_COUNT_AS_SHAPE) &&
(io_binding_info.GetMemoryType() == TRITONSERVER_MEMORY_GPU)) {
bool cuda_used = false;
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_,
payload_->responses_,
CopyBuffer(
"CUDA graph batch input", mem_type, mem_type_id,
io_binding_info.GetMemoryType(),
io_binding_info.GetMemoryTypeId(), total_byte_size,
input_buffer, io_binding_info.GetBuffer(), input_copy_stream_,
&cuda_used),
"error copying the batch input buffer");
if (cuda_used) {
cudaEventRecord(
events_[next_set_].input_ready_, input_copy_stream_);
}
}
}
input_idx++;
}
}
// Ensure inputs are ready before execution.
// Output buffers are guaranteed to be available at this point when
// the execution and output copy are on the same stream.
cudaStreamWaitEvent(stream_, events_[next_set_].input_ready_, 0);
#ifdef TRITON_ENABLE_STATS
cudaStreamWaitEvent(signal_stream_, events_[next_set_].input_ready_, 0);
cudaEventRecord(events_[next_set_].compute_input_end_, signal_stream_);
#endif // TRITON_ENABLE_STATS
// Wait for the output buffers to be available at this point when
// the execution and output copy are on separate streams
if (model_state_->SeparateOutputStream()) {
cudaStreamWaitEvent(stream_, events_[next_set_].output_ready_, 0);
}
// Async execute the inference using a CUDA graph if available for
// the batch-size, otherwise execution normally.
if (cuda_graph != nullptr) {
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("Context with profile ") + citr->second.profile_name_ +
" [" + std::to_string(citr->first) + "] is launching CUDA graph for " +
Name())
.c_str());
cudaError_t cuda_err =
cudaGraphLaunch(cuda_graph->cuda_graph_exec_, stream_);
if (cuda_err != cudaSuccess) {
cudaStreamSynchronize(stream_);
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("unable to execute graph for inference ") + name_ +
": " + cudaGetErrorString(cuda_err))
.c_str()),
"failed to run TRT inference");
}
// [DLIS-4283] [FIXME] should not need this as TRT adopted the new CUDA
// graph API that exposed event activity
// Event recorded during CUDA graph capture is not visible outside
// of the graph, need to explicitly record it.
cudaEventRecord(events_[next_set_].ready_for_input_, stream_);
} else {
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("Context with profile ") + citr->second.profile_name_ +
" [" + std::to_string(citr->first) + "] is being executed for " +
Name())
.c_str());
if (citr->second.context_->inferShapes(0, nullptr) != 0) {
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"failed to specify the dimensions of all input tensors or values "
"of all input shape tensors"),
"failed to run TRT inference");
}
if (!interface_->Enqueue(citr->second.context_.get())) {
cudaStreamSynchronize(stream_);
FAIL_ALL_AND_RETURN_IF_ERROR(
payload_->requests_, payload_->request_count_, payload_->responses_,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("unable to enqueue for inference ") + Name())
.c_str()),
"failed to run TRT inference");
}
}
cudaEventRecord(events_[next_set_].ready_for_output_, stream_);
#ifdef TRITON_ENABLE_STATS
cudaStreamWaitEvent(signal_stream_, events_[next_set_].ready_for_output_, 0);
cudaEventRecord(events_[next_set_].compute_output_start_, signal_stream_);
#endif // TRITON_ENABLE_STATS
// Collect the names of requested outputs. Do not include outputs
// for requests that have already responded with an error.
std::vector<std::set<std::string>> request_required_outputs(
payload_->request_count_);
for (size_t idx = 0; idx < payload_->request_count_; idx++) {
const auto& request = payload_->requests_[idx];
auto& response = payload_->responses_[idx];
if (response != nullptr) {
uint32_t output_count;
RESPOND_AND_SET_NULL_IF_ERROR(
&response, TRITONBACKEND_RequestOutputCount(request, &output_count));
if (response != nullptr) {
for (uint32_t output_idx = 0; output_idx < output_count; output_idx++) {
const char* output_name;
RESPOND_AND_SET_NULL_IF_ERROR(
&response, TRITONBACKEND_RequestOutputName(
request, output_idx, &output_name));
if (response != nullptr) {
request_required_outputs[idx].insert(output_name);
}
}
}
}
}
// Wait for the inference to be completed before copying output if
// output copy is on a separate stream
if (model_state_->SeparateOutputStream()) {
cudaStreamWaitEvent(
output_copy_stream_, events_[next_set_].ready_for_output_, 0);
}
const auto output_stream =
model_state_->SeparateOutputStream() ? output_copy_stream_ : stream_;
// For each requested output, verify that the output can accept the
// actual model output and then copy that output from the GPU
payload_->responder_.reset(new BackendOutputResponder(
payload_->requests_, payload_->request_count_, &payload_->responses_,
model_state_->TritonMemoryManager(), model_state_->MaxBatchSize() > 0,
model_state_->EnablePinnedOutput(), output_stream,
events_[next_set_].output_ready_, zero_copy_support_));
for (int io_index = 0; io_index < total_io_tensors_; ++io_index) {
auto& io_binding_info =
io_binding_infos_[next_buffer_binding_set_][io_index];
const std::string& name = tensor_names_[io_index];
if (IsInput(engine_.get(), name)) {
continue;
}
nvinfer1::Dims dims;