-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathpb_stub.cc
More file actions
2235 lines (2016 loc) · 78.8 KB
/
Copy pathpb_stub.cc
File metadata and controls
2235 lines (2016 loc) · 78.8 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 2021-2026, 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 "pb_stub.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <atomic>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/thread/thread_time.hpp>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <regex>
#include <thread>
#include <unordered_map>
#include "correlation_id.h"
#include "model_loader.h"
#include "pb_error.h"
#include "pb_map.h"
#include "pb_preferred_memory.h"
#include "pb_response_iterator.h"
#include "pb_string.h"
#include "pb_stub_log.h"
#include "pb_utils.h"
#include "response_sender.h"
#include "scoped_defer.h"
#include "shm_manager.h"
#include "triton/common/nvtx.h"
#ifdef _WIN32
#include <signal.h> // SIGINT & SIGTERM
#include <windows.h>
#else
#include <sys/wait.h>
#endif
#ifdef TRITON_ENABLE_GPU
#include <cuda_runtime_api.h>
#endif // TRITON_ENABLE_GPU
namespace py = pybind11;
using namespace pybind11::literals;
namespace bi = boost::interprocess;
#ifndef TRITON_ENABLE_GPU
using cudaStream_t = void*;
#endif
namespace triton { namespace backend { namespace python {
std::atomic<bool> non_graceful_exit = {false};
void
SignalHandler(int signum)
{
// Skip the SIGINT and SIGTERM
}
template <typename PYTYPE>
PYTYPE
PyDefaultArgumentToMutableType(const py::object& argument)
{
// The default argument on Python functions always reference the same copy,
// meaning if the default argument is changed by the function, then it is
// changed for all subsequent calls to the function. Thus, default arguments
// should be limited to basic types (i.e. None). This helper function returns
// an empty expected type, if the argument is None (i.e. default initialized).
// If the argument is neither None nor expected type, an exception is thrown.
if (py::isinstance<py::none>(argument)) {
return PYTYPE();
}
if (py::isinstance<PYTYPE>(argument)) {
return argument;
}
throw PythonBackendException(
std::string("Expect ") + typeid(PYTYPE).name() + ", got " +
std::string(py::str(argument.get_type())));
}
std::string
PyParametersToJSON(const py::dict& parameters)
{
for (const auto& pair : parameters) {
if (!py::isinstance<py::str>(pair.first)) {
throw PythonBackendException(
"Expect parameters keys to have type str, found type " +
std::string(py::str(pair.first.get_type())));
}
if (!py::isinstance<py::bool_>(pair.second) &&
!py::isinstance<py::int_>(pair.second) &&
!py::isinstance<py::str>(pair.second)) {
throw PythonBackendException(
"Expect parameters values to have type bool/int/str, found type " +
std::string(py::str(pair.second.get_type())));
}
}
py::module_ py_json = py::module_::import("json");
std::string parameters_str = py::str(py_json.attr("dumps")(parameters));
return parameters_str;
}
void
AsyncEventFutureDoneCallback(const py::object& py_future)
{
auto stub = Stub::GetOrCreateInstance();
stub->BackgroundFutureDone(py_future);
}
void
Stub::Instantiate(
int64_t shm_growth_size, int64_t shm_default_size,
const std::string& shm_region_name, const std::string& model_path,
const std::string& model_version, const std::string& triton_install_path,
bi::managed_external_buffer::handle_t ipc_control_handle,
const std::string& name, const std::string& python_runtime_model)
{
model_context_.Init(
model_path, python_runtime_model, triton_install_path, model_version);
name_ = name;
health_mutex_ = nullptr;
initialized_ = false;
finalizing_ = false;
stub_to_parent_thread_ = false;
parent_to_stub_thread_ = false;
try {
shm_pool_ = std::make_unique<SharedMemoryManager>(
shm_region_name, shm_default_size, shm_growth_size, false /* create */);
AllocatedSharedMemory<IPCControlShm> ipc_control =
shm_pool_->Load<IPCControlShm>(ipc_control_handle);
ipc_control_ = ipc_control.data_.get();
health_mutex_ = &(ipc_control_->stub_health_mutex);
stub_message_queue_ = MessageQueue<bi::managed_external_buffer::handle_t>::
LoadFromSharedMemory(shm_pool_, ipc_control_->stub_message_queue);
parent_message_queue_ =
MessageQueue<bi::managed_external_buffer::handle_t>::
LoadFromSharedMemory(shm_pool_, ipc_control_->parent_message_queue);
stub_to_parent_mq_ = MessageQueue<bi::managed_external_buffer::handle_t>::
LoadFromSharedMemory(shm_pool_, ipc_control_->stub_to_parent_mq);
parent_to_stub_mq_ = MessageQueue<bi::managed_external_buffer::handle_t>::
LoadFromSharedMemory(shm_pool_, ipc_control_->parent_to_stub_mq);
memory_manager_message_queue_ =
MessageQueue<uint64_t>::LoadFromSharedMemory(
shm_pool_, ipc_control_->memory_manager_message_queue);
// If the Python model is using an execution environment, we need to
// remove the first part of the LD_LIBRARY_PATH before the colon (i.e.
// <Python Shared Lib>:$OLD_LD_LIBRARY_PATH). The <Python Shared Lib>
// section was added before launching the stub process and it may
// interfere with the shared library resolution of other executable and
// binaries.
if (ipc_control_->uses_env) {
#ifndef _WIN32
char* ld_library_path = std::getenv("LD_LIBRARY_PATH");
if (ld_library_path != nullptr) {
std::string ld_library_path_str = ld_library_path;
// If we use an Execute Environment, the path must contain a colon.
size_t find_pos = ld_library_path_str.find(':');
if (find_pos == std::string::npos) {
throw PythonBackendException(
"LD_LIBRARY_PATH must contain a colon when passing an "
"execution environment.");
}
ld_library_path_str = ld_library_path_str.substr(find_pos + 1);
int status = setenv(
"LD_LIBRARY_PATH", const_cast<char*>(ld_library_path_str.c_str()),
1 /* overwrite */);
if (status != 0) {
throw PythonBackendException(
"Failed to correct the LD_LIBRARY_PATH environment in the "
"Python backend stub.");
}
} else {
throw PythonBackendException(
"When using an execution environment, LD_LIBRARY_PATH variable "
"cannot be empty.");
}
#else
throw PythonBackendException(
"Custom execution environments are not currently supported on "
"Windows.");
#endif
}
}
catch (const PythonBackendException& pb_exception) {
LOG_INFO << pb_exception.what() << std::endl;
exit(1);
}
}
std::unique_ptr<MessageQueue<uint64_t>>&
Stub::MemoryManagerQueue()
{
return memory_manager_message_queue_;
}
bool&
Stub::Health()
{
return ipc_control_->stub_health;
}
std::unique_ptr<SharedMemoryManager>&
Stub::SharedMemory()
{
return shm_pool_;
}
std::unique_ptr<IPCMessage>
Stub::PopMessage()
{
bool success = false;
std::unique_ptr<IPCMessage> ipc_message;
bi::managed_external_buffer::handle_t message;
while (!success) {
message = stub_message_queue_->Pop(1000, success);
}
ipc_message = IPCMessage::LoadFromSharedMemory(shm_pool_, message);
return ipc_message;
}
bool
Stub::IsDecoupled()
{
return ipc_control_->decoupled;
}
bool
Stub::RunCommand()
{
NVTX_RANGE(nvtx_, "RunCommand " + name_);
std::unique_ptr<IPCMessage> ipc_message;
{
// Release the GIL lock when waiting for new message. Without this line, the
// other threads in the user's Python model cannot make progress if they
// give up GIL.
py::gil_scoped_release release;
ipc_message = this->PopMessage();
}
switch (ipc_message->Command()) {
case PYTHONSTUB_CommandType::PYTHONSTUB_AutoCompleteRequest: {
// Only run this case when auto complete was requested by
// Triton core.
bool has_exception = false;
std::string error_string;
std::string auto_complete_config;
std::unique_ptr<IPCMessage> auto_complete_response_msg =
IPCMessage::Create(shm_pool_, false /* inline_response */);
auto_complete_response_msg->Command() = PYTHONSTUB_AutoCompleteResponse;
std::unique_ptr<PbString> error_string_shm;
std::unique_ptr<PbString> auto_complete_config_shm;
AllocatedSharedMemory<AutoCompleteResponseShm> auto_complete_response =
shm_pool_->Construct<AutoCompleteResponseShm>();
ScopedDefer receive_autocomplete_finalize(
[this] { stub_message_queue_->Pop(); });
ScopedDefer _([this, &auto_complete_response_msg] {
SendIPCMessage(auto_complete_response_msg);
});
auto_complete_response.data_->response_has_error = false;
auto_complete_response.data_->response_is_error_set = false;
auto_complete_response.data_->response_has_model_config = false;
auto_complete_response_msg->Args() = auto_complete_response.handle_;
try {
AutoCompleteModelConfig(ipc_message->Args(), &auto_complete_config);
}
catch (const PythonBackendException& pb_exception) {
has_exception = true;
error_string = pb_exception.what();
}
catch (const py::error_already_set& error) {
has_exception = true;
error_string = error.what();
}
if (has_exception) {
// Do not delete the region. The region will be deleted by the parent
// process.
shm_pool_->SetDeleteRegion(false);
LOG_INFO << "Failed to initialize Python stub for auto-complete: "
<< error_string;
auto_complete_response.data_->response_has_error = true;
auto_complete_response.data_->response_is_error_set = false;
LOG_IF_EXCEPTION(
error_string_shm = PbString::Create(shm_pool_, error_string));
if (error_string_shm != nullptr) {
auto_complete_response.data_->response_is_error_set = true;
auto_complete_response.data_->response_error =
error_string_shm->ShmHandle();
}
return true; // Terminate the stub process.
} else {
LOG_IF_EXCEPTION(
auto_complete_config_shm =
PbString::Create(shm_pool_, auto_complete_config));
if (auto_complete_config_shm != nullptr) {
auto_complete_response.data_->response_has_model_config = true;
auto_complete_response.data_->response_model_config =
auto_complete_config_shm->ShmHandle();
}
}
} break;
case PYTHONSTUB_CommandType::PYTHONSTUB_InitializeRequest: {
bool has_exception = false;
std::string error_string;
std::unique_ptr<IPCMessage> initialize_response_msg =
IPCMessage::Create(shm_pool_, false /* inline_response */);
initialize_response_msg->Command() = PYTHONSTUB_InitializeResponse;
std::unique_ptr<PbString> error_string_shm;
AllocatedSharedMemory<InitializeResponseShm> initialize_response =
shm_pool_->Construct<InitializeResponseShm>();
// The initialization is done in three steps. First the main process sends
// a message to the stub process asking to begin to initialize the Python
// model. After that is finished stub process sends a message to the
// parent process that the initialization is finished. Finally, the
// parent process sends a message to the stub process asking the stub
// process to release any objects it has held in shared memory.
ScopedDefer receive_initialize_finalize(
[this] { stub_message_queue_->Pop(); });
ScopedDefer _([this, &initialize_response_msg] {
SendIPCMessage(initialize_response_msg);
});
initialize_response.data_->response_has_error = false;
initialize_response.data_->response_is_error_set = false;
initialize_response_msg->Args() = initialize_response.handle_;
try {
Initialize(ipc_message->Args());
}
catch (const PythonBackendException& pb_exception) {
has_exception = true;
error_string = pb_exception.what();
}
catch (const py::error_already_set& error) {
has_exception = true;
error_string = error.what();
}
if (has_exception) {
// Do not delete the region. The region will be deleted by the parent
// process.
shm_pool_->SetDeleteRegion(false);
LOG_INFO << "Failed to initialize Python stub: " << error_string;
initialize_response.data_->response_has_error = true;
initialize_response.data_->response_is_error_set = false;
LOG_IF_EXCEPTION(
error_string_shm = PbString::Create(shm_pool_, error_string));
if (error_string_shm != nullptr) {
initialize_response.data_->response_is_error_set = true;
initialize_response.data_->response_error =
error_string_shm->ShmHandle();
}
return true; // Terminate the stub process.
}
} break;
case PYTHONSTUB_CommandType::PYTHONSTUB_ExecuteRequest: {
AllocatedSharedMemory<char> request_batch =
shm_pool_->Load<char>(ipc_message->Args());
RequestBatch* request_batch_shm_ptr =
reinterpret_cast<RequestBatch*>(request_batch.data_.get());
ProcessRequests(request_batch_shm_ptr);
} break;
case PYTHONSTUB_CommandType::PYTHONSTUB_FinalizeRequest:
ipc_message->Command() = PYTHONSTUB_FinalizeResponse;
// Clean up response_iterator_map_ before sending sending message back to
// the parent process to make sure that the clean up message can be
// processed before the message queue is destroyed.
{
std::lock_guard<std::mutex> lock(response_iterator_map_mu_);
std::unordered_map<void*, std::shared_ptr<ResponseIterator>>().swap(
response_iterator_map_);
}
SendIPCMessage(ipc_message);
return true; // Terminate the stub process
case PYTHONSTUB_CommandType::PYTHONSTUB_LoadGPUBuffers:
try {
LoadGPUBuffers(ipc_message);
}
catch (const PythonBackendException& pb_exception) {
LOG_ERROR
<< "An error occurred while trying to load GPU buffers in the "
"Python backend stub: "
<< pb_exception.what() << std::endl;
}
break;
default:
break;
}
return false;
}
py::module
Stub::StubSetup()
{
py::module sys = py::module_::import("sys");
model_context_.StubSetup(sys);
py::module python_backend_utils =
py::module_::import("triton_python_backend_utils");
py::module c_python_backend_utils =
py::module_::import("c_python_backend_utils");
py::setattr(
python_backend_utils, "TritonError",
c_python_backend_utils.attr("TritonError"));
py::setattr(
python_backend_utils, "TritonModelException",
c_python_backend_utils.attr("TritonModelException"));
py::setattr(
python_backend_utils, "Tensor", c_python_backend_utils.attr("Tensor"));
py::setattr(
python_backend_utils, "InferenceRequest",
c_python_backend_utils.attr("InferenceRequest"));
py::setattr(
python_backend_utils, "InferenceResponse",
c_python_backend_utils.attr("InferenceResponse"));
py::setattr(
python_backend_utils, "Logger", c_python_backend_utils.attr("Logger"));
py::setattr(
python_backend_utils, "PreferredMemory",
c_python_backend_utils.attr("PreferredMemory"));
py::setattr(
python_backend_utils, "TRITONSERVER_MEMORY_GPU",
c_python_backend_utils.attr("TRITONSERVER_MEMORY_GPU"));
py::setattr(
python_backend_utils, "TRITONSERVER_MEMORY_CPU",
c_python_backend_utils.attr("TRITONSERVER_MEMORY_CPU"));
py::setattr(
python_backend_utils, "MetricFamily",
c_python_backend_utils.attr("MetricFamily"));
py::setattr(
python_backend_utils, "load_model",
c_python_backend_utils.attr("load_model"));
py::setattr(
python_backend_utils, "unload_model",
c_python_backend_utils.attr("unload_model"));
py::setattr(
python_backend_utils, "is_model_ready",
c_python_backend_utils.attr("is_model_ready"));
c_python_backend_utils.attr("shared_memory") = py::cast(shm_pool_.get());
deserialize_bytes_ = python_backend_utils.attr("deserialize_bytes_tensor");
serialize_bytes_ = python_backend_utils.attr("serialize_byte_tensor");
return sys;
}
void
Stub::AutoCompleteModelConfig(
bi::managed_external_buffer::handle_t string_handle,
std::string* auto_complete_config)
{
py::module sys = StubSetup();
std::unique_ptr<PbString> pb_string_shm =
PbString::LoadFromSharedMemory(shm_pool_, string_handle);
py::module python_backend_utils =
py::module_::import("triton_python_backend_utils");
py::object model_config =
python_backend_utils.attr("ModelConfig")(pb_string_shm->String());
python_backend_utils.def(
"get_model_dir",
[]() {
auto stub = Stub::GetOrCreateInstance();
return stub->GetModelDir();
},
py::return_value_policy::reference);
if (py::hasattr(sys.attr("TritonPythonModel"), "auto_complete_config")) {
model_config = sys.attr("TritonPythonModel")
.attr("auto_complete_config")(model_config);
}
if (!py::isinstance(model_config, python_backend_utils.attr("ModelConfig"))) {
throw PythonBackendException(
"auto_complete_config function in model '" + name_ +
"' must return a valid pb.ModelConfig object.");
}
py::module json = py::module_::import("json");
(*auto_complete_config) = std::string(
py::str(json.attr("dumps")(model_config.attr("_model_config"))));
}
void
Stub::Initialize(bi::managed_external_buffer::handle_t map_handle)
{
py::module sys = StubSetup();
py::module python_backend_utils =
py::module_::import("triton_python_backend_utils");
py::module c_python_backend_utils =
py::module_::import("c_python_backend_utils");
py::setattr(
python_backend_utils, "TritonError",
c_python_backend_utils.attr("TritonError"));
py::setattr(
python_backend_utils, "TritonModelException",
c_python_backend_utils.attr("TritonModelException"));
py::setattr(
python_backend_utils, "Tensor", c_python_backend_utils.attr("Tensor"));
py::setattr(
python_backend_utils, "InferenceRequest",
c_python_backend_utils.attr("InferenceRequest"));
py::setattr(
python_backend_utils, "InferenceResponse",
c_python_backend_utils.attr("InferenceResponse"));
c_python_backend_utils.attr("shared_memory") = py::cast(shm_pool_.get());
async_event_loop_ = py::none();
background_futures_ = py::set();
py::object TritonPythonModel = sys.attr("TritonPythonModel");
deserialize_bytes_ = python_backend_utils.attr("deserialize_bytes_tensor");
serialize_bytes_ = python_backend_utils.attr("serialize_byte_tensor");
python_backend_utils.def(
"get_model_dir",
[]() {
auto stub = Stub::GetOrCreateInstance();
return stub->GetModelDir();
},
py::return_value_policy::reference);
model_instance_ = TritonPythonModel();
std::unordered_map<std::string, std::string> map;
std::unique_ptr<PbMap> pb_map_shm =
PbMap::LoadFromSharedMemory(shm_pool_, map_handle);
// Get the unordered_map representation of the map in shared memory.
map = pb_map_shm->UnorderedMap();
py::dict model_config_params;
for (const auto& pair : map) {
model_config_params[pair.first.c_str()] = pair.second;
}
LaunchStubToParentQueueMonitor();
LaunchParentToStubQueueMonitor();
// Call initialize if exists.
if (py::hasattr(model_instance_, "initialize")) {
model_instance_.attr("initialize")(model_config_params);
}
// Cache whether is_ready() function defined in the Python model.
ipc_control_->stub_has_user_model_readiness_fn =
py::hasattr(model_instance_, "is_ready");
initialized_ = true;
}
void
Stub::LoadGPUBuffers(std::unique_ptr<IPCMessage>& ipc_message)
{
ScopedDefer load_gpu_buffer_response([this] {
// LoadGPUBuffers must let the parent process know when loading the
// buffers have been finished.
parent_message_queue_->Push(DUMMY_MESSAGE);
gpu_tensors_.clear();
});
AllocatedSharedMemory<GPUBuffersShm> gpu_buffers_handle =
shm_pool_->Load<GPUBuffersShm>(ipc_message->Args());
if (!gpu_buffers_handle.data_->success) {
std::unique_ptr<PbString> error = PbString::LoadFromSharedMemory(
shm_pool_, gpu_buffers_handle.data_->error);
throw PythonBackendException(
"Failed to load GPU buffers: " + error->String());
}
uint64_t gpu_buffer_count = gpu_buffers_handle.data_->buffer_count;
AllocatedSharedMemory<bi::managed_external_buffer::handle_t>
gpu_buffers_handle_shm =
shm_pool_->Load<bi::managed_external_buffer::handle_t>(
gpu_buffers_handle.data_->buffers);
if (gpu_tensors_.size() != gpu_buffer_count) {
throw PythonBackendException(
std::string("GPU buffers size does not match the provided buffers: ") +
std::to_string(gpu_tensors_.size()) +
" != " + std::to_string(gpu_buffer_count));
}
std::vector<std::unique_ptr<PbMemory>> dst_buffers;
for (size_t i = 0; i < gpu_tensors_.size(); i++) {
std::unique_ptr<PbMemory> dst_buffer = PbMemory::LoadFromSharedMemory(
shm_pool_, gpu_buffers_handle_shm.data_.get()[i],
true /* open_cuda_handle */);
dst_buffers.emplace_back(std::move(dst_buffer));
}
for (size_t i = 0; i < gpu_tensors_.size(); i++) {
std::shared_ptr<PbTensor>& src_buffer = gpu_tensors_[i];
PbMemory::CopyBuffer(dst_buffers[i], src_buffer->Memory());
}
}
py::list
Stub::LoadRequestsFromSharedMemory(RequestBatch* request_batch_shm_ptr)
{
uint32_t batch_size = request_batch_shm_ptr->batch_size;
py::list py_request_list;
if (batch_size == 0) {
return py_request_list;
}
bi::managed_external_buffer::handle_t* request_shm_handle =
reinterpret_cast<bi::managed_external_buffer::handle_t*>(
reinterpret_cast<char*>(request_batch_shm_ptr) +
sizeof(RequestBatch));
for (size_t i = 0; i < batch_size; i++) {
std::shared_ptr<InferRequest> infer_request =
InferRequest::LoadFromSharedMemory(
shm_pool_, request_shm_handle[i], true /* open_cuda_handle */,
&ipc_control_->decoupled /* is_model_decoupled */);
py_request_list.append(infer_request);
}
return py_request_list;
}
void
Stub::ProcessRequests(RequestBatch* request_batch_shm_ptr)
{
py::list py_request_list =
LoadRequestsFromSharedMemory(request_batch_shm_ptr);
std::unique_ptr<IPCMessage> execute_response;
std::optional<AllocatedSharedMemory<char>> response_batch;
bool has_exception = false;
std::string error_string;
std::unique_ptr<PbString> error_string_shm;
std::string err_message;
ScopedDefer execute_finalize([this] { stub_message_queue_->Pop(); });
ScopedDefer _(
[this, &execute_response] { SendIPCMessage(execute_response); });
py::object execute_return;
py::object coroutine_return;
try {
if (!py::hasattr(model_instance_, "execute")) {
std::string message = "Python model " + model_context_.PythonModelPath() +
" does not implement `execute` method.";
throw PythonBackendException(message);
}
{
NVTX_RANGE(nvtx_, "PyExecute " + name_);
execute_return = model_instance_.attr("execute")(py_request_list);
bool is_coroutine = py::module::import("asyncio")
.attr("iscoroutine")(execute_return)
.cast<bool>();
if (is_coroutine) {
if (IsDecoupled()) {
// Do not wait for async decoupled execute to return.
RunCoroutine(execute_return, true /* in_background */);
} else {
coroutine_return =
RunCoroutine(execute_return, false /* in_background */);
ProcessReturnedResponses(
py_request_list, coroutine_return, response_batch);
}
} else {
ProcessReturnedResponses(
py_request_list, execute_return, response_batch);
}
}
}
catch (const PythonBackendException& pb_exception) {
has_exception = true;
error_string = pb_exception.what();
}
catch (const py::error_already_set& error) {
has_exception = true;
error_string = error.what();
}
if (has_exception) {
err_message = std::string(
"Failed to process the request(s) for model '" + name_ +
"', message: ") +
error_string;
LOG_ERROR << err_message.c_str();
if (!response_batch) {
response_batch = shm_pool_->Construct<char>(
sizeof(ResponseBatch) + sizeof(IPCMessageShm));
}
ResponseBatch* response_batch_shm_ptr = reinterpret_cast<ResponseBatch*>(
response_batch.value().data_.get() + sizeof(IPCMessageShm));
// The backend will clean up the response factory if there is an error in
// the response batch. For decoupled mode, it is necessary to handle cases
// where the response sender should have already cleaned up, ensuring the
// backend does not delete the response factory again during error handling.
if (IsDecoupled()) {
for (py::handle py_request : py_request_list) {
InferRequest* request = py_request.cast<InferRequest*>();
if (request->GetResponseSender()->IsClosed()) {
response_batch_shm_ptr->is_response_factory_deleted = true;
}
}
}
response_batch_shm_ptr->has_error = true;
error_string_shm = PbString::Create(shm_pool_, err_message);
response_batch_shm_ptr->error = error_string_shm->ShmHandle();
response_batch_shm_ptr->is_error_set = true;
response_batch_shm_ptr->batch_size = 0;
// Once the error is sent to the backend, the backend is supposed to close
// all response factories if not already closed, so closing all response
// senders if not already closed to prevent the model from sending more
// responses after the factories are closed.
for (py::handle py_request : py_request_list) {
InferRequest* request = py_request.cast<InferRequest*>();
request->GetResponseSender()->Close();
}
} else {
if (!response_batch) {
response_batch = shm_pool_->Construct<char>(
sizeof(ResponseBatch) + sizeof(IPCMessageShm));
ResponseBatch* response_batch_shm_ptr = reinterpret_cast<ResponseBatch*>(
response_batch.value().data_.get() + sizeof(IPCMessageShm));
response_batch_shm_ptr->batch_size = 0;
}
ResponseBatch* response_batch_shm_ptr = reinterpret_cast<ResponseBatch*>(
response_batch.value().data_.get() + sizeof(IPCMessageShm));
response_batch_shm_ptr->has_error = false;
response_batch_shm_ptr->is_error_set = false;
}
execute_response = IPCMessage::Create(
reinterpret_cast<IPCMessageShm*>(response_batch.value().data_.get()),
response_batch.value().handle_);
execute_response->Args() =
response_batch.value().handle_ + sizeof(IPCMessageShm);
execute_response->InlineResponse() = false;
execute_response->Command() = PYTHONSTUB_ExecuteResponse;
_.Complete();
execute_finalize.Complete();
}
void
Stub::ProcessResponse(InferResponse* response)
{
response->SaveToSharedMemory(shm_pool_, false /* copy_gpu */);
for (auto& output_tensor : response->OutputTensors()) {
if (!output_tensor->IsCPU()) {
gpu_tensors_.push_back(output_tensor);
}
}
}
void
Stub::ProcessReturnedResponses(
py::list py_requests, py::object py_responses_obj,
std::optional<AllocatedSharedMemory<char>>& response_batch)
{
// Return if there is nothing to process.
if (py::isinstance<py::none>(py_responses_obj)) {
return;
}
// Only non-decoupled may return responses.
if (IsDecoupled()) {
throw PythonBackendException(
"Python model '" + name_ +
"' is using the decoupled mode and the execute function must return "
"None.");
}
// Check responses is a list.
if (!py::isinstance<py::list>(py_responses_obj)) {
throw PythonBackendException(
"Expected a list in the execute return, found type '" +
std::string(py::str(py_responses_obj.get_type())) + "'.");
}
py::list py_responses = py_responses_obj;
// Responses and requests length must match.
size_t requests_size = py::len(py_requests);
size_t responses_size = py::len(py_responses);
if (requests_size != responses_size) {
throw PythonBackendException(
"Number of InferenceResponse objects do not match the number of "
"InferenceRequest objects. InferenceRequest(s) size is:" +
std::to_string(requests_size) + ", and InferenceResponse(s) size is:" +
std::to_string(responses_size) + "\n");
}
for (size_t i = 0; i < responses_size; i++) {
if (!py::isinstance<py::none>(py_responses[i])) {
InferRequest* request = py_requests[i].cast<InferRequest*>();
// Response must be None if rescheduled.
if (request->ReleaseFlags() == TRITONSERVER_REQUEST_RELEASE_RESCHEDULE) {
throw PythonBackendException(
"Expected a None object in the execute function return list for "
"reschduled request, found type '" +
std::string(py::str(py_responses[i].get_type())) + "'.");
}
// Send the response.
if (!py::isinstance<InferResponse>(py_responses[i])) {
throw PythonBackendException(
"Expected an 'InferenceResponse' object in the execute function "
"return list, found type '" +
std::string(py::str(py_responses[i].get_type())) + "'.");
}
InferResponse* response = py_responses[i].cast<InferResponse*>();
try {
request->GetResponseSender()->UpdateStateAndCounters(
response, TRITONSERVER_RESPONSE_COMPLETE_FINAL);
}
catch (const PythonBackendException& pb_exception) {
// Handle the exception here to catch the error when there's a response
// returned from `execute()`.
if (request->GetResponseSender()->IsClosed()) {
response_batch = std::move(shm_pool_->Construct<char>(
sizeof(ResponseBatch) + sizeof(IPCMessageShm)));
ResponseBatch* response_batch_shm_ptr =
reinterpret_cast<ResponseBatch*>(
response_batch.value().data_.get() + sizeof(IPCMessageShm));
response_batch_shm_ptr->batch_size = 0;
response_batch_shm_ptr->is_response_factory_deleted = true;
}
throw pb_exception;
}
}
}
// Return all the created responses using response_batch. The reason
// that both of the paths are available is that sending the responses
// using response_batch is faster than using `response_sender`.
response_batch = std::move(shm_pool_->Construct<char>(
sizeof(IPCMessageShm) +
requests_size * sizeof(bi::managed_external_buffer::handle_t) +
sizeof(ResponseBatch)));
ResponseBatch* response_batch_shm_ptr = reinterpret_cast<ResponseBatch*>(
response_batch.value().data_.get() + sizeof(IPCMessageShm));
bi::managed_external_buffer::handle_t* responses_shm_handle =
reinterpret_cast<bi::managed_external_buffer::handle_t*>(
response_batch.value().data_.get() + sizeof(ResponseBatch) +
sizeof(IPCMessageShm));
for (size_t i = 0; i < responses_size; i++) {
// Check the return type of execute function.
InferRequest* infer_request = py_requests[i].cast<InferRequest*>();
InferResponse* infer_response = py_responses[i].cast<InferResponse*>();
if (!py::isinstance<py::none>(py_responses[i])) {
infer_response->PruneOutputTensors(infer_request->RequestedOutputNames());
ProcessResponse(infer_response);
responses_shm_handle[i] = infer_response->ShmHandle();
} else {
responses_shm_handle[i] = 0;
}
}
response_batch_shm_ptr->batch_size = requests_size;
}
py::object
Stub::GetAsyncEventLoop()
{
if (py::isinstance<py::none>(async_event_loop_)) {
// Create the event loop if not already.
py::module asyncio = py::module_::import("asyncio");
async_event_loop_ = asyncio.attr("new_event_loop")();
asyncio.attr("set_event_loop")(async_event_loop_);
py::object py_thread =
py::module_::import("threading")
.attr("Thread")(
"target"_a = async_event_loop_.attr("run_forever"),
"daemon"_a = true);
py_thread.attr("start")();
}
return async_event_loop_;
}
py::object
Stub::RunCoroutine(py::object coroutine, bool in_background)
{
py::object loop = GetAsyncEventLoop();
py::object py_future = py::module_::import("asyncio").attr(
"run_coroutine_threadsafe")(coroutine, loop);
if (in_background) {
py_future.attr("add_done_callback")(
py::module_::import("c_python_backend_utils")
.attr("async_event_future_done_callback"));
background_futures_.attr("add")(py_future);
return py::none();
}
return py_future.attr("result")();
}
void
Stub::BackgroundFutureDone(const py::object& py_future)
{
ScopedDefer _([this, &py_future] {
// Remove future from background
try {
background_futures_.attr("remove")(py_future);
}
catch (const py::error_already_set& error) {
LOG_ERROR << "Cannot remove future from background; " << error.what();
}
});
// TODO: Why using `py_future.result()` with error hangs on exit?
try {
py::object exception = py_future.attr("exception")();
if (!py::isinstance<py::none>(exception)) {
std::string err_msg = "";
py::object traceback = py::module_::import("traceback")
.attr("TracebackException")
.attr("from_exception")(exception)
.attr("format")();
for (py::handle line : traceback) {
err_msg += py::str(line);
}
LOG_ERROR << err_msg;
}
}
catch (const PythonBackendException& pb_exception) {
LOG_ERROR << pb_exception.what();
}
catch (const py::error_already_set& error) {
LOG_ERROR << error.what();
}
}
void
Stub::UpdateHealth()
{
bi::scoped_lock<bi::interprocess_mutex> lock(*health_mutex_);
ipc_control_->stub_health = true;
}
void
Stub::Finalize()
{
finalizing_ = true;
if (initialized_) {
// Stop async event loop if created.
if (!py::isinstance<py::none>(async_event_loop_)) {
async_event_loop_.attr("stop")();
}
// Call finalize if exists.
if (py::hasattr(model_instance_, "finalize")) {