Image Classification

Preparing the Input Data Structure

Classification expects a directory of images with the following structure, where each class has its own directory with the class name. The naming convention for train/val/test can be different because the path of each set is individually specified in the spec file. See the Specification File for Classification section for more information.

|--dataset_root:
    |--train
        |--audi:
            |--1.jpg
            |--2.jpg
        |--bmw:
            |--01.jpg
            |--02.jpg
    |--val
        |--audi:
            |--3.jpg
            |--4.jpg
        |--bmw:
            |--03.jpg
            |--04.jpg
    |--test
        |--audi:
            |--5.jpg
            |--6.jpg
        |--bmw:
            |--05.jpg
            |--06.jpg

Creating an Experiment Spec File - Specification File for Classification

Here is an example of a specification file for model classification:

model_config {
# Model Architecture can be chosen from:
# ['resnet', 'vgg', 'googlenet', 'alexnet']
arch: "resnet"
# for resnet --> n_layers can be [10, 18, 50]
# for vgg --> n_layers can be [16, 19]
n_layers: 101
use_batch_norm: True
use_bias: False
all_projections: False
use_pooling: True
use_imagenet_head: True
resize_interpolation_method: BICUBIC
# if you want to use the pretrained model,
# image size should be "3,224,224"
# otherwise, it can be "3, X, Y", where X,Y >= 16
input_image_size: "3,224,224"
}
train_config {
train_dataset_path: "/path/to/your/train/data"
val_dataset_path: "/path/to/your/val/data"
pretrained_model_path: "/path/to/your/pretrained/model"
# Only ['sgd', 'adam'] are supported for optimizer
optimizer {
    sgd {
    lr: 0.01
    decay: 0.0
    momentum: 0.9
    nesterov: False
    }
}
batch_size_per_gpu: 50
n_epochs: 150
# Number of CPU cores for loading data
n_workers: 16
# regularizer
reg_config {
    # regularizer type can be "L1", "L2" or "None".
    type: "L2"
    # if the type is not "None",
    # scope can be either "Conv2D" or "Dense" or both.
    scope: "Conv2D,Dense"
    # 0 < weight decay < 1
    weight_decay: 0.000015
}
# learning_rate
lr_config {
    cosine {
    learning_rate: 0.04
    soft_start: 0.0
    }
}
enable_random_crop: True
enable_center_crop: True
enable_color_augmentation: True
mixup_alpha: 0.2
label_smoothing: 0.1
}

The classification experiment specification consists of three main components:

  • model_config

  • eval_config

  • train_config

Model Config

The table below describes the configurable parameters in the model_config.

Parameter

Datatype

Default

Description

Supported Values

all_projections

bool

False

For templates with shortcut connections, this parameter defines whether or not all shortcuts should be instantiated with 1x1 projection layers irrespective of whether there is a change in stride across the input and output.

True or False (only to be used in ResNet templates)

arch

string

resnet

This defines the architecture of the back bone feature extractor to be used to train.

  • resnet

  • vgg

  • mobilenet_v1

  • mobilenet_v2

  • googlenet

  • darknet

  • efficientnet_b0

n_layers

int

18

Depth of the feature extractor for scalable templates.

  • resnets: 10, 18, 34, 50, 101

  • vgg: 16, 19

  • darknet: 19, 53

use_pooling

Boolean

False

Choose between using strided convolutions or MaxPooling while downsampling. When True, MaxPooling is used to down sample, however for the object detection network, NVIDIA recommends setting this to False and using strided convolutions.

True or False

use_batch_norm

Boolean

False

Boolean variable to use batch normalization layers or not.

True or False

freeze_blocks

float (repeated)

This parameter defines which blocks may be frozen from the instantiated feature extractor template, and is different for different feature extractor templates.

  • ResNet series: For the ResNet series, the block ID’s valid for freezing is any subset of {0, 1, 2, 3}(inclusive)

  • VGG series: For the VGG series, the block ID’s valid for freezing is any subset of {1, 2, 3, 4, 5}(inclusive)

  • MobileNet V1: For the MobileNet V1, the block ID’s valid for freezing is any subset of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}(inclusive)

  • MobileNet V2: For the MobileNet V2, the block ID’s valid for freezing is any subset of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}(inclusive)

  • GoogLeNet: For the GoogLeNet, the block ID’s valid for freezing is any subset of {0, 1, 2, 3, 4, 5, 6, 7}(inclusive)

  • DarkNet: For DarkNet, the valid blocks IDs is any subset of {0, 1, 2, 3, 4, 5}(inclusive)

  • EfficientNet B0: For EfficientNet, the valid block IDs is any subset of {0, 1, 2, 3, 4, 5, 6, 7}(inclusive)

freeze_bn

Boolean

False

You can choose to freeze the Batch Normalization layers in the model during training.

True or False

input_image_size

String

"3,224,224"

The dimension of the input layer of the model. Images in the dataset will be resized to this shape by the dataloader when fed to the model for training.

C,X,Y, where C=1 or C=3 and X,Y >=16 and X,Y are integers.

resize_interpolation_method

enum

BILEANER

The interpolation method for resizing the input images.

BILINEAR, BICUBIC

use_imagenet_head

Boolean

False

Whether or not to use the header layers as in the original implementation on ImageNet. Set this to True to reproduce the accuracy on ImageNet as in the literature. If set to False, a Dense layer will be used for header, which can be different from the literature.

True or False

dropout

float

0.0

Dropout rate for Dropout layers in the model. This is only valid for VGG and SqueezeNet.

Float in the interval [0, 1)

batch_norm_config

proto message

Parameters for BatchNormalization layers.

activation

proto message

Parameters for the activation functions in the model.

BatchNormalization Parameters

The parameter batch_norm_config defines parameters for BatchNormalization layers in the model (momentum and epsilon).

Parameter

Datatype

Default

Description

Supported Values

momentum

float

0.9

Momentum of BatchNormalization layers.

float in the interval (0, 1), usually close to 1.0.

epsilon

float

1e-5

Epsilon to avoid zero division.

float that is close to 0.0.

Activation functions

The parameter activation defines the parameters for activation functions in the model.

Parameter

Datatype

Default

Description

Supported Values

activation_type

String

Type of the activation function.

Only relu and swish are supported.

Eval Config

The table below defines the configurable parameters for evaluating a classification model.

Parameter

Datatype

Default

Description

Supported Values

eval_dataset_path

string

UNIX format path to the root directory of the evaluation dataset.

UNIX format path.

model_path

string

UNIX format path to the root directory of the model file you would like to evaluate.

UNIX format path.

top_k

int

5

The number elements to look at when calculating the top-K classification categorical accuracy metric.

1, 3, 5

batch_size

int

256

Number of images per batch when evaluating the model.

>1 (bound by the number of images that can be fit in the GPU memory)

n_workers

int

8

Number of workers fetching batches of images in the evaluation dataloader.

>1

enable_center_crop

Boolean

True

Enable center crop for input images or not. Usually this parameter is set to True to achieve better accuracy.

True or False

Training Config

This section defines the configurable parameters for the classification model trainer.

Parameter

Datatype

Default

Description

Supported Values

val_dataset_path

string

UNIX format path to the root directory of the validation dataset.

UNIX format path.

train_dataset_path

string

UNIX format path to the root directory of the training dataset.

UNIX format path.

pretrained_model_path

string

UNIX format path to the model file containing the pretrained weights to initialize the model from.

UNIX format path.

batch_size_per_gpu

int

32

This parameter defines the number of images per batch per gpu.

>1

n_epochs

int

120

This parameter defines the total number of epochs to run the experiment.

n_workers

int

False

Number of workers fetching batches of images in the training/validation dataloader.

>1

lr_config

proto message

The parameters for learning rate scheduler.

reg_config

proto message

The parameters for regularizers.

optimizer

proto message

This parameter defines which optimizer to use for training. Can be choosen from sgd, adam, or rmsprop

random_seed

int

Random seed for training.

enable_random_crop

Boolean

True

A flag to enable random crop during training.

True or False

enable_center_crop

Boolean

True

A flag to enable center crop during validation.

True or False

enable_color_augmentation

Boolean

True

A flag to enable color augmentation during training.

True or False

label_smoothing

float

0.1

A factor used for label smoothing.

in the interval (0, 1)

mixup_alpha

float

0.2

A factor used for mixup augmentation.

in the interval (0, 1)

preprocess_mode

string

'caffe'

Mode for input image preprocessing. Defaults to ‘caffe’.

‘caffe’, ‘torch’, ‘tf’

Learning Rate Scheduler

The parameter lr_config defines the parameters for learning rate scheduler The learning rate scheduler can be either step, soft_anneal or cosine.

Step

The parameter step defines the step learning rate scheduler.

Parameter

Datatype

Default

Description

Supported Values

learning_rate

float

The base(maximum) learning rate value.

Positive, usually in the interval (0, 1).

step_size

int

The progress (percentage of the entire training duration) after which the learning rate will be decreased.

Less than 100.

gamma

float

The multiplicative factor used to decrease the learning rate.

In the interval (0, 1).

Note

The learning rate is automatically scaled with the number of GPUs used during training, or the effective learning rate is learning_rate * n_gpu.

Soft Annealing

The parameter soft_anneal defines the soft annealing learning rate scheduler.

Parameter

Datatype

Default

Description

Supported Values

learning_rate

float

The base (maximum) learning rate value.

Positive, usually in the interval (0, 1).

soft_start

float

The progress at which learning rate achieves the base learning rate.

In the interval (0, 1).

annealing_divider

float

The divider by which the learning rate will be scaled down.

Greater than 1.0.

annealing_points

repeated float

Points of progress at which the learning rate will be decreased.

List of floats. Each will be in the interval (0, 1).

Cosine

The parameter cosine defines the cosine learning rate scheduler.

Parameter

Datatype

Default

Description

Supported Values

learning_rate

float

The base (maximum) learning rate.

Usually less than 1.0

min_lr_ratio

float

The ratio of minimum learning rate to the base learning rate.

Less than 1.0

soft_start

float

The progress at which learning rate achieves the base learning rate.

In the interval (0, 1).

Training the model

Use the tlt classification train command to tune a pre-trained model:

tlt classification train -e <spec file>
                         -k <encoding key>
                         -r <result directory>
                         [--gpus <num GPUs>]
                         [--gpu_index <gpu_index>]
                         [--use_amp]
                         [--log_file <log_file_path>]
                         [-h]

Required Arguments

  • -r, --results_dir: Path to a folder where the experiment outputs should be written.

  • -k, --key: User specific encoding key to save or load a .tlt model.

  • -e, --experiment_spec_file: Path to the experiment spec file.

Optional Arguments

  • --gpus: Number of GPUs to use and processes to launch for training. The default value is 1.

  • --gpu_index: The GPU indices used to run the training. We can specify the GPU indices used to run training when the machine has multiple GPUs installed.

  • --use_amp: A flag to enable AMP training.

  • --log_file: Path to the log file. Defaults to stdout.

  • -h, --help: Print the help message.

Note

See the Specification File for Classification section for more details.

Here’s an example of using the tlt classification train command:

tlt classification train -e /workspace/tlt_drive/spec/spec.cfg -r /workspace/output -k $YOUR_KEY

Evaluating the Model

After the model has been trained, using the experiment config file, and by following the steps to train a model, the next step is to evaluate this model on a test set to measure the accuracy of the model. The TLT toolkit includes the tlt classification evaluate command to do this.

The classification app computes evaluation loss, Top-k accuracy, precision, and recall as metrics.

When training is complete, the model is stored in the output directory of your choice in $OUTPUT_DIR. Evaluate a model using the tlt classification evaluate command:

tlt classification evaluate -e <experiment_spec_file>
                            -k <key>
                            [--gpu_index <gpu_index>]
                            [--log_file <log_file>]
                            [-h]

Required Arguments

  • -e, --experiment_spec_file: Path to the experiment spec file.

  • -k, –key: Provide the encryption key to decrypt the model.

Optional Arguments

  • -h, --help: Show this help message and exit.

  • --gpu_index: The GPU indices used to run the training. We can specify the GPU indices used to run training when the machine has multiple GPUs installed.

  • --log_file: Path to the log file. Defaults to stdout.

If you followed the example in training a classification model, run the evaluation:

tlt classification evaluate -e classification_spec.cfg -k $YOUR_KEY

TLT evaluates for classification and produces the following metrics:

  • Loss

  • Top-K accuracy

  • Precision (P): TP / (TP + FP)

  • Recall (R): TP / (TP + FN)

  • Confusion Matrix

Running Inference on a Model

The tlt classification inference command runs the inference on a specified set of input images. For classification, tlt classification inference provides class label output over the command-line for a single image or a csv file containing the image path and the corresponding labels for multiple images. TensorRT Python inference can also be enabled.

Execute tlt classification inference on a classification model trained on TLT.

tlt classification inference -m <model> -i <image> -d <image  dir> -k <key> -cm <classmap> -e <experiment_spec_file> [-b <batch size>] [--gpu_index <gpu_index>] [--log_file <log_file>] [-h]

Here are the arguments of the tlt classification inference tool:

Required arguments

  • -m, --model: Path to the pretrained model (TLT model).

  • -i, --image: A single image file for inference.

  • -d, --image_dir: The directory of input images for inference.

  • -k, --key: Key to load model.

  • -cm, --class_map: The json file that specifies the class index and label mapping.

  • -e, --experiment_spec_file: Path to the experiment spec file.

Optional arguments

  • --batch_size: Inference batch size, default: 1

  • -h, --help: Show this help message and exit.

  • --gpu_index: The GPU indices used to run the training. We can specify the GPU indices used to run training when the machine has multiple GPUs installed.

  • --log_file: Path to the log file. Defaults to stdout.

Note

The inference tool requires a cluster_params.json file to configure the post processing block. When executing with -d, or directory mode, a result.csv file is created and stored in the directory you specify using -d. The result.csv has the file path in the first column and predicted labels in the second.

Note

In both single image and directory modes, a classmap (-cm) is required, which should be a by product (-classmap.json) of your training process.

Pruning the Model

Pruning removes parameters from the model to reduce the model size without compromising the integrity of the model itself using the tlt classification prune command.

The tlt classification prune command includes these parameters:

tlt classification prune -m <model>
                         -o <output_file>
                         -k <key>
                         [-n <normalizer>
                         [-eq <equalization_criterion>]
                         [-pg <pruning_granularity>]
                         [-pth <pruning threshold>]
                         [-nf <min_num_filters>]
                         [-el <excluded_list>]
                         [--gpu_index <gpu_index>]
                         [--log_file <log_file>]
                         [-h]

Required Arguments

  • -m, --model: Path to pretrained model

  • -o, --output_file: Path to output checkpoints

  • -k, --key: Key to load a .tlt model

Optional Arguments

  • -h, --help: Show this help message and exit.

  • -n, –normalizer: max to normalize by dividing each norm by the maximum norm within a layer; L2 to normalize by dividing by the L2 norm of the vector comprising all kernel norms. (default: max)

  • -eq, --equalization_criterion: Criteria to equalize the stats of inputs to an elementwise op layer, or depth-wise convolutional layer. This parameter is useful for ResNet and MobileNet. Options are arithmetic_mean, geometric_mean, union, and intersection. (default: union)

  • -pg, -pruning_granularity: Number of filters to remove at a time (default: 8)

  • -pth: Threshold to compare normalized norm against (default: 0.1)

  • -nf, --min_num_filters: Minimum number of filters to keep per layer (default: 16)

  • -el, --excluded_layers: List of excluded_layers. Examples: -i item1 item2 (default: [])

  • --gpu_index: The GPU indices used to run the training. We can specify the GPU indices used to run training when the machine has multiple GPUs installed.

  • --log_file: Path to the log file. Defaults to stdout.

After pruning, the model needs to be retrained. See Re-training the Pruned Model for more details.

Using the Prune Command

Here’s an example of using the tlt classification prune command:

tlt classification prune -m /workspace/output/weights/resnet_003.tlt \
                     -o /workspace/output/weights/resnet_003_pruned.tlt \
                     -eq union \
                     -pth 0.7 -k $KEY

Re-training the Pruned Model

After the model has been pruned, there might be a slight decrease in accuracy. This happens because some previously useful weights may have been removed. In order to regain the accuracy, NVIDIA recommends that you retrain this pruned model over the same dataset. To do this, use the tlt classification train command as documented in Training the model, with an updated spec file that points to the newly pruned model as the pretrained model file.

Users are advised to turn off the regularizer in the training_config for classification to recover the accuracy when retraining a pruned model. You may do this by setting the regularizer type to NO_REG. All the other parameters may be retained in the spec file from the previous training.

Exporting the model

Exporting the model decouples the training process from inference and allows conversion to TensorRT engines outside the TLT environment. TensorRT engines are specific to each hardware configuration and should be generated for each unique inference environment. The exported model may be used universally across training and deployment hardware. The exported model format is referred to as .etlt. Like .tlt, the .etlt model format is also a encrypted model format with the same key of the .tlt model that it is exported from. This key is required when deploying this model.

INT8 Mode Overview

TensorRT engines can be generated in INT8 mode to improve performance, but require a calibration cache at engine creation-time. The calibration cache is generated using a calibration tensor file, if export is run with the --data_type flag set to int8. Pre-generating the calibration information and caching it removes the need for calibrating the model on the inference device. Using the calibration cache also speeds up engine creation as building the cache can take several minutes to generate depending on the size of the calibration data and the model itself.

The export tool can generate INT8 calibration cache by ingesting calibration dataset generated by the command tlt classification calibration_tensorfile.

Here is an example of the tlt calibration_tensorfile command:

tlt classification calibration_tensorfile -e <experiment_spec_file>
                                          -o <output_tensorfile>
                                          [-m <num_batches>]
                                          [-v]
                                          [--use_validation_set]

Required Arguments

  • -o, --output: Path to output tensorfile.

  • -e, --experiment_spec: Path to the spec file.

Optional Arguments

  • -m, --max_batches: Number of batches of calibration data. The batch size is the training batch size as in spec file.

  • -v, --verbose: Set verbosity of the log.

  • --use_validation_set: Use validation dataset only if this flag is set.

FP16/FP32 Model

The calibration.bin is only required if you need to run inference at INT8 precision. For FP16/FP32 based inference, the export step is much simpler. All that is required is to provide a .tlt model from the training/retraining step to be converted into an .etlt.

Exporting the Model

Here’s an example of the tlt classification export command:

tlt classification export
            -m <path to the .tlt model file generated by training>
            -k <key>
            [-o <path to output file>]
            [--cal_data_file <path to tensor file>]
            [--cal_cache_file <path to output calibration file>]
            [--data_type <data type for the TensorRT backend during export>]
            [--batches <number of batches to calibrate over>]
            [--max_batch_size <maximum trt batch size>]
            [--max_workspace_size <maximum workspace size]
            [--batch_size <batch size for calibration data>]
            [--engine_file <path to the TensorRT engine file>]
            [--verbose]
            [--force_ptq]
            [--gpu_index <gpu_index>]
            [--log_file <log_file_path>]

Required Arguments

  • -m, --model: Path to the .tlt model file to be exported.

  • -k, --key: Key used to save the .tlt model file.

Optional Arguments

  • -o, --output_file: Path to save the exported model to. The default is ./<input_file>.etlt.

  • --data_type: Desired engine data type, generates calibration cache if in INT8 mode. The options are: {fp32, fp16, int8} The default value is fp32. If using INT8, the following INT8 arguments are required.

  • -s, --strict_type_constraints: A Boolean flag to indicate whether or not to apply the TensorRT strict type constraints when building the TensorRT engine.

  • --gpu_index: The index of (descrete) GPUs used for exporting the model. We can specify the GPU index to run export if the machine has multiple GPUs installed. Note that export can only run on a single GPU.

  • --log_file: Path to the log file. Defaults to stdout.

  • -v, --verbose: Verbose log.

INT8 Export Mode Required Arguments

  • --cal_data_file: The input tensorfile for calibration.

INT8 Export Optional Arguments

  • --cal_cache_file: Path to save the calibration cache file. The default value is ./cal.bin.

  • --batches: Number of batches to use for calibration and inference testing. The default value is 10.

  • --batch_size: Batch size to use for calibration. The default value is 8.

  • --max_batch_size: Maximum batch size of TensorRT engine. The default value is 16.

  • --max_workspace_size: Maximum workspace size of TensorRT engine. The default value is: 1073741824(1<<30).

  • --engine_file: Path to the serialized TensorRT engine file. Note that this file is hardware specific and cannot be generalized across GPUs. Useful to quickly test your model accuracy using TensorRT on the host. As TensorRT engine file is hardware specific, you cannot use this engine file for deployment unless the deployment GPU is identical to training GPU.

  • --force_ptq: A boolean flag to force post training quantization on the exported etlt model.

Note

When exporting a model trained with Quantization Aware Training (QAT) enabled, the tensor scale factors to calibrate the activations are peeled out of the model and serialized to a TensorRT readable cache file defined by the cal_cache_file argument. However, note that the current version of QAT doesn’t natively support DLA INT8 deployment in Jetson. In order to deploy this model on a Jetson with DLA INT8, use the --force_ptq flag to use TensorRT post training quantization to generate the calibration cache file.

Exporting a Model

Here’s a sample command using the data loader for loading calibration data to calibrate a classification model.

tlt classification export
            -m $USER_EXPERIMENT_DIR/output_retrain/weights/resnet_$EPOCH.tlt
            -o $USER_EXPERIMENT_DIR/export/final_model.etlt
            -k $KEY
            --cal_data_file $USER_EXPERIMENT_DIR/export/calibration.tensor
            --data_type int8
            --batches 10
            --cal_cache_file $USER_EXPERIMENT_DIR/export/final_model_int8_cache.bin
            -v

Deploying to DeepStream

The deep learning and computer vision models that you trained can be deployed on edge devices, such as a Jetson Xavier, Jetson Nano, or a discrete GPU or in the cloud with NVIDIA GPUs. TLT has been designed to integrate with DeepStream SDK, so models trained with TLT will work out of the box with DeepStream SDK.

DeepStream SDK is a streaming analytic toolkit to accelerate building AI-based video analytic applications. This section describes how to deploy a TLT classification model to DeepStream SDK.

There are two options to choose from when deploying a model trained by TLT to DeepStream:

  • Option 1: Integrate the .etlt model directly in the DeepStream app. The model file is generated by export.

  • Option 2: Generate a device-specific optimized TensorRT engine, using tlt-converter. The generated TensorRT engine file can also be ingested by DeepStream.

Machine specific optimizations are done as part of the engine creation process, so a distinct engine should be generated for each environment and hardware configuration. If the inference environment’s TensorRT or CUDA libraries are updated, including minor version updates or if a new model is generated, new engines need to be generated. Running an engine that was generated with a different version of TensorRT and CUDA is not supported and will cause unknown behavior that affects inference speed, accuracy, and stability, or it may fail to run altogether.

Option 1 is very straightforward. The .etlt file and calibration cache are directly used by DeepStream. DeepStream will automatically generate a TensorRT engine file and then run inference. The generation of the TensorRT engine can take some time depending on size of the model and type of hardware. The generation of the TensorRT engine can be done ahead of time with Option 2. With option 2, use tlt-converter to convert the .etlt file to TensorRT engine and then provide the engine file directly to DeepStream.

Running TLT models on DeepStream for image classification, shown on the top half of the table is very straightforward. All that is required is the encrypted TLT model (.etlt), optional INT8 calibration cache, and a DeepStream config file.

Generating an Engine Using tlt-converter

The tlt-converter is a tool that is provided with TLT to facilitate the deployment of TLT trained models on TensorRT and/or Deepstream. For deployment platforms with an x86 based CPU and discrete GPU’s, the tlt-converter is distributed within the TLT Docker. Therefore, it is suggested to use Docker to generate the engine. However, this requires that the user adhere to the same minor version of TensorRT as distributed with Docker. The TLT Docker includes TensorRT version 7.1. In order to use the engine with a different minor version of TensorRT, copy the converter from /opt/nvidia/tools/tlt-converter to the target machine and follow the instructions for x86 to run it and generate a TensorRT engine.

Instructions for x86

For an x86 platform with discrete GPUs, the default TLT package includes the tlt-converter built for TensorRT 7.2 with CUDA 11.1 and CUDNN 8.0. However, for any other version of CUDA and TensorRT, please refer to the overview section for download. Once the tlt-converter is downloaded, follow the instructions below to generate a TensorRT engine.

  1. Unzip the zip file on the target machine.

  2. Install the OpenSSL package using the command:

    sudo apt-get install libssl-dev
    
  3. Export the following environment variables:

$ export TRT_LIB_PATH=”/usr/lib/aarch64-linux-gnu”
$ export TRT_INC_PATH=”/usr/include/aarch64-linux-gnu”
  1. Run the tlt-converter using the sample command below and generate the engine.

Note

Make sure to follow the output node names as mentioned in Exporting the Model.

Instructions for Jetson

For the Jetson platform, the tlt-converter is available to download in the NVIDIA developer zone. You may choose the version you wish to download as listed in the overview section. Once the tlt-converter is downloaded, please follow the instructions below to generate a TensorRT engine.

  1. Unzip the zip file on the target machine.

  2. Install the OpenSSL package using the command:

    sudo apt-get install libssl-dev
    
  3. Export the following environment variables:

$ export TRT_LIB_PATH=”/usr/lib/aarch64-linux-gnu”
$ export TRT_INC_PATH=”/usr/include/aarch64-linux-gnu”
  1. For Jetson devices, TensorRT 7.1 comes pre-installed with Jetpack. If you are using older JetPack, upgrade to JetPack 4.4 or JetPack 4.5.

  2. Run the tlt-converter using the sample command below and generate the engine.

Note

Make sure to follow the output node names as mentioned in Exporting the Model.

Using the tlt-converter

tlt-converter -k <encryption_key>
              -d <input_dimensions>
              -o <comma separated output nodes>
              [-c <path to calibration cache file>]
              [-e <path to output engine>]
              [-b <calibration batch size>]
              [-m <maximum batch size of the TRT engine>]
              [-t <engine datatype>]
              [-w <maximum workspace size of the TRT Engine>]
              [-i <input dimension ordering>]
              [-p <optimization_profiles>]
              [-s]
              [-u <DLA_core>]
              [-h]
              input_file
Required Arguments
  • input_file: Path to the .etlt model exported using export.

  • -k: The key used to encode the .tlt model when doing the traning.

  • -d: Comma-separated list of input dimensions that should match the dimensions used for tlt classification export. Unlike tlt classification export this cannot be inferred from calibration data. This parameter is not required for new models introduced in TLT v3.0 (for example, LPRNet, UNet, GazeNet, etc).

  • -o: Comma-separated list of output blob names that should match the output configuration used for tlt classification export. This parameter is not required for new models introduced in TLT v3.0 (for example, LPRNet, UNet, GazeNet, etc). For classification, set this argument to predictions/Softmax.

Optional Arguments
  • -e: Path to save the engine to. The default value is ./saved.engine.

  • -t: Desired engine data type, generates calibration cache if in INT8 mode. The default value is fp32. The options are {fp32, fp16, int8}.

  • -w: Maximum workspace size for the TensorRT engine. The default value is 1073741824(1<<30).

  • -i: Input dimension ordering, all other TLT commands use NCHW. The default value is nchw. The options are {nchw, nhwc, nc}. For classification, we can omit it (defaults to nchw).

  • -p: Optimization profiles for .etlt models with dynamic shape. Comma separated list of optimization profile shapes in the format <input_name>,<min_shape>,<opt_shape>,<max_shape>, where each shape has the format: <n>x<c>x<h>x<w>. Can be specified multiple times if there are multiple input tensors for the model. This is only useful for new models introduced in TLT v3.0. This parameter is not required for models that are already existed in TLT v2.0.

  • -s: TensorRT strict type constraints. A Boolean to apply TensorRT strict type constraints when building the TensorRT engine.

  • -u: Use DLA core. Specifying DLA core index when building the TensorRT engine on Jetson devices.

INT8 Mode Arguments
  • -c: Path to calibration cache file, only used in INT8 mode. The default value is ./cal.bin.

  • -b: Batch size used during the export step for INT8 calibration cache generation. (default: 8).

  • -m: Maximum batch size for TensorRT engine.(default: 16). If met with out-of-memory issue, decrease the batch size accordingly. This parameter is not required for .etlt models generated with dynamic shape. This is only possible for new models introduced in TLT v3.0.

Sample Output Log

Here is a sample log for converting a classification model.

tlt-converter $USER_EXPERIMENT_DIR/export/final_model.etlt
               -k $KEY
               -c $USER_EXPERIMENT_DIR/export/final_model_int8_cache.bin
               -o predictions/Softmax
               -d 3,224,224
               -i nchw
               -m 64 -t int8
               -e $USER_EXPERIMENT_DIR/export/final_model.trt
               -b 64

[INFO] Some tactics do not have sufficient workspace memory to run. Increasing workspace size may increase performance, please check verbose output.
[INFO] Detected 1 inputs and 1 output network tensors.

Integrating the model to DeepStream

There are 2 options to integrate models from TLT with DeepStream:

  • Option 1: Integrate the model (.etlt) with the encrypted key directly in the DeepStream app. The model file is generated by tlt classification export.

  • Option 2: Generate a device specific optimized TensorRT engine, using tlt-converter. The TensorRT engine file can also be ingested by DeepStream.

In order to integrate the models with DeepStream, you need the following:

  1. Download and install DeepStream SDK. The installation instructions for DeepStream are provided in the DeepStream Development Guide.

  2. An exported .etlt model file and optional calibration cache for INT8 precision.

  3. A labels.txt file containing the labels for classes in the order in which the networks produces outputs.

  4. A sample config_infer_*.txt file to configure the nvinfer element in DeepStream. The nvinfer element handles everything related to TensorRT optimization and engine creation in DeepStream.

DeepStream SDK ships with an end-to-end reference application which is fully configurable. Users can configure input sources, inference model and output sinks. The app requires a primary object detection model, followed by an optional secondary classification model. The reference application is installed as deepstream-app. The graphic below shows the architecture of the reference application.

../_images/arch_ref_appl.png

There are typically 2 or more configuration files that are used with this app. In the install directory, the config files are located in samples/configs/deepstream-app or sample/configs/tlt_pretrained_models. The main config file configures all the high level parameters in the pipeline above. This would set input source and resolution, number of inferences, tracker and output sinks. The other supporting config files are for each individual inference engine. The inference specific config files are used to specify models, inference resolution, batch size, number of classes and other customization. The main config file will call all the supporting config files. Here are some config files in samples/configs/deepstream-app for your reference.

  • source4_1080p_dec_infer-resnet_tracker_sgie_tiled_display_int8.txt: Main config file

  • config_infer_primary.txt: Supporting config file for primary detector in the pipeline above

  • config_infer_secondary_*.txt: Supporting config file for secondary classifier in the pipeline above

The deepstream-app will only work with the main config file. This file will most likely remain the same for all models and can be used directly from the DeepStream SDK will little to no change. Users will only have to modify or create config_infer_primary.txt and config_infer_secondary_*.txt.

Integrating a Classification Model

See Exporting The Model for more details on how to export a TLT model. After the model has been generated, two extra files are required:

  1. Label file

  2. DeepStream configuration file

Label File

The label file is a text file, containing the names of the classes that the TLT model is trained to classify against. The order in which the classes are listed must match the order in which the model predicts the output. This order may be deduced from the classmap.json file that is generated by TLT. This file is a simple dictionary containing the ‘class_name’ to ‘index map’. For example, in the sample classification sample notebook file included with the TLT Docker, the classmap.json file generated for Pascal Visual Object Classes (VOC) would look like this:

{"sheep": 16,"horse": 12,"bicycle": 1, "aeroplane": 0, "cow": 9,
 "sofa": 17, "bus": 5, "dog": 11, "cat": 7, "person": 14, "train": 18,
 "diningtable": 10, "bottle": 4, "car": 6, "pottedplant": 15,
 "tvmonitor": 19, "chair": 8, "bird": 2, "boat": 3, "motorbike": 13}

The 0th index corresponds to aeroplane, the 1st index corresponds to bicycle, etc. up to 19 which corresponds to tvmonitor. Here is a sample label.txt file, classification_labels.txt, arranged in the order of index.

aeroplane
bicycle
bird
boat
bottle
bus
..
..
tvmonitor
DeepStream Configuration File

A typical use case for video analytic is first to do an object detection and then crop the detected object and send it further for classification. This is supported by deepstream-app and the app architecture can be seen above. For example, to classify models of cars on the road, first you will need to detect all the cars in a frame. Once you do detection, you perform classification on the cropped image of the car. In the sample DeepStream app, the classifier is configured as a secondary inference engine after the primary detection. If configured appropriately, deepstream-app will automatically crop the detected image and send the frame to the secondary classifier. The config_infer_secondary_*.txt is used to configure the classification model.

../_images/dstream_deploy_options2.png

Option 1: Integrate the model (.etlt) directly in the DeepStream app. For this option, users will need to add the following parameters in the configuration file. The int8-calib-file is only required for INT8 precision.

tlt-encoded-model=<TLT exported .etlt>
tlt-model-key=<Model export key>
int8-calib-file=<Calibration cache file>

Option 2: Integrate the TensorRT engine file with the DeepStream app.

Step 1: Generate the TensorRT engine using tlt-converter. Detail instructions are provided in the Generating an Engine Using tlt-converter section.

Step 2: After the engine file is generated successfully, modify the following parameters to use this engine with DeepStream.

model-engine-file=<PATH to generated TensorRT engine>

All other parameters are common between the 2 approaches. Add the label file generated above using:

labelfile-path=<Classification labels>

For all the options, see the configuration file below. To learn about what all the parameters are used for, refer to DeepStream Development Guide.

[property]
gpu-id=0
# preprocessing parameters: These are the same for all classification models generated by TLT.
net-scale-factor=1.0
offsets=103.939;116.779;123.68
model-color-format=1
batch-size=30

# Model specific paths. These need to be updated for every classification model.
int8-calib-file=<Path to optional INT8 calibration cache>
labelfile-path=<Path to classification_labels.txt>
tlt-encoded-model=<Path to Classification TLT model>
tlt-model-key=<Key to decrypt model>
input-dims=c;h;w;0 # where c = number of channels, h = height of the model input, w = width of model input, 0: implies CHW format.
uff-input-blob-name=input_1
output-blob-names=predictions/Softmax #output node name for classification

## 0=FP32, 1=INT8, 2=FP16 mode
network-mode=0
# process-mode: 2 - inferences on crops from primary detector, 1 - inferences on whole frame
process-mode=2
interval=0
network-type=1 # defines that the model is a classifier.
gie-unique-id=1
classifier-threshold=0.2