forked from triton-inference-server/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsequence_batch_scheduler.cc
1973 lines (1731 loc) · 74.8 KB
/
sequence_batch_scheduler.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 2018-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "sequence_batch_scheduler.h"
#ifndef _WIN32
#include <sys/resource.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif
#include <algorithm>
#include "constants.h"
#include "dynamic_batch_scheduler.h"
#include "model_config_utils.h"
#include "server.h"
#include "triton/common/logging.h"
namespace triton { namespace core {
namespace {
template <typename TimeUnit>
inline uint64_t
Now()
{
return std::chrono::duration_cast<TimeUnit>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
void
SetThreadPriority(const int nice, const char* thread_name)
{
#ifndef _WIN32
if (setpriority(PRIO_PROCESS, syscall(SYS_gettid), nice) == 0) {
LOG_VERBOSE(1) << "Starting " << thread_name << " thread at nice " << nice
<< "...";
} else {
LOG_VERBOSE(1) << "Starting " << thread_name
<< " thread at default nice (requested nice " << nice
<< " failed)...";
}
#else
LOG_VERBOSE(1) << "Starting " << thread_name << " thread at default nice...";
#endif
}
} // namespace
Status
SequenceBatchScheduler::Create(
TritonModel* model,
const std::vector<std::shared_ptr<TritonModelInstance>>& new_instances,
const std::unordered_map<std::string, bool>& enforce_equal_shape_tensors,
std::unique_ptr<Scheduler>* scheduler)
{
std::unique_ptr<SequenceBatchScheduler> sched(
new SequenceBatchScheduler(model, enforce_equal_shape_tensors));
// For debugging and testing,
const char* dstr = getenv("TRITONSERVER_BACKLOG_DELAY_SCHEDULER");
sched->backlog_delay_cnt_ = 0;
if (dstr != nullptr) {
sched->backlog_delay_cnt_ = atoi(dstr);
LOG_INFO << "Delaying scheduler until " << sched->backlog_delay_cnt_
<< " backlog queued requests...";
}
auto& config = model->Config();
// Max sequence idle...
sched->max_sequence_idle_microseconds_ =
config.sequence_batching().max_sequence_idle_microseconds();
sched->max_batch_size_ = config.max_batch_size();
// Implicit States
auto& states = config.sequence_batching().state();
for (const inference::ModelSequenceBatching_State& state : states) {
sched->state_output_config_map_.insert({state.output_name(), state});
if (state.initial_state_size() > 1) {
return Status(
Status::Code::INVALID_ARG,
std::string(
std::string("initial_state field for state input '") +
state.input_name() +
"' must contain exactly one or zero element. Found '" +
std::to_string(state.initial_state_size()) + "' elements."));
}
// If the model configuration has initial_state field.
if (state.initial_state_size() == 1) {
auto& initial_state = state.initial_state(0);
RETURN_IF_ERROR(
sched->GenerateInitialStateData(initial_state, state, model));
}
}
// Get the number of candidate sequence slots to allow for each
// runner. This is at least 1 even if the model doesn't support
// batching.
const size_t model_batch_size = std::max(1, config.max_batch_size());
sched->seq_slot_cnt_ = model_batch_size;
if (config.sequence_batching().has_oldest()) {
sched->seq_slot_cnt_ =
config.sequence_batching().oldest().max_candidate_sequences();
}
// Create a batcher for each instance.
RETURN_IF_ERROR(sched->CreateBatchers(new_instances));
// Create background threads that watch for different sequence states.
sched->StartBackgroundThreads();
scheduler->reset(sched.release());
return Status::Success;
}
Status
SequenceBatchScheduler::Update(
const std::vector<std::shared_ptr<TritonModelInstance>>& added_instances,
const std::vector<std::shared_ptr<TritonModelInstance>>& removed_instances)
{
std::lock_guard<std::mutex> lk(mu_);
// Add the new batchers.
RETURN_IF_ERROR(CreateBatchers(added_instances));
// All sequence slots of the removed instances are pending to be removed.
// Track them in 'pending_removal_seq_slots_' and they will be erased once
// they become ready.
for (auto& instance : removed_instances) {
pending_removal_seq_slots_.emplace(
instance.get(),
std::make_pair(batchers_[instance.get()]->SeqSlotCnt(), instance));
}
// Erase pending removal sequence slots that are already at ready.
std::priority_queue<
BatcherSequenceSlot, std::vector<BatcherSequenceSlot>,
BatcherSequenceSlotCompare>
new_ready_batcher_seq_slots;
while (!ready_batcher_seq_slots_.empty()) {
auto& ready_seq_slot = ready_batcher_seq_slots_.top();
if (pending_removal_seq_slots_.find(ready_seq_slot.model_instance_) ==
pending_removal_seq_slots_.end()) {
// The ready slot is not being removed.
new_ready_batcher_seq_slots.push(ready_seq_slot);
} else {
// The ready slot is being removed, erase the slot.
EraseBatcherSequenceSlot(ready_seq_slot);
}
ready_batcher_seq_slots_.pop();
}
ready_batcher_seq_slots_.swap(new_ready_batcher_seq_slots);
return Status::Success;
}
bool
SequenceBatchScheduler::EraseBatcherSequenceSlot(
const BatcherSequenceSlot& seq_slot)
{
// Find the sequence slot from pending removal sequence slots.
auto it = pending_removal_seq_slots_.find(seq_slot.model_instance_);
if (it == pending_removal_seq_slots_.end()) {
// The sequence slot is not pending removal.
return false;
}
LOG_VERBOSE(1) << "Removing slot for batcher "
<< seq_slot.model_instance_->Name() << ", slot "
<< seq_slot.seq_slot_;
// Subtract the number of slots, and erase the batcher if no more slots left.
size_t& remaining_slots = it->second.first;
if (--remaining_slots == 0) {
LOG_VERBOSE(1) << "Removing batcher " << seq_slot.model_instance_->Name();
// Erase batcher.
auto batcher_it = batchers_.find(seq_slot.model_instance_);
auto& pending_removal_batcher = batcher_it->second;
removed_batchers_.emplace_back(std::move(pending_removal_batcher));
batchers_.erase(batcher_it);
// Stop tracking the removed instance.
auto& pending_removal_instance = it->second.second;
removed_instances_.emplace_back(std::move(pending_removal_instance));
// Erase from debugging/testing info.
queue_request_cnts_.erase(seq_slot.model_instance_);
// Erase sequence slot from pending.
pending_removal_seq_slots_.erase(it);
// Notify the clean-up thread.
clean_up_cv_.notify_one();
}
// The sequence slot was pending removal.
return true;
}
Status
SequenceBatchScheduler::CreateBatchers(
const std::vector<std::shared_ptr<TritonModelInstance>>& instances)
{
auto& config = model_->Config();
// Based on the model configuration create input tensors for control
// signals indicating sequence start, sequence continue, and
// sequence not ready.
std::shared_ptr<ControlInputs> start;
std::shared_ptr<ControlInputs> end;
std::shared_ptr<ControlInputs> startend;
std::shared_ptr<ControlInputs> cont;
std::shared_ptr<ControlInputs> notready;
RETURN_IF_ERROR(CreateBooleanControlTensors(
config, &start, &end, &startend, &cont, ¬ready));
bool has_optional_input = false;
for (const auto& input : config.input()) {
if (input.optional()) {
has_optional_input = true;
break;
}
}
// Create one SequenceBatch object for each requested runner. The
// SequenceBatch object has a thread that manages the batch of
// requests.
for (const auto& instance : instances) {
bool init_state;
std::unique_ptr<SequenceBatch> sb;
// Create the SequenceBatch derivative that handles the requested
// scheduling strategy.
if (config.sequence_batching().has_oldest()) {
sb.reset(new OldestSequenceBatch(
this, instance.get(), seq_slot_cnt_, enforce_equal_shape_tensors_,
has_optional_input, start, end, startend, cont, notready,
&init_state));
} else {
sb.reset(new DirectSequenceBatch(
this, instance.get(), seq_slot_cnt_, enforce_equal_shape_tensors_,
has_optional_input, start, end, startend, cont, notready,
&init_state));
}
if (init_state) {
batchers_.emplace(instance.get(), std::move(sb));
// All sequence slots in the batcher are initially ready for a
// new sequence.
for (size_t b = 0; b < seq_slot_cnt_; ++b) {
ready_batcher_seq_slots_.push(
SequenceBatchScheduler::BatcherSequenceSlot(instance.get(), b));
}
}
}
if (batchers_.empty()) {
return Status(
Status::Code::INTERNAL,
"Initialization failed for all sequence-batch scheduler threads");
}
return Status::Success;
}
Status
SequenceBatchScheduler::GenerateInitialStateData(
const inference::ModelSequenceBatching_InitialState& initial_state,
const inference::ModelSequenceBatching_State& state, TritonModel* model)
{
if (initial_state.data_type() != state.data_type()) {
return Status(
Status::Code::INVALID_ARG,
std::string("The data type used for 'initial_state' field of state '") +
state.input_name() + "' does not match the state data type.");
}
if (initial_state.name().size() == 0) {
return Status(
Status::Code::INVALID_ARG,
std::string("Field 'name' must be set when using initial_state for "
"state input '") +
state.input_name() + "'.");
}
auto initial_state_itr = initial_state_.find(state.input_name());
if (initial_state_itr != initial_state_.end()) {
return Status(
Status::Code::INVALID_ARG, std::string("State input name '") +
state.input_name() +
"' specified more than once.");
}
if (initial_state.dims().size() != state.dims().size()) {
return Status(
Status::Code::INVALID_ARG,
std::string(
"Number of dimensions in 'initial_state' doesn't match the size of"
" 'state' dimensions for state input '") +
state.input_name() + "'. " +
std::to_string(initial_state.dims().size()) +
" != " + std::to_string(state.dims().size()));
}
// Check the dimensions to make sure it doesn't have variable-sized dims and
// matches the state description.
auto initial_state_dim = initial_state.dims().begin();
auto state_dim = state.dims().begin();
for (; initial_state_dim != initial_state.dims().end();
initial_state_dim++, state_dim++) {
if (*initial_state_dim == -1) {
return Status(
Status::Code::INVALID_ARG,
std::string("'initial_state' field for state input name '") +
state.input_name() + "' contains variable dimensions.");
} else {
if (*state_dim != -1 && *initial_state_dim != *state_dim) {
return Status(
Status::Code::INVALID_ARG,
std::string("'initial_state' dim for input name '") +
state.input_name() +
"' doesn't match 'state' dim description. " +
std::to_string(*initial_state_dim) +
" != " + std::to_string(*state_dim));
}
}
}
const auto& initial_state_pair = initial_state_.emplace(
std::piecewise_construct, std::forward_as_tuple(state.input_name()),
std::forward_as_tuple(initial_state.name()));
auto& initial_state_data = initial_state_pair.first->second;
// Calculate total memory byte size
auto element_count = triton::common::GetElementCount(initial_state.dims());
size_t dtype_byte_size =
triton::common::GetDataTypeByteSize(initial_state.data_type());
size_t total_byte_size = element_count * dtype_byte_size;
// Custom handling for TYPE_BYTES
if (dtype_byte_size == 0) {
total_byte_size = sizeof(int32_t) * element_count;
}
switch (initial_state.state_data_case()) {
case inference::ModelSequenceBatching_InitialState::StateDataCase::
kZeroData: {
initial_state_data.data_ = std::make_shared<AllocatedMemory>(
total_byte_size, TRITONSERVER_MEMORY_CPU /* memory_type */,
0 /* memory_type_id */);
TRITONSERVER_MemoryType memory_type;
int64_t memory_type_id;
char* data_ptr = initial_state_data.data_->MutableBuffer(
&memory_type, &memory_type_id);
memset(data_ptr, 0, total_byte_size);
break;
}
case inference::ModelSequenceBatching_InitialState::StateDataCase::
kDataFile: {
std::string file_input;
RETURN_IF_ERROR(ReadTextFile(
JoinPath(
{model->LocalizedModelPath(), kInitialStateFolder,
(initial_state.data_file())}),
&file_input));
if (initial_state.data_type() == inference::DataType::TYPE_STRING) {
total_byte_size = file_input.size();
} else if (total_byte_size > file_input.size()) {
return Status(
Status::Code::INVALID_ARG,
"initial_state setting expects " + std::to_string(total_byte_size) +
" bytes, but the data "
"provided from " +
initial_state.data_file() + "only has " +
std::to_string(file_input.size()) + " bytes.");
}
TRITONSERVER_MemoryType memory_type;
int64_t memory_type_id;
initial_state_data.data_ = std::make_shared<AllocatedMemory>(
total_byte_size, TRITONSERVER_MEMORY_CPU /* memory_type */,
0 /* memory_type_id */);
char* data_ptr = initial_state_data.data_->MutableBuffer(
&memory_type, &memory_type_id);
memcpy(data_ptr, file_input.data(), total_byte_size);
break;
}
default:
return Status(
Status::Code::INVALID_ARG,
std::string("initial_state setting expects state'") +
state.input_name() + "' to have state_data set");
}
return Status::Success;
}
SequenceBatchScheduler::~SequenceBatchScheduler()
{
StopBackgroundThreads();
// Release 'batchers_' before other member variables because 'batchers_'
// can access 'this' and we need to make sure the member variables live
// longer than 'batchers_'
batchers_.clear();
removed_batchers_.clear();
}
namespace {
Status
GetBooleanOverrideInputs(
const std::string& tensor_name, const bool support_batching,
const inference::DataType tensor_datatype, const float fp32_false_value,
const float fp32_true_value, const int32_t int32_false_value,
const int32_t int32_true_value, const bool bool_false_value,
const bool bool_true_value,
std::shared_ptr<InferenceRequest::Input>* true_override,
std::shared_ptr<InferenceRequest::Input>* false_override)
{
TRITONSERVER_MemoryType memory_type;
int64_t memory_type_id;
const std::vector<int64_t> tensor_shape{1};
std::vector<int64_t> tensor_shape_with_batch_dim{1};
if (support_batching) {
tensor_shape_with_batch_dim.push_back(1);
}
const size_t size_p = triton::common::GetDataTypeByteSize(tensor_datatype);
auto true_p =
std::make_shared<AllocatedMemory>(size_p, TRITONSERVER_MEMORY_CPU, 0);
char* true_p_ptr = true_p->MutableBuffer(&memory_type, &memory_type_id);
if ((true_p_ptr == nullptr) ||
((memory_type != TRITONSERVER_MEMORY_CPU) &&
(memory_type != TRITONSERVER_MEMORY_CPU_PINNED)) ||
(memory_type_id != 0)) {
return Status(
Status::Code::INTERNAL,
"failed to allocate sequence control signal in CPU memory");
}
auto false_p =
std::make_shared<AllocatedMemory>(size_p, TRITONSERVER_MEMORY_CPU, 0);
char* false_p_ptr = false_p->MutableBuffer(&memory_type, &memory_type_id);
if ((false_p_ptr == nullptr) ||
((memory_type != TRITONSERVER_MEMORY_CPU) &&
(memory_type != TRITONSERVER_MEMORY_CPU_PINNED)) ||
(memory_type_id != 0)) {
return Status(
Status::Code::INTERNAL,
"failed to allocate sequence control signal in CPU memory");
}
if (tensor_datatype == inference::DataType::TYPE_INT32) {
*(reinterpret_cast<int32_t*>(true_p_ptr)) = int32_true_value;
*(reinterpret_cast<int32_t*>(false_p_ptr)) = int32_false_value;
} else if (tensor_datatype == inference::DataType::TYPE_FP32) {
*(reinterpret_cast<float*>(true_p_ptr)) = fp32_true_value;
*(reinterpret_cast<float*>(false_p_ptr)) = fp32_false_value;
} else {
*(reinterpret_cast<bool*>(true_p_ptr)) = bool_true_value;
*(reinterpret_cast<bool*>(false_p_ptr)) = bool_false_value;
}
auto ltrue_override = std::make_shared<InferenceRequest::Input>(
tensor_name, tensor_datatype, tensor_shape);
*ltrue_override->MutableShape() = ltrue_override->OriginalShape();
*ltrue_override->MutableShapeWithBatchDim() = tensor_shape_with_batch_dim;
RETURN_IF_ERROR(ltrue_override->SetData(true_p));
auto lfalse_override = std::make_shared<InferenceRequest::Input>(
tensor_name, tensor_datatype, tensor_shape);
*lfalse_override->MutableShape() = lfalse_override->OriginalShape();
*lfalse_override->MutableShapeWithBatchDim() = tensor_shape_with_batch_dim;
RETURN_IF_ERROR(lfalse_override->SetData(false_p));
*true_override = std::move(ltrue_override);
*false_override = std::move(lfalse_override);
return Status::Success;
}
} // namespace
Status
SequenceBatchScheduler::CreateBooleanControlTensors(
const inference::ModelConfig& config,
std::shared_ptr<ControlInputs>* start_input_overrides,
std::shared_ptr<ControlInputs>* end_input_overrides,
std::shared_ptr<ControlInputs>* startend_input_overrides,
std::shared_ptr<ControlInputs>* continue_input_overrides,
std::shared_ptr<ControlInputs>* notready_input_overrides)
{
// Currently only batch-size 1 requests are supported so only need
// to provide control vectors of that size.
*start_input_overrides = std::make_shared<ControlInputs>();
*end_input_overrides = std::make_shared<ControlInputs>();
*startend_input_overrides = std::make_shared<ControlInputs>();
*continue_input_overrides = std::make_shared<ControlInputs>();
*notready_input_overrides = std::make_shared<ControlInputs>();
std::string tensor_name;
inference::DataType tensor_datatype;
int32_t int32_false_value, int32_true_value;
float fp32_false_value, fp32_true_value;
bool bool_false_value, bool_true_value;
// START, optional
{
RETURN_IF_ERROR(GetBooleanSequenceControlProperties(
config.sequence_batching(), config.name(),
inference::ModelSequenceBatching::Control::CONTROL_SEQUENCE_START,
false /* required */, &tensor_name, &tensor_datatype, &fp32_false_value,
&fp32_true_value, &int32_false_value, &int32_true_value,
&bool_false_value, &bool_true_value));
if (!tensor_name.empty()) {
std::shared_ptr<InferenceRequest::Input> true_override;
std::shared_ptr<InferenceRequest::Input> false_override;
RETURN_IF_ERROR(GetBooleanOverrideInputs(
tensor_name, config.max_batch_size() != 0, tensor_datatype,
fp32_false_value, fp32_true_value, int32_false_value,
int32_true_value, bool_false_value, bool_true_value, &true_override,
&false_override));
(*start_input_overrides)->emplace_back(true_override);
(*end_input_overrides)->emplace_back(false_override);
(*startend_input_overrides)->emplace_back(true_override);
(*continue_input_overrides)->emplace_back(false_override);
(*notready_input_overrides)->emplace_back(false_override);
}
}
// END, optional
{
RETURN_IF_ERROR(GetBooleanSequenceControlProperties(
config.sequence_batching(), config.name(),
inference::ModelSequenceBatching::Control::CONTROL_SEQUENCE_END,
false /* required */, &tensor_name, &tensor_datatype, &fp32_false_value,
&fp32_true_value, &int32_false_value, &int32_true_value,
&bool_false_value, &bool_true_value));
if (!tensor_name.empty()) {
std::shared_ptr<InferenceRequest::Input> true_override;
std::shared_ptr<InferenceRequest::Input> false_override;
RETURN_IF_ERROR(GetBooleanOverrideInputs(
tensor_name, config.max_batch_size() != 0, tensor_datatype,
fp32_false_value, fp32_true_value, int32_false_value,
int32_true_value, bool_false_value, bool_true_value, &true_override,
&false_override));
(*start_input_overrides)->emplace_back(false_override);
(*end_input_overrides)->emplace_back(true_override);
(*startend_input_overrides)->emplace_back(true_override);
(*continue_input_overrides)->emplace_back(false_override);
(*notready_input_overrides)->emplace_back(false_override);
}
}
// READY, optional
{
RETURN_IF_ERROR(GetBooleanSequenceControlProperties(
config.sequence_batching(), config.name(),
inference::ModelSequenceBatching::Control::CONTROL_SEQUENCE_READY,
false /* required */, &tensor_name, &tensor_datatype, &fp32_false_value,
&fp32_true_value, &int32_false_value, &int32_true_value,
&bool_false_value, &bool_true_value));
if (!tensor_name.empty()) {
std::shared_ptr<InferenceRequest::Input> true_override;
std::shared_ptr<InferenceRequest::Input> false_override;
RETURN_IF_ERROR(GetBooleanOverrideInputs(
tensor_name, config.max_batch_size() != 0, tensor_datatype,
fp32_false_value, fp32_true_value, int32_false_value,
int32_true_value, bool_false_value, bool_true_value, &true_override,
&false_override));
(*start_input_overrides)->emplace_back(true_override);
(*end_input_overrides)->emplace_back(true_override);
(*startend_input_overrides)->emplace_back(true_override);
(*continue_input_overrides)->emplace_back(true_override);
(*notready_input_overrides)->emplace_back(false_override);
}
}
return Status::Success;
}
Status
SequenceBatchScheduler::Enqueue(std::unique_ptr<InferenceRequest>& irequest)
{
// Queue timer starts at the beginning of the queueing and
// scheduling process
irequest->CaptureQueueStartNs();
INFER_TRACE_ACTIVITY(
irequest->TraceProxy(), TRITONSERVER_TRACE_QUEUE_START,
irequest->QueueStartNs());
// Record time at the beginning of the batcher queueing
irequest->CaptureBatcherStartNs();
// For now the request must have batch-size 1 since the sequence
// batcher does not yet support requests that are statically
// batched.
if (irequest->BatchSize() > 1) {
return Status(
Status::Code::INVALID_ARG,
"inference request to model '" + irequest->ModelName() +
"' must specify batch-size 1 due to requirements of sequence "
"batcher");
}
// A request must have a correlation ID to be processed correctly by
// this scheduler. A value of 0 (zero) or "" (empty) indicates that the
// request doesn't have a correlation ID.
const InferenceRequest::SequenceId& correlation_id =
irequest->CorrelationId();
if (!correlation_id.InSequence()) {
return Status(
Status::Code::INVALID_ARG,
"inference request to model '" + irequest->ModelName() +
"' must specify a non-zero or non-empty correlation ID");
}
BatcherSequenceSlot* target = nullptr;
const bool seq_start =
((irequest->Flags() & TRITONSERVER_REQUEST_FLAG_SEQUENCE_START) != 0);
const bool seq_end =
((irequest->Flags() & TRITONSERVER_REQUEST_FLAG_SEQUENCE_END) != 0);
bool wake_reaper_thread = false;
std::unique_lock<std::mutex> lock(mu_);
// Check if the request is one of the in-flight sequence (not starting new
// sequence), we consider sequences in backlog as also in-flight.
if (stop_ && seq_start) {
return Status(
Status::Code::UNAVAILABLE,
"Server is stopping, scheduler for model has stopped accepting new "
"inference requests");
}
auto sb_itr = sequence_to_batcherseqslot_map_.find(correlation_id);
auto bl_itr = sequence_to_backlog_map_.find(correlation_id);
// If this request is not starting a new sequence its correlation ID
// should already be known with a target in either a sequence slot
// or in the backlog. If it doesn't then the sequence wasn't started
// correctly or there has been a correlation ID conflict. In either
// case fail this request.
if (!seq_start && (sb_itr == sequence_to_batcherseqslot_map_.end()) &&
(bl_itr == sequence_to_backlog_map_.end())) {
std::string correlation_id_str{""};
if (correlation_id.Type() ==
InferenceRequest::SequenceId::DataType::STRING) {
correlation_id_str = correlation_id.StringValue();
} else if (
correlation_id.Type() ==
InferenceRequest::SequenceId::DataType::UINT64) {
correlation_id_str = std::to_string(correlation_id.UnsignedIntValue());
}
return Status(
Status::Code::INVALID_ARG,
"inference request for sequence " + correlation_id_str + " to model '" +
irequest->ModelName() +
"' must specify the START flag on the first request of the "
"sequence");
}
// Record the timestamp of this request for the correlation ID. The
// reaper thread will check to make sure that
// max_sequence_idle_microseconds value is not exceed for any
// sequence, and if it is it will release the sequence slot (if any)
// allocated to that sequence.
uint64_t now_us = Now<std::chrono::microseconds>();
correlation_id_timestamps_[correlation_id] = now_us;
// If this request starts a new sequence but the correlation ID
// already has an in-progress sequence then that previous sequence
// did not end correctly, or there is a correlation ID conflict. In
// this case we continue the new sequence (in either backlog or
// sequence slot). It is ok for a backlog/slot to have multiple
// starts... as long as it has a single end. The previous sequence
// that was not correctly ended will have its existing requests
// handled and then the new sequence will start.
if (seq_start && ((sb_itr != sequence_to_batcherseqslot_map_.end()) ||
(bl_itr != sequence_to_backlog_map_.end()))) {
LOG_WARNING
<< "sequence " << correlation_id << " for model '"
<< irequest->ModelName()
<< "' has a conflict. The previous sequence did not end before this "
"sequence start. Previous sequence will be terminated early.";
}
// This request already has an assigned slot...
if (sb_itr != sequence_to_batcherseqslot_map_.end()) {
target = &sb_itr->second;
}
// This request already has a queue in the backlog...
else if (bl_itr != sequence_to_backlog_map_.end()) {
LOG_VERBOSE(1) << "Enqueuing CORRID " << correlation_id
<< " into existing backlog: " << irequest->ModelName();
auto& backlog = bl_itr->second;
if (irequest->TimeoutMicroseconds() != 0) {
backlog->expiration_timestamp_ = std::min(
backlog->expiration_timestamp_,
now_us + irequest->TimeoutMicroseconds());
if (backlog->expiration_timestamp_ < timeout_timestamp_) {
timeout_timestamp_ = backlog->expiration_timestamp_;
wake_reaper_thread = true;
}
}
backlog->queue_->emplace_back(std::move(irequest));
// If the sequence is ending then forget correlation ID
// connection to this backlog queue. If another sequence starts
// with the same correlation ID it will be collected in another
// backlog queue.
if (seq_end) {
sequence_to_backlog_map_.erase(bl_itr);
}
// Waking up reaper so it received latest timeout to be waited for,
// shouldn't incur actual reaper work.
if (wake_reaper_thread) {
reaper_cv_.notify_all();
}
return Status::Success;
}
// This request does not have an assigned backlog or sequence
// slot. By the above checks it must be starting. If there is a free
// sequence slot available then assign this sequence to that slot...
else if (!ready_batcher_seq_slots_.empty()) {
target = &sequence_to_batcherseqslot_map_[correlation_id];
*target = ready_batcher_seq_slots_.top();
ready_batcher_seq_slots_.pop();
}
// Last option is to assign this request to the backlog...
else {
LOG_VERBOSE(1) << "Enqueuing CORRID " << correlation_id
<< " into new backlog: " << irequest->ModelName();
auto backlog = std::make_shared<BacklogQueue>();
if (irequest->TimeoutMicroseconds() != 0) {
backlog->expiration_timestamp_ = now_us + irequest->TimeoutMicroseconds();
if (backlog->expiration_timestamp_ < timeout_timestamp_) {
timeout_timestamp_ = backlog->expiration_timestamp_;
wake_reaper_thread = true;
}
}
backlog_queues_.push_back(backlog);
backlog->queue_->emplace_back(std::move(irequest));
if (!seq_end) {
sequence_to_backlog_map_[correlation_id] = std::move(backlog);
}
// Waking up reaper so it received latest timeout to be waited for,
// shouldn't incur actual reaper work.
if (wake_reaper_thread) {
reaper_cv_.notify_all();
}
return Status::Success;
}
// Need to grab the target contents before the erase below since
// that can free it.
const TritonModelInstance* model_instance = target->model_instance_;
const uint32_t seq_slot = target->seq_slot_;
// At this point the request has been assigned to a sequence
// slot. If the sequence is ending then stop tracking the
// correlation.
if (seq_end) {
sequence_to_batcherseqslot_map_.erase(correlation_id);
}
// Enqueue request into batcher and sequence slot. Don't hold the
// lock while enqueuing in a specific batcher.
lock.unlock();
LOG_VERBOSE(1) << "Enqueuing CORRID " << correlation_id << " into batcher "
<< model_instance->Name() << ", sequence slot " << seq_slot
<< ": " << irequest->ModelName();
batchers_[model_instance]->Enqueue(seq_slot, correlation_id, irequest);
return Status::Success;
}
InferenceRequest::SequenceId
SequenceBatchScheduler::ReleaseSequenceSlot(
const BatcherSequenceSlot& batcher_seq_slot,
std::deque<std::unique_ptr<InferenceRequest>>* requests)
{
std::unique_lock<std::mutex> lock(mu_);
// If the instance behind the slot is pending to be removed, do not add the
// slot back to ready and erase it instead.
if (EraseBatcherSequenceSlot(batcher_seq_slot)) {
// The slot is erased.
return InferenceRequest::SequenceId();
}
// If there is a backlogged sequence and it is requested, return it
// so that it can use the newly available sequence slot.
if (!backlog_queues_.empty()) {
auto& backlog = backlog_queues_.front()->queue_;
*requests = std::move(*backlog);
backlog_queues_.pop_front();
if (!requests->empty()) { // should never be empty...
const auto& irequest = requests->back();
const InferenceRequest::SequenceId& correlation_id =
irequest->CorrelationId();
// If the last queue entry is not an END request then the entire
// sequence is not contained in the backlog. In that case must
// update backlog and batcherseqslot maps so that future
// requests get directed to the batcher sequence-slot instead of
// the backlog.
const bool seq_end =
((irequest->Flags() & TRITONSERVER_REQUEST_FLAG_SEQUENCE_END) != 0);
if (!seq_end) {
// Since the correlation ID is being actively collected in the
// backlog, there should not be any in-flight sequences with
// that same correlation ID that have an assigned slot.
if (sequence_to_batcherseqslot_map_.find(correlation_id) !=
sequence_to_batcherseqslot_map_.end()) {
LOG_ERROR << irequest->LogRequest() << "internal: backlog sequence "
<< correlation_id
<< " conflicts with in-flight sequence for model '"
<< irequest->ModelName() << "'";
}
sequence_to_backlog_map_.erase(correlation_id);
sequence_to_batcherseqslot_map_[correlation_id] = batcher_seq_slot;
}
LOG_VERBOSE(1) << irequest->LogRequest() << "CORRID " << correlation_id
<< " reusing batcher "
<< batcher_seq_slot.model_instance_->Name() << ", slot "
<< batcher_seq_slot.seq_slot_ << ": "
<< irequest->ModelName();
return correlation_id;
}
}
// There is no backlogged sequence so just release the batch slot
LOG_VERBOSE(1) << "Freeing slot in batcher "
<< batcher_seq_slot.model_instance_->Name() << ", slot "
<< batcher_seq_slot.seq_slot_;
ready_batcher_seq_slots_.push(batcher_seq_slot);
return InferenceRequest::SequenceId();
}
bool
SequenceBatchScheduler::DelayScheduler(
const TritonModelInstance* model_instance, const size_t cnt,
const size_t total)
{
std::unique_lock<std::mutex> lock(mu_);
queue_request_cnts_[model_instance] = cnt;
size_t seen = 0;
for (auto c : queue_request_cnts_) {
seen += c.second;
}
if (seen < total) {
return true;
}
if (backlog_delay_cnt_ > 0) {
size_t backlog_seen = 0;
for (const auto& q : backlog_queues_) {
backlog_seen += q->queue_->size();
}
if (backlog_seen < backlog_delay_cnt_) {
return true;
}
}
return false;
}
void
SequenceBatchScheduler::StartBackgroundThreads()
{
// Create a reaper thread that watches for idle sequences.
reaper_thread_exit_ = false;
reaper_thread_.reset(
new std::thread([this]() { ReaperThread(10 /* nice */); }));
// Create a clean-up thread that asynchronously erase removed resources.
clean_up_thread_exit_ = false;
clean_up_thread_.reset(
new std::thread([this]() { CleanUpThread(20 /* nice */); }));
}
void
SequenceBatchScheduler::StopBackgroundThreads()
{
// Exit the clean-up thread.
clean_up_thread_exit_ = true;
clean_up_cv_.notify_one();
if (clean_up_thread_ && clean_up_thread_->joinable()) {
clean_up_thread_->join();
}
// Exit the reaper thread.
reaper_thread_exit_ = true;
reaper_cv_.notify_one();
if (reaper_thread_ && reaper_thread_->joinable()) {
reaper_thread_->join();
}
}
void
SequenceBatchScheduler::ReaperThread(const int nice)
{
SetThreadPriority(nice, "sequence-batch reaper" /* thread_name */);
const uint64_t backlog_idle_wait_microseconds = 50 * 1000;
uint64_t idle_timestamp =
Now<std::chrono::microseconds>() + max_sequence_idle_microseconds_;
timeout_timestamp_ = std::numeric_limits<uint64_t>::max();
while (!reaper_thread_exit_) {
uint64_t now_us = Now<std::chrono::microseconds>();
// Reap idle assigned sequence
if (now_us >= idle_timestamp) {
uint64_t wait_microseconds = max_sequence_idle_microseconds_;
BatcherSequenceSlotMap force_end_sequences;
{
std::unique_lock<std::mutex> lock(mu_);
for (auto cid_itr = correlation_id_timestamps_.cbegin();
cid_itr != correlation_id_timestamps_.cend();) {
int64_t remaining_microseconds =
(int64_t)max_sequence_idle_microseconds_ -
(now_us - cid_itr->second);
if (remaining_microseconds > 0) {
wait_microseconds = std::min(
wait_microseconds, (uint64_t)remaining_microseconds + 1);
++cid_itr;
continue;
}
const InferenceRequest::SequenceId& idle_correlation_id =
cid_itr->first;
LOG_VERBOSE(1) << "Reaper: CORRID " << idle_correlation_id
<< ": max sequence idle exceeded";
auto idle_sb_itr =
sequence_to_batcherseqslot_map_.find(idle_correlation_id);
// If the idle correlation ID has an assigned sequence slot,
// then release that assignment so it becomes available for
// another sequence. Release is done by enqueuing and must be
// done outside the lock, so just collect needed info here.
if (idle_sb_itr != sequence_to_batcherseqslot_map_.end()) {