// Control data structure for the communication between the Python stub and the// main stub.structIPCControlShm{boolstub_health;boolparent_health;booluses_env;booldecoupled;bi::interprocess_mutexparent_health_mutex;bi::interprocess_mutexstub_health_mutex;bi::managed_external_buffer::handle_tstub_message_queue;bi::managed_external_buffer::handle_tparent_message_queue;bi::managed_external_buffer::handle_tstub_to_parent_mq;bi::managed_external_buffer::handle_tparent_to_stub_mq;bi::managed_external_buffer::handle_tmemory_manager_message_queue;};
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_releaserelease;ipc_message=this->PopMessage();}switch(ipc_message->Command()){casePYTHONSTUB_CommandType::PYTHONSTUB_InitializeRequest://...}
#include<pybind11/embed.h>#include<pybind11/numpy.h>#include<pybind11/stl.h>namespacepy=pybind11;voidStub::Initialize(bi::managed_external_buffer::handle_tmap_handle){py::modulesys=StubSetup();py::modulepython_backend_utils=py::module_::import("triton_python_backend_utils");py::modulec_python_backend_utils=py::module_::import("c_python_backend_utils");// ......c_python_backend_utils.attr("shared_memory")=py::cast(shm_pool_.get());async_event_loop_=py::none();background_futures_=py::set();// 创建一个TritonPythonModel对象,这个对象是用户实现的python类,用户需要在类中实现initialize、execute、finalizer等函数py::objectTritonPythonModel=sys.attr("TritonPythonModel");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::dictmodel_config_params;for(constauto&pair:map){model_config_params[pair.first.c_str()]=pair.second;}// Call initialize if exists.// 调用用户实现的initialize函数if(py::hasattr(model_instance_,"initialize")){model_instance_.attr("initialize")(model_config_params);}}