FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
TensorRT/python/src/infer/pyCore.cpp at main · NVIDIA/TensorRT · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
NVIDIA
/
TensorRT
Public
Notifications
You must be signed in to change notification settings
Fork
2.4k
Star
13.3k
Code
Issues
573
Pull requests
56
Actions
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Security and quality
Insights
Expand file tree
Breadcrumbs
TensorRT
/
python
/
src
/
infer
/
pyCore.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
1910 lines (1706 loc) · 90.9 KB
Breadcrumbs
TensorRT
/
python
/
src
/
infer
/
pyCore.cpp
Copy path
File metadata and controls
1910 lines (1706 loc) · 90.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* SPDX-FileCopyrightText: Copyright (c) 1993-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
This contains the core elements of the API, i.e. builder, logger, engine, runtime, context.
#
include
"
ForwardDeclarations.h
"
#
include
"
utils.h
"
#
include
<
chrono
>
#
include
<
iomanip
>
#
include
<
pybind11/stl.h
>
#
include
"
infer/pyCoreDoc.h
"
#
include
<
cuda.h
>
#
include
<
cuda_runtime_api.h
>
namespace
tensorrt
{
using
namespace
nvinfer1
;
//
Long lambda functions should go here rather than being inlined into the bindings (1 liners are OK).
namespace
lambdas
{
//
For IOptimizationProfile
static
auto
const
opt_profile_set_shape
= [](IOptimizationProfile& self, std::string
const
& inputName, Dims
const
& min, Dims
const
& opt, Dims
const
& max) {
PY_ASSERT_RUNTIME_ERROR
(self.
setDimensions
(inputName.
c_str
(), OptProfileSelector::
kMIN
, min),
"
Shape provided for min is inconsistent with other shapes.
"
);
PY_ASSERT_RUNTIME_ERROR
(self.
setDimensions
(inputName.
c_str
(), OptProfileSelector::
kOPT
, opt),
"
Shape provided for opt is inconsistent with other shapes.
"
);
PY_ASSERT_RUNTIME_ERROR
(self.
setDimensions
(inputName.
c_str
(), OptProfileSelector::
kMAX
, max),
"
Shape provided for max is inconsistent with other shapes.
"
);
};
static
auto
const
opt_profile_get_shape
= [](IOptimizationProfile& self, std::string
const
& inputName) -> std::vector<Dims> {
std::vector<Dims> shapes{};
Dims minShape = self.
getDimensions
(inputName.
c_str
(), OptProfileSelector::
kMIN
);
if
(minShape.
nbDims
!= -
1
)
{
shapes.
emplace_back
(minShape);
shapes.
emplace_back
(self.
getDimensions
(inputName.
c_str
(), OptProfileSelector::
kOPT
));
shapes.
emplace_back
(self.
getDimensions
(inputName.
c_str
(), OptProfileSelector::
kMAX
));
}
return
shapes;
};
static
auto
const
opt_profile_set_shape_input = [](IOptimizationProfile& self, std::string
const
& inputName,
std::vector<
int64_t
>
const
& min, std::vector<
int64_t
>
const
& opt,
std::vector<
int64_t
>
const
& max) {
PY_ASSERT_RUNTIME_ERROR
(self.
setShapeValuesV2
(inputName.
c_str
(), OptProfileSelector::
kMIN
, min.
data
(), min.
size
()),
"
min input provided for shape tensor is inconsistent with other inputs.
"
);
PY_ASSERT_RUNTIME_ERROR
(self.
setShapeValuesV2
(inputName.
c_str
(), OptProfileSelector::
kOPT
, opt.
data
(), opt.
size
()),
"
opt input provided for shape tensor is inconsistent with other inputs.
"
);
PY_ASSERT_RUNTIME_ERROR
(self.
setShapeValuesV2
(inputName.
c_str
(), OptProfileSelector::
kMAX
, max.
data
(), max.
size
()),
"
max input provided for shape tensor is inconsistent with other inputs.
"
);
};
static
auto
const
opt_profile_get_shape_input
= [](IOptimizationProfile& self, std::string
const
& inputName) -> std::vector<std::vector<
int64_t
>> {
std::vector<std::vector<
int64_t
>> shapes{};
int32_t
const
shapeSize = self.
getNbShapeValues
(inputName.
c_str
());
int64_t
const
* shapePtr = self.
getShapeValuesV2
(inputName.
c_str
(), OptProfileSelector::
kMIN
);
//
In the Python bindings, it is impossible to set only one shape in an optimization profile.
if
(shapePtr && shapeSize >=
0
)
{
shapes.
emplace_back
(shapePtr, shapePtr + shapeSize);
shapePtr = self.
getShapeValuesV2
(inputName.
c_str
(), OptProfileSelector::
kOPT
);
PY_ASSERT_RUNTIME_ERROR
(shapePtr !=
nullptr
,
"
Invalid shape for OPT.
"
);
shapes.
emplace_back
(shapePtr, shapePtr + shapeSize);
shapePtr = self.
getShapeValuesV2
(inputName.
c_str
(), OptProfileSelector::
kMAX
);
PY_ASSERT_RUNTIME_ERROR
(shapePtr !=
nullptr
,
"
Invalid shape for MAX.
"
);
shapes.
emplace_back
(shapePtr, shapePtr + shapeSize);
}
return
shapes;
};
//
For IExecutionContext
static
auto
const
execute_v2 = [](IExecutionContext& self, std::vector<
size_t
>& bindings) {
return
self.
executeV2
(
reinterpret_cast
<
void
**>(bindings.
data
()));
};
std::vector<
char
const
*>
infer_shapes
(IExecutionContext& self)
{
int32_t
const
size{self.
getEngine
().
getNbIOTensors
()};
std::vector<
char
const
*>
names
(size);
int32_t
const
nbNames = self.
inferShapes
(names.
size
(), names.
data
());
if
(nbNames <
0
)
{
std::stringstream msg;
msg <<
"
infer_shapes error code:
"
<< nbNames;
py::gil_scoped_acquire gil{};
utils::throwPyError
(PyExc_RuntimeError, msg.
str
().
c_str
());
}
names.
resize
(nbNames);
return
names;
}
bool
execute_async_v3
(IExecutionContext& self,
size_t
streamHandle)
{
return
self.
enqueueV3
(
reinterpret_cast
<cudaStream_t>(streamHandle));
}
bool
set_tensor_address
(IExecutionContext& self,
char
const
* tensor_name,
size_t
memory)
{
return
self.
setTensorAddress
(tensor_name,
reinterpret_cast
<
void
*>(memory));
}
size_t
get_tensor_address
(IExecutionContext& self,
char
const
* tensor_name)
{
return
reinterpret_cast
<
size_t
>(self.
getTensorAddress
(tensor_name));
}
bool
set_input_consumed_event
(IExecutionContext& self,
size_t
inputConsumed)
{
return
self.
setInputConsumedEvent
(
reinterpret_cast
<cudaEvent_t>(inputConsumed));
}
size_t
get_input_consumed_event
(IExecutionContext& self)
{
return
reinterpret_cast
<
size_t
>(self.
getInputConsumedEvent
());
}
void
set_aux_streams
(IExecutionContext& self, std::vector<
size_t
> streamHandle)
{
self.
setAuxStreams
(
reinterpret_cast
<cudaStream_t*>(streamHandle.
data
()),
static_cast
<
int32_t
>(streamHandle.
size
()));
}
template
<
typename
PyIterable>
Dims
castDimsFromPyIterable
(PyIterable& in)
{
int32_t
const
maxDims{
static_cast
<
int32_t
>(Dims::
MAX_DIMS
)};
Dims dims{};
dims.
nbDims
=
py::len
(in);
PY_ASSERT_RUNTIME_ERROR
(
dims.
nbDims
<= maxDims,
"
The number of input dims exceeds the maximum allowed number of dimensions
"
);
for
(
int32_t
i =
0
; i < dims.
nbDims
; ++i)
{
dims.
d
[i] = in[i].
template
cast
<
int32_t
>();
}
return
dims;
}
template
<
typename
PyIterable>
bool
setInputShape
(IExecutionContext& self,
char
const
* tensorName, PyIterable& in)
{
return
self.
setInputShape
(tensorName, castDimsFromPyIterable<PyIterable>(in));
}
//
For IRuntime
static
auto
const
runtime_deserialize_cuda_engine = [](IRuntime& self, py::buffer& serializedEngine) {
py::buffer_info info = serializedEngine.
request
();
py::gil_scoped_release releaseGil{};
return
self.
deserializeCudaEngine
(info.
ptr
, info.
size
* info.
itemsize
);
};
static
auto
const
reader_v2_read = [](IStreamReaderV2& self,
void
* destination,
int64_t
nbBytes,
size_t
stream) {
return
self.
read
(destination, nbBytes,
reinterpret_cast
<cudaStream_t>(stream));
};
//
For ICudaEngine
//
TODO: Add slicing support?
static
auto
const
engine_getitem = [](ICudaEngine& self,
int32_t
pyIndex) {
//
Support python's negative indexing
int32_t
const
index = (pyIndex <
0
) ?
static_cast
<
int32_t
>(self.
getNbIOTensors
()) + pyIndex : pyIndex;
PY_ASSERT_INDEX_ERROR
(index < self.
getNbIOTensors
());
return
self.
getIOTensorName
(index);
};
std::vector<Dims>
get_tensor_profile_shape
(ICudaEngine& self, std::string
const
& tensorName,
int32_t
profileIndex)
{
std::string
const
errorMsg{
"
Could not get profile shape for tensor '
"
+ tensorName
+
"
'. Is the tensor name an input and the profile index valid?
"
};
std::vector<Dims> shapes{};
shapes.
emplace_back
(
utils::checkDims
(self.
getProfileShape
(tensorName.
c_str
(), profileIndex, OptProfileSelector::
kMIN
), errorMsg));
shapes.
emplace_back
(
utils::checkDims
(self.
getProfileShape
(tensorName.
c_str
(), profileIndex, OptProfileSelector::
kOPT
), errorMsg));
shapes.
emplace_back
(
utils::checkDims
(self.
getProfileShape
(tensorName.
c_str
(), profileIndex, OptProfileSelector::
kMAX
), errorMsg));
return
shapes;
}
std::vector<std::vector<
int64_t
>>
get_tensor_profile_values
(
ICudaEngine& self,
int32_t
profileIndex, std::string
const
& tensorName)
{
char
const
*
const
name = tensorName.
c_str
();
bool
const
isShapeInput{self.
isShapeInferenceIO
(name) && self.
getTensorIOMode
(name) == TensorIOMode::
kINPUT
};
PY_ASSERT_RUNTIME_ERROR
(isShapeInput,
"
Binding index does not correspond to an input shape tensor.
"
);
Dims
const
shape = self.
getTensorShape
(name);
PY_ASSERT_RUNTIME_ERROR
(shape.
nbDims
>=
0
,
"
Missing shape for input shape tensor
"
);
auto
const
shapeSize{
utils::volume
(shape)};
PY_ASSERT_RUNTIME_ERROR
(shapeSize >=
0
,
"
Negative volume for input shape tensor
"
);
std::vector<std::vector<
int64_t
>> shapes{};
//
In the Python bindings, it is impossible to set only one shape in an optimization profile.
int64_t
const
* shapePtr{self.
getProfileTensorValuesV2
(name, profileIndex, OptProfileSelector::
kMIN
)};
if
(shapePtr)
{
shapes.
emplace_back
(shapePtr, shapePtr + shapeSize);
shapePtr = self.
getProfileTensorValuesV2
(name, profileIndex, OptProfileSelector::
kOPT
);
shapes.
emplace_back
(shapePtr, shapePtr + shapeSize);
shapePtr = self.
getProfileTensorValuesV2
(name, profileIndex, OptProfileSelector::
kMAX
);
shapes.
emplace_back
(shapePtr, shapePtr + shapeSize);
}
return
shapes;
}
//
For IGpuAllocator
void
*
allocate_async
(
IGpuAllocator& self,
uint64_t
const
size,
uint64_t
const
alignment, AllocatorFlags
const
flags,
size_t
streamHandle)
{
return
self.
allocateAsync
(size, alignment, flags,
reinterpret_cast
<cudaStream_t>(streamHandle));
}
bool
deallocate_async
(IGpuAllocator& self,
void
*
const
memory,
size_t
streamHandle)
{
return
self.
deallocateAsync
(memory,
reinterpret_cast
<cudaStream_t>(streamHandle));
}
//
For IOutputAllocator
void
*
reallocate_output_async
(IOutputAllocator& self,
char
const
* tensorName,
void
* currentMemory,
uint64_t
size,
uint64_t
alignment,
size_t
streamHandle)
{
return
self.
reallocateOutputAsync
(
tensorName, currentMemory, size, alignment,
reinterpret_cast
<cudaStream_t>(streamHandle));
}
#
if
EXPORT_ALL_BINDINGS
//
For IBuilderConfig
static
auto
const
netconfig_get_profile_stream
= [](IBuilderConfig& self) ->
size_t
{
return
reinterpret_cast
<
size_t
>(self.
getProfileStream
()); };
static
auto
const
netconfig_set_profile_stream = [](IBuilderConfig& self,
size_t
streamHandle) {
self.
setProfileStream
(
reinterpret_cast
<cudaStream_t>(streamHandle));
};
static
auto
const
netconfig_create_timing_cache = [](IBuilderConfig& self, py::buffer& serializedTimingCache) {
py::buffer_info info = serializedTimingCache.
request
();
py::gil_scoped_release releaseGil{};
return
self.
createTimingCache
(info.
ptr
, info.
size
* info.
itemsize
);
};
static
auto
const
get_plugins_to_serialize = [](IBuilderConfig& self) {
std::vector<std::string> paths;
int64_t
const
nbPlugins = self.
getNbPluginsToSerialize
();
if
(nbPlugins <
0
)
{
utils::throwPyError
(PyExc_RuntimeError,
"
Internal error
"
);
}
paths.
reserve
(nbPlugins);
for
(
int64_t
i =
0
; i < nbPlugins; ++i)
{
paths.
emplace_back
(std::string{self.
getPluginToSerialize
(i)});
}
return
paths;
};
static
auto
const
set_plugins_to_serialize = [](IBuilderConfig& self, std::vector<std::string>
const
& paths) {
std::vector<
char
const
*> cStrings;
cStrings.
reserve
(paths.
size
());
for
(
auto
const
& path : paths)
{
cStrings.
push_back
(path.
c_str
());
}
self.
setPluginsToSerialize
(
reinterpret_cast
<
char
const
*
const
*>(cStrings.
data
()), cStrings.
size
());
};
static
auto
const
get_remote_auto_tuning_config
= [](IBuilderConfig& self) {
return
std::string{self.
getRemoteAutoTuningConfig
()}; };
static
auto
const
set_remote_auto_tuning_config
= [](IBuilderConfig& self, std::string
const
& config) { self.
setRemoteAutoTuningConfig
(config.
c_str
()); };
static
auto
const
get_build_route = [](IBuilderConfig& self) {
return
std::string{self.
getBuildRoute
()}; };
static
auto
const
set_build_route
= [](IBuilderConfig& self, std::string
const
& buildRoute) { self.
setBuildRoute
(buildRoute.
c_str
()); };
static
auto
const
get_all_build_routes = [](IBuilderConfig& self) {
return
std::string{self.
getAllBuildRoutes
()}; };
#
endif
//
EXPORT_ALL_BINDINGS
//
For IRefitter
static
auto
const
refitter_get_missing = [](IRefitter& self) {
//
First get the number of missing weights.
int32_t
const
size{self.
getMissing
(
0
,
nullptr
,
nullptr
)};
//
Now that we know how many weights are missing, we can create the buffers appropriately.
std::vector<
const
char
*>
layerNames
(size);
std::vector<WeightsRole>
roles
(size);
self.
getMissing
(size, layerNames.
data
(), roles.
data
());
return
std::pair<std::vector<
const
char
*>, std::vector<WeightsRole>>{layerNames, roles};
};
static
auto
const
refitter_get_missing_weights = [](IRefitter& self) {
//
First get the number of missing weights.
int32_t
const
size{self.
getMissingWeights
(
0
,
nullptr
)};
//
Now that we know how many weights are missing, we can create the buffers appropriately.
std::vector<
char
const
*>
names
(size);
self.
getMissingWeights
(size, names.
data
());
return
names;
};
static
auto
const
refitter_get_all = [](IRefitter& self) {
int32_t
const
size{self.
getAll
(
0
,
nullptr
,
nullptr
)};
std::vector<
char
const
*>
layerNames
(size);
std::vector<WeightsRole>
roles
(size);
self.
getAll
(size, layerNames.
data
(), roles.
data
());
return
std::pair<std::vector<
const
char
*>, std::vector<WeightsRole>>{layerNames, roles};
};
static
auto
const
refitter_get_all_weights = [](IRefitter& self) {
int32_t
const
size{self.
getAllWeights
(
0
,
nullptr
)};
std::vector<
char
const
*>
names
(size);
self.
getAllWeights
(size, names.
data
());
return
names;
};
static
auto
const
refitter_refit_cuda_engine_async = [](IRefitter& self,
size_t
streamHandle) {
return
self.
refitCudaEngineAsync
(
reinterpret_cast
<cudaStream_t>(streamHandle));
};
static
auto
const
context_set_optimization_profile_async
= [](IExecutionContext& self,
int32_t
const
profileIndex,
size_t
streamHandle) {
PY_ASSERT_RUNTIME_ERROR
(
self.
setOptimizationProfileAsync
(profileIndex,
reinterpret_cast
<cudaStream_t>(streamHandle)),
"
Error in set optimization profile async.
"
);
return
true
;
};
void
context_set_device_memory
(IExecutionContext& self,
size_t
memory)
{
self.
setDeviceMemory
(
reinterpret_cast
<
void
*>(memory));
}
void
context_set_device_memory_v2
(IExecutionContext& self,
size_t
memory,
int64_t
size)
{
self.
setDeviceMemoryV2
(
reinterpret_cast
<
void
*>(memory), size);
}
void
serialization_config_set_flags
(ISerializationConfig& self,
uint32_t
flags)
{
if
(!self.
setFlags
(flags))
{
utils::throwPyError
(PyExc_RuntimeError,
"
Provided serialization flags is incorrect
"
);
}
}
//
For IDebugListener, this function is intended to be override by client.
//
The bindings here will never be called and is for documentation purpose only.
void
docProcessDebugTensor
(IDebugListener& self,
void
const
* addr, TensorLocation location, DataType type,
Dims
const
& shape,
char
const
* name,
size_t
stream)
{
return
;
}
uint64_t
getTacticHash
(TimingCacheValue
const
& value)
{
return
value.
tacticHash
;
}
void
setTacticHash
(TimingCacheValue& value,
uint64_t
tacticHash)
{
value.
tacticHash
= tacticHash;
}
float
getTimingMSec
(TimingCacheValue
const
& value)
{
return
value.
timingMSec
;
}
void
setTimingMSec
(TimingCacheValue& value,
float
timingMSec)
{
value.
timingMSec
= timingMSec;
}
namespace
detail
{
constexpr
int64_t
kBYTES_PER_KEY
=
16
;
constexpr
int64_t
kCHARS_PER_BYTE
=
2
;
constexpr
int64_t
kPREFIX_CHARS
=
2
;
constexpr
int64_t
kTOTAL_CHARS
=
kPREFIX_CHARS
+
kBYTES_PER_KEY
*
kCHARS_PER_BYTE
;
}
//
namespace detail
TimingCacheKey
parseTimingCacheKey
(std::string
const
& text)
{
using
namespace
detail
;
if
(text.
size
() !=
kTOTAL_CHARS
)
{
std::ostringstream msg;
msg <<
"
The text should have exactly
"
<<
kTOTAL_CHARS
<<
"
characters.
"
;
utils::throwPyError
(PyExc_ValueError, msg.
str
().
c_str
());
}
int
offset =
0
;
sscanf
(text.
c_str
(),
"
0%*[xX]%n
"
, &offset);
PY_ASSERT_VALUE_ERROR
(offset ==
2
,
"
The text should start with prefix `0x` or `0X`.
"
);
TimingCacheKey key;
for
(
int64_t
i =
0
; i <
kBYTES_PER_KEY
; ++i, offset +=
kCHARS_PER_BYTE
)
{
int64_t
numReceived =
sscanf
(text.
c_str
() + offset,
"
%2
"
SCNx8, &key.
data
[i]);
PY_ASSERT_VALUE_ERROR
(numReceived ==
1
,
"
The text has invalid content.
"
);
}
return
key;
}
std::string
convertTimingCacheKeyToString
(TimingCacheKey
const
& key)
{
using
namespace
detail
;
char
buffer[
kTOTAL_CHARS
+
1
] =
"
0x
"
;
for
(
int64_t
i =
0
; i <
kBYTES_PER_KEY
; ++i)
{
int64_t
offset =
kPREFIX_CHARS
+
kCHARS_PER_BYTE
* i;
sprintf
(buffer + offset,
"
%02
"
PRIx8, key.
data
[i]);
}
return
std::string
(buffer);
}
std::vector<TimingCacheKey>
queryTimingCacheKeys
(ITimingCache
const
& cache)
{
int64_t
numKeys = cache.
queryKeys
(
nullptr
,
0
);
PY_ASSERT_RUNTIME_ERROR
(numKeys >=
0
,
"
Failed to get the number of keys in the timing cache
"
);
std::vector<TimingCacheKey>
keys
(numKeys);
PY_ASSERT_RUNTIME_ERROR
(
numKeys == cache.
queryKeys
(keys.
data
(), keys.
size
()),
"
Failed to get keys from the timing cache
"
);
return
keys;
}
}
//
namespace lambdas
namespace
PyGpuAllocatorHelper
{
template
<
typename
TAllocator,
typename
... Args>
void
*
allocHelper
(TAllocator* allocator,
char
const
* pyFuncName,
bool
showWarning, Args&&... args)
noexcept
{
try
{
py::gil_scoped_acquire gil{};
py::function pyAllocFunc =
utils::getOverride
(
static_cast
<TAllocator*>(allocator), pyFuncName, showWarning);
if
(!pyAllocFunc)
{
return
nullptr
;
}
py::object ptr =
pyAllocFunc
(std::forward<Args>(args)...);
try
{
return
reinterpret_cast
<
void
*>(ptr.
cast
<
size_t
>());
}
catch
(py::cast_error
const
& e)
{
std::cerr <<
"
[ERROR] Return value of allocate() could not be interpreted as an int
"
<< std::endl;
}
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in allocate():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in allocate()
"
<< std::endl;
return
nullptr
;
}
return
nullptr
;
}
}
//
namespace PyGpuAllocatorHelper
class
PyGpuAllocator
:
public
IGpuAllocator
{
public:
using
IGpuAllocator::IGpuAllocator;
void
*
allocate
(
uint64_t
size,
uint64_t
alignment, AllocatorFlags flags)
noexcept
override
{
return
PyGpuAllocatorHelper::allocHelper<IGpuAllocator>(
this
,
"
allocate
"
,
true
, size, alignment, flags);
}
void
*
reallocate
(
void
* baseAddr,
uint64_t
alignment,
uint64_t
newSize)
noexcept
override
{
return
PyGpuAllocatorHelper::allocHelper<IGpuAllocator>(
this
,
"
reallocate
"
,
true
,
reinterpret_cast
<
size_t
>(baseAddr), alignment, newSize);
}
bool
deallocate
(
void
* memory)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
py::function pyDeallocate =
utils::getOverride
(
static_cast
<IGpuAllocator*>(
this
),
"
deallocate
"
);
if
(!pyDeallocate)
{
return
false
;
}
py::object status{};
status =
pyDeallocate
(
reinterpret_cast
<
size_t
>(memory));
return
status.
cast
<
bool
>();
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in deallocate():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in deallocate()
"
<< std::endl;
}
return
false
;
}
};
//
PyGpuAllocator
//
/////////
class
PyGpuAsyncAllocator
:
public
IGpuAsyncAllocator
{
public:
using
IGpuAsyncAllocator::IGpuAsyncAllocator;
void
*
allocateAsync
(
uint64_t
size,
uint64_t
alignment, AllocatorFlags flags, cudaStream_t stream)
noexcept
override
{
intptr_t
cudaStreamPtr =
reinterpret_cast
<
intptr_t
>(stream);
return
PyGpuAllocatorHelper::allocHelper<IGpuAsyncAllocator>(
this
,
"
allocate_async
"
,
true
, size, alignment, flags, cudaStreamPtr);
}
void
*
reallocate
(
void
* baseAddr,
uint64_t
alignment,
uint64_t
newSize)
noexcept
override
{
return
PyGpuAllocatorHelper::allocHelper<IGpuAsyncAllocator>(
this
,
"
reallocate
"
,
true
,
reinterpret_cast
<
size_t
>(baseAddr), alignment, newSize);
}
bool
deallocateAsync
(
void
* memory, cudaStream_t stream)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
py::function pyDeallocateAsync
=
utils::getOverride
(
static_cast
<IGpuAsyncAllocator*>(
this
),
"
deallocate_async
"
);
if
(!pyDeallocateAsync)
{
return
false
;
}
py::object status{};
intptr_t
cudaStreamPtr =
reinterpret_cast
<
intptr_t
>(stream);
status =
pyDeallocateAsync
(
reinterpret_cast
<
size_t
>(memory), cudaStreamPtr);
return
status.
cast
<
bool
>();
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in deallocate():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in deallocate()
"
<< std::endl;
}
return
false
;
}
};
//
PyGpuAsyncAllocator
//
///////////////////////////
class
PyOutputAllocator
:
public
IOutputAllocator
{
public:
void
*
reallocateOutput
(
char
const
* tensorName,
void
* currentMemory,
uint64_t
size,
uint64_t
alignment)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
py::function pyFunc =
utils::getOverride
(
static_cast
<IOutputAllocator*>(
this
),
"
reallocate_output
"
);
if
(!pyFunc)
{
return
nullptr
;
}
py::object ptr =
pyFunc
(tensorName,
reinterpret_cast
<
size_t
>(currentMemory), size, alignment);
try
{
return
reinterpret_cast
<
void
*>(ptr.
cast
<
size_t
>());
}
catch
(py::cast_error
const
& e)
{
std::cerr <<
"
[ERROR] Return value of reallocateOutput() could not be interpreted as an int
"
<< std::endl;
}
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in reallocateOutput():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in reallocateOutput()
"
<< std::endl;
return
nullptr
;
}
return
nullptr
;
}
void
*
reallocateOutputAsync
(
char
const
* tensorName,
void
* currentMemory,
uint64_t
size,
uint64_t
alignment,
cudaStream_t stream)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
py::function pyFunc
=
utils::getOverride
(
static_cast
<IOutputAllocator*>(
this
),
"
reallocate_output_async
"
,
false
);
if
(!pyFunc)
{
//
! For legacy implementation, the user might not have implemented this method, so we go for the default
//
! method.
return
reallocateOutput
(tensorName, currentMemory, size, alignment);
}
intptr_t
cudaStreamPtr =
reinterpret_cast
<
intptr_t
>(stream);
py::object ptr
=
pyFunc
(tensorName,
reinterpret_cast
<
size_t
>(currentMemory), size, alignment, cudaStreamPtr);
try
{
return
reinterpret_cast
<
void
*>(ptr.
cast
<
size_t
>());
}
catch
(py::cast_error
const
& e)
{
std::cerr <<
"
[ERROR] Return value of reallocateOutputAsync() could not be interpreted as an int
"
<< std::endl;
}
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in reallocateOutputAsync():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in reallocateOutputAsync()
"
<< std::endl;
return
nullptr
;
}
return
nullptr
;
}
void
notifyShape
(
char
const
* tensorName, Dims
const
& dims)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
PYBIND11_OVERLOAD_PURE_NAME
(
void
, IOutputAllocator,
"
notify_shape
"
, notifyShape, tensorName, dims);
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in notifyShape():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in notifyShape()
"
<< std::endl;
}
}
};
class
PyStreamReaderV2
:
public
IStreamReaderV2
{
using
TFnPointerGetAttribute = CUresult (*)(
void
*, CUpointer_attribute, CUdeviceptr);
using
TFnMemcpyHtoD = CUresult (*)(CUdeviceptr,
void
const
*,
size_t
);
public:
PyStreamReaderV2
()
{
py::gil_scoped_acquire gil{};
mCudaHandle
=
utils::nvdllOpen
(
CUDA_LIB_NAME
);
if
(!
mCudaHandle
)
{
utils::throwPyError
(PyExc_RuntimeError,
"
[ERROR] Failed to open cuda driver.
"
);
}
mFnPointerGetAttribute
=
reinterpret_cast
<TFnPointerGetAttribute>(
utils::dllGetSym
(
mCudaHandle
,
"
cuPointerGetAttribute
"
));
mFnMemcpyHtoD
=
reinterpret_cast
<TFnMemcpyHtoD>(
utils::dllGetSym
(
mCudaHandle
,
"
cuMemcpyHtoD_v2
"
));
}
~PyStreamReaderV2
()
{
try
{
py::gil_scoped_acquire gil{};
utils::dllClose
(
mCudaHandle
);
}
catch
(...)
{
std::cerr <<
"
[ERROR] An exception occurred while closing the CUDA driver.
"
;
}
}
int64_t
read
(
void
* destination,
int64_t
nbBytes, cudaStream_t stream)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
if
(!
mFnPointerGetAttribute
|| !
mFnMemcpyHtoD
)
{
utils::throwPyError
(PyExc_RuntimeError,
"
[ERROR] Read is skipped due to failed to get necessary API entry in cuda driver.
"
);
return
0
;
}
py::function pyReadFunc =
utils::getOverride
(
static_cast
<IStreamReaderV2*>(
this
),
"
read
"
);
if
(!pyReadFunc)
{
utils::throwPyError
(PyExc_RuntimeError,
"
[ERROR] Failed to find override read function in python.
"
);
return
0
;
}
//
Check destination memory location.
uint32_t
attributes{};
CUresult ret =
mFnPointerGetAttribute
(
&attributes,
CU_POINTER_ATTRIBUTE_MEMORY_TYPE
,
reinterpret_cast
<CUdeviceptr>(destination));
if
(ret ==
CUDA_ERROR_INVALID_VALUE
)
{
attributes =
CU_MEMORYTYPE_HOST
;
}
else
{
CUDA_CALL_WITH_RET
(ret,
0
);
}
bool
const
useH2DCopy = attributes ==
CU_MEMORYTYPE_DEVICE
;
auto
copyDestination =
static_cast
<std::byte*>(destination);
auto
cudaStreamPtr =
reinterpret_cast
<
intptr_t
>(stream);
//
In C++ we can use GDS to reduce host memory usage. For Python, we handle this in the bindings by copying
//
data chunk by chunk.
int64_t
totalBytesRead{};
while
(totalBytesRead < nbBytes)
{
int64_t
bytesToRead = nbBytes - totalBytesRead;
py::buffer data =
pyReadFunc
(bytesToRead, cudaStreamPtr);
py::buffer_info info = data.
request
();
//
User might chunk the memory into pieces to save peak host memory usage.
int64_t
bytesRead =
std::min
(info.
size
* info.
itemsize
, bytesToRead);
if
(bytesRead ==
0
)
{
std::cerr
<<
"
[ERROR] User aborted the operation, the read function in streamReaderV2 returned 0 bytes.
"
;
break
;
}
if
(useH2DCopy)
{
CUDA_CALL_WITH_RET
(
mFnMemcpyHtoD
(
reinterpret_cast
<CUdeviceptr>(copyDestination + totalBytesRead),
info.
ptr
, bytesRead),
totalBytesRead);
}
else
{
std::memcpy
(copyDestination + totalBytesRead, info.
ptr
, bytesRead);
}
totalBytesRead += bytesRead;
}
return
totalBytesRead;
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in read():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in read()
"
<< std::endl;
}
return
0
;
}
bool
seek
(
int64_t
offset, SeekPosition where)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
py::function pySeekFunc =
utils::getOverride
(
static_cast
<IStreamReaderV2*>(
this
),
"
seek
"
);
if
(!pySeekFunc)
{
std::cerr <<
"
[ERROR] Failed to find override seek function in python.
"
<< std::endl;
return
0
;
}
py::bool_ ret =
pySeekFunc
(offset, where);
return
ret;
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in seek():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in seek()
"
<< std::endl;
}
return
false
;
}
private:
void
*
mCudaHandle
{};
TFnPointerGetAttribute
mFnPointerGetAttribute
{};
TFnMemcpyHtoD
mFnMemcpyHtoD
{};
};
class
PyStreamWriter
:
public
IStreamWriter
{
public:
int64_t
write
(
void
const
* data,
int64_t
size)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
py::function pyFunc =
utils::getOverride
(
static_cast
<IStreamWriter*>(
this
),
"
write
"
);
if
(!pyFunc)
{
return
0
;
}
auto
const
pyBytes =
py::bytes
(
static_cast
<
char
const
*>(data), size);
py::object bytesWritten =
pyFunc
(pyBytes);
if
(!py::isinstance<py::int_>(bytesWritten))
{
std::cerr <<
"
[ERROR] StreamWriter shall returns the written bytes count in integer.
"
<< std::endl;
return
0
;
}
return
bytesWritten.
cast
<
int64_t
>();
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in write():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in write()
"
<< std::endl;
}
return
0
;
}
};
class
PyDebugListener
:
public
IDebugListener
{
public:
bool
processDebugTensor
(
void
const
* addr, TensorLocation location, DataType type, Dims
const
& shape,
char
const
* name, cudaStream_t stream)
override
{
try
{
py::gil_scoped_acquire gil{};
py::function pyFunc =
utils::getOverride
(
static_cast
<IDebugListener*>(
this
),
"
process_debug_tensor
"
);
if
(!pyFunc)
{
return
false
;
}
pyFunc
(
reinterpret_cast
<
size_t
>(addr), location, type, shape, name,
reinterpret_cast
<
size_t
>(stream));
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in processDebugTensor():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in processDebugTensor()
"
<< std::endl;
}
return
true
;
}
};
//
NOLINTNEXTLINE(readability-function-cognitive-complexity)
void
bindCore
(py::
module
& m)
{
class
PyLogger
:
public
ILogger
{
public:
virtual
void
log
(Severity severity,
char
const
* msg)
noexcept
override
{
try
{
py::gil_scoped_acquire gil{};
PYBIND11_OVERLOAD_PURE_NAME
(
void
, ILogger,
"
log
"
, log, severity, msg);
}
catch
(std::exception
const
& e)
{
std::cerr <<
"
[ERROR] Exception caught in log():
"
<< e.
what
() << std::endl;
}
catch
(...)
{
std::cerr <<
"
[ERROR] Exception caught in log()
"
<< std::endl;
}
}
};
py::class_<ILogger, PyLogger> baseLoggerBinding{m,
"
ILogger
"
, ILoggerDoc::descr,
py::module_local
()};
py::enum_<ILogger::Severity>(
baseLoggerBinding,
"
Severity
"
,
py::arithmetic
(), SeverityDoc::descr,
py::module_local
())
.
value
(
"
INTERNAL_ERROR
"
, ILogger::Severity::
kINTERNAL_ERROR
, SeverityDoc::internal_error)
.
value
(
"
ERROR
"
, ILogger::Severity::
kERROR
, SeverityDoc::error)
.
value
(
"
WARNING
"
, ILogger::Severity::
kWARNING
, SeverityDoc::warning)
.
value
(
"
INFO
"
, ILogger::Severity::
kINFO
, SeverityDoc::info)
.
value
(
"
VERBOSE
"
, ILogger::Severity::
kVERBOSE
, SeverityDoc::verbose)
//
We export into the outer scope, so we can access with trt.ILogger.X.
.
export_values
();
baseLoggerBinding.
def
(py::init<>()).
def
(
"
log
"
, &ILogger::log,
"
severity
"
_a,
"
msg
"
_a, ILoggerDoc::log);
class
DefaultLogger
:
public
ILogger
{
public:
DefaultLogger
(Severity minSeverity = Severity::
kWARNING
)
:
mMinSeverity
(minSeverity)
{
}
virtual
void
log
(Severity severity,
char
const
* msg)
noexcept
override
{
//
INFO is the largest value, so this comparison is inverted.
if
(severity >
mMinSeverity
)
return
;
//
prepend timestamp
std::
time_t
timestamp =
std::time
(
nullptr
);
tm* tm_local =
std::localtime
(×tamp);
std::cout <<
"
[
"
;
std::cout <<
std::setw
(
2
) <<
std::setfill
(
'
0
'
) <<
1
+ tm_local->
tm_mon
<<
"
/
"
;
std::cout <<
std::setw
(
2
) <<
std::setfill
(
'
0
'
) << tm_local->
tm_mday
<<
"
/
"
;
std::cout <<
std::setw
(
4
) <<
std::setfill
(
'
0
'
) <<
1900
+ tm_local->
tm_year
<<
"
-
"
;
std::cout <<
std::setw
(
2
) <<
std::setfill
(
'
0
'
) << tm_local->
tm_hour
<<
"
:
"
;
std::cout <<
std::setw
(
2
) <<
std::setfill
(
'
0
'
) << tm_local->
tm_min
<<
"
:
"
;
std::cout <<
std::setw
(
2
) <<
std::setfill
(
'
0
'
) << tm_local->
tm_sec
<<
"
]
"
;
std::string loggingPrefix =
"
[TRT]
"
;
switch
(severity)
{
case
Severity::
kINTERNAL_ERROR
:
{
loggingPrefix +=
"
[F]
"
;
break
;
}
case
Severity::
kERROR
:
{
loggingPrefix +=
"
[E]
"
;
break
;
}
case
Severity::
kWARNING
:
{
loggingPrefix +=
"
[W]
"
;
break
;
}
case
Severity::
kINFO
:
{
loggingPrefix +=
"
[I]
"
;
break
;
}
case
Severity::
kVERBOSE
:
{
loggingPrefix +=
"
[V]
"
;
break
;
}
}
std::cout << loggingPrefix << msg << std::endl;
}
Severity
mMinSeverity
;
};
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL