ATLAS Offline Software
Loading...
Searching...
No Matches
TritonTool.cxx
Go to the documentation of this file.
1// Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
2
3// Local include(s).
5
6// Project include(s).
9
10// External include(s).
11#include <grpc_client.h>
12#include <grpc_service.pb.h>
13
14// System include(s).
15#include <cassert>
16#include <chrono>
17#include <cstring>
18#include <string>
19#include <thread>
20#include <vector>
21
23namespace tc = triton::client;
24
26#define TRITON_CHECK(EXP) \
27 do { \
28 const tc::Error err = EXP; \
29 if (!err.IsOk()) { \
30 ATH_MSG_ERROR("Failed to execute: " << #EXP \
31 << ": " \
32 << err); \
33 return StatusCode::FAILURE; \
34 } \
35 } while (false)
36
37namespace AthInfer {
38
40template <typename T>
42template <>
43struct TritonDType<float> {
44 static constexpr const char* value = "FP32";
45};
46template <>
47struct TritonDType<int64_t> {
48 static constexpr const char* value = "INT64";
49};
50
52
53 // Inherit the constructor(s) from AthMessaging
55
56 StatusCode getClient(tc::InferenceServerGrpcClient*& client,
57 const std::string& url, int port, bool useSSL) const {
58
59 thread_local std::unique_ptr<tc::InferenceServerGrpcClient> threadClient;
60 if (!threadClient) {
61
62 const std::string urlAndPort =
63 url + ":" + std::to_string(port); // always use the gRPC port
64
65 constexpr bool verbose = false;
66 TRITON_CHECK(tc::InferenceServerGrpcClient::Create(
67 &threadClient, urlAndPort, verbose, useSSL));
68
69 ATH_MSG_INFO("Triton client created for url: " << urlAndPort);
70 }
71 client = threadClient.get();
72
73 return StatusCode::SUCCESS;
74 }
75
76 tc::Error checkServerHealth(tc::InferenceServerGrpcClient& client) const {
77
78 tc::Headers httpHeaders;
79 bool live = false;
80 tc::Error err =
81 client.IsServerLive(&live, httpHeaders, m_options->client_timeout_);
82 if (!err.IsOk()) {
83 return err;
84 }
85 if (!live) {
86 return tc::Error("Triton server is not live");
87 }
88
89 bool serverReady = false;
90 err = client.IsServerReady(&serverReady, httpHeaders,
91 m_options->client_timeout_);
92 if (!err.IsOk()) {
93 return err;
94 }
95 if (!serverReady) {
96 return tc::Error("Triton server is not ready");
97 }
98
99 bool modelReady = false;
100 err = client.IsModelReady(&modelReady, m_options->model_name_,
101 m_options->model_version_, httpHeaders,
102 m_options->client_timeout_);
103 if (!err.IsOk()) {
104 return err;
105 }
106 if (!modelReady) {
107 return tc::Error("Triton model " + m_options->model_name_ + " is not ready");
108 }
109
110 return tc::Error::Success;
111 }
112
113 void waitBeforeRetry(const int retryDelayMs) const {
114 if (retryDelayMs > 0) {
115 std::this_thread::sleep_for(std::chrono::milliseconds(retryDelayMs));
116 }
117 }
118
119 StatusCode runInference(
120 tc::InferenceServerGrpcClient& client,
121 const std::vector<tc::InferInput*>& rawInputs,
122 const int maxRetries, const int retryDelayMs,
123 std::shared_ptr<tc::InferResult>& results) const {
124
125 tc::Headers httpHeaders;
126 grpc_compression_algorithm compressionAlgorithm =
127 grpc_compression_algorithm::GRPC_COMPRESS_NONE;
128
129 tc::Error err;
130 for (int attempt = 0; attempt <= maxRetries; ++attempt) {
131 if (m_parentAsyncAlg == nullptr) {
132 tc::InferResult* rawResultPtr = nullptr;
133 err = client.Infer(&rawResultPtr, *m_options, rawInputs, {},
134 httpHeaders, compressionAlgorithm);
135 if (err.IsOk() && rawResultPtr != nullptr) {
136 results.reset(rawResultPtr);
137 err = results->RequestStatus();
138 } else if (err.IsOk()) {
139 err = tc::Error("Triton synchronous inference returned no result");
140 }
141 } else {
142 using Promise_t = boost::fibers::promise<tc::InferResult*>;
143 using Future_t = boost::fibers::future<tc::InferResult*>;
144 Promise_t promise{};
145 Future_t future = promise.get_future();
146 auto callback = [&promise](tc::InferResult* resultPtr) {
147 promise.set_value(resultPtr);
148 };
149 err = client.AsyncInfer(callback, *m_options, rawInputs, {},
150 httpHeaders, compressionAlgorithm);
151 if (err.IsOk()) {
152 results.reset(future.get());
153 ATH_CHECK(m_parentAsyncAlg->restoreAfterSuspend());
154 if (results != nullptr) {
155 err = results->RequestStatus();
156 } else {
157 err = tc::Error("Triton asynchronous inference returned no "
158 "result");
159 }
160 }
161 }
162
163 if (err.IsOk()) {
164 return StatusCode::SUCCESS;
165 }
166
167 if (attempt == maxRetries) {
168 ATH_MSG_ERROR("Triton inference failed after " << (attempt + 1)
169 << " attempt(s): "
170 << err);
171 return StatusCode::FAILURE;
172 }
173
174 ATH_MSG_WARNING("Triton inference attempt " << (attempt + 1)
175 << " failed: " << err
176 << "; retrying");
177 waitBeforeRetry(retryDelayMs);
178 }
179
180 return StatusCode::FAILURE;
181 }
182
183 template <typename T>
184 StatusCode prepareInput(
185 const std::string& name, const std::vector<int64_t>& shape,
186 const std::vector<T>& data,
187 std::vector<std::unique_ptr<tc::InferInput>>& inputs) const {
188
189 const char* dtype = TritonDType<T>::value;
190 tc::InferInput* rawInputPtr = nullptr;
191
192 // create the InferInput object with the predefined name, shape, and data
193 // type.
194 TRITON_CHECK(tc::InferInput::Create(&rawInputPtr, name, shape, dtype));
195 assert(rawInputPtr != nullptr);
196
197 // Append tensor values for this input from a byte array.
198 // Note: The vector is not copied and so it must not be modified or
199 // destroyed until this input is no longer needed (that is until the Infer()
200 // call(s) that use the input have completed). Multiple calls can be made to
201 // this API to keep adding tensor data for this input. The data will be
202 // delivered in the order it was added.
203 std::unique_ptr<tc::InferInput> input{rawInputPtr};
204 TRITON_CHECK(input->AppendRaw(reinterpret_cast<const uint8_t*>(data.data()),
205 data.size() * sizeof(T)));
206
207 inputs.push_back(std::move(input));
208 return StatusCode::SUCCESS;
209 }
210
211 template <typename T>
212 StatusCode extractOutput(const std::string& name,
213 const tc::InferResult& result,
214 std::vector<T>& outputVec) const {
215
216 const uint8_t* rawData = nullptr;
217 size_t size = 0;
218
219 // Get access to the buffer holding raw results of specified output returned
220 // by the server. Note: the buffer is owned by InferResult instance. Users
221 // can copy out the data if required to extend the lifetime.
222 TRITON_CHECK(result.RawData(name, &rawData, &size));
223
224 outputVec.resize(size / sizeof(T));
225 std::memcpy(outputVec.data(), rawData, size);
226 return StatusCode::SUCCESS;
227 }
228
230 std::unique_ptr<tc::InferOptions> m_options;
231
232}; // struct TritonTool::Impl
233
234TritonTool::TritonTool(const std::string& type, const std::string& name,
235 const IInterface* parent)
236 : base_class(type, name, parent) {}
237
238TritonTool::~TritonTool() = default;
239
241
242 // Set up the implementation object.
243 m_impl = std::make_unique<Impl>(name() + "::Impl");
244 m_impl->m_options = std::make_unique<tc::InferOptions>(m_modelName.value());
245 m_impl->m_options->model_version_ = m_modelVersion;
246 m_impl->m_options->client_timeout_ = m_clientTimeout;
247
248 // Figure out if parent is an AthAsynchronousAlgorithm, and set pointer if it
249 // is
250 const IAlgTool* p = dynamic_cast<const IAlgTool*>(this);
251 // Follow chain of parents up until we hit one that can't be converted to an
252 // IAlgTool
253 const IInterface* myParent = nullptr;
254 while (p != nullptr) {
255 myParent = p->parent();
256 p = dynamic_cast<const IAlgTool*>(myParent);
257 }
258 // If this ultimate ancestor can be converted to an AthAsynchronousAlgorithm,
259 // set the member variable
260 m_impl->m_parentAsyncAlg =
261 dynamic_cast<const AthAsynchronousAlgorithm*>(myParent);
262 if (m_impl->m_parentAsyncAlg != nullptr) {
264 "Owned by an AthAsynchronousAlgorithm, using asynchronous inference");
265 } else {
267 "Not owned by an AthAsynchronousAlgorithm, not using asynchronous "
268 "inference");
269 }
270
271 // Make sure already during initialization that a client can be created.
272 tc::InferenceServerGrpcClient* dummyClient = nullptr;
273 ATH_CHECK(m_impl->getClient(dummyClient, m_url, m_port, m_useSSL));
274
275 // Check that the server is live and ready, and that the model is ready.
276 tc::Error err = m_impl->checkServerHealth(*dummyClient);
277 if (!err.IsOk()) {
278 ATH_MSG_ERROR("Failed to check server health: " << err);
279 return StatusCode::FAILURE;
280 }
281
282 // Return gracefully.
283 return StatusCode::SUCCESS;
284}
285
287 OutputDataMap& outputData) const {
288
289 assert(m_impl);
290
291 // Create the tensor for the input data.
292 // Use shared_ptr to manage the memory of the InferInput objects.
293 std::vector<std::unique_ptr<tc::InferInput>> inputs;
294 inputs.reserve(inputData.size());
295
296 for (auto& [inputName, inputInfo] : inputData) {
297
298 const std::vector<int64_t>& inputShape = inputInfo.first;
299 const DataVariant& variant = inputInfo.second;
300
301 ATH_CHECK(std::visit(
302 [&](const auto& dataVec) {
303 using T = std::decay_t<decltype(dataVec[0])>;
304 return m_impl->prepareInput<T>(inputName, inputShape, dataVec,
305 inputs);
306 },
307 variant));
308 }
309
310 // construct raw points for inference
311 std::vector<tc::InferInput*> rawInputs;
312 for (auto& input : inputs) {
313 rawInputs.push_back(input.get());
314 }
315
316 // Get the triton client object.
317 tc::InferenceServerGrpcClient* client = nullptr;
318 ATH_CHECK(m_impl->getClient(client, m_url, m_port, m_useSSL));
319 assert(client != nullptr);
320
321 // perform the inference.
322 std::shared_ptr<tc::InferResult> results;
323 const int maxRetriesValue = m_maxRetries.value();
324 const int retryDelayMsValue = m_retryDelayMs.value();
325 const int maxRetries = maxRetriesValue < 0 ? 0 : maxRetriesValue;
326 const int retryDelayMs = retryDelayMsValue < 0 ? 0 : retryDelayMsValue;
327 ATH_CHECK(
328 m_impl->runInference(*client, rawInputs, maxRetries, retryDelayMs,
329 results));
330 assert(results != nullptr);
331
332 // Get the result of the inference.
333 for (auto& [outputName, outputInfo] : outputData) {
334
335 DataVariant& variant = outputInfo.second;
336
337 ATH_CHECK(std::visit(
338 [&](auto& dataVec) {
339 using T = std::decay_t<decltype(dataVec[0])>;
340 return m_impl->extractOutput<T>(outputName, *results, dataVec);
341 },
342 variant));
343 }
344
345 // Return gracefully.
346 return StatusCode::SUCCESS;
347}
348
349void TritonTool::print() const {}
350
351} // namespace AthInfer
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_ERROR(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_WARNING(x)
static Double_t tc
size_t size() const
Number of registered mappings.
#define TRITON_CHECK(EXP)
Shorthand for the Triton client namespace.
An algorithm that can be suspended while work is offloaded to an accelerator.
virtual StatusCode inference(InputDataMap &inputData, OutputDataMap &outputData) const override final
Run inference with multiple inputs and multiple outputs.
StringProperty m_modelVersion
Definition TritonTool.h:49
virtual StatusCode initialize() override
Initialize the tool.
virtual void print() const override
Print the tool's properties and configuration.
FloatProperty m_clientTimeout
Definition TritonTool.h:51
virtual ~TritonTool()
Destructor.
IntegerProperty m_maxRetries
Definition TritonTool.h:57
StringProperty m_modelName
Definition TritonTool.h:47
IntegerProperty m_retryDelayMs
Definition TritonTool.h:60
StringProperty m_url
Definition TritonTool.h:54
TritonTool(const std::string &type, const std::string &name, const IInterface *parent)
Constructor.
IntegerProperty m_port
Definition TritonTool.h:48
BooleanProperty m_useSSL
Definition TritonTool.h:55
std::unique_ptr< Impl > m_impl
Pointer to the implementation details.
Definition TritonTool.h:69
AthMessaging(IMessageSvc *msgSvc, const std::string &name)
Constructor.
bool verbose
Definition hcg.cxx:75
std::map< std::string, InferenceData > OutputDataMap
std::variant< std::vector< float >, std::vector< int64_t > > DataVariant
std::map< std::string, InferenceData > InputDataMap
static constexpr const char * value
static constexpr const char * value
DType traits for Triton.
StatusCode prepareInput(const std::string &name, const std::vector< int64_t > &shape, const std::vector< T > &data, std::vector< std::unique_ptr< tc::InferInput > > &inputs) const
StatusCode runInference(tc::InferenceServerGrpcClient &client, const std::vector< tc::InferInput * > &rawInputs, const int maxRetries, const int retryDelayMs, std::shared_ptr< tc::InferResult > &results) const
tc::Error checkServerHealth(tc::InferenceServerGrpcClient &client) const
const AthAsynchronousAlgorithm * m_parentAsyncAlg
void waitBeforeRetry(const int retryDelayMs) const
std::unique_ptr< tc::InferOptions > m_options
StatusCode extractOutput(const std::string &name, const tc::InferResult &result, std::vector< T > &outputVec) const
AthMessaging(IMessageSvc *msgSvc, const std::string &name)
Constructor.
StatusCode getClient(tc::InferenceServerGrpcClient *&client, const std::string &url, int port, bool useSSL) const