-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathsampleInference.cpp
1782 lines (1600 loc) · 59.3 KB
/
sampleInference.cpp
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-2024 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.
*/
#include <algorithm>
#include <array>
#include <chrono>
#include <cuda_profiler_api.h>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <numeric>
#include <set>
#include <sstream>
#include <thread>
#include <utility>
#include <vector>
#if defined(__QNX__)
#include <sys/neutrino.h>
#include <sys/syspage.h>
#endif
#include "NvInfer.h"
#include "ErrorRecorder.h"
#include "bfloat16.h"
#include "logger.h"
#include "sampleDevice.h"
#include "sampleEngines.h"
#include "sampleInference.h"
#include "sampleOptions.h"
#include "sampleReporting.h"
#include "sampleUtils.h"
using namespace nvinfer1;
namespace sample
{
template <class MapType, class EngineType>
bool validateTensorNames(MapType const& map, EngineType const* engine, int32_t const endBindingIndex)
{
// Check if the provided input tensor names match the input tensors of the engine.
// Throw an error if the provided input tensor names cannot be found because it implies a potential typo.
for (auto const& item : map)
{
bool tensorNameFound{false};
for (int32_t b = 0; b < endBindingIndex; ++b)
{
auto const tensorName = engine->getIOTensorName(b);
auto const tensorIOMode = engine->getTensorIOMode(tensorName);
if (tensorIOMode == nvinfer1::TensorIOMode::kINPUT && matchStringWithOneWildcard(item.first, tensorName))
{
tensorNameFound = true;
break;
}
}
if (!tensorNameFound)
{
sample::gLogError << "Cannot find input tensor with name \"" << item.first << "\" in the engine bindings! "
<< "Please make sure the input tensor names are correct." << std::endl;
return false;
}
}
return true;
}
template <class EngineType, class ContextType>
class FillBindingClosure
{
private:
using InputsMap = std::unordered_map<std::string, std::string>;
using BindingsVector = std::vector<std::unique_ptr<Bindings>>;
EngineType const* engine;
ContextType const* context;
InputsMap const& inputs;
BindingsVector& bindings;
int32_t batch;
int32_t endBindingIndex;
int32_t profileIndex;
void fillOneBinding(TensorInfo const& tensorInfo)
{
auto const name = tensorInfo.name;
auto const* bindingInOutStr = tensorInfo.isInput ? "Input" : "Output";
for (auto& binding : bindings)
{
auto const input = findPlausible(inputs, name);
if (tensorInfo.isInput && input != inputs.end())
{
sample::gLogInfo << "Using values loaded from " << input->second << " for input " << name << std::endl;
binding->addBinding(tensorInfo, input->second);
}
else
{
if (tensorInfo.isInput)
{
sample::gLogInfo << "Using random values for input " << name << std::endl;
}
binding->addBinding(tensorInfo);
}
if (tensorInfo.isDynamic)
{
sample::gLogInfo << bindingInOutStr << " binding for " << name
<< " is dynamic and will be created during execution using OutputAllocator."
<< std::endl;
}
else
{
sample::gLogInfo << bindingInOutStr << " binding for " << name << " with dimensions " << tensorInfo.dims
<< " is created." << std::endl;
}
}
}
bool fillAllBindings(int32_t batch, int32_t endBindingIndex)
{
if (!validateTensorNames(inputs, engine, endBindingIndex))
{
sample::gLogError << "Invalid tensor names found in --loadInputs flag." << std::endl;
return false;
}
for (int32_t b = 0; b < endBindingIndex; b++)
{
TensorInfo tensorInfo;
tensorInfo.bindingIndex = b;
getTensorInfo(tensorInfo);
tensorInfo.updateVolume(batch);
fillOneBinding(tensorInfo);
}
return true;
}
void getTensorInfo(TensorInfo& tensorInfo);
public:
FillBindingClosure(EngineType const* _engine, ContextType const* _context, InputsMap const& _inputs,
BindingsVector& _bindings, int32_t _batch, int32_t _endBindingIndex, int32_t _profileIndex)
: engine(_engine)
, context(_context)
, inputs(_inputs)
, bindings(_bindings)
, batch(_batch)
, endBindingIndex(_endBindingIndex)
, profileIndex(_profileIndex)
{
}
bool operator()()
{
return fillAllBindings(batch, endBindingIndex);
}
};
template <>
void FillBindingClosure<nvinfer1::ICudaEngine, nvinfer1::IExecutionContext>::getTensorInfo(TensorInfo& tensorInfo)
{
auto const b = tensorInfo.bindingIndex;
auto const name = engine->getIOTensorName(b);
tensorInfo.name = name;
tensorInfo.dims = context->getTensorShape(name);
tensorInfo.isDynamic = std::any_of(
tensorInfo.dims.d, tensorInfo.dims.d + tensorInfo.dims.nbDims, [](int32_t dim) { return dim == -1; });
tensorInfo.comps = engine->getTensorComponentsPerElement(name, profileIndex);
tensorInfo.strides = context->getTensorStrides(name);
tensorInfo.vectorDimIndex = engine->getTensorVectorizedDim(name, profileIndex);
tensorInfo.isInput = engine->getTensorIOMode(name) == TensorIOMode::kINPUT;
tensorInfo.dataType = engine->getTensorDataType(name);
}
template <>
void FillBindingClosure<nvinfer1::safe::ICudaEngine, nvinfer1::safe::IExecutionContext>::getTensorInfo(
TensorInfo& tensorInfo)
{
// Use enqueueV3 for safe engine/context
auto const b = tensorInfo.bindingIndex;
auto const name = engine->getIOTensorName(b);
tensorInfo.name = name;
tensorInfo.dims = engine->getTensorShape(name);
tensorInfo.isDynamic = false;
tensorInfo.comps = engine->getTensorComponentsPerElement(name);
tensorInfo.strides = context->getTensorStrides(name);
tensorInfo.vectorDimIndex = engine->getTensorVectorizedDim(name);
tensorInfo.isInput = engine->getTensorIOMode(name) == TensorIOMode::kINPUT;
tensorInfo.dataType = engine->getTensorDataType(name);
}
namespace
{
bool allocateContextMemory(InferenceEnvironment& iEnv, InferenceOptions const& inference)
{
auto* engine = iEnv.engine.get();
iEnv.deviceMemory.resize(inference.infStreams);
// Delay context memory allocation until input shapes are specified because runtime allocation would require actual
// input shapes.
for (int32_t i = 0; i < inference.infStreams; ++i)
{
auto const& ec = iEnv.contexts.at(i);
if (inference.memoryAllocationStrategy == MemoryAllocationStrategy::kSTATIC)
{
sample::gLogInfo << "Created execution context with device memory size: "
<< (engine->getDeviceMemorySize() / 1.0_MiB) << " MiB" << std::endl;
}
else
{
size_t sizeToAlloc{0};
const char* allocReason{nullptr};
if (inference.memoryAllocationStrategy == MemoryAllocationStrategy::kPROFILE)
{
auto const p = inference.optProfileIndex;
sizeToAlloc = engine->getDeviceMemorySizeForProfile(p);
allocReason = "current profile";
}
else if (inference.memoryAllocationStrategy == MemoryAllocationStrategy::kRUNTIME)
{
sizeToAlloc = ec->updateDeviceMemorySizeForShapes();
allocReason = "current input shapes";
}
else
{
sample::gLogError << "Unrecognizable memory allocation strategy." << std::endl;
return false;
}
iEnv.deviceMemory.at(i) = std::move(TrtDeviceBuffer(sizeToAlloc));
ec->setDeviceMemory(iEnv.deviceMemory.at(i).get());
sample::gLogInfo << "Maximum device memory size across all profiles: "
<< (engine->getDeviceMemorySize() / 1.0_MiB) << " MiB" << std::endl;
sample::gLogInfo << "Only allocated device memory enough for " << allocReason << ": "
<< (sizeToAlloc / 1.0_MiB) << " MiB" << std::endl;
}
}
return true;
}
} // namespace
bool setUpInference(InferenceEnvironment& iEnv, InferenceOptions const& inference, SystemOptions const& system)
{
int32_t device{};
cudaCheck(cudaGetDevice(&device));
cudaDeviceProp properties;
cudaCheck(cudaGetDeviceProperties(&properties, device));
// Use managed memory on integrated devices when transfers are skipped
// and when it is explicitly requested on the commandline.
bool useManagedMemory{(inference.skipTransfers && properties.integrated) || inference.useManaged};
using FillSafeBindings = FillBindingClosure<nvinfer1::safe::ICudaEngine, nvinfer1::safe::IExecutionContext>;
if (iEnv.safe)
{
ASSERT(sample::hasSafeRuntime());
auto* safeEngine = iEnv.engine.getSafe();
SMP_RETVAL_IF_FALSE(safeEngine != nullptr, "Got invalid safeEngine!", false, sample::gLogError);
// Release serialized blob to save memory space.
iEnv.engine.releaseBlob();
for (int32_t s = 0; s < inference.infStreams; ++s)
{
auto ec = safeEngine->createExecutionContext();
if (ec == nullptr)
{
sample::gLogError << "Unable to create execution context for stream " << s << "." << std::endl;
return false;
}
sample::gLogInfo << "Created safe execution context with device memory size: "
<< (safeEngine->getDeviceMemorySize() / 1.0_MiB) << " MiB" << std::endl;
iEnv.safeContexts.emplace_back(ec);
iEnv.bindings.emplace_back(new Bindings(useManagedMemory));
}
int32_t const nbIOTensor = safeEngine->getNbIOTensors();
auto const* safeContext = iEnv.safeContexts.front().get();
// batch is set to 1 because safety only support explicit batch.
return FillSafeBindings(safeEngine, safeContext, inference.inputs, iEnv.bindings, 1, nbIOTensor, 0)();
}
using FillStdBindings = FillBindingClosure<nvinfer1::ICudaEngine, nvinfer1::IExecutionContext>;
auto* engine = iEnv.engine.get();
SMP_RETVAL_IF_FALSE(engine != nullptr, "Got invalid engine!", false, sample::gLogError);
// Release serialized blob to save memory space.
iEnv.engine.releaseBlob();
// Setup weight streaming if enabled
if (engine->getStreamableWeightsSize() > 0)
{
auto const& budget = inference.weightStreamingBudget;
int64_t wsBudget = budget.bytes;
if (budget.percent != WeightStreamingBudget::kDISABLE)
{
double const percent = budget.percent;
ASSERT(percent > 0.0);
auto const min = engine->getMinimumWeightStreamingBudget();
auto const max = engine->getStreamableWeightsSize();
wsBudget = (max >= min) ? (1 - percent / 100) * (max - min) + min : WeightStreamingBudget::kDISABLE;
}
bool success = engine->setWeightStreamingBudget(wsBudget);
SMP_RETVAL_IF_FALSE(success, "Failed to set weight streaming limit!", false, sample::gLogError);
switch (wsBudget)
{
case WeightStreamingBudget::kDISABLE:
{
sample::gLogInfo << "Weight streaming has been disabled at runtime." << std::endl;
break;
}
case WeightStreamingBudget::kAUTOMATIC:
{
sample::gLogInfo << "The weight streaming budget will automatically be chosen by TensorRT." << std::endl;
break;
}
default:
{
sample::gLogInfo << "Weight streaming is enabled with a device memory limit of " << wsBudget << " bytes."
<< std::endl;
break;
}
}
}
int32_t const nbOptProfiles = engine->getNbOptimizationProfiles();
if (inference.optProfileIndex >= nbOptProfiles)
{
sample::gLogError << "Selected profile index " << inference.optProfileIndex
<< " exceeds the number of profiles that the engine holds. " << std::endl;
return false;
}
if (nbOptProfiles > 1 && !inference.setOptProfile)
{
sample::gLogWarning << nbOptProfiles
<< " profiles detected but not set. Running with profile 0. Please use "
"--dumpOptimizationProfile to see all available profiles."
<< std::endl;
}
cudaStream_t setOptProfileStream;
CHECK(cudaStreamCreate(&setOptProfileStream));
for (int32_t s = 0; s < inference.infStreams; ++s)
{
IExecutionContext* ec{nullptr};
if (inference.memoryAllocationStrategy == MemoryAllocationStrategy::kSTATIC)
{
// Let TRT pre-allocate and manage the memory.
ec = engine->createExecutionContext();
}
else
{
// Allocate based on the current profile or runtime shapes.
ec = engine->createExecutionContext(ExecutionContextAllocationStrategy::kUSER_MANAGED);
}
if (ec == nullptr)
{
sample::gLogError << "Unable to create execution context for stream " << s << "." << std::endl;
return false;
}
ec->setNvtxVerbosity(inference.nvtxVerbosity);
int32_t const persistentCacheLimit
= samplesCommon::getMaxPersistentCacheSize() * inference.persistentCacheRatio;
sample::gLogInfo << "Setting persistentCacheLimit to " << persistentCacheLimit << " bytes." << std::endl;
ec->setPersistentCacheLimit(persistentCacheLimit);
auto setProfile = ec->setOptimizationProfileAsync(inference.optProfileIndex, setOptProfileStream);
CHECK(cudaStreamSynchronize(setOptProfileStream));
if (!setProfile)
{
sample::gLogError << "Set optimization profile failed. " << std::endl;
if (inference.infStreams > 1)
{
sample::gLogError
<< "Please ensure that the engine is built with preview feature profileSharing0806 enabled. "
<< std::endl;
}
return false;
}
iEnv.contexts.emplace_back(ec);
iEnv.bindings.emplace_back(new Bindings(useManagedMemory));
}
CHECK(cudaStreamDestroy(setOptProfileStream));
if (iEnv.profiler)
{
iEnv.contexts.front()->setProfiler(iEnv.profiler.get());
// Always run reportToProfiler() after enqueue launch
iEnv.contexts.front()->setEnqueueEmitsProfile(false);
}
int32_t const endBindingIndex = engine->getNbIOTensors();
// Make sure that the tensor names provided in command-line args actually exist in any of the engine bindings
// to avoid silent typos.
if (!validateTensorNames(inference.shapes, engine, endBindingIndex))
{
sample::gLogError << "Invalid tensor names found in --shapes flag." << std::endl;
return false;
}
for (int32_t b = 0; b < endBindingIndex; ++b)
{
auto const& name = engine->getIOTensorName(b);
auto const& mode = engine->getTensorIOMode(name);
if (mode == TensorIOMode::kINPUT)
{
Dims const dims = iEnv.contexts.front()->getTensorShape(name);
bool isShapeInferenceIO{false};
isShapeInferenceIO = engine->isShapeInferenceIO(name);
bool const hasRuntimeDim = std::any_of(dims.d, dims.d + dims.nbDims, [](int32_t dim) { return dim == -1; });
auto const shape = findPlausible(inference.shapes, name);
if (hasRuntimeDim || isShapeInferenceIO)
{
// Set shapeData to either dimensions of the input (if it has a dynamic shape)
// or set to values of the input (if it is an input shape tensor).
std::vector<int32_t> shapeData;
if (shape == inference.shapes.end())
{
// No information provided. Use default value for missing data.
constexpr int32_t kDEFAULT_VALUE = 1;
if (isShapeInferenceIO)
{
// Set shape tensor to all ones.
shapeData.assign(volume(dims, 0, dims.nbDims), kDEFAULT_VALUE);
sample::gLogWarning << "Values missing for input shape tensor: " << name
<< "Automatically setting values to: " << shapeData << std::endl;
}
else
{
// Use default value for unspecified runtime dimensions.
shapeData.resize(dims.nbDims);
std::transform(dims.d, dims.d + dims.nbDims, shapeData.begin(),
[&](int32_t dimension) { return dimension >= 0 ? dimension : kDEFAULT_VALUE; });
sample::gLogWarning << "Shape missing for input with dynamic shape: " << name
<< "Automatically setting shape to: " << shapeData << std::endl;
}
}
else if (inference.inputs.count(shape->first) && isShapeInferenceIO)
{
// Load shape tensor from file.
int64_t const size = volume(dims, 0, dims.nbDims);
shapeData.resize(size);
auto const& filename = inference.inputs.at(shape->first);
auto dst = reinterpret_cast<char*>(shapeData.data());
loadFromFile(filename, dst, size * sizeof(decltype(shapeData)::value_type));
}
else
{
shapeData = shape->second;
}
int32_t* shapeTensorData{nullptr};
if (isShapeInferenceIO)
{
// Save the data in iEnv, in a way that it's address does not change
// before enqueueV3 is called.
iEnv.inputShapeTensorValues.emplace_back(shapeData);
shapeTensorData = iEnv.inputShapeTensorValues.back().data();
}
for (auto& c : iEnv.contexts)
{
if (isShapeInferenceIO)
{
sample::gLogInfo << "Set input shape tensor " << name << " to: " << shapeData << std::endl;
if (!c->setTensorAddress(name, shapeTensorData))
{
return false;
}
}
else
{
sample::gLogInfo << "Set shape of input tensor " << name << " to: " << shapeData
<< std::endl;
if (!c->setInputShape(name, toDims(shapeData)))
{
return false;
}
}
}
}
else if (nbOptProfiles && shape != inference.shapes.end())
{
// Check if the provided shape matches the static dimensions in the engine.
for (auto& c : iEnv.contexts)
{
if (!c->setInputShape(name, toDims(shape->second)))
{
sample::gLogError << "The engine was built with static shapes for input tensor " << name
<< " but the provided shapes do not match the static shapes!" << std::endl;
return false;
}
}
}
}
}
// Create Debug Listener and turn on debug states if client requested dumping debug tensors.
if (!inference.debugTensorFileNames.empty())
{
iEnv.listener.reset(new DebugTensorWriter(inference.debugTensorFileNames));
iEnv.contexts.front()->setDebugListener(iEnv.listener.get());
for (auto const& s : inference.debugTensorFileNames)
{
iEnv.contexts.front()->setTensorDebugState(s.first.c_str(), true);
}
}
if (!allocateContextMemory(iEnv, inference))
{
return false;
}
auto const* context = iEnv.contexts.front().get();
return FillStdBindings(
engine, context, inference.inputs, iEnv.bindings, 1, endBindingIndex, inference.optProfileIndex)();
}
TaskInferenceEnvironment::TaskInferenceEnvironment(
std::string engineFile, InferenceOptions inference, int32_t deviceId, int32_t DLACore, int32_t bs)
: iOptions(inference)
, device(deviceId)
, batch(bs)
{
BuildEnvironment bEnv(/* isSafe */ false, /* versionCompatible */ false, DLACore, "", getTempfileControlDefaults());
loadEngineToBuildEnv(engineFile, false, bEnv, sample::gLogError);
std::unique_ptr<InferenceEnvironment> tmp(new InferenceEnvironment(bEnv));
iEnv = std::move(tmp);
cudaCheck(cudaSetDevice(device));
SystemOptions system{};
system.device = device;
system.DLACore = DLACore;
if (!setUpInference(*iEnv, iOptions, system))
{
sample::gLogError << "Inference set up failed" << std::endl;
}
}
namespace
{
#if defined(__QNX__)
using TimePoint = double;
#else
using TimePoint = std::chrono::time_point<std::chrono::high_resolution_clock>;
#endif
TimePoint getCurrentTime()
{
#if defined(__QNX__)
uint64_t const currentCycles = ClockCycles();
uint64_t const cyclesPerSecond = SYSPAGE_ENTRY(qtime)->cycles_per_sec;
// Return current timestamp in ms.
return static_cast<TimePoint>(currentCycles) * 1000. / cyclesPerSecond;
#else
return std::chrono::high_resolution_clock::now();
#endif
}
//!
//! \struct SyncStruct
//! \brief Threads synchronization structure
//!
struct SyncStruct
{
std::mutex mutex;
TrtCudaStream mainStream;
TrtCudaEvent gpuStart{cudaEventBlockingSync};
TimePoint cpuStart{};
float sleep{};
};
struct Enqueue
{
explicit Enqueue(nvinfer1::IExecutionContext& context)
: mContext(context)
{
}
nvinfer1::IExecutionContext& mContext;
};
//!
//! \class EnqueueExplicit
//! \brief Functor to enqueue inference with explict batch
//!
class EnqueueExplicit : private Enqueue
{
public:
explicit EnqueueExplicit(nvinfer1::IExecutionContext& context, Bindings const& bindings)
: Enqueue(context)
, mBindings(bindings)
{
ASSERT(mBindings.setTensorAddresses(mContext));
}
bool operator()(TrtCudaStream& stream) const
{
try
{
bool const result = mContext.enqueueV3(stream.get());
// Collecting layer timing info from current profile index of execution context, except under capturing
// mode.
if (!isStreamCapturing(stream) && mContext.getProfiler() && !mContext.getEnqueueEmitsProfile()
&& !mContext.reportToProfiler())
{
gLogWarning << "Failed to collect layer timing info from previous enqueueV3()" << std::endl;
}
return result;
}
catch (const std::exception&)
{
return false;
}
return false;
}
private:
// Helper function to check if a stream is in capturing mode.
bool isStreamCapturing(TrtCudaStream& stream) const
{
cudaStreamCaptureStatus status{cudaStreamCaptureStatusNone};
cudaCheck(cudaStreamIsCapturing(stream.get(), &status));
return status != cudaStreamCaptureStatusNone;
}
Bindings const& mBindings;
};
//!
//! \class EnqueueGraph
//! \brief Functor to enqueue inference from CUDA Graph
//!
class EnqueueGraph
{
public:
explicit EnqueueGraph(nvinfer1::IExecutionContext& context, TrtCudaGraph& graph)
: mGraph(graph)
, mContext(context)
{
}
bool operator()(TrtCudaStream& stream) const
{
if (mGraph.launch(stream))
{
// Collecting layer timing info from current profile index of execution context
if (mContext.getProfiler() && !mContext.getEnqueueEmitsProfile() && !mContext.reportToProfiler())
{
gLogWarning << "Failed to collect layer timing info from previous CUDA graph launch" << std::endl;
}
return true;
}
return false;
}
TrtCudaGraph& mGraph;
nvinfer1::IExecutionContext& mContext;
};
//!
//! \class EnqueueGraphSafe
//! \brief Functor to enqueue inference from CUDA Graph
//!
class EnqueueGraphSafe
{
public:
explicit EnqueueGraphSafe(TrtCudaGraph& graph)
: mGraph(graph)
{
}
bool operator()(TrtCudaStream& stream) const
{
return mGraph.launch(stream);
}
TrtCudaGraph& mGraph;
};
//!
//! \class EnqueueSafe
//! \brief Functor to enqueue safe execution context
//!
class EnqueueSafe
{
public:
explicit EnqueueSafe(nvinfer1::safe::IExecutionContext& context, Bindings const& bindings)
: mContext(context)
, mBindings(bindings)
{
ASSERT(mBindings.setSafeTensorAddresses(mContext));
}
bool operator()(TrtCudaStream& stream) const
{
try
{
return mContext.enqueueV3(stream.get());
}
catch (const std::exception&)
{
return false;
}
return false;
}
nvinfer1::safe::IExecutionContext& mContext;
private:
Bindings const& mBindings;
};
using EnqueueFunction = std::function<bool(TrtCudaStream&)>;
enum class StreamType : int32_t
{
kINPUT = 0,
kCOMPUTE = 1,
kOUTPUT = 2,
kNUM = 3
};
enum class EventType : int32_t
{
kINPUT_S = 0,
kINPUT_E = 1,
kCOMPUTE_S = 2,
kCOMPUTE_E = 3,
kOUTPUT_S = 4,
kOUTPUT_E = 5,
kNUM = 6
};
using MultiStream = std::array<TrtCudaStream, static_cast<int32_t>(StreamType::kNUM)>;
using MultiEvent = std::array<std::unique_ptr<TrtCudaEvent>, static_cast<int32_t>(EventType::kNUM)>;
using EnqueueTimes = std::array<TimePoint, 2>;
//!
//! \class Iteration
//! \brief Inference iteration and streams management
//!
template <class ContextType>
class Iteration
{
public:
Iteration(int32_t id, InferenceOptions const& inference, ContextType& context, Bindings& bindings)
: mBindings(bindings)
, mStreamId(id)
, mDepth(1 + inference.overlap)
, mActive(mDepth)
, mEvents(mDepth)
, mEnqueueTimes(mDepth)
, mContext(&context)
{
for (int32_t d = 0; d < mDepth; ++d)
{
for (int32_t e = 0; e < static_cast<int32_t>(EventType::kNUM); ++e)
{
mEvents[d][e].reset(new TrtCudaEvent(!inference.spin));
}
}
createEnqueueFunction(inference, context, bindings);
}
bool query(bool skipTransfers)
{
if (mActive[mNext])
{
return true;
}
if (!skipTransfers)
{
record(EventType::kINPUT_S, StreamType::kINPUT);
setInputData(false);
record(EventType::kINPUT_E, StreamType::kINPUT);
wait(EventType::kINPUT_E, StreamType::kCOMPUTE); // Wait for input DMA before compute
}
record(EventType::kCOMPUTE_S, StreamType::kCOMPUTE);
recordEnqueueTime();
if (!mEnqueue(getStream(StreamType::kCOMPUTE)))
{
return false;
}
recordEnqueueTime();
record(EventType::kCOMPUTE_E, StreamType::kCOMPUTE);
if (!skipTransfers)
{
wait(EventType::kCOMPUTE_E, StreamType::kOUTPUT); // Wait for compute before output DMA
record(EventType::kOUTPUT_S, StreamType::kOUTPUT);
fetchOutputData(false);
record(EventType::kOUTPUT_E, StreamType::kOUTPUT);
}
mActive[mNext] = true;
moveNext();
return true;
}
float sync(
TimePoint const& cpuStart, TrtCudaEvent const& gpuStart, std::vector<InferenceTrace>& trace, bool skipTransfers)
{
if (mActive[mNext])
{
if (skipTransfers)
{
getEvent(EventType::kCOMPUTE_E).synchronize();
}
else
{
getEvent(EventType::kOUTPUT_E).synchronize();
}
trace.emplace_back(getTrace(cpuStart, gpuStart, skipTransfers));
mActive[mNext] = false;
return getEvent(EventType::kCOMPUTE_S) - gpuStart;
}
return 0;
}
void syncAll(
TimePoint const& cpuStart, TrtCudaEvent const& gpuStart, std::vector<InferenceTrace>& trace, bool skipTransfers)
{
for (int32_t d = 0; d < mDepth; ++d)
{
sync(cpuStart, gpuStart, trace, skipTransfers);
moveNext();
}
}
void wait(TrtCudaEvent& gpuStart)
{
getStream(StreamType::kINPUT).wait(gpuStart);
}
void setInputData(bool sync)
{
mBindings.transferInputToDevice(getStream(StreamType::kINPUT));
// additional sync to avoid overlapping with inference execution.
if (sync)
{
getStream(StreamType::kINPUT).synchronize();
}
}
void fetchOutputData(bool sync)
{
mBindings.transferOutputToHost(getStream(StreamType::kOUTPUT));
// additional sync to avoid overlapping with inference execution.
if (sync)
{
getStream(StreamType::kOUTPUT).synchronize();
}
}
private:
void moveNext()
{
mNext = mDepth - 1 - mNext;
}
TrtCudaStream& getStream(StreamType t)
{
return mStream[static_cast<int32_t>(t)];
}
TrtCudaEvent& getEvent(EventType t)
{
return *mEvents[mNext][static_cast<int32_t>(t)];
}
void record(EventType e, StreamType s)
{
getEvent(e).record(getStream(s));
}
void recordEnqueueTime()
{
mEnqueueTimes[mNext][enqueueStart] = getCurrentTime();
enqueueStart = 1 - enqueueStart;
}
TimePoint getEnqueueTime(bool start)
{
return mEnqueueTimes[mNext][start ? 0 : 1];
}
void wait(EventType e, StreamType s)
{
getStream(s).wait(getEvent(e));
}
InferenceTrace getTrace(TimePoint const& cpuStart, TrtCudaEvent const& gpuStart, bool skipTransfers)
{
float is
= skipTransfers ? getEvent(EventType::kCOMPUTE_S) - gpuStart : getEvent(EventType::kINPUT_S) - gpuStart;
float ie
= skipTransfers ? getEvent(EventType::kCOMPUTE_S) - gpuStart : getEvent(EventType::kINPUT_E) - gpuStart;
float os
= skipTransfers ? getEvent(EventType::kCOMPUTE_E) - gpuStart : getEvent(EventType::kOUTPUT_S) - gpuStart;
float oe
= skipTransfers ? getEvent(EventType::kCOMPUTE_E) - gpuStart : getEvent(EventType::kOUTPUT_E) - gpuStart;
return InferenceTrace(mStreamId,
std::chrono::duration<float, std::milli>(getEnqueueTime(true) - cpuStart).count(),
std::chrono::duration<float, std::milli>(getEnqueueTime(false) - cpuStart).count(), is, ie,
getEvent(EventType::kCOMPUTE_S) - gpuStart, getEvent(EventType::kCOMPUTE_E) - gpuStart, os, oe);
}
void createEnqueueFunction(
InferenceOptions const& inference, nvinfer1::IExecutionContext& context, Bindings& bindings)
{
mEnqueue = EnqueueFunction(EnqueueExplicit(context, mBindings));
if (inference.graph)
{
sample::gLogInfo << "Capturing CUDA graph for the current execution context" << std::endl;
TrtCudaStream& stream = getStream(StreamType::kCOMPUTE);
// Avoid capturing initialization calls by executing the enqueue function at least
// once before starting CUDA graph capture.
auto const ret = mEnqueue(stream);
if (!ret)
{
throw std::runtime_error("Inference enqueue failed.");
}
stream.synchronize();
mGraph.beginCapture(stream);
// The built TRT engine may contain operations that are not permitted under CUDA graph capture mode.
// When the stream is capturing, the enqueue call may return false if the current CUDA graph capture fails.
if (mEnqueue(stream))
{
mGraph.endCapture(stream);
mEnqueue = EnqueueFunction(EnqueueGraph(context, mGraph));
sample::gLogInfo << "Successfully captured CUDA graph for the current execution context" << std::endl;
}
else
{
mGraph.endCaptureOnError(stream);
// Ensure any CUDA error has been cleaned up.
cudaCheck(cudaGetLastError());
sample::gLogWarning << "The built TensorRT engine contains operations that are not permitted under "
"CUDA graph capture mode."
<< std::endl;
sample::gLogWarning << "The specified --useCudaGraph flag has been ignored. The inference will be "
"launched without using CUDA graph launch."
<< std::endl;
}
}
}
void createEnqueueFunction(InferenceOptions const& inference, nvinfer1::safe::IExecutionContext& context, Bindings&)
{
mEnqueue = EnqueueFunction(EnqueueSafe(context, mBindings));
if (inference.graph)
{
TrtCudaStream& stream = getStream(StreamType::kCOMPUTE);
ASSERT(mEnqueue(stream));
stream.synchronize();
mGraph.beginCapture(stream);
ASSERT(mEnqueue(stream));
mGraph.endCapture(stream);
mEnqueue = EnqueueFunction(EnqueueGraphSafe(mGraph));
}
}
Bindings& mBindings;
TrtCudaGraph mGraph;
EnqueueFunction mEnqueue;
int32_t mStreamId{0};