forked from triton-inference-server/python_backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse_sender.cc
More file actions
289 lines (251 loc) · 9.97 KB
/
Copy pathresponse_sender.cc
File metadata and controls
289 lines (251 loc) · 9.97 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
// Copyright 2022-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 "response_sender.h"
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include "pb_stub.h"
#include "pb_stub_utils.h"
#include "scoped_defer.h"
namespace triton { namespace backend { namespace python {
void
CheckResponseSenderArguments(
const std::shared_ptr<InferResponse>& response, const uint32_t flags)
{
// Check the correctness of the provided flags.
if (flags != TRITONSERVER_RESPONSE_COMPLETE_FINAL && flags != 0) {
throw PythonBackendException(
"Unable to send response. Unsupported flag provided.");
}
if (flags == 0 && response == nullptr) {
throw PythonBackendException(
"Inference Response object must be provided when the response flags is "
"set to zero.");
}
}
ResponseSender::ResponseSender(
intptr_t request_address, intptr_t response_factory_address,
bool const* is_decoupled,
const std::set<std::string>& requested_output_names,
std::unique_ptr<SharedMemoryManager>& shm_pool,
const std::shared_ptr<PbCancel>& pb_cancel)
: request_address_(request_address),
response_factory_address_(response_factory_address),
is_decoupled_(is_decoupled),
requested_output_names_(requested_output_names), shm_pool_(shm_pool),
pb_cancel_(pb_cancel), closed_(false), number_of_response_sent_(0),
response_factory_deleted_(false)
{
}
ResponseSender::~ResponseSender()
{
DeleteResponseFactory();
}
void
ResponseSender::UpdateStateAndCounters(
InferResponse* response, const uint32_t flags)
{
if (is_decoupled_ == nullptr) {
// TODO: Can a model access the response sender on a BLS infer request?
throw PythonBackendException(
"Unable to send response. Response sender has no reference to the "
"decoupled state of the model.");
}
bool is_decoupled = *is_decoupled_;
std::lock_guard<std::mutex> lk(mu_);
if (!is_decoupled) {
if (response != nullptr && number_of_response_sent_ > 0) {
throw PythonBackendException(
"Unable to send response. Non-decoupled model cannot send more than "
"one response.");
}
if (response == nullptr && flags == TRITONSERVER_RESPONSE_COMPLETE_FINAL &&
number_of_response_sent_ == 0) {
throw PythonBackendException(
"Unable to send response. Non-decoupled model cannot send complete "
"final before sending a response.");
}
}
if (closed_) {
throw PythonBackendException(
"Unable to send response. Response sender has been closed.");
}
if (flags == TRITONSERVER_RESPONSE_COMPLETE_FINAL) {
response_factory_deleted_.exchange(true);
closed_ = true;
}
number_of_response_sent_++;
}
void
ResponseSender::Send(
std::shared_ptr<InferResponse> infer_response, const uint32_t flags)
{
// Release the GIL. This avoids a potential deadlock situation in the parent
// process, where every thread in the thread pool is indirectly waiting for a
// function in the stub process that acquires the GIL. Meanwhile, the current
// thread, which holds the GIL, is also waiting for the parent side to have
// the next available thread to pick up the job during resource contention.
py::gil_scoped_release release;
CheckResponseSenderArguments(infer_response, flags);
UpdateStateAndCounters(infer_response.get(), flags);
if (infer_response) {
infer_response->PruneOutputTensors(requested_output_names_);
}
auto stub = Stub::GetOrCreateInstance();
AllocatedSharedMemory<ResponseSendMessage> response_send_message =
shm_pool_->Construct<ResponseSendMessage>(
1 /* count */, true /* aligned */);
if (infer_response) {
infer_response->SaveToSharedMemory(shm_pool_, false /* copy_gpu */);
}
ResponseSendMessage* send_message_payload = response_send_message.data_.get();
new (&(send_message_payload->mu)) bi::interprocess_mutex;
new (&(send_message_payload->cv)) bi::interprocess_condition;
send_message_payload->is_stub_turn = false;
send_message_payload->request_address = request_address_;
send_message_payload->response_factory_address = response_factory_address_;
if (infer_response) {
send_message_payload->response = infer_response->ShmHandle();
} else {
send_message_payload->response = 0;
}
send_message_payload->has_error = false;
send_message_payload->is_error_set = false;
send_message_payload->flags = flags;
std::unique_ptr<IPCMessage> ipc_message =
IPCMessage::Create(shm_pool_, false /* inline_response */);
ipc_message->Command() = PYTHONSTUB_ResponseSend;
ipc_message->Args() = response_send_message.handle_;
ScopedDefer _([send_message_payload] {
{
bi::scoped_lock<bi::interprocess_mutex> guard{send_message_payload->mu};
send_message_payload->is_stub_turn = false;
send_message_payload->cv.notify_all();
}
});
{
bi::scoped_lock<bi::interprocess_mutex> guard{send_message_payload->mu};
// The server will destruct the response factory if the final flag is set.
if (flags == TRITONSERVER_RESPONSE_COMPLETE_FINAL) {
response_factory_deleted_.exchange(true);
}
stub->SendIPCUtilsMessage(ipc_message);
while (!send_message_payload->is_stub_turn) {
send_message_payload->cv.wait(guard);
}
}
bool has_gpu_output = false;
std::vector<std::shared_ptr<PbTensor>> gpu_tensors;
if (infer_response) {
for (auto& tensor : infer_response->OutputTensors()) {
if (!tensor->IsCPU()) {
has_gpu_output = true;
gpu_tensors.push_back(tensor);
}
}
}
if (has_gpu_output) {
ScopedDefer _([send_message_payload] {
bi::scoped_lock<bi::interprocess_mutex> guard{send_message_payload->mu};
send_message_payload->is_stub_turn = false;
send_message_payload->cv.notify_one();
while (!send_message_payload->is_stub_turn) {
// Wait for the stub process to send the response and populate error
// message if any.
send_message_payload->cv.wait(guard);
}
});
AllocatedSharedMemory<GPUBuffersShm> gpu_buffers_handle =
shm_pool_->Load<GPUBuffersShm>(
send_message_payload->gpu_buffers_handle);
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());
}
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);
uint64_t gpu_buffer_count = gpu_buffers_handle.data_->buffer_count;
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));
std::shared_ptr<PbTensor>& src_buffer = gpu_tensors[i];
PbMemory::CopyBuffer(dst_buffers[i], src_buffer->Memory());
}
}
if (send_message_payload->has_error) {
if (send_message_payload->is_error_set) {
std::unique_ptr<PbString> error = PbString::LoadFromSharedMemory(
shm_pool_, send_message_payload->error);
throw PythonBackendException(error->String());
} else {
throw PythonBackendException(
"An error occurred while sending a response.");
}
}
}
bool
ResponseSender::IsCancelled()
{
return pb_cancel_->IsCancelled();
}
bool
ResponseSender::IsClosed()
{
std::lock_guard<std::mutex> lk(mu_);
return closed_;
}
void
ResponseSender::Close()
{
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
response_factory_deleted_.exchange(true);
}
void
ResponseSender::DeleteResponseFactory()
{
bool already_deleted = response_factory_deleted_.exchange(true);
if (!already_deleted) {
auto stub = Stub::GetOrCreateInstance();
stub->EnqueueCleanupId(
reinterpret_cast<void*>(response_factory_address_),
PYTHONSTUB_DecoupledResponseFactoryCleanup);
}
}
}}} // namespace triton::backend::python