BYOM Image Classification

Note

There are differences in running some of the subtasks for BYOM classification. Most commands will be similar to the regular TAO UNet model.

Preparing the Input Data Structure

See the Data Annotation Format page for more information about the data format for image classification.

Creating an Experiment Spec File - Specification File for Classification

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

model_config {
  # BYOM Model Architecture can be chosen
  arch: "byom"
  # Pass the path of the converted BYOM model path
  byom_model: "/path/to/your/byom/.tltb"
  # If use_imagenet_head is set False, -p should have been
  # passed to tao_byom command
  use_imagenet_head: False
  resize_interpolation_method: BICUBIC
  # the input image size should match that of your original ONNX model.
  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
  preprocess_mode: "caffe"
  image_mean {
    key: 'b'
    value: 103.9
  }
  image_mean {
    key: 'g'
    value: 116.8
  }
  image_mean {
    key: 'r'
    value: 123.7
  }
}
eval_config {
  eval_dataset_path: "/path/to/your/test/data"
  model_path: "/workspace/tao-experiments/classification/weights/byom_080.tlt"
  top_k: 3
  batch_size: 256
  n_workers: 8
  enable_center_crop: True
}

For more information about the configuration, refer to the image classification page.

Training the model

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

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

Required Arguments

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

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

  • -e, --experiment_spec_file: The path to the experiment spec file

Optional Arguments

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

  • --num_processes, -np: The number of processes to be spawned for training. The default value is -1 (equal to --gpus for the use case of data parallelism). In the case of model parallelism, this argument should be explicitly set to 1 or more. Setting --gpus to larger than 1 and --num_processes to 1 corresponds to the model parallelism use case, while setting both --gpus and num_processes to larger than 1 corresponds to the use case of enabling both model parallelism and data parallelism. For example, --gpus=4 and --num_processes=2 means two Horovod processes will be spawned and each will occupy two GPUs for model parallelism.

  • --gpu_index: The GPU indices used to run the training. You 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: The path to the log file. The default path is stdout.

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

Note

See the Specification File for Classification section for more details.

Input Requirement

  • Input size: 3 * H * W (W, H >= 32)

  • Input format: JPG, JPEG, PNG

Note

Classification input images do not need to be manually resized. The input dataloader automatically resizes images to the input size.

Sample Usage

The following is an example of using the tao classification train command:

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

Model Parallelism

Image classification supports model parallelism, which is a technique to split the entire model for multiple GPUs, with each GPU holding a part of the model. A model is split by layers. For example, if a model has 100 layers, you can place layer 0-49 on GPU 0 and layer 50-99 on GPU 1. Model parallelism is useful when the model is so large that it cannot fit into a single GPU, even with batch size 1. Model parallelism is also useful if you want to increase the batch size that is seen by BatchNormalization layers and hence potentially improve the accuracy. This feature can be enabled by setting model_parallelism in training_config.

In the following example, a two-GPU model parallelism is enabled, where the first GPU will hold 30% of the model layers and the second GPU will hold 70% of the model layers.

model_parallelism: 0.3
model_parallelism: 0.7

The percentage of model layers can be adjusted with some trial-and-error so all GPUs consumes almost the same GPU memory size, and in that case you can use the largest batch size for this model-parallelised training.

Model parallelism can be enabled jointly with data parallelism. For example, the above case enables a two-GPU model parallelism, but at the same time you can enable four Horovod processes for it. In this case, there are four horovod processes for data parallelism, and each process will have the model split between two GPUs.

Evaluating the Model

After the model has been trained using the experiment config file, the next step is to use the tao classification evaluate command to evaluate this model on a test set to measure the accuracy of the model.

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 the model using the tao classification evaluate command:

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

Required Arguments

  • -e, --experiment_spec_file:The path to the experiment spec file

  • -k, –key: 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. You can specify the GPU indices used to run training when the machine has multiple GPUs installed.

  • --log_file: The path to the log file. The default path is stdout.

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

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

TAO 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 tao classification inference command runs inference on a specified set of input images. For classification, tao 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 tao classification inference on a classification model trained on TAO Toolkit.

tao classification inference [-h] -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>]

Here are the arguments of the tao classification inference tool:

Required arguments

  • -m, --model: The path to the pretrained model (TAO model)

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

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

  • -k, --key: The key to load the model

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

  • -e, --experiment_spec_file: The path to the experiment spec file

Optional arguments

  • --batch_size: The inference batch size. The default value 1.

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

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

  • --log_file: The path to the log file. The default path is 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 tao classification prune command.

The tao classification prune command includes these parameters:

tao classification prune [-h] -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>]
                              [-bm <byom model path>]

Required Arguments

  • -m, --model: The path to the pretrained model

  • -o, --output_file: The path to the output checkpoints

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

Optional Arguments

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

  • -n, –normalizer: This value can be max or L2. max normalizes by dividing each norm by the maximum norm within a layer; L2 normalizes by dividing by the L2 norm of the vector comprising all kernel norms. The default setting is max.

  • -eq, --equalization_criterion: The 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. The options are arithmetic_mean, geometric_mean, union, and intersection. The default value is union.

  • -pg, -pruning_granularity: Number of filters to remove at a time. The default value is 8.

  • -pth: The threshold to compare the normalized norm against. The default value is 0.1.

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

  • -el, --excluded_layers: The list of excluded_layers (e.g. -i item1 item2). The default value is [].

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

  • --log_file: The path to the log file. The default value is stdout.

  • -bm, --byom_model_path: The path to the BYOM model in .tltb. This argument is only applicable to BYOM models.

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 tao classification prune command:

tao classification prune -m /workspace/output/weights/resnet_003.tlt
                         -o /workspace/output/weights/resnet_003_pruned.tlt
                         -bm /workspace/byom_model/resnet18.tltb
                         -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. To regain the accuracy, NVIDIA recommends that you retrain this pruned model over the same dataset. To do this, use the tao 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 TAO 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

Note

Unlike regular TAO classification models, the BYOM classification model does not require the calibration_tensorfile step for INT8 export.

TensorRT engines can be generated in INT8 mode to run with lower precision, and thus improve performance. This process requires a cache file that contains scale factors for the tensors to help combat quantization errors, which may arise due to low-precision arithmetic. The calibration cache is generated using a calibration tensorfile when 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 machine. Moving the calibration cache is usually much more convenient than moving the calibration tensorfile since it is a much smaller file and can be moved with the exported model. 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 Tensorfile and the model itself.

The export tool can generate an INT8 calibration cache by ingesting training data. You will need to point the tool to a directory of images to use for calibrating the model. You will also need to create a sub-sampled directory of random images that best represent your training dataset.

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 BYOM Model

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

tao classification export [-h] -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>]
                               [--strict_type_constraints <Flag to apply strict type constraints>]
                               [--gen_ds_config] <Flag to generate ds config and label file>]
                               [--engine_file <path to the TensorRT engine file>]
                               [--verbose]
                               [--force_ptq]
                               [--gpu_index <gpu_index>]
                               [--log_file <log_file_path>]
                               [--classmap_json CLASSMAP_JSON]
                               [-e <experiment_spec_file>]
                               [--is_byom]

Required Arguments

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

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

Optional Arguments

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

  • --data_type: The desired engine data type, which generates a calibration cache if in INT8 mode. The options are fp32, fp16, and int8. The default value is fp32. If using INT8, the INT8 arguments specified in the following section are required.

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

  • --gen_ds_config: A Boolean flag indicating whether to generate the template DeepStream related configuration (“nvinfer_config.txt”), as well as a label file (“labels.txt”) in the same directory as the output_file. Note that the config file is not a complete configuration file and requires the user to update the sample config files in DeepStream with the parameters generated.

  • --classmap_json: The path to the classmap_json file. It is already generated in training result folder. This file is required if gen_ds_config is enabled.

  • --gpu_index: The index of (discrete) GPUs used for exporting the model. You 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: The path to the log file. The default path is stdout.

  • -v, --verbose: Enables verbose logging.

  • -e, --experiment_spec_file: The path to the experiment spec file

  • --is_byom: If set, the provided model is from BYOM.

INT8 Export Mode Required Arguments

  • --cal_data_file: The output file used with --cal_image_dir.

  • --cal_image_dir: The directory of images to use for calibration.

Note

If a valid path is provided to the --cal_data_file argument over the command line, the export tool produces an intermediate TensorFile for re-use from random batches of images in the --cal_image_dir directory of images . This tensorfile is used for calibration. If --cal_image_dir is not provided, random input tensors are used for calibration. The number of batches in the generated tensorfile is obtained from the value set to the --batches parameter, and the batch_size is obtained from the value set to the --batch_size parameter. Ensure that the directory specified in --cal_image_dir has at least batch_size * batches number of images in it. The valid image extensions are .jpg, .jpeg, and .png. In this case, the input_dimensions of the calibration tensors are derived from the input layer of the .tlt model.

INT8 Export Optional Arguments

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

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

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

  • --max_batch_size: The maximum batch size of the TensorRT engine. The default value is 1.

  • --min_batch_size: The minimum batch size of the TensorRT engine. The default value is 1.

  • --opt_batch_size: The optimum batch size of the TensorRT engine. The default value is 1.

  • --max_workspace_size: The maximum workspace size of the TensorRT engine. The default value is 1073741824 = 1<<30

  • --experiment_spec: The experiment_spec for training/inference/evaluation.

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

Note

The BYOM classification model currently does not support Quantization Aware Training (QAT).

Exporting a Model

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

tao classification export -e /ws/specs/retrain_spec.cfg
                          -m /ws/output_retrain/weights/byom_$EPOCH.tlt
                          -o /ws/export/final_model.etlt
                          -k $KEY
                          --is_byom
                          --cal_data_file /ws/export/calibration.txt
                          --cal_cache_file /ws/export/final_model_int8_cache.bin
                          --data_type int8
                          --batches 1
                          --max_batch_size 16

Deploying to DeepStream

The deep learning and computer vision models that you’ve trained can be deployed on edge devices, such as a Jetson Xavier or Jetson Nano, a discrete GPU, or in the cloud with NVIDIA GPUs. TAO Toolkit has been designed to integrate with DeepStream SDK, so models trained with TAO Toolkit 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 will describe how to deploy your trained model to DeepStream SDK.

To deploy a model trained by TAO Toolkit to DeepStream we have two options:

  • 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 tao-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 TensorRT or CUDA libraries of the inference environment 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 the TensorRT engine file and then run inference. TensorRT engine generation can take some time depending on size of the model and type of hardware. Engine generation can be done ahead of time with Option 2. With option 2, the tao-converter is used to convert the .etlt file to TensorRT; this file is then provided directly to DeepStream.

See the Exporting the Model section for more details on how to export a TAO model.

Generating an Engine Using tao-converter

The tao-converter tool is provided with the TAO Toolkit to facilitate the deployment of TAO trained models on TensorRT and/or Deepstream. This section elaborates on how to generate a TensorRT engine using tao-converter.

For deployment platforms with an x86-based CPU and discrete GPUs, the tao-converter is distributed within the TAO docker. Therefore, we suggest using the docker to generate the engine. However, this requires that the user adhere to the same minor version of TensorRT as distributed with the docker. The TAO docker includes TensorRT version 8.0.

Instructions for x86

For an x86 platform with discrete GPUs, the default TAO package includes the tao-converter built for TensorRT 8.2.5.1 with CUDA 11.4 and CUDNN 8.2. However, for any other version of CUDA and TensorRT, please refer to the overview section for download. Once the tao-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/x86_64-linux-gnu”
$ export TRT_INC_PATH=”/usr/include/x86_64-linux-gnu”
  1. Run the tao-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 section of the respective model.

Instructions for Jetson

For the Jetson platform, the tao-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 tao-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 comes pre-installed with Jetpack. If you are using older JetPack, upgrade to JetPack-5.0DP.

  2. Run the tao-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 section of the respective model.

Using the tao-converter

tao-converter [-h] -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>]
                   input_file
Required Arguments
  • input_file: The path to the .etlt model exported using export.

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

  • -d: A comma-separated list of input dimensions that should match the dimensions used for tao classification export. Unlike tao classification export, this cannot be inferred from calibration data. This parameter is not required for new models introduced in TAO Toolkit 3.0-21.08 or later (e.g. LPRNet, UNet, GazeNet).

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

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

  • -t: The desired engine data type, which generates a calibration cache if in INT8 mode. The default value is fp32. The options are fp32, fp16, and int8.

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

  • -i: The input dimension ordering; all other TAO commands use NCHW. The default value is nchw. The options are nchw, nhwc, and nc (the default value is nchw). For classification, this argument can be omitted.

  • -p: Optimization profiles for .etlt models with dynamic shape. A 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>. This is only useful for new models introduced in TAO Toolkit v3.0. This parameter is not required for models that were already part of TAO Toolkit v2.0.

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

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

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

  • -b: The batch size used during the export step for INT8 calibration cache generation. The default value is 8.

  • -m: The maximum batch size for the TensorRT engine. The default value is 16. If you encounter 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 models introduced in TAO Toolkit 3.0-21.08.

Sample Output Log

Here is a sample log for exporting a BYOM classification model.

tao-converter /ws/export/final_model.etlt
              -k $KEY
              -c /ws/export/final_model_int8_cache.bin
              -i nchw
              -t int8
              -e /ws/export/final_model.trt
              -p input_1,1x3x224x224,4x3x224x224,16x3x224x224

[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 with DeepStream

There are two options to integrate models from TAO with DeepStream:

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

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

To integrate the models with DeepStream, you need the following:

  • The DeepStream SDK: The installation instructions for DeepStream are provided in the DeepStream Development Guide.

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

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

  • 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 two 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 the 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. The following are config files in samples/configs/deepstream-app for reference:

  • source4_1080p_dec_infer-resnet_tracker_sgie_tiled_display_int8.txt: The main config file

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

  • config_infer_secondary_*.txt: The supporting config file for the 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 with 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 <exporting_the_model_byom> for more details on how to export a TAO model. After the model has been generated, two extra files are required:

  • The label file

  • The deepStream configuration file

Label File

The label file is a text file containing the names of the classes that the TAO 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 TAO. 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 TAO Toolkit package, 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, up to 19, which corresponds to tvmonitor. Here is a sample classification_labels.txt file, arranged in order of index:

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

A typical use case for video analytics 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=<TAO Toolkit 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.

  1. Generate the TensorRT engine using tao-converter. Detailed instructions are provided in the Generating an Engine Using tao-converter section.

  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 two approaches. Add the label file generated above using the following:

labelfile-path=<Classification labels>

For all the options, see the configuration file below. To learn about what 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 TAO Toolkit.
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 etlt model>
tlt-model-key=<Key to decrypt model>
infer-dims=c;h;w # where c = number of channels, h = height of the model input, w = width of model input
uff-input-blob-name=input_1
uff-input-order=0
output-blob-names=predictions/Softmax

## 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