File size: 27,090 Bytes
f53e03f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#include "InferenceEngine.h"
#include "Log.h"
#include "picosha2.h"

#include <fstream>
#include <array>
#include <bitset>
#include <vector>
#include <map>
#include <iostream>

#include <NvInfer.h>
#include <NvOnnxParser.h>

namespace
{
    class Logger : public nvinfer1::ILogger
    {
    public:
        Logger( bool verbose )
            : m_flags( UINT8_MAX )
        {
            m_flags.set( static_cast<size_t>( Severity::kVERBOSE ), verbose );
        }

        void log( Severity severity, const char* msg ) noexcept override

        {
            if ( !m_flags.test( static_cast<size_t>( severity ) ) )
                return;

            switch ( severity )
            {
                case Severity::kINFO:
                case Severity::kVERBOSE:
                    LOG_INFO( msg );
                break;
                case Severity::kWARNING:
                    LOG_WARNING( msg );
                break;
                case Severity::kERROR:
                case Severity::kINTERNAL_ERROR:
                    LOG_ERROR( msg );
                break;
            }
        }

        void log( cudaError_t error )

        {
            if ( error == cudaError_t::cudaSuccess )
                return;

            LOG_ERROR( "CUDA failed with error [ " + std::to_string( error ) + " : " + cudaGetErrorName( error ) + " ]: " + cudaGetErrorString( error ) );
        }

    private:
        static constexpr uint8_t NB_FLAGS = static_cast<uint8_t>( Severity::kVERBOSE ) + 1;
        std::bitset<NB_FLAGS> m_flags;
    };

    Logger s_logger(false);

    bool FileExists( const std::string& filepath )

    {
        return std::ifstream( filepath.c_str() ).good();
    }

    std::string GetCudaDeviceName( int deviceID )

    {
        int deviceCount = 0;
        cudaGetDeviceCount( &deviceCount );

        if ( deviceID >= deviceCount )
            return std::string();

        cudaDeviceProp prop;
        cudaGetDeviceProperties( &prop, deviceID );
        return std::string( prop.name );
    }

    int SizeOfTensorDataType( nvinfer1::DataType dataType )

    {
        int size = -1;
        switch ( dataType )
        {
            case nvinfer1::DataType::kINT64:
            size = sizeof( uint64_t );
            break;
            
            case nvinfer1::DataType::kINT32:
            case nvinfer1::DataType::kFLOAT:
            size = sizeof( uint32_t );
            break;
            
            case nvinfer1::DataType::kHALF:
            case nvinfer1::DataType::kBF16:
            size = sizeof( uint16_t );
            break;
            
            case nvinfer1::DataType::kFP8:
            case nvinfer1::DataType::kINT8:
            case nvinfer1::DataType::kBOOL:
            case nvinfer1::DataType::kUINT8:
            size = sizeof( uint8_t );
            break;
            
            default:
            break;
        }

        return size;
    }
}

bool ConvertONNXToTRT(

    const Options& options,

    const std::string& onnxModelPath,

    std::string& trtFile,

    const std::string prefix,

    bool forceConvert

)

{
    if ( !FileExists( onnxModelPath ) )
    {
        LOG_ERROR( "Cannot find ONNX mode at path: " + onnxModelPath );
        return false;
    }

    // Find a hash string identifying the onnx we're going to convert to 
    // tensorrt, plus the gpu we're going to convert it for:
    std::ifstream file(onnxModelPath, std::ios::binary);
    std::string trtHash = picosha2::hash256_hex_string(
        std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()
    );

    // hash in the cuda device name and precision::
    trtHash = picosha2::hash256_hex_string(trtHash + GetCudaDeviceName( options.deviceID ));
    trtHash = picosha2::hash256_hex_string(trtHash + std::to_string(int(options.precision)));

    // name of the tensorrt we're going to write to (same directory as the ONNX model):
    const auto filenamePos = onnxModelPath.find_last_of( '/' ) + 1;
    const auto onnxDir = onnxModelPath.substr(0, filenamePos);
    trtFile = onnxDir + prefix + onnxModelPath.substr( filenamePos, onnxModelPath.find_last_of( '.' ) - filenamePos );
    trtFile += ".trt";

    if (!forceConvert && FileExists( trtFile ) )
    {
        std::ifstream file(trtFile, std::ios::binary);
        
        std::string hashInFile;
        hashInFile.resize(trtHash.size());

        file.read(const_cast<char*>(hashInFile.c_str()), trtHash.size());

        std::cerr << "hash value in file " <<  hashInFile << std::endl;
        std::cerr << "hash of onnx/gpu type " << trtHash << std::endl;

        if(hashInFile == trtHash)
        {
            return true;
        }
        LOG_INFO( "TRT file " + trtFile + " is out of date and needs to be regenerated. This could take a while..." );
    }
    else
    {
        LOG_INFO( "TRT file " + trtFile + " not found. This could take a while to generate..." );
    }


    // Create engine builder
    auto builder = std::unique_ptr<nvinfer1::IBuilder>( nvinfer1::createInferBuilder( s_logger ) );
    if ( !builder )
    {
        LOG_ERROR( "Could not create builder." );
        return false;
    }

    // Create network
    const uint32_t explicitBatch = 1U << static_cast<uint32_t>( nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH );
    auto network = std::unique_ptr<nvinfer1::INetworkDefinition>( builder->createNetworkV2( explicitBatch ) );
    if ( !network )
    {
        LOG_ERROR( "Could not create network." );
        return false;
    }

    // Create a parser for reading the onnx file.
    auto parser = std::unique_ptr<nvonnxparser::IParser>( nvonnxparser::createParser( *network, s_logger ) );
    if ( !parser )
    {
        LOG_ERROR( "Could not create ONNX parser." );
        return false;
    }

    // Read and parse the ONNX file
    auto parsed = parser->parseFromFile( onnxModelPath.c_str(), 0 );
    if ( !parsed )
    {
        LOG_ERROR( "Unable to parse the ONNX model at: " + onnxModelPath );
        return false;
    }

    // Ensure that all the inputs have the same batch size
    const int32_t inputCount = network->getNbInputs();
    if ( inputCount < 1 )
    {
        LOG_ERROR( "Model has no inputs." );
        return false;
    }

    // Set dynamic axis info for inputs:
    auto profile = builder->createOptimizationProfile();
    for ( int32_t i = 0; i < inputCount; ++i )
    {
        auto t = network->getInput( i );
        const auto name = t->getName();
        auto dims = t->getDimensions();

        bool hasDynamicAxes = false;
        auto dimsMin = dims;
        auto dimsOpt = dims;
        auto dimsMax = dims;

        for ( int32_t n = 0; n < dims.nbDims; ++n )
        {
            if ( dims.d[n] == -1 )
            {
                auto axis_sizes = options.defaultSizes;
                if (options.dynamic_axes_names.contains(t->getName()))
                {
                    auto& dynamic_axis_names = options.dynamic_axes_names.at(t->getName());
                    if (!dynamic_axis_names.contains(n))
                    {
                        LOG_ERROR("Tensor " + std::string(t->getName()) + " has a dynamic axes, but its name isn't specified in options.input_dynamic_axes");
                        return false;
                    }

                    auto axis_name = dynamic_axis_names.at(n);
                    if (!options.dynamic_axes_sizes.contains(axis_name))
                    {
                        LOG_ERROR("Named axis " + axis_name + " has no entry in options.dynamic_axes_sizes");
                        return false;
                    }
                    axis_sizes = options.dynamic_axes_sizes.at(axis_name);
                }

                hasDynamicAxes = true;
                dimsMin.d[n] = std::get<0>( axis_sizes );
                dimsOpt.d[n] = std::get<1>( axis_sizes );
                dimsMax.d[n] = std::get<2>( axis_sizes );
            }
        }
        profile->setDimensions( name, nvinfer1::OptProfileSelector::kMIN, dimsMin );
        profile->setDimensions( name, nvinfer1::OptProfileSelector::kOPT, dimsOpt );
        profile->setDimensions( name, nvinfer1::OptProfileSelector::kMAX, dimsMax );

        if ( t->isShapeTensor() )
        {
            if ( !options.shape_tensor_sizes.contains( name ) )
            {
                LOG_ERROR( "Tensor " + std::string( name ) + " controls the shape of an internal tensor and needs an entry in options.shape_tensor_sizes" );
                return false;
            }
            auto &sizes = options.shape_tensor_sizes.at( name );

            profile->setShapeValues( name, nvinfer1::OptProfileSelector::kMIN, std::get<0>( sizes ).data(), std::get<0>( sizes ).size());
            profile->setShapeValues( name, nvinfer1::OptProfileSelector::kOPT, std::get<1>( sizes ).data(), std::get<1>( sizes ).size() );
            profile->setShapeValues( name, nvinfer1::OptProfileSelector::kMAX, std::get<2>( sizes ).data(), std::get<2>( sizes ).size() );
        }
    }

    auto config = std::unique_ptr<nvinfer1::IBuilderConfig>( builder->createBuilderConfig() );
    if ( !config )
    {
        LOG_ERROR( "Could not create builder config." );
        return false;
    }
    config->addOptimizationProfile( profile );

    // Set the precision level
    if ( options.precision == Precision::FP16 )
    {
        // Ensure the GPU supports FP16 inference
        if ( !builder->platformHasFastFp16() )
        {
            LOG_ERROR( "GPU does not support FP16 precision." );
            return false;
        }
        config->setFlag( nvinfer1::BuilderFlag::kFP16 );
    }

    // CUDA stream used for profiling by the builder.
    cudaStream_t stream;
    s_logger.log( cudaStreamCreate( &stream ) );
    config->setProfileStream( stream );

    // Build the engine
    // If this call fails, it is suggested to increase the logger verbosity to kVERBOSE and try rebuilding the engine.
    // Doing so will provide you with more information on why exactly it is failing.
    auto serializedNetwork = builder->buildSerializedNetwork( *network, *config );
    if ( !serializedNetwork )
    {
        s_logger.log( cudaStreamDestroy( stream ) );

        LOG_ERROR( "Failed to build the engine!" );
        return false;
    }

    // Write the engine to disk
    std::ofstream outfile( trtFile, std::ofstream::binary );

    // Write the onnx/gpu hash first:
    outfile.write( trtHash.c_str(), trtHash.size() );

    // Write the engine:
    outfile.write( reinterpret_cast<const char*>( serializedNetwork->data() ), serializedNetwork->size() );

    LOG_INFO( "Saved TRT file to " + trtFile );
    s_logger.log( cudaStreamDestroy( stream ) );

    return true;
}

class TRTInferenceEngine::Impl
{
public:
    
    ~Impl()
    {
        Destroy();
    }

    bool Initialize( const std::string& trtPath, int deviceIndex, const Options::AxisNames& axisNames )

    {
        Destroy();

        // Read the serialized model from disk
        std::ifstream file( trtPath, std::ios::binary | std::ios::ate );
        std::streamsize size = file.tellg();
        if (size < 0)
        {
            LOG_ERROR("Unable to read engine file!");
            return false;
        }

        file.seekg( 0, std::ios::beg );
        std::vector<char> buffer( size );
        if ( !file.read( buffer.data(), size ) )
        {
            LOG_ERROR( "Unable to read engine file!" );
            return false;
        }

        // Create runtime to deserialize the engine file.
        m_runtime = std::unique_ptr<nvinfer1::IRuntime>( nvinfer1::createInferRuntime( s_logger ) );
        if ( !m_runtime )
        {
            LOG_ERROR( "Unable to create a runtime inference model." );
            return false;
        }

        // Set the device index
        if ( cudaSetDevice( deviceIndex ) != cudaError_t::cudaSuccess )
        {
            int gpuCount;
            cudaGetDeviceCount( &gpuCount );
            LOG_ERROR( "Unable to set GPU device index to " + std::to_string( deviceIndex ) + ". Current device has " + std::to_string( gpuCount ) + " CUDA - capable GPU(s)." );
            return false;
        }

        // Create an engine, a representation of the optimized model.
        // skip the first 64 bytes when deserializing the engine file as they just contain a hash:
        m_engine = std::unique_ptr<nvinfer1::ICudaEngine>( m_runtime->deserializeCudaEngine( buffer.data() + 64, buffer.size() - 64 ) );
        if ( !m_engine )
        {
            LOG_ERROR("Unable to create engine.");
            return false;
        }

        // The execution context contains all of the state associated with a particular invocation
        m_context = std::unique_ptr<nvinfer1::IExecutionContext>( m_engine->createExecutionContext() );
        if ( !m_context )
        {
            LOG_ERROR("Unable to create execution context.");
            return false;
        }

        m_axis_names = axisNames;

        const uint32_t tensorCount = m_engine->getNbIOTensors();
        for (int32_t i = 0; i < tensorCount; ++i)
        {
            const auto tensorName = m_engine->getIOTensorName(i);
            const auto tensorIOMode = m_engine->getTensorIOMode(tensorName);
            m_dataTypeSizes[tensorName] = SizeOfTensorDataType(m_engine->getTensorDataType(tensorName));
        }
        
        return true;
    }


    bool InitInputs(const AxisSizes& axisSizes)

    {
        DestroyBuffers();

        const uint32_t tensorCount = m_engine->getNbIOTensors();
        for (int32_t i = 0; i < tensorCount; ++i)
        {
            const auto tensorName = m_engine->getIOTensorName(i);
            const auto tensorIOMode = m_engine->getTensorIOMode(tensorName);
            auto tensorShape = m_engine->getTensorShape(tensorName);
            const auto tensorDataType = m_engine->getTensorDataType(tensorName);

            for (int32_t n = 0; n < tensorShape.nbDims; ++n)
            {
                if (tensorShape.d[n] == -1)
                {
                    int64_t batchSize = 1;
                    if (m_axis_names.contains(tensorName))
                    {

                        auto& dynamic_axis_names = m_axis_names.at(tensorName);
                        if (!dynamic_axis_names.contains(n))
                        {
                            LOG_ERROR("Tensor " + std::string(tensorName) + " has a dynamic axes, but its name isn't specified in axisNames");
                            return false;
                        }

                        auto axis_name = dynamic_axis_names.at(n);
                        if (!axisSizes.contains(axis_name))
                        {
                            LOG_ERROR("Named axis " + axis_name + " has no entry in axisSizes");
                            return false;
                        }

                        batchSize = axisSizes.at(axis_name);
                    }
                    else if (axisSizes.size() > 0)
                    {
                        batchSize = axisSizes.begin()->second;
                    }

                    tensorShape.d[n] = batchSize;
                    if (tensorIOMode == nvinfer1::TensorIOMode::kINPUT)
                    {
                        auto batchMin = m_engine->getProfileShape(tensorName, 0, nvinfer1::OptProfileSelector::kMIN).d[n];
                        auto batchMax = m_engine->getProfileShape(tensorName, 0, nvinfer1::OptProfileSelector::kMAX).d[n];
                        if (batchSize < batchMin || batchSize > batchMax)
                        {
                            LOG_ERROR("Batch size " + std::to_string(batchSize) + " is outside of possible range [ " + std::to_string(batchMin) + ", " + std::to_string(batchMax) + "].");
                            return false;
                        }
                    }
                }
            }

            m_tensorShapes[tensorName] = tensorShape;
            static const std::string dataTypeStr[] = { "FLOAT", "HALF", "INT8", "INT32", "BOOL", "UINT8", "FP8", "BF16", "INT64" };
            static const std::string ioTypeStr[] = { "NONE", "INPUT", "OUTPUT" };
            std::string tensorInfo = ioTypeStr[int(tensorIOMode)] + " Tensor: " + std::string(tensorName) + " [";
            size_t elementCount = 1;
            for (int32_t d = 0; d < tensorShape.nbDims; ++d)
            {
                if (d != 0)
                    tensorInfo += ", ";

                tensorInfo += std::to_string(tensorShape.d[d]);

                if (elementCount > INT64_MAX / tensorShape.d[d])
                {
                    LOG_ERROR("Tensor too large: element count overflow");
                    return false;
                }
                elementCount *= tensorShape.d[d];
            }
            tensorInfo += "]. " + std::to_string(elementCount) + " elements of type " + dataTypeStr[int(tensorDataType)];
            LOG_INFO(tensorInfo);

            const auto sizeOfTensorData = SizeOfTensorDataType(tensorDataType);
            if (sizeOfTensorData == -1)
            {
                LOG_ERROR("Unknown tensor data type " + std::to_string((int)tensorDataType) + ".");
                return false;
            }

            void* cudaBuffer;
            size_t size = elementCount * sizeOfTensorData;
            auto err = cudaMalloc(&cudaBuffer, size);
            s_logger.log(err);
            if (err != cudaSuccess)
            {
                LOG_ERROR("Failed to allocate CUDA memory");
                return false;
            }

            s_logger.log(cudaMemset(cudaBuffer, 0, size));

            m_context->setTensorAddress(tensorName, cudaBuffer);
            if (tensorIOMode == nvinfer1::TensorIOMode::kINPUT)
            {
                m_inputBuffers[tensorName] = cudaBuffer;
            }
            else
            {
                m_outputBuffers[tensorName] = cudaBuffer;
            }
        }

        // Set input tensor shapes to specified batch size
        for (int i = 0; i < tensorCount; ++i)
        {
            const auto tensorName = m_engine->getIOTensorName(i);
            if (m_engine->getTensorIOMode(tensorName) != nvinfer1::TensorIOMode::kINPUT)
                continue;

            auto tensorShape = m_tensorShapes[tensorName];

            m_context->setInputShape(tensorName, tensorShape);
        }

        return true;
    }

    void DestroyBuffers()

    {
        for (auto& kv : m_inputBuffers)
        {
            s_logger.log(cudaFree(kv.second));
        }
        for (auto& kv : m_outputBuffers)
        {
            s_logger.log(cudaFree(kv.second));
        }

        m_inputBuffers.clear();
        m_outputBuffers.clear();
        m_tensorShapes.clear();
    }

    void Destroy()

    {
        DestroyBuffers();

        m_context.reset();
        m_engine.reset();
        m_runtime.reset();
    }

    bool ValidateTensorSize(const std::string& name, size_t byteCount) const

    {
        if (m_tensorShapes.empty())
        {
            LOG_ERROR("ValidateTensorSize: InitInputs has not been called.");
            return false;
        }

        if (!m_tensorShapes.contains(name))
        {
            LOG_ERROR("ValidateTensorSize: Tensor " + name + " not found.");
            return false;
        }

        size_t elementCount = 1;
        const auto& tensorShape = m_tensorShapes.at(name);
        for (int32_t d = 0; d < tensorShape.nbDims; ++d)
            elementCount *= tensorShape.d[d];

        const size_t expectedByteCount = elementCount * m_dataTypeSizes.at(name);
        if (expectedByteCount != byteCount)
        {
            LOG_ERROR(
                "Invalid data size for tensor [" + name + "] containing " + std::to_string(elementCount) + " elements. Expected " +
                std::to_string(expectedByteCount) + " bytes, got " + std::to_string(byteCount) + " bytes instead.");
            return false;
        }

        return true;
    }

    std::vector<std::string> GetInputBufferNames() const

    {
        std::vector<std::string> names;
        names.reserve(m_inputBuffers.size());

        for (const auto& pair : m_inputBuffers) 
        {
            names.push_back(pair.first);
        }
        return names;
    }

    std::vector<std::string> GetOutputBufferNames() const

    {
        std::vector<std::string> names;
        names.reserve(m_outputBuffers.size());

        for (const auto& pair : m_outputBuffers)
        {
            names.push_back(pair.first);
        }
        return names;
    }

    void SetInputData(const std::string& name, const void* data, size_t byteCount)

    {
        if(!ValidateTensorSize(name, byteCount))
        {
            LOG_ERROR("SetInputData: Tensor " + name + " is not valid.");
            return;
        }
        s_logger.log(cudaMemcpy(m_inputBuffers[name], data, byteCount, cudaMemcpyHostToDevice));
    }

    void SetInputDataAsync(const std::string& name, const void* data, size_t byteCount, cudaStream_t stream)

    {
        if(!ValidateTensorSize(name, byteCount))
        {
            LOG_ERROR("SetInputDataAsync: Tensor " + name + " is not valid.");
            return;
        }
        s_logger.log(cudaMemcpyAsync(m_inputBuffers[name], data, byteCount, cudaMemcpyHostToDevice, stream));
    }

    void GetOutputData(const std::string& name, void* data, size_t byteCount)

    {
        if(!ValidateTensorSize(name, byteCount))
        {
            LOG_ERROR("GetOutputData: Tensor " + name + " is not valid.");
            return;
        }
        s_logger.log(cudaMemcpy(data, m_outputBuffers[name], byteCount, cudaMemcpyDeviceToHost));
    }

    void GetOutputDataAsync(const std::string& name, void* data, size_t byteCount, cudaStream_t stream)

    {
        if(!ValidateTensorSize(name, byteCount))
        {
            LOG_ERROR("GetOutputDataAsync: Tensor " + name + " is not valid.");
            return;
        }
        s_logger.log(cudaMemcpyAsync(data, m_outputBuffers[name], byteCount, cudaMemcpyDeviceToHost, stream));
    }

    bool Enqueue( cudaStream_t stream )

    {
        if (m_tensorShapes.empty())
        {
            LOG_ERROR("Enqueue: InitInputs has not been called.");
            return false;
        }

        if (!m_context->allInputDimensionsSpecified())
        {
            LOG_ERROR("Inference engine inputs aren't defined.");
            return false;
        }

        if(!m_context->enqueueV3(stream))
        {
            LOG_ERROR("Enqueue: Failed to enqueue.");
            return false;
        }
        return true;
    }

    bool GetTensorShape(std::string name, std::vector<int64_t>& shape) const

    {
        if (m_tensorShapes.empty())
        {
            LOG_ERROR("ValidateTensorSize: InitInputs has not been called.");
            return false;
        }

        if (!m_tensorShapes.contains(name))
        {
            LOG_ERROR("ValidateTensorSize: Tensor " + name + " not found.");
            return false;
        }

        const auto& tensorShape = m_tensorShapes.at(name);
        shape.clear();
        for (int dim=0; dim < tensorShape.nbDims; ++dim)
        {
            shape.push_back(tensorShape.d[dim]);
        }
        return true;
    }

    nvinfer1::DataType GetTensorDataType(std::string name) const

    {
        auto tensorDataType = m_engine->getTensorDataType(name.c_str());
        return tensorDataType;
    }

    std::unique_ptr<nvinfer1::IExecutionContext> m_context = nullptr;
    std::unique_ptr<nvinfer1::ICudaEngine> m_engine = nullptr;
    std::unique_ptr<nvinfer1::IRuntime> m_runtime = nullptr;

    std::map<std::string, nvinfer1::Dims> m_tensorShapes;

    std::map<std::string, void*> m_inputBuffers;
    std::map<std::string, void*> m_outputBuffers;

    std::map<std::string, int> m_dataTypeSizes;

    Options::AxisNames m_axis_names;
};

TRTInferenceEngine::TRTInferenceEngine() : m_impl( new Impl )
{
}

TRTInferenceEngine::~TRTInferenceEngine()
{
}

bool TRTInferenceEngine::Initialize(const std::string& trtPath, int deviceIndex, const Options::AxisNames& axisNames)

{
    return m_impl->Initialize(trtPath, deviceIndex, axisNames);
}

bool TRTInferenceEngine::InitInputs(const AxisSizes& axisSizes)

{
    return m_impl->InitInputs(axisSizes);
}

void TRTInferenceEngine::Destroy()

{
    m_impl->Destroy();
}

std::vector<std::string> TRTInferenceEngine::GetInputTensorNames() const

{
    return m_impl->GetInputBufferNames();
}

std::vector<std::string> TRTInferenceEngine::GetOutputTensorNames() const

{
    return m_impl->GetOutputBufferNames();
}

void TRTInferenceEngine::SetInputData(const std::string& name, const void* data, size_t byteCount)

{
    m_impl->SetInputData(name, data, byteCount);
}

void TRTInferenceEngine::GetOutputData(const std::string& name, void* data, size_t byteCount)

{
    m_impl->GetOutputData( name, data, byteCount);
}

void TRTInferenceEngine::SetInputDataAsync(const std::string& name, const void* data, size_t byteCount, cudaStream_t stream)

{
    m_impl->SetInputDataAsync(name, data, byteCount, stream);
}

void TRTInferenceEngine::GetOutputDataAsync(const std::string& name, void* data, size_t byteCount, cudaStream_t stream)

{
    m_impl->GetOutputDataAsync(name, data, byteCount, stream);
}

bool TRTInferenceEngine::Enqueue(cudaStream_t stream)

{
    return m_impl->Enqueue(stream);
}

bool TRTInferenceEngine::GetTensorShape(std::string name, std::vector<int64_t>& shape) const

{
    return m_impl->GetTensorShape(name, shape);
}

DataType TRTInferenceEngine::GetTensorDataType(std::string name) const

{
    auto dataType = m_impl->GetTensorDataType(name);
    switch (dataType)
    {
        case nvinfer1::DataType::kFLOAT:
        return DataType::FLOAT;
        case nvinfer1::DataType::kHALF:
        return DataType::HALF;
        case nvinfer1::DataType::kINT8:
        return DataType::INT8;
        case nvinfer1::DataType::kINT32:
        return DataType::INT32;
        case nvinfer1::DataType::kBOOL:
        return DataType::BOOL;
        case nvinfer1::DataType::kUINT8:
        return DataType::UINT8;
        case nvinfer1::DataType::kINT64:
        return DataType::INT64;
        default:
        LOG_ERROR("ValidateTensorSize: Tensor " + name + " not found.");
        return DataType::UNKNOWN;
    }
}