-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathtritonserver_pybind.cc
More file actions
2276 lines (2083 loc) · 82.1 KB
/
Copy pathtritonserver_pybind.cc
File metadata and controls
2276 lines (2083 loc) · 82.1 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 2023-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 <pybind11/functional.h>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <triton/core/tritonserver.h>
#include <iostream>
#include <mutex>
// This binding is merely used to map Triton C API into Python equivalent,
// and therefore, the naming will be the same as the one used in corresponding
// sections. However, there are a few exceptions to better transit to Python:
// Structs:
// * Triton structs are encapsulated in a thin wrapper to isolate raw pointer
// operations which is not supported in pure Python. A thin 'PyWrapper' base
// class is defined with common utilities
// * Trivial getters and setters are grouped to be a Python class property.
// However, this creates asymmetry that some APIs are called like function
// while some like member variables. So I am open to expose getter / setter
// if it may be more intuitive.
// * The wrapper is only served as communication between Python and C, it will
// be unwrapped when control reaches C API and the C struct will be wrapped
// when control reaches Python side. Python binding user should respect the
// "ownership" and lifetime of the wrapper in the same way as described in
// the C API. Python binding user must not assume the same C struct will
// always be referred through the same wrapper object.
// Enums:
// * In C API, the enum values are prefixed by the enum name. The Python
// equivalent is an enum class and thus the prefix is removed to avoid
// duplication, i.e. Python user may specify a value by
// 'TRITONSERVER_ResponseCompleteFlag.FINAL'.
// Functions / Callbacks:
// * Output parameters are converted to return value. APIs that return an error
// will be thrown as an exception. The same applies to callbacks.
// ** Note that in the C API, the inference response may carry an error object
// that represent an inference failure. The equivalent Python API will raise
// the corresponding exception if the response contains error object.
// * The function parameters and return values are exposed in Python style,
// for example, object pointer becomes py::object, C array and length
// condenses into Python array.
namespace py = pybind11;
namespace triton { namespace core { namespace python {
// Macro used by PyWrapper
#define DISALLOW_COPY(TypeName) TypeName(const TypeName&) = delete;
#define DISALLOW_ASSIGN(TypeName) void operator=(const TypeName&) = delete;
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
DISALLOW_COPY(TypeName) \
DISALLOW_ASSIGN(TypeName)
#define DESTRUCTOR_WITH_LOG(TypeName, DeleteFunction) \
~TypeName() \
{ \
if (owned_ && triton_object_) { \
auto err__ = (DeleteFunction(triton_object_)); \
if (err__) { \
std::shared_ptr<TRITONSERVER_Error> managed_err( \
err__, TRITONSERVER_ErrorDelete); \
py::print(TRITONSERVER_ErrorMessage(err__)); \
} \
}}
// base exception for all Triton error code
struct TritonError : public std::runtime_error {
explicit TritonError(const std::string& what) : std::runtime_error(what) {}
};
// triton::core::python exceptions map 1:1 to TRITONSERVER_Error_Code.
struct UnknownError : public TritonError {
explicit UnknownError(const std::string& what) : TritonError(what) {}
};
struct InternalError : public TritonError {
explicit InternalError(const std::string& what) : TritonError(what) {}
};
struct NotFoundError : public TritonError {
explicit NotFoundError(const std::string& what) : TritonError(what) {}
};
struct InvalidArgumentError : public TritonError {
explicit InvalidArgumentError(const std::string& what) : TritonError(what) {}
};
struct UnavailableError : public TritonError {
explicit UnavailableError(const std::string& what) : TritonError(what) {}
};
struct UnsupportedError : public TritonError {
explicit UnsupportedError(const std::string& what) : TritonError(what) {}
};
struct AlreadyExistsError : public TritonError {
explicit AlreadyExistsError(const std::string& what) : TritonError(what) {}
};
TRITONSERVER_Error*
CreateTRITONSERVER_ErrorFrom(const py::error_already_set& ex)
{
// Reserved lookup to get Python type of the exceptions,
// 'TRITONSERVER_ERROR_UNKNOWN' is the fallback error code.
// static auto uk =
// py::module::import("triton_bindings").attr("UnknownError");
static auto it = py::module::import("triton_bindings").attr("InternalError");
static auto nf = py::module::import("triton_bindings").attr("NotFoundError");
static auto ia =
py::module::import("triton_bindings").attr("InvalidArgumentError");
static auto ua =
py::module::import("triton_bindings").attr("UnavailableError");
static auto us =
py::module::import("triton_bindings").attr("UnsupportedError");
static auto ae =
py::module::import("triton_bindings").attr("AlreadyExistsError");
TRITONSERVER_Error_Code code = TRITONSERVER_ERROR_UNKNOWN;
if (ex.matches(it.ptr())) {
code = TRITONSERVER_ERROR_INTERNAL;
} else if (ex.matches(nf.ptr())) {
code = TRITONSERVER_ERROR_NOT_FOUND;
} else if (ex.matches(ia.ptr())) {
code = TRITONSERVER_ERROR_INVALID_ARG;
} else if (ex.matches(ua.ptr())) {
code = TRITONSERVER_ERROR_UNAVAILABLE;
} else if (ex.matches(us.ptr())) {
code = TRITONSERVER_ERROR_UNSUPPORTED;
} else if (ex.matches(ae.ptr())) {
code = TRITONSERVER_ERROR_ALREADY_EXISTS;
}
return TRITONSERVER_ErrorNew(code, ex.what());
}
void
ThrowIfError(TRITONSERVER_Error* err)
{
if (err == nullptr) {
return;
}
std::shared_ptr<TRITONSERVER_Error> managed_err(
err, TRITONSERVER_ErrorDelete);
std::string msg = TRITONSERVER_ErrorMessage(err);
switch (TRITONSERVER_ErrorCode(err)) {
case TRITONSERVER_ERROR_INTERNAL:
throw InternalError(std::move(msg));
case TRITONSERVER_ERROR_NOT_FOUND:
throw NotFoundError(std::move(msg));
case TRITONSERVER_ERROR_INVALID_ARG:
throw InvalidArgumentError(std::move(msg));
case TRITONSERVER_ERROR_UNAVAILABLE:
throw UnavailableError(std::move(msg));
case TRITONSERVER_ERROR_UNSUPPORTED:
throw UnsupportedError(std::move(msg));
case TRITONSERVER_ERROR_ALREADY_EXISTS:
throw AlreadyExistsError(std::move(msg));
default:
throw UnknownError(std::move(msg));
}
}
template <typename TritonStruct>
class PyWrapper {
public:
explicit PyWrapper(TritonStruct* triton_object, bool owned)
: triton_object_(triton_object), owned_(owned)
{
}
PyWrapper() = default;
// Destructor will be defined per specialization for now as a few
// Triton object delete functions have different signatures, which
// requires a function wrapper to generalize the destructor.
// Use internally to get the pointer of the underlying Triton object
TritonStruct* Ptr() { return triton_object_; }
DISALLOW_COPY_AND_ASSIGN(PyWrapper);
protected:
TritonStruct* triton_object_{nullptr};
bool owned_{false};
};
class PyParameter : public PyWrapper<struct TRITONSERVER_Parameter> {
public:
explicit PyParameter(struct TRITONSERVER_Parameter* p, const bool owned)
: PyWrapper(p, owned)
{
}
PyParameter(const char* name, const std::string& val)
: PyWrapper(
TRITONSERVER_ParameterNew(
name, TRITONSERVER_PARAMETER_STRING, val.c_str()),
true)
{
}
PyParameter(const char* name, int64_t val)
: PyWrapper(
TRITONSERVER_ParameterNew(name, TRITONSERVER_PARAMETER_INT, &val),
true)
{
}
PyParameter(const char* name, double val)
: PyWrapper(
TRITONSERVER_ParameterNew(
name, TRITONSERVER_PARAMETER_DOUBLE, &val),
true)
{
}
PyParameter(const char* name, bool val)
: PyWrapper(
TRITONSERVER_ParameterNew(name, TRITONSERVER_PARAMETER_BOOL, &val),
true)
{
}
PyParameter(const char* name, const void* byte_ptr, uint64_t size)
: PyWrapper(TRITONSERVER_ParameterBytesNew(name, byte_ptr, size), true)
{
}
~PyParameter()
{
if (owned_ && triton_object_) {
TRITONSERVER_ParameterDelete(triton_object_);
}
}
};
class PyBufferAttributes
: public PyWrapper<struct TRITONSERVER_BufferAttributes> {
public:
DESTRUCTOR_WITH_LOG(PyBufferAttributes, TRITONSERVER_BufferAttributesDelete);
PyBufferAttributes()
{
ThrowIfError(TRITONSERVER_BufferAttributesNew(&triton_object_));
owned_ = true;
}
explicit PyBufferAttributes(
struct TRITONSERVER_BufferAttributes* ba, const bool owned)
: PyWrapper(ba, owned)
{
}
void SetMemoryTypeId(int64_t memory_type_id)
{
ThrowIfError(TRITONSERVER_BufferAttributesSetMemoryTypeId(
triton_object_, memory_type_id));
}
void SetMemoryType(TRITONSERVER_MemoryType memory_type)
{
ThrowIfError(TRITONSERVER_BufferAttributesSetMemoryType(
triton_object_, memory_type));
}
void SetCudaIpcHandle(uintptr_t cuda_ipc_handle)
{
ThrowIfError(TRITONSERVER_BufferAttributesSetCudaIpcHandle(
triton_object_, reinterpret_cast<void*>(cuda_ipc_handle)));
}
void SetByteSize(size_t byte_size)
{
ThrowIfError(
TRITONSERVER_BufferAttributesSetByteSize(triton_object_, byte_size));
}
// Define methods to get buffer attribute fields
int64_t MemoryTypeId()
{
int64_t memory_type_id = 0;
ThrowIfError(TRITONSERVER_BufferAttributesMemoryTypeId(
triton_object_, &memory_type_id));
return memory_type_id;
}
TRITONSERVER_MemoryType MemoryType()
{
TRITONSERVER_MemoryType memory_type = TRITONSERVER_MEMORY_CPU;
ThrowIfError(
TRITONSERVER_BufferAttributesMemoryType(triton_object_, &memory_type));
return memory_type;
}
uintptr_t CudaIpcHandle()
{
void* cuda_ipc_handle = nullptr;
ThrowIfError(TRITONSERVER_BufferAttributesCudaIpcHandle(
triton_object_, &cuda_ipc_handle));
return reinterpret_cast<uintptr_t>(cuda_ipc_handle);
}
size_t ByteSize()
{
size_t byte_size;
ThrowIfError(
TRITONSERVER_BufferAttributesByteSize(triton_object_, &byte_size));
return byte_size;
}
};
class PyResponseAllocator
: public PyWrapper<struct TRITONSERVER_ResponseAllocator> {
public:
DESTRUCTOR_WITH_LOG(
PyResponseAllocator, TRITONSERVER_ResponseAllocatorDelete);
// Callback resource that holds Python user provided buffer and
// Triton C callback wrappers. This struct will be used for both
// 'allocator_userp' and 'buffer_userp'
struct CallbackResource {
CallbackResource(const py::object& a, const py::object& uo)
: allocator(a), user_object(uo)
{
}
// Storing the py::object of PyResponseAllocator to have convenient access
// to callbacks.
py::object allocator;
py::object user_object;
};
using AllocFn = std::function<
std::tuple<uintptr_t, py::object, TRITONSERVER_MemoryType, int64_t>(
py::object, std::string, size_t, TRITONSERVER_MemoryType, int64_t,
py::object)>;
using ReleaseFn = std::function<void(
py::object, uintptr_t, py::object, size_t, TRITONSERVER_MemoryType,
int64_t)>;
using StartFn = std::function<void(py::object, py::object)>;
// size as input, optional?
using QueryFn = std::function<std::tuple<TRITONSERVER_MemoryType, int64_t>(
py::object, py::object, std::string, std::optional<size_t>,
TRITONSERVER_MemoryType, int64_t)>;
using BufferAttributesFn = std::function<py::object(
py::object, std::string, py::object, py::object, py::object)>;
PyResponseAllocator(AllocFn alloc, ReleaseFn release)
: alloc_fn_(alloc), release_fn_(release)
{
ThrowIfError(TRITONSERVER_ResponseAllocatorNew(
&triton_object_, PyTritonAllocFn, PyTritonReleaseFn, nullptr));
owned_ = true;
}
PyResponseAllocator(AllocFn alloc, ReleaseFn release, StartFn start)
: alloc_fn_(alloc), release_fn_(release), start_fn_(start)
{
ThrowIfError(TRITONSERVER_ResponseAllocatorNew(
&triton_object_, PyTritonAllocFn, PyTritonReleaseFn, PyTritonStartFn));
owned_ = true;
}
// Below implements the Triton callbacks, note that when registering the
// callbacks in Triton, an wrapped 'CallbackResource' must be used to bridge
// the gap between the Python API and C API.
static TRITONSERVER_Error* PyTritonAllocFn(
struct TRITONSERVER_ResponseAllocator* allocator, const char* tensor_name,
size_t byte_size, TRITONSERVER_MemoryType memory_type,
int64_t memory_type_id, void* userp, void** buffer, void** buffer_userp,
TRITONSERVER_MemoryType* actual_memory_type,
int64_t* actual_memory_type_id)
{
py::gil_scoped_acquire gil;
struct TRITONSERVER_Error* err = nullptr;
auto cr = reinterpret_cast<CallbackResource*>(userp);
try {
auto res = cr->allocator.cast<PyResponseAllocator*>()->alloc_fn_(
cr->allocator, tensor_name, byte_size, memory_type, memory_type_id,
cr->user_object);
*buffer = reinterpret_cast<void*>(std::get<0>(res));
{
// In C API usage, its typical to allocate user object within the
// callback and place the release logic in release callback. The same
// logic can't trivially ported to Python as user object is scoped,
// therefore the binding needs to wrap the object to ensure the user
// object will not be garbage collected until after release callback.
*buffer_userp = new CallbackResource(cr->allocator, std::get<1>(res));
}
*actual_memory_type = std::get<2>(res);
*actual_memory_type_id = std::get<3>(res);
}
catch (py::error_already_set& ex) {
err = CreateTRITONSERVER_ErrorFrom(ex);
}
return err;
}
static TRITONSERVER_Error* PyTritonReleaseFn(
struct TRITONSERVER_ResponseAllocator* allocator, void* buffer,
void* buffer_userp, size_t byte_size, TRITONSERVER_MemoryType memory_type,
int64_t memory_type_id)
{
py::gil_scoped_acquire gil;
struct TRITONSERVER_Error* err = nullptr;
auto cr = reinterpret_cast<CallbackResource*>(buffer_userp);
try {
cr->allocator.cast<PyResponseAllocator*>()->release_fn_(
cr->allocator, reinterpret_cast<uintptr_t>(buffer), cr->user_object,
byte_size, memory_type, memory_type_id);
}
catch (py::error_already_set& ex) {
err = CreateTRITONSERVER_ErrorFrom(ex);
}
// Done with CallbackResource associated with this buffer
delete cr;
return err;
}
static TRITONSERVER_Error* PyTritonStartFn(
struct TRITONSERVER_ResponseAllocator* allocator, void* userp)
{
py::gil_scoped_acquire gil;
struct TRITONSERVER_Error* err = nullptr;
auto cr = reinterpret_cast<CallbackResource*>(userp);
try {
cr->allocator.cast<PyResponseAllocator*>()->start_fn_(
cr->allocator, cr->user_object);
}
catch (py::error_already_set& ex) {
err = CreateTRITONSERVER_ErrorFrom(ex);
}
return err;
}
static TRITONSERVER_Error* PyTritonQueryFn(
struct TRITONSERVER_ResponseAllocator* allocator, void* userp,
const char* tensor_name, size_t* byte_size,
TRITONSERVER_MemoryType* memory_type, int64_t* memory_type_id)
{
py::gil_scoped_acquire gil;
struct TRITONSERVER_Error* err = nullptr;
auto cr = reinterpret_cast<CallbackResource*>(userp);
try {
std::optional<size_t> bs;
if (byte_size) {
bs = *byte_size;
}
auto res = cr->allocator.cast<PyResponseAllocator*>()->query_fn_(
cr->allocator, cr->user_object, tensor_name, bs, *memory_type,
*memory_type_id);
*memory_type = std::get<0>(res);
*memory_type_id = std::get<1>(res);
}
catch (py::error_already_set& ex) {
err = CreateTRITONSERVER_ErrorFrom(ex);
}
return err;
}
static TRITONSERVER_Error* PyTritonBufferAttributesFn(
struct TRITONSERVER_ResponseAllocator* allocator, const char* tensor_name,
struct TRITONSERVER_BufferAttributes* buffer_attributes, void* userp,
void* buffer_userp)
{
py::gil_scoped_acquire gil;
struct TRITONSERVER_Error* err = nullptr;
auto cr = reinterpret_cast<CallbackResource*>(userp);
auto bcr = reinterpret_cast<CallbackResource*>(buffer_userp);
PyBufferAttributes pba{buffer_attributes, false /* owned_ */};
try {
// Python version of BufferAttributes callback has return value
// to be the filled buffer attributes. The callback implementation
// should modify the passed PyBufferAttributes object and return it.
// However, the implementation may construct new PyBufferAttributes
// which requires additional checking to properly return the attributes
// through C API.
auto res =
cr->allocator.cast<PyResponseAllocator*>()->buffer_attributes_fn_(
cr->allocator, tensor_name,
py::cast(pba, py::return_value_policy::reference),
cr->user_object, bcr->user_object);
// Copy if 'res' is new object, otherwise the attributes have been set.
auto res_pba = res.cast<PyBufferAttributes*>();
if (res_pba->Ptr() != buffer_attributes) {
pba.SetMemoryTypeId(res_pba->MemoryTypeId());
pba.SetMemoryType(res_pba->MemoryType());
pba.SetCudaIpcHandle(res_pba->CudaIpcHandle());
pba.SetByteSize(res_pba->ByteSize());
}
}
catch (py::error_already_set& ex) {
err = CreateTRITONSERVER_ErrorFrom(ex);
}
return err;
}
void SetBufferAttributesFunction(BufferAttributesFn baf)
{
buffer_attributes_fn_ = baf;
ThrowIfError(TRITONSERVER_ResponseAllocatorSetBufferAttributesFunction(
triton_object_, PyTritonBufferAttributesFn));
}
void SetQueryFunction(QueryFn qf)
{
query_fn_ = qf;
ThrowIfError(TRITONSERVER_ResponseAllocatorSetQueryFunction(
triton_object_, PyTritonQueryFn));
}
private:
AllocFn alloc_fn_{nullptr};
ReleaseFn release_fn_{nullptr};
StartFn start_fn_{nullptr};
QueryFn query_fn_{nullptr};
BufferAttributesFn buffer_attributes_fn_{nullptr};
};
class PyMessage : public PyWrapper<struct TRITONSERVER_Message> {
public:
DESTRUCTOR_WITH_LOG(PyMessage, TRITONSERVER_MessageDelete);
PyMessage(const std::string& serialized_json)
{
ThrowIfError(TRITONSERVER_MessageNewFromSerializedJson(
&triton_object_, serialized_json.c_str(), serialized_json.size()));
owned_ = true;
}
explicit PyMessage(struct TRITONSERVER_Message* m, const bool owned)
: PyWrapper(m, owned)
{
}
std::string SerializeToJson()
{
const char* base = nullptr;
size_t byte_size = 0;
ThrowIfError(
TRITONSERVER_MessageSerializeToJson(triton_object_, &base, &byte_size));
return std::string(base, byte_size);
}
};
class PyMetrics : public PyWrapper<struct TRITONSERVER_Metrics> {
public:
DESTRUCTOR_WITH_LOG(PyMetrics, TRITONSERVER_MetricsDelete);
explicit PyMetrics(struct TRITONSERVER_Metrics* metrics, bool owned)
: PyWrapper(metrics, owned)
{
}
std::string Formatted(TRITONSERVER_MetricFormat format)
{
const char* base = nullptr;
size_t byte_size = 0;
ThrowIfError(TRITONSERVER_MetricsFormatted(
triton_object_, format, &base, &byte_size));
return std::string(base, byte_size);
}
};
class PyTrace : public PyWrapper<struct TRITONSERVER_InferenceTrace> {
public:
DESTRUCTOR_WITH_LOG(PyTrace, TRITONSERVER_InferenceTraceDelete);
using TimestampActivityFn = std::function<void(
py::object, TRITONSERVER_InferenceTraceActivity, uint64_t, py::object)>;
using TensorActivityFn = std::function<void(
py::object, TRITONSERVER_InferenceTraceActivity, std::string,
TRITONSERVER_DataType, uintptr_t, size_t, py::array_t<int64_t>,
TRITONSERVER_MemoryType, int64_t, py::object)>;
using ReleaseFn = std::function<void(std::shared_ptr<PyTrace>, py::object)>;
struct CallbackResource {
CallbackResource(
TimestampActivityFn ts, TensorActivityFn t, ReleaseFn r,
const py::object& uo)
: timestamp_fn(ts), tensor_fn(t), release_fn(r), user_object(uo)
{
}
TimestampActivityFn timestamp_fn{nullptr};
TensorActivityFn tensor_fn{nullptr};
ReleaseFn release_fn{nullptr};
py::object user_object;
// The trace API will use the same 'trace_userp' for all traces associated
// with the request, and because there is no guarantee that the root trace
// must be released last, need to track all trace seen / released to
// determine whether this CallbackResource may be released.
std::set<uintptr_t> seen_traces;
};
// Use internally when interacting with C APIs that takes ownership,
// this function will also release the ownership of the callback resource
// because once the ownership is transferred, the callback resource
// will be accessed in the callback pipeline and should not be tied to the
// PyWrapper's lifecycle. The callback resource will be released in the
// Triton C callback wrapper.
struct TRITONSERVER_InferenceTrace* Release()
{
owned_ = false;
callback_resource_.release();
return triton_object_;
}
PyTrace(
int level, uint64_t parent_id, TimestampActivityFn timestamp,
ReleaseFn release, const py::object& user_object)
: callback_resource_(
new CallbackResource(timestamp, nullptr, release, user_object))
{
ThrowIfError(TRITONSERVER_InferenceTraceNew(
&triton_object_, static_cast<TRITONSERVER_InferenceTraceLevel>(level),
parent_id, PyTritonTraceTimestampActivityFn, PyTritonTraceRelease,
callback_resource_.get()));
owned_ = true;
}
PyTrace(
int level, uint64_t parent_id, TimestampActivityFn timestamp,
TensorActivityFn tensor, ReleaseFn release, const py::object& user_object)
: callback_resource_(
new CallbackResource(timestamp, tensor, release, user_object))
{
ThrowIfError(TRITONSERVER_InferenceTraceTensorNew(
&triton_object_, static_cast<TRITONSERVER_InferenceTraceLevel>(level),
parent_id, PyTritonTraceTimestampActivityFn,
PyTritonTraceTensorActivityFn, PyTritonTraceRelease,
callback_resource_.get()));
owned_ = true;
}
explicit PyTrace(struct TRITONSERVER_InferenceTrace* t, const bool owned)
: PyWrapper(t, owned)
{
}
CallbackResource* ReleaseCallbackResource()
{
return callback_resource_.release();
}
uint64_t Id()
{
uint64_t val = 0;
ThrowIfError(TRITONSERVER_InferenceTraceId(triton_object_, &val));
return val;
}
uint64_t ParentId()
{
uint64_t val = 0;
ThrowIfError(TRITONSERVER_InferenceTraceParentId(triton_object_, &val));
return val;
}
std::string ModelName()
{
const char* val = nullptr;
ThrowIfError(TRITONSERVER_InferenceTraceModelName(triton_object_, &val));
return val;
}
int64_t ModelVersion()
{
int64_t val = 0;
ThrowIfError(TRITONSERVER_InferenceTraceModelVersion(triton_object_, &val));
return val;
}
std::string RequestId()
{
const char* val = nullptr;
ThrowIfError(TRITONSERVER_InferenceTraceRequestId(triton_object_, &val));
return val;
}
// Below implements the Triton callbacks, note that when registering the
// callbacks in Triton, an wrapped 'CallbackResource' must be used to bridge
// the gap between the Python API and C API.
static void PyTritonTraceTimestampActivityFn(
struct TRITONSERVER_InferenceTrace* trace,
TRITONSERVER_InferenceTraceActivity activity, uint64_t timestamp_ns,
void* userp)
{
py::gil_scoped_acquire gil;
// Note that 'trace' associated with the activity is not necessary the
// root trace captured in Callback Resource, so need to always wrap 'trace'
// in PyTrace for the Python callback to interact with the correct trace.
PyTrace pt(trace, false /* owned */);
auto cr = reinterpret_cast<CallbackResource*>(userp);
cr->seen_traces.insert(reinterpret_cast<uintptr_t>(trace));
cr->timestamp_fn(
py::cast(pt, py::return_value_policy::reference), activity,
timestamp_ns, cr->user_object);
}
static void PyTritonTraceTensorActivityFn(
struct TRITONSERVER_InferenceTrace* trace,
TRITONSERVER_InferenceTraceActivity activity, const char* name,
TRITONSERVER_DataType datatype, const void* base, size_t byte_size,
const int64_t* shape, uint64_t dim_count,
TRITONSERVER_MemoryType memory_type, int64_t memory_type_id, void* userp)
{
py::gil_scoped_acquire gil;
// See 'PyTritonTraceTimestampActivityFn' for 'pt' explanation.
PyTrace pt(trace, false /* owned */);
auto cr = reinterpret_cast<CallbackResource*>(userp);
cr->seen_traces.insert(reinterpret_cast<uintptr_t>(trace));
cr->tensor_fn(
py::cast(pt, py::return_value_policy::reference), activity, name,
datatype, reinterpret_cast<uintptr_t>(base), byte_size,
py::array_t<int64_t>(dim_count, shape), memory_type, memory_type_id,
cr->user_object);
}
static void PyTritonTraceRelease(
struct TRITONSERVER_InferenceTrace* trace, void* userp)
{
py::gil_scoped_acquire gil;
// See 'PyTritonTraceTimestampActivityFn' for 'pt' explanation.
// wrap in shared_ptr to transfer ownership to Python
auto managed_pt = std::make_shared<PyTrace>(trace, true /* owned */);
auto cr = reinterpret_cast<CallbackResource*>(userp);
cr->release_fn(managed_pt, cr->user_object);
cr->seen_traces.erase(reinterpret_cast<uintptr_t>(trace));
if (cr->seen_traces.empty()) {
delete cr;
}
}
private:
std::unique_ptr<CallbackResource> callback_resource_{nullptr};
};
class PyInferenceResponse
: public PyWrapper<struct TRITONSERVER_InferenceResponse> {
public:
DESTRUCTOR_WITH_LOG(
PyInferenceResponse, TRITONSERVER_InferenceResponseDelete);
explicit PyInferenceResponse(
struct TRITONSERVER_InferenceResponse* response, bool owned)
: PyWrapper(response, owned)
{
}
void ThrowIfResponseError()
{
ThrowIfError(TRITONSERVER_InferenceResponseError(triton_object_));
}
std::tuple<std::string, int64_t> Model()
{
const char* model_name = nullptr;
int64_t model_version = 0;
ThrowIfError(TRITONSERVER_InferenceResponseModel(
triton_object_, &model_name, &model_version));
return {model_name, model_version};
}
std::string Id()
{
const char* val = nullptr;
ThrowIfError(TRITONSERVER_InferenceResponseId(triton_object_, &val));
return val;
}
uint32_t ParameterCount()
{
uint32_t val = 0;
ThrowIfError(
TRITONSERVER_InferenceResponseParameterCount(triton_object_, &val));
return val;
}
std::tuple<std::string, TRITONSERVER_ParameterType, py::object> Parameter(
uint32_t index)
{
const char* name = nullptr;
TRITONSERVER_ParameterType type = TRITONSERVER_PARAMETER_STRING;
const void* value = nullptr;
ThrowIfError(TRITONSERVER_InferenceResponseParameter(
triton_object_, index, &name, &type, &value));
py::object py_value;
switch (type) {
case TRITONSERVER_PARAMETER_STRING:
py_value = py::str(reinterpret_cast<const char*>(value));
break;
case TRITONSERVER_PARAMETER_INT:
py_value = py::int_(*reinterpret_cast<const int*>(value));
break;
case TRITONSERVER_PARAMETER_BOOL:
py_value = py::bool_(*reinterpret_cast<const bool*>(value));
break;
case TRITONSERVER_PARAMETER_DOUBLE:
py_value = py::float_(*reinterpret_cast<const double*>(value));
break;
default:
throw UnsupportedError(
std::string("Unexpected type '") +
TRITONSERVER_ParameterTypeString(type) +
"' received as response parameter");
break;
}
return {name, type, py_value};
}
uint32_t OutputCount()
{
uint32_t val = 0;
ThrowIfError(
TRITONSERVER_InferenceResponseOutputCount(triton_object_, &val));
return val;
}
std::tuple<
std::string, TRITONSERVER_DataType, py::array_t<int64_t>, uintptr_t,
size_t, TRITONSERVER_MemoryType, int64_t>
Output(uint32_t index)
{
const char* name = nullptr;
TRITONSERVER_DataType datatype = TRITONSERVER_TYPE_INVALID;
const int64_t* shape = nullptr;
uint64_t dim_count = 0;
const void* base = nullptr;
size_t byte_size = 0;
TRITONSERVER_MemoryType memory_type = TRITONSERVER_MEMORY_CPU;
int64_t memory_type_id = 0;
void* userp = nullptr;
ThrowIfError(TRITONSERVER_InferenceResponseOutput(
triton_object_, index, &name, &datatype, &shape, &dim_count, &base,
&byte_size, &memory_type, &memory_type_id, &userp));
return {
name,
datatype,
py::array_t<int64_t>(dim_count, shape),
reinterpret_cast<uintptr_t>(base),
byte_size,
memory_type,
memory_type_id};
}
std::string OutputClassificationLabel(uint32_t index, size_t class_index)
{
const char* val = nullptr;
ThrowIfError(TRITONSERVER_InferenceResponseOutputClassificationLabel(
triton_object_, index, class_index, &val));
return (val == nullptr) ? "" : val;
}
};
// forward declaration
class PyServer;
class PyInferenceRequest
: public PyWrapper<struct TRITONSERVER_InferenceRequest> {
public:
DESTRUCTOR_WITH_LOG(PyInferenceRequest, TRITONSERVER_InferenceRequestDelete);
// Defer definition until PyServer is defined
PyInferenceRequest(
PyServer& server, const std::string& model_name,
const int64_t model_version);
explicit PyInferenceRequest(
struct TRITONSERVER_InferenceRequest* r, const bool owned)
: PyWrapper(r, owned)
{
}
void SetReleaseCallback(const std::shared_ptr<PyInferenceRequest>& request)
{
// The request wrapper needs to be kept alive until the release callback is
// invoked, so the Triton request can be deleted after the core/backend is
// done with it.
std::shared_ptr<PyInferenceRequest>* request_ptr =
new std::shared_ptr<PyInferenceRequest>(request);
ThrowIfError(TRITONSERVER_InferenceRequestSetReleaseCallback(
triton_object_, ReleaseCallback,
reinterpret_cast<void*>(request_ptr) /* request_release_userp */));
}
static void ReleaseCallback(
struct TRITONSERVER_InferenceRequest* request, const uint32_t flags,
void* userp)
{
std::shared_ptr<PyInferenceRequest>* request_ptr =
reinterpret_cast<std::shared_ptr<PyInferenceRequest>*>(userp);
delete request_ptr;
}
struct ResponseAllocatorDeleter {
void operator()(struct TRITONSERVER_ResponseAllocator* allocator) const
{
if (allocator != nullptr) {
ThrowIfError(TRITONSERVER_ResponseAllocatorDelete(allocator));
}
};
};
void SetResponseAllocator()
{
// The response allocator is shared among all instances of this class, so it
// needs to be initialized once and once only.
// TODO: Why 'numpy.ones(2**27)' gets stuck when the response allocator is
// static initialized?
static std::once_flag allocator_init_once;
std::call_once(allocator_init_once, [this]() {
struct TRITONSERVER_ResponseAllocator* allocator_raw = nullptr;
ThrowIfError(TRITONSERVER_ResponseAllocatorNew(
&allocator_raw, ResponseAllocatorAllocFn, ResponseAllocatorReleaseFn,
nullptr /* start_fn */));
allocator_.reset(allocator_raw);
ThrowIfError(TRITONSERVER_ResponseAllocatorSetQueryFunction(
allocator_.get(), ResponseAllocatorQueryFn));
ThrowIfError(TRITONSERVER_ResponseAllocatorSetBufferAttributesFunction(
allocator_.get(), ResponseAllocatorBufferAttributesFn));
});
}
static TRITONSERVER_Error* ResponseAllocatorQueryFn(
struct TRITONSERVER_ResponseAllocator* allocator, void* userp,
const char* tensor_name, size_t* byte_size,
TRITONSERVER_MemoryType* memory_type, int64_t* memory_type_id)
{
// TODO: Support GPU memory.
*memory_type = TRITONSERVER_MEMORY_CPU;
*memory_type_id = 0;
return nullptr;
}
static TRITONSERVER_Error* ResponseAllocatorBufferAttributesFn(
struct TRITONSERVER_ResponseAllocator* allocator, const char* tensor_name,
struct TRITONSERVER_BufferAttributes* buffer_attributes, void* userp,
void* buffer_userp)
{
TRITONSERVER_Error* err = TRITONSERVER_BufferAttributesSetMemoryType(
buffer_attributes, TRITONSERVER_MEMORY_CPU);
if (err != nullptr) {
return err;
}
err = TRITONSERVER_BufferAttributesSetMemoryTypeId(
buffer_attributes, 0 /* memory_type_id */);
return err;
}
static TRITONSERVER_Error* ResponseAllocatorAllocFn(
struct TRITONSERVER_ResponseAllocator* allocator, const char* tensor_name,
size_t byte_size, TRITONSERVER_MemoryType memory_type,
int64_t memory_type_id, void* userp, void** buffer, void** buffer_userp,
TRITONSERVER_MemoryType* actual_memory_type,
int64_t* actual_memory_type_id)
{
*buffer = malloc(byte_size * sizeof(uint8_t));
*actual_memory_type = TRITONSERVER_MEMORY_CPU;
*actual_memory_type_id = 0;
return nullptr;
}
static TRITONSERVER_Error* ResponseAllocatorReleaseFn(
struct TRITONSERVER_ResponseAllocator* allocator, void* buffer,
void* buffer_userp, size_t byte_size, TRITONSERVER_MemoryType memory_type,
int64_t memory_type_id)
{
if (memory_type != TRITONSERVER_MEMORY_CPU || memory_type_id != 0) {
throw InvalidArgumentError("invalid memory type or id to be released");
}
free(buffer);
return nullptr;
}
void SetResponseCallback(const std::shared_ptr<PyInferenceRequest>& request)
{
// Keep the request wrapper alive until RESPONSE_COMPLETE_FINAL is
// received, so that AddNextResponse never operates on a freed object.
std::shared_ptr<PyInferenceRequest>* request_ptr =
new std::shared_ptr<PyInferenceRequest>(request);
ThrowIfError(TRITONSERVER_InferenceRequestSetResponseCallback(
triton_object_, allocator_.get(),
nullptr /* response_allocator_userp */, ResponseCallback,
reinterpret_cast<void*>(request_ptr) /* response_userp */));
}
static void ResponseCallback(
struct TRITONSERVER_InferenceResponse* response, const uint32_t flags,
void* userp)
{
auto* request_ptr =
reinterpret_cast<std::shared_ptr<PyInferenceRequest>*>(userp);
(*request_ptr)->AddNextResponse(response, flags);
if (flags & TRITONSERVER_RESPONSE_COMPLETE_FINAL) {
delete request_ptr;
}
}