forked from triton-inference-server/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfer_request.cc
1507 lines (1339 loc) · 49.2 KB
/
infer_request.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 2020-2022, 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 "infer_request.h"
#include <algorithm>
#include <deque>
#include "model.h"
#include "model_config_utils.h"
#include "server.h"
#include "triton/common/logging.h"
#ifdef TRITON_ENABLE_TRACING
#include "cuda_utils.h"
#endif // TRITON_ENABLE_TRACING
namespace triton { namespace core {
namespace {
// Utilities for Null request feature.
TRITONSERVER_Error*
NullResponseAlloc(
TRITONSERVER_ResponseAllocator* allocator, const char* tensor_name,
size_t byte_size, TRITONSERVER_MemoryType preferred_memory_type,
int64_t preferred_memory_type_id, void* userp, void** buffer,
void** buffer_userp, TRITONSERVER_MemoryType* actual_memory_type,
int64_t* actual_memory_type_id)
{
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"unexpected allocation for null request, no output should be requested.");
}
TRITONSERVER_Error*
NullResponseRelease(
TRITONSERVER_ResponseAllocator* allocator, void* buffer, void* buffer_userp,
size_t byte_size, TRITONSERVER_MemoryType memory_type,
int64_t memory_type_id)
{
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"unexpected release for null request, no output should be requested.");
}
ResponseAllocator null_allocator = ResponseAllocator(
NullResponseAlloc, NullResponseRelease, nullptr /* start_fn */);
void
NullResponseComplete(
TRITONSERVER_InferenceResponse* iresponse, const uint32_t flags,
void* userp)
{
if (iresponse != nullptr) {
LOG_TRITONSERVER_ERROR(
TRITONSERVER_InferenceResponseDelete(iresponse),
"deleting null response");
}
}
void
NullRequestComplete(
TRITONSERVER_InferenceRequest* request, const uint32_t flags, void* userp)
{
if ((flags & TRITONSERVER_REQUEST_RELEASE_ALL) != 0) {
LOG_TRITONSERVER_ERROR(
TRITONSERVER_InferenceRequestDelete(request), "deleting null request");
}
}
} // namespace
InferenceRequest::InferenceRequest(
const std::shared_ptr<Model>& model, const int64_t requested_model_version)
: InferenceRequest(model.get(), requested_model_version)
{
model_shared_ = model;
}
InferenceRequest::InferenceRequest(
Model* model, const int64_t requested_model_version)
: needs_normalization_(true), model_raw_(model),
requested_model_version_(requested_model_version), flags_(0),
correlation_id_(0), batch_size_(0), timeout_us_(0), collect_stats_(true)
{
SetPriority(0);
}
const std::string&
InferenceRequest::ModelName() const
{
return model_raw_->Name();
}
int64_t
InferenceRequest::ActualModelVersion() const
{
return model_raw_->Version();
}
void
InferenceRequest::SetPriority(uint32_t p)
{
if ((p == 0) || (p > model_raw_->MaxPriorityLevel())) {
priority_ = model_raw_->DefaultPriorityLevel();
} else {
priority_ = p;
}
}
#ifdef TRITON_ENABLE_TRACING
Status
InferenceRequest::TraceInputTensors(
TRITONSERVER_InferenceTraceActivity activity, const std::string& msg)
{
const auto& inputs = this->ImmutableInputs();
TRITONSERVER_MemoryType dst_memory_type = TRITONSERVER_MEMORY_CPU;
int64_t dst_memory_type_id = 0;
for (const auto& pr : inputs) {
InferenceRequest::Input* ti = pr.second;
// input data
const std::string& name = ti->Name();
TRITONSERVER_DataType datatype = DataTypeToTriton(ti->DType());
uint64_t byte_size = ti->Data()->TotalByteSize();
const int64_t* shape = ti->ShapeWithBatchDim().data();
uint32_t dim_count = ti->ShapeWithBatchDim().size();
uint32_t buffer_count = ti->DataBufferCount();
// chunk buffer
Status status;
const void* buffer;
uint64_t buffer_size;
TRITONSERVER_MemoryType src_memory_type;
int64_t src_memory_type_id;
bool cuda_used;
if (buffer_count == 0) {
LOG_STATUS_ERROR(
status, LogRequest() +
TRITONSERVER_InferenceTraceActivityString(activity) +
": " + msg + ": tensor: " + name + ": no buffer chunk");
continue;
}
if (buffer_count == 1) {
status = ti->DataBuffer(
0, &buffer, &buffer_size, &src_memory_type, &src_memory_type_id);
if (!status.IsOk()) {
LOG_STATUS_ERROR(
status, LogRequest() +
TRITONSERVER_InferenceTraceActivityString(activity) +
": " + msg + ": tensor: " + name +
": fail to get data buffer: " + status.Message());
return status;
}
if (buffer_size != byte_size) {
LOG_STATUS_ERROR(
status,
LogRequest() + TRITONSERVER_InferenceTraceActivityString(activity) +
": " + msg + ": tensor: " + name + ": truncated buffer");
continue;
}
INFER_TRACE_TENSOR_ACTIVITY(
this->trace_, activity, name.c_str(), datatype,
const_cast<void*>(buffer), buffer_size, shape, dim_count,
src_memory_type, src_memory_type_id);
continue;
}
// input buffer
std::vector<char> in_buffer(byte_size);
char* base = in_buffer.data();
size_t offset = 0;
for (uint32_t b = 0; b < buffer_count; ++b) {
status = ti->DataBuffer(
b, &buffer, &buffer_size, &src_memory_type, &src_memory_type_id);
if (!status.IsOk()) {
LOG_STATUS_ERROR(
status, LogRequest() +
TRITONSERVER_InferenceTraceActivityString(activity) +
": " + msg + ": tensor: " + name +
": fail to get data buffer: " + status.Message());
return status;
}
status = CopyBuffer(
"InferenceRequest TraceInputTensors", src_memory_type,
src_memory_type_id, dst_memory_type, dst_memory_type_id, buffer_size,
buffer, base + offset, nullptr, &cuda_used);
if (!status.IsOk()) {
LOG_STATUS_ERROR(
status, LogRequest() +
TRITONSERVER_InferenceTraceActivityString(activity) +
": " + msg + ": tensor: " + name +
": fail to copy buffer: " + status.Message());
return status;
}
offset += buffer_size;
}
INFER_TRACE_TENSOR_ACTIVITY(
this->trace_, activity, name.c_str(), datatype,
static_cast<void*>(base), byte_size, shape, dim_count, dst_memory_type,
dst_memory_type_id);
}
return Status::Success;
}
#endif // TRITON_ENABLE_TRACING
Status
InferenceRequest::OutputBufferProperties(
const char* name, size_t* byte_size, TRITONSERVER_MemoryType* memory_type,
int64_t* memory_type_id)
{
const auto allocator = response_factory_->Allocator();
if ((allocator == nullptr) || (allocator->QueryFn() == nullptr)) {
return Status(
Status::Code::UNAVAILABLE,
(LogRequest() + "Output properties are not available").c_str());
} else {
RETURN_IF_TRITONSERVER_ERROR(allocator->QueryFn()(
reinterpret_cast<TRITONSERVER_ResponseAllocator*>(
const_cast<ResponseAllocator*>(allocator)),
response_factory_->AllocatorUserp(), name, byte_size, memory_type,
memory_type_id));
}
return Status::Success;
}
Status
InferenceRequest::Run(std::unique_ptr<InferenceRequest>& request)
{
return request->model_raw_->Enqueue(request);
}
void
InferenceRequest::RespondIfError(
std::unique_ptr<InferenceRequest>& request, const Status& status,
const bool release_request)
{
if (status.IsOk()) {
return;
}
// Use the response factory to create a response, set the status,
// and send it. If something goes wrong all we can do is log the
// error. Because this is sending an error we assume that this is
// the last response for the request and so set the FINAL flag.
std::unique_ptr<InferenceResponse> response;
LOG_STATUS_ERROR(
request->response_factory_->CreateResponse(&response),
(request->LogRequest() + "failed to create error response").c_str());
LOG_STATUS_ERROR(
InferenceResponse::SendWithStatus(
std::move(response), TRITONSERVER_RESPONSE_COMPLETE_FINAL, status),
(request->LogRequest() + "failed to send error response").c_str());
// If releasing the request then invoke the release callback which
// gives ownership to the callback. So can't access 'request' after
// this point.
if (release_request) {
InferenceRequest::Release(
std::move(request), TRITONSERVER_REQUEST_RELEASE_ALL);
}
}
void
InferenceRequest::RespondIfError(
std::vector<std::unique_ptr<InferenceRequest>>& requests,
const Status& status, const bool release_requests)
{
if (status.IsOk()) {
return;
}
for (auto& request : requests) {
RespondIfError(request, status, release_requests);
}
}
void
InferenceRequest::Release(
std::unique_ptr<InferenceRequest>&& request, const uint32_t release_flags)
{
// Invoke the release callbacks added internally before releasing the
// request to user provided callback.
for (auto it = request->release_callbacks_.rbegin();
it != request->release_callbacks_.rend(); it++) {
(*it)();
}
request->release_callbacks_.clear();
#ifdef TRITON_ENABLE_TRACING
// If tracing then record request end and release the trace.
// This must be before the request callback to ensure the trace
// is properly layered, as the request may be nested in an ensemble
// and the callback may interact with upper level trace.
if (request->trace_ != nullptr) {
request->trace_->ReportNow(TRITONSERVER_TRACE_REQUEST_END);
request->ReleaseTrace();
}
#endif // TRITON_ENABLE_TRACING
void* userp = request->release_userp_;
auto& release_fn = request->release_fn_;
release_fn(
reinterpret_cast<TRITONSERVER_InferenceRequest*>(request.release()),
release_flags, userp);
}
InferenceRequest*
InferenceRequest::CopyAsNull(const InferenceRequest& from)
{
// Create a copy of 'from' request with artifical inputs and no requested
// outputs. Maybe more efficient to share inputs and other metadata,
// but that binds the Null request with 'from' request's lifecycle.
std::unique_ptr<InferenceRequest> lrequest(
new InferenceRequest(from.model_raw_, from.requested_model_version_));
lrequest->needs_normalization_ = false;
lrequest->batch_size_ = from.batch_size_;
lrequest->collect_stats_ = false;
// Three passes: first to construct input for the shape tensors inputs, second
// to obtain the max input byte size for allocating a large enough buffer for
// all non shape tensor inputs; third to construct the inputs for these
// tensors.
// First pass
for (const auto& input : from.OriginalInputs()) {
// Handle only shape tensors in this pass
if (!input.second.IsShapeTensor()) {
continue;
}
// Prepare the memory to hold input data
size_t byte_size = input.second.Data()->TotalByteSize();
auto mem_type = TRITONSERVER_MEMORY_CPU;
int64_t mem_id = 0;
std::shared_ptr<MutableMemory> data =
std::make_shared<AllocatedMemory>(byte_size, mem_type, mem_id);
// Get the source buffer. Assumes shape tensors be in a single buffer on the
// CPU
const auto& from_data = input.second.Data();
size_t from_data_byte_size;
TRITONSERVER_MemoryType from_data_memory_type;
int64_t from_data_memory_id;
const char* from_data_buffer = from_data->BufferAt(
0 /* idx */, &from_data_byte_size, &from_data_memory_type,
&from_data_memory_id);
if (from_data_byte_size != byte_size) {
LOG_WARNING
<< lrequest->LogRequest()
<< "The byte size of shape tensor to be copied does not match";
}
// Copy the shape values to the input buffer
std::memcpy(data->MutableBuffer(), from_data_buffer, from_data_byte_size);
Input* new_input;
lrequest->AddOriginalInput(
input.first, input.second.DType(), input.second.Shape(), &new_input);
// Must normalize shape here...
*new_input->MutableShape() = input.second.Shape();
*new_input->MutableShapeWithBatchDim() = input.second.ShapeWithBatchDim();
new_input->SetData(data);
}
// Second pass
size_t max_byte_size = 0;
size_t max_str_byte_size = 0;
const std::string* max_input_name;
for (const auto& input : from.OriginalInputs()) {
// Skip shape tensors in this pass
if (input.second.IsShapeTensor()) {
continue;
}
if (input.second.DType() == inference::DataType::TYPE_STRING) {
int64_t element_count =
triton::common::GetElementCount(input.second.Shape());
size_t str_byte_size = static_cast<size_t>(4 * element_count);
max_str_byte_size = std::max(str_byte_size, max_str_byte_size);
if (str_byte_size > max_byte_size) {
max_byte_size = str_byte_size;
max_input_name = &(input.first);
}
} else {
if (input.second.Data()->TotalByteSize() >= max_byte_size) {
max_byte_size = input.second.Data()->TotalByteSize();
max_input_name = &(input.first);
}
}
}
// Third pass
// [DLIS-1268] should use one growable static buffer for all null requests
auto mem_type = TRITONSERVER_MEMORY_CPU;
int64_t mem_id = 0;
std::shared_ptr<MutableMemory> data =
std::make_shared<AllocatedMemory>(max_byte_size, mem_type, mem_id);
auto data_base = data->BufferAt(0, &max_byte_size, &mem_type, &mem_id);
// Zero initialization is only required when there is a TYPE_BYTES tensor in
// the request. Only set the required number of bytes to zero.
if (max_str_byte_size > 0) {
std::fill(
data->MutableBuffer(), data->MutableBuffer() + max_str_byte_size, 0);
}
for (const auto& input : from.OriginalInputs()) {
// skip shape tensors in this pass
if (input.second.IsShapeTensor()) {
continue;
}
Input* new_input;
lrequest->AddOriginalInput(
input.first, input.second.DType(), input.second.Shape(), &new_input);
// Must normalize shape here...
*new_input->MutableShape() = input.second.Shape();
*new_input->MutableShapeWithBatchDim() = input.second.ShapeWithBatchDim();
// Note that the input that have max byte size will be responsible for
// holding the artifical data, while other inputs will hold a reference to
// it with byte size that matches 'from'
if (input.first == *max_input_name) {
new_input->SetData(data);
} else {
if (inference::DataType::TYPE_STRING == input.second.DType()) {
new_input->AppendData(
data_base,
triton::common::GetElementCount(input.second.Shape()) * 4, mem_type,
mem_id);
} else {
new_input->AppendData(
data_base, input.second.Data()->TotalByteSize(), mem_type, mem_id);
}
}
}
// No outputs were requested and thus there should be no allocations.
lrequest->SetResponseCallback(
&null_allocator, nullptr, NullResponseComplete, nullptr);
lrequest->SetReleaseCallback(NullRequestComplete, nullptr);
// Must normalize inputs here...
for (auto& pr : lrequest->original_inputs_) {
lrequest->inputs_.emplace(
std::make_pair(pr.second.Name(), std::addressof(pr.second)));
}
return lrequest.release();
}
Status
InferenceRequest::MutableOriginalInput(
const std::string& name, InferenceRequest::Input** input)
{
auto itr = original_inputs_.find(name);
if (itr == original_inputs_.end()) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "input '" + name + "' does not exist in request");
}
*input = &(itr->second);
return Status::Success;
}
Status
InferenceRequest::ImmutableInput(
const std::string& name, const InferenceRequest::Input** input) const
{
auto itr = inputs_.find(name);
if (itr == inputs_.end()) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "input '" + name + "' does not exist in request");
}
*input = itr->second;
return Status::Success;
}
Status
InferenceRequest::AddOriginalInput(
const std::string& name, const inference::DataType datatype,
const int64_t* shape, const uint64_t dim_count,
InferenceRequest::Input** input)
{
const auto& pr = original_inputs_.emplace(
std::piecewise_construct, std::forward_as_tuple(name),
std::forward_as_tuple(name, datatype, shape, dim_count));
if (!pr.second) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "input '" + name + "' already exists in request");
}
if (input != nullptr) {
*input = std::addressof(pr.first->second);
}
needs_normalization_ = true;
return Status::Success;
}
Status
InferenceRequest::AddOriginalInput(
const std::string& name, const inference::DataType datatype,
const std::vector<int64_t>& shape, InferenceRequest::Input** input)
{
return AddOriginalInput(name, datatype, &shape[0], shape.size(), input);
}
Status
InferenceRequest::AddRawInput(
const std::string& name, InferenceRequest::Input** input)
{
if (original_inputs_.size() != 0) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "raw input '" + name +
"' can't be added to request with other inputs");
}
const auto& pr = original_inputs_.emplace(
std::piecewise_construct, std::forward_as_tuple(name),
std::forward_as_tuple());
if (!pr.second) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "input '" + name + "' already exists in request");
}
if (input != nullptr) {
*input = std::addressof(pr.first->second);
}
raw_input_name_ = name;
needs_normalization_ = true;
return Status::Success;
}
Status
InferenceRequest::RemoveOriginalInput(const std::string& name)
{
if (original_inputs_.erase(name) != 1) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "input '" + name + "' does not exist in request");
}
if (name == raw_input_name_) {
raw_input_name_.clear();
}
needs_normalization_ = true;
return Status::Success;
}
Status
InferenceRequest::RemoveAllOriginalInputs()
{
original_inputs_.clear();
raw_input_name_.clear();
needs_normalization_ = true;
return Status::Success;
}
Status
InferenceRequest::AddOverrideInput(
const std::string& name, const inference::DataType datatype,
const int64_t batch_size, const std::vector<int64_t>& shape,
std::shared_ptr<InferenceRequest::Input>* input)
{
std::shared_ptr<Input> i = std::make_shared<Input>(name, datatype, shape);
*(i->MutableShape()) = i->OriginalShape();
if (batch_size > 0) {
*(i->MutableShapeWithBatchDim()) = {batch_size};
i->MutableShapeWithBatchDim()->insert(
i->MutableShapeWithBatchDim()->end(), i->OriginalShape().begin(),
i->OriginalShape().end());
} else {
*(i->MutableShapeWithBatchDim()) = i->OriginalShape();
}
RETURN_IF_ERROR(AddOverrideInput(i));
if (input != nullptr) {
*input = std::move(i);
}
return Status::Success;
}
Status
InferenceRequest::AddOverrideInput(
const std::shared_ptr<InferenceRequest::Input>& input)
{
LOG_VERBOSE(1) << LogRequest() << "adding input override for "
<< input->Name() << ": " << *this;
const auto& pr =
override_inputs_.emplace(std::make_pair(input->Name(), input));
if (!pr.second) {
pr.first->second = input;
}
// Add or replace this override in the inputs...
const auto res = inputs_.emplace(std::make_pair(input->Name(), input.get()));
if (!res.second) {
res.first->second = input.get();
}
LOG_VERBOSE(1) << LogRequest() << "added input override for " << input->Name()
<< ": " << *this;
return Status::Success;
}
Status
InferenceRequest::AddOriginalRequestedOutput(const std::string& name)
{
original_requested_outputs_.insert(name);
needs_normalization_ = true;
return Status::Success;
}
Status
InferenceRequest::LoadInputStates()
{
// Add the input states to the inference request.
if (sequence_states_ != nullptr) {
if (sequence_states_->IsNullRequest()) {
sequence_states_ =
SequenceStates::CopyAsNull(sequence_states_->NullSequenceStates());
}
for (auto& input_state_pair : sequence_states_->InputStates()) {
auto& input_state = input_state_pair.second;
std::shared_ptr<InferenceRequest::Input> input =
std::make_shared<InferenceRequest::Input>(
input_state->Name(), input_state->DType(), input_state->Shape());
*input->MutableShapeWithBatchDim() = input_state->Shape();
input->SetData(input_state->Data());
AddOverrideInput(input);
}
}
return Status::Success;
}
Status
InferenceRequest::RemoveOriginalRequestedOutput(const std::string& name)
{
original_requested_outputs_.erase(name);
needs_normalization_ = true;
return Status::Success;
}
Status
InferenceRequest::RemoveAllOriginalRequestedOutputs()
{
original_requested_outputs_.clear();
needs_normalization_ = true;
return Status::Success;
}
Status
InferenceRequest::PrepareForInference()
{
// Remove override inputs as those are added during any previous
// inference execution.
inputs_.clear();
override_inputs_.clear();
// Renormalize if anything has changed in the inference request in a
// way that could impact renormalization.
if (needs_normalization_) {
RETURN_IF_ERROR(Normalize());
needs_normalization_ = false;
}
// Initially show the actual inputs to be only the original
// inputs. If overrides are added later they will be added to
// 'inputs_'.
for (auto& pr : original_inputs_) {
inputs_.emplace(
std::make_pair(pr.second.Name(), std::addressof(pr.second)));
}
// Clear the timestamps
queue_start_ns_ = 0;
batcher_start_ns_ = 0;
#ifdef TRITON_ENABLE_STATS
request_start_ns_ = 0;
#endif // TRITON_ENABLE_STATS
LOG_VERBOSE(1) << LogRequest() << "prepared: " << *this;
return Status::Success;
}
Status
InferenceRequest::Normalize()
{
const inference::ModelConfig& model_config = model_raw_->Config();
// Fill metadata for raw input
if (!raw_input_name_.empty()) {
const bool has_multiple_inputs =
(original_inputs_.size() != 1) || (model_config.input_size() != 1);
if (has_multiple_inputs) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "Raw request must only have 1 input (found " +
std::to_string(original_inputs_.size()) +
") to be deduced but got " +
std::to_string(model_config.input_size()) + " inputs in '" +
ModelName() + "' model configuration");
}
auto it = original_inputs_.begin();
if (raw_input_name_ != it->first) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "Unexpected reference name for raw input '" +
raw_input_name_ + "' got '" + it->first + "'");
}
const auto& config_input = model_config.input(0);
auto& raw_input = it->second;
std::vector<int64_t> shape;
if (model_config.max_batch_size() != 0) {
shape.emplace_back(1);
}
int64_t dynamic_axis = -1;
size_t element_cnt = 1;
for (const auto& dim : config_input.dims()) {
if (dim == triton::common::WILDCARD_DIM) {
if (dynamic_axis != -1) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "The shape of the raw input '" +
config_input.name() +
"' can not be deduced because there are more than one "
"variable-sized dimension");
}
dynamic_axis = shape.size();
} else {
element_cnt *= (size_t)dim;
}
shape.emplace_back(dim);
}
if ((config_input.data_type() == inference::DataType::TYPE_STRING)) {
const bool has_one_element = (dynamic_axis == -1) && (element_cnt == 1);
if (!has_one_element) {
return Status(
Status::Code::INVALID_ARG, LogRequest() +
"For BYTE datatype raw input, the "
"model must have input shape [1]");
}
// In the case of BYTE data type, we will prepend the byte size to follow
// the Triton convention.
raw_input_size_ = raw_input.Data()->TotalByteSize();
RETURN_IF_ERROR(raw_input.PrependData(
&raw_input_size_, sizeof(uint32_t), TRITONSERVER_MEMORY_CPU, 0));
// Limit the BYTE raw input not to have host policy specific input for
// simplicity, such case won't happen given the current protocol spec.
// Will need to extend Input::PrependData() if needed.
if (!raw_input.HostPolicyData().empty()) {
return Status(
Status::Code::INVALID_ARG, LogRequest() +
"Raw input with data associated "
"with a host policy setting is not "
"currently supported");
}
} else if (dynamic_axis != -1) {
shape[dynamic_axis] =
raw_input.Data()->TotalByteSize() / element_cnt /
triton::common::GetDataTypeByteSize(config_input.data_type());
}
raw_input.SetMetadata(config_input.name(), config_input.data_type(), shape);
}
// Initialize the requested outputs to be used during inference. If
// original_requested_outputs_ is empty assume all outputs specified
// in model config are being requested.
requested_outputs_.clear();
if (original_requested_outputs_.size() == 0) {
for (const auto& output : model_config.output()) {
requested_outputs_.insert(output.name());
}
} else {
// Validate if the original requested output name exists in the
// model configuration.
for (const auto& output_name : original_requested_outputs_) {
const inference::ModelOutput* output_config;
RETURN_IF_ERROR(model_raw_->GetOutput(output_name, &output_config));
}
}
// Make sure that the request is providing the number of inputs
// as is expected by the model.
if ((original_inputs_.size() > (size_t)model_config.input_size()) ||
(original_inputs_.size() < model_raw_->RequiredInputCount())) {
// If no input is marked as optional, then use exact match error message
// for consistency / backward compatibility
if ((size_t)model_config.input_size() == model_raw_->RequiredInputCount()) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "expected " +
std::to_string(model_config.input_size()) + " inputs but got " +
std::to_string(original_inputs_.size()) + " inputs for model '" +
ModelName() + "'");
} else {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "expected number of inputs between " +
std::to_string(model_raw_->RequiredInputCount()) + " and " +
std::to_string(model_config.input_size()) + " but got " +
std::to_string(original_inputs_.size()) + " inputs for model '" +
ModelName() + "'");
}
}
// Determine the batch size and shape of each input.
if (model_config.max_batch_size() == 0) {
// Model does not support Triton-style batching so set as
// batch-size 0 and leave the tensor shapes as they are.
batch_size_ = 0;
for (auto& pr : original_inputs_) {
auto& input = pr.second;
*input.MutableShape() = input.OriginalShape();
}
} else {
// Model does support Triton-style batching so each input tensor
// must have the same first dimension which is the batch
// size. Adjust the shape of the input tensors to remove the batch
// dimension.
batch_size_ = 0;
for (auto& pr : original_inputs_) {
auto& input = pr.second;
// For a shape tensor, keep the tensor's shape as it is and mark
// that the input is a shape tensor.
const inference::ModelInput* input_config;
RETURN_IF_ERROR(model_raw_->GetInput(input.Name(), &input_config));
if (input_config->is_shape_tensor()) {
*input.MutableShape() = input.OriginalShape();
input.SetIsShapeTensor(true);
continue;
}
if (input.OriginalShape().size() == 0) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "input '" + input.Name() +
"' has no shape but model requires batch dimension for '" +
ModelName() + "'");
}
if (batch_size_ == 0) {
batch_size_ = input.OriginalShape()[0];
} else if (input.OriginalShape()[0] != batch_size_) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "input '" + input.Name() +
"' batch size does not match other inputs for '" + ModelName() +
"'");
}
input.MutableShape()->assign(
input.OriginalShape().begin() + 1, input.OriginalShape().end());
}
}
// Make sure request batch-size doesn't exceed what is supported by
// the model.
if ((int)batch_size_ > model_config.max_batch_size()) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "inference request batch-size must be <= " +
std::to_string(model_config.max_batch_size()) + " for '" +
ModelName() + "'");
}
// Verify that each input shape is valid for the model, make
// adjustments for reshapes and find the total tensor size.
for (auto& pr : original_inputs_) {
const inference::ModelInput* input_config;
RETURN_IF_ERROR(model_raw_->GetInput(pr.second.Name(), &input_config));
auto& input = pr.second;
auto shape = input.MutableShape();
if (input.DType() != input_config->data_type()) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "inference input data-type is '" +
std::string(
triton::common::DataTypeToProtocolString(input.DType())) +
"', model expects '" +
std::string(triton::common::DataTypeToProtocolString(
input_config->data_type())) +
"' for '" + ModelName() + "'");
}
// Validate input shape
{
bool match_config = true;
const auto& config_dims = input_config->dims();
const auto& input_dims = *shape;
if (config_dims.size() != (int64_t)input_dims.size()) {
match_config = false;
} else {
for (int i = 0; i < config_dims.size(); ++i) {
if (input_dims[i] == triton::common::WILDCARD_DIM) {
return Status(
Status::Code::INVALID_ARG,
LogRequest() +
"All input dimensions should be specified for input '" +
pr.first + "' for model '" + ModelName() + "', got " +
triton::common::DimsListToString(input.OriginalShape()));
} else if (
(config_dims[i] != triton::common::WILDCARD_DIM) &&
(config_dims[i] != input_dims[i])) {
match_config = false;
break;
}
}
}
if (!match_config) {
triton::common::DimsList full_dims;
std::string implicit_batch_note = "";
if (model_config.max_batch_size() > 0) {
full_dims.Add(triton::common::WILDCARD_DIM);
implicit_batch_note =
"NOTE: Setting a non-zero max_batch_size in the model config "
"requires a batch dimension to be prepended to each input shape. "
"If you want to specify the full shape including the batch dim "
"in your input dims config, try setting max_batch_size to zero. "
"See the model configuration docs for more info on "
"max_batch_size.";
}
for (int i = 0; i < input_config->dims_size(); ++i) {
full_dims.Add(input_config->dims(i));
}
return Status(
Status::Code::INVALID_ARG,
LogRequest() + "unexpected shape for input '" + pr.first +
"' for model '" + ModelName() + "'. Expected " +
triton::common::DimsListToString(full_dims) + ", got " +
triton::common::DimsListToString(input.OriginalShape()) + ". " +
implicit_batch_note);
}
}
// If there is a reshape for this input then adjust them to
// match the reshape. As reshape may have variable-size
// dimensions, we need to record corresponding value so that we
// can set the value correctly for reshape.
if (input_config->has_reshape()) {
std::deque<int64_t> variable_size_values;
for (int64_t idx = 0; idx < input_config->dims_size(); idx++) {
if (input_config->dims(idx) == -1) {
variable_size_values.push_back((*shape)[idx]);
}
}
shape->clear();
for (const auto& dim : input_config->reshape().shape()) {