RetinaNet ========= .. _retinanet: With RetinaNet, the following tasks are supported: * train * evaluate * prune * inference * export These tasks may be invoke from the TLT launcher by following the below mentioned convention from command line: .. code:: tlt retinanet where, :code:`args_per_subtask` are the command line arguments required for a given subtask. Each of these sub-tasks are explained in detail below. Creating a Configuration File ----------------------------- .. _specification_file_retinanet: Below is a sample for the RetinaNet spec file. It has 6 major components: :code:`retinanet_config`, :code:`training_config`, :code:`eval_config`, :code:`nms_config`, :code:`augmentation_config` and :code:`dataset_config`. The format of the spec file is a protobuf text (prototxt) message and each of its fields can be either a basic data type or a nested message. The top level structure of the spec file is summarized in the table below: .. code:: random_seed: 42 retinanet_config { aspect_ratios_global: "[1.0, 2.0, 0.5]" scales: "[0.045, 0.09, 0.2, 0.4, 0.55, 0.7]" two_boxes_for_ar1: false clip_boxes: false loss_loc_weight: 0.8 focal_loss_alpha: 0.25 focal_loss_gamma: 2.0 variances: "[0.1, 0.1, 0.2, 0.2]" arch: "resnet" nlayers: 18 n_kernels: 1 n_anchor_levels: 1 feature_size: 256 freeze_bn: false freeze_blocks: 0 } training_config { enable_qat: False batch_size_per_gpu: 24 num_epochs: 100 pretrain_model_path: "YOUR_PRETRAINED_MODEL" optimizer { sgd { momentum: 0.9 nesterov: True } } learning_rate { soft_start_annealing_schedule { min_learning_rate: 4e-5 max_learning_rate: 1.5e-2 soft_start: 0.15 annealing: 0.5 } } regularizer { type: L1 weight: 2e-5 } } eval_config { validation_period_during_training: 10 average_precision_mode: SAMPLE batch_size: 24 matching_iou_threshold: 0.5 } nms_config { confidence_threshold: 0.01 clustering_iou_threshold: 0.6 top_k: 200 } augmentation_config { output_width: 384 output_height: 1248 output_channel: 3 } dataset_config { data_sources: { label_directory_path: "/workspace/tlt-experiments/data/training/label_2" image_directory_path: "/workspace/tlt-experiments/data/training/image_2" } target_class_mapping { key: "car" value: "car" } target_class_mapping { key: "pedestrian" value: "pedestrian" } target_class_mapping { key: "cyclist" value: "cyclist" } target_class_mapping { key: "van" value: "car" } target_class_mapping { key: "person_sitting" value: "pedestrian" } validation_data_sources: { label_directory_path: "/workspace/tlt-experiments/data/val/label" image_directory_path: "/workspace/tlt-experiments/data/val/image" } } Training Config ^^^^^^^^^^^^^^^ The training configuration(:code:`training_config`) defines the parameters needed for the training, evaluation and inference. Details are summarized in the table below. +--------------------+--------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +--------------------+--------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | batch_size_per_gpu | The batch size for each GPU, so the effective batch size is batch_size_per_gpu * num_gpus. | Unsigned int, positive | - | +--------------------+--------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | num_epochs | The anchor batch size used to train the RPN. | Unsigned int, positive. | -- | +--------------------+--------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | enable_qat | Whether to use quantization aware training. | Boolean | - | +--------------------+--------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | learning_rate | Only soft_start_annealing_schedule with these nested parameters is supported. | Message type. | -- | | | | | | | | 1. min_learning_rate: minimum learning late to be seen during the entire experiment. | | | | | 2. max_learning_rate: maximum learning rate to be seen during the entire experiment | | | | | 3. soft_start: Time to be lapsed before warm up ( expressed in percentage of progress between 0 and 1) | | | | | 4. annealing: Time to start annealing the learning rate | | | +--------------------+--------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | regularizer | This parameter configures the regularizer to be used while training and contains | Message type. | L1 (Note: NVIDIA suggests using L1 regularizer when training a network | | | the following nested parameters. | | before pruning as L1 regularization helps making the network weights more prunable.) | | | | | | | | 1. type: The type or regularizer to use. NVIDIA supports NO_REG, L1 or L2 | | | | | 2. weight: The floating point value for regularizer weight | | | +--------------------+--------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | optimizer | Can be one of adam, sgd and rmsprop. Each type has following parameters: | Message type. | -- | | | | | | | | 1. adam: epsilon, beta1, beta2, amsgrad | | | | | 2. sgd: momentum, nesterov | | | | | 3. rmsprop: rho, momentum, epsilon, centered | | | | | | | | | | The meanings of above parameters are same as these in Keras (keras.io/api/optimizers) | | | +---------------------+-------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | pretrain_model_path | Path to pretrained model if any. | String | -- | | | | | | | | At most one of pretrain_model_path, resume_model_path, pruned_model_path may present. | | | +---------------------+-------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | resume_model_path | Path to TLT checkpoint model to resume training if any. | String | -- | | | | | | | | At most one of pretrain_model_path, resume_model_path, pruned_model_path may present. | | | +---------------------+-------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | pruned_model_path | Path to a TLT pruned model for re-training if any. | String | -- | | | | | | | | At most one of pretrain_model_path, resume_model_path, pruned_model_path may present. | | | +---------------------+-------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ | checkpoint_interval | The number of training epochs per which one model checkpoint / validation should run. | Unsigned int, positive | 10 | +---------------------+-------------------------------------------------------------------------------------------------------+-------------------------------+--------------------------------------------------------------------------------------+ .. Note:: The learning rate is automatically scaled with the number of GPUs used during training, or the effective learning rate is :code:`learning_rate * n_gpu`. Evaluation Config ^^^^^^^^^^^^^^^^^ The evaluation configuration (:code:`eval_config`) defines the parameters needed for the evaluation either during training or standalone. Details are summarized in the table below. +-----------------------------------+-------------------------------------------------------------------------------------------+----------------------------------+-------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +-----------------------------------+-------------------------------------------------------------------------------------------+----------------------------------+-------------------------------+ | validation_period_during_training | The number of training epochs per which one validation should run. | Unsigned int, positive | 10 | +-----------------------------------+-------------------------------------------------------------------------------------------+----------------------------------+-------------------------------+ | average_precision_mode | Average Precision (AP) calculation mode can be either SAMPLE or INTEGRATE. SAMPLE is | ENUM type ( SAMPLE or INTEGRATE) | SAMPLE | | | used as VOC metrics for VOC 2009 or before. INTEGRATE is used for VOC 2010 or after that. | | | +-----------------------------------+-------------------------------------------------------------------------------------------+----------------------------------+-------------------------------+ | matching_iou_threshold | The lowest IoU of predicted box and ground truth box that can be considered a match. | Boolean | 0.5 | +-----------------------------------+-------------------------------------------------------------------------------------------+----------------------------------+-------------------------------+ NMS Config ^^^^^^^^^^ The NMS configuration (:code:`nms_config`) defines the parameters needed for the NMS postprocessing. NMS config applies to the NMS layer of the model in training, validation, evaluation, inference and export. Details are summarized in the table below. +-----------------------+-------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +-----------------------+-------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ | confidence_threshold | Boxes with a confidence score less than confidence_threshold are discarded before | float | 0.01 | | | applying NMS. | | | +-----------------------+-------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ | cluster_iou_threshold | IoU threshold below which boxes will go through NMS process. | float | 0.6 | +-----------------------+-------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ | top_k | top_k boxes will be outputted after the NMS keras layer. If the number of valid | Unsigned int | 200 | | | boxes is less than k, the returned array will be padded with boxes whose confidence | | | | | score is 0. | | | +-----------------------+-------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ Augmentation Config ^^^^^^^^^^^^^^^^^^^ The :code:`augmentation_config` parameter defines the image size after preprocessing. The augmentation methods in the SSD `paper`_ will be performed during training, including random flip, zoom-in, zoom-out and color jittering. And the augmented images will be resized to the output shape defined in :code:`augmentation_config`. In evaluation process, only the resize will be performed. .. Note:: The details of augmentation methods can be found in setcion 2.2 and 3.6 of the `paper`_. .. _paper: https://arxiv.org/abs/1512.02325v5 +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | output_channel | Output image channel of augmentation pipeline. | float of [0, 1] | 0.1 | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | output_width | Output image width of augmentation pipeline. | integer, multiple of 32 | -- | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | output_height | Output image height of augmentation pipeline | integer, multiple of 32 | -- | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ Dataset Config ^^^^^^^^^^^^^^ The RetinaNet dataloader assumes data are prepared in KITTI format (images and labels in two separate folders where each image in image folder has a txt label file with same filename in label folder. The label file content follows KITTI format) and training/validation split is already done. The parameters in :code:`dataset_config` are defined as follows: * :code:`data_sources`: Captures the path to datasets to train on. If you have multiple data sources for training, you may use multiple :code:`data_sources`. This field contains 2 parameters: * :code:`label_directory_path`: Path to the data source label folder * :code:`image_directory_path`: Path to the data source image folder * :code:`include_difficult_in_training`: Whether to include difficult boxes in training. If set to false, difficult boxes will be ignored. Difficult boxes are those with occlusion level 2 in KITTI labels. * :code:`target_class_mapping`: This parameter maps the class names in the labels to the target class to be trained in the network. An element is defined for every source class to target class mapping. This field was included with the intention of grouping similar class objects under one umbrella. For example: car, van, heavy_truck etc. may be grouped under automobile. The “key” field is the value of the class name in the tfrecords file, and the “value” field corresponds to the value that the network is expected to learn. * :code:`validation_data_sources`: Captures the path to datasets to validate on. If you have multiple data sources for validation, you may use multiple :code:`validation_data_sources`. This field contains 2 parameters same as :code:`data_sources`. .. Note:: The class names key in the target_class_mapping must be identical to the one shown in the KITTI labels so that the correct classes are picked up for training. RetinaNet Config ^^^^^^^^^^^^^^^^ The RetinaNet configuration (:code:`retinanet_config`) defines the parameters needed for building the RetinaNet model. Details are summarized in the table below. +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | aspect_ratios_global | Anchor boxes of aspect ratios defined in aspect_ratios_global will be generated for each feature layer | string | “[1.0, 2.0, 0.5]” | | | used for prediction. Note: Only one of aspect_ratios_global or aspect_ratios is required. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | aspect_ratios | The length of the outer list must be equivalent to the number of feature layers used for anchor box | string | “[[1.0,2.0,0.5], | | | generation. And the i-th layer will have anchor boxes with aspect ratios defined in aspect_ratios[i]. | | [1.0,2.0,0.5], | | | | | [1.0,2.0,0.5], | | | **Note**: Only one of aspect_ratios_global or aspect_ratios is required. | | [1.0,2.0,0.5], | | | | | [1.0,2.0,0.5], | | | | | [1.0, 2.0, 0.5, 3.0, 0.33]]” | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | two_boxes_for_ar1 | This setting is only relevant for layers that have 1.0 as the aspect ratio. If two_boxes_for_ar1 is | Boolean | True | | | true, two boxes will be generated with an aspect ratio of 1. One whose scale is the scale for this | | | | | layer and the other one whose scale is the geometric mean of the scale for this layer and the scale for | | | | | the next layer. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | clip_boxes | If true, all corner anchor boxes will be truncated so they are fully inside the feature images. | Boolean | False | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | scales | scales is a list of positive floats containing scaling factors per convolutional predictor layer. This | string | “[0.05, 0.1, 0.25, 0.4, 0.55, 0.7, 0.85]” | | | list must be one element longer than the number of predictor layers, so if two_boxes_for_ar1 is true, | | | | | the second aspect ratio 1.0 box for the last layer can have a proper scale. Except for the last element | | | | | in this list, each positive float is the scaling factor for boxes in that layer. For example, if for one | | | | | layer the scale is 0.1, then the generated anchor box with aspect ratio 1 for that layer (the first aspect | | | | | ratio 1 box if two_boxes_for_ar1 is true) will have its height and width as 0.1*min(img_h, img_w). | | | | | | | | | | min_scale and max_scale are two positive floats. If both of them appear in the config, the program can | | | | | automatically generate the scales by evenly splitting the space between min_scale and max_scale. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | min_scale/max_scale | If both appear in the config, scales will be generated evenly by splitting the space between min_scale and | float | -- | | | max_scale. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | loss_loc_weight | This is a positive float controlling how much location regression loss should contribute to the final loss. | float | 1.0 | | | The final loss is calculated as classification_loss + loss_loc_weight * loc_loss | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | focal_loss_alpha | Alpha is the focal loss equation. | float | 0.25 | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | focal_loss_gamma | Gamma is the focal loss equation. | float | 2.0 | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | variances | Variances should be a list of 4 positive floats. The four floats, in order, represent variances for box center x, | | -- | | | box center y, log box height, log box width. The box offset for box center (cx, cy) and log box size (height/width) | | | | | w.r.t. anchor will be divided by their respective variance value. Therefore, larger variances result in less | | | | | significant differences between two different boxes on encoded offsets. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | steps | An optional list inside quotation marks whose length is the number of feature layers for prediction. The elements | string | -- | | | should be floats or tuples/lists of two floats. Steps define how many pixels apart the anchor box center points should | | | | | be. If the element is a float, both vertical and horizontal margin is the same. Otherwise, the first value is | | | | | step_vertical and the second value is step_horizontal. If steps are not provided, anchor boxes will be distributed | | | | | uniformly inside the image. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | offsets | An optional list of floats inside quotation marks whose length is the number of feature layers for prediction. The first | string | -- | | | anchor box will have offsets[i]*steps[i] pixels margin from the left and top borders. If offsets are not provided, 0.5 | | | | | will be used as default value. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | arch | Backbone for feature extraction. Currently, “resnet”, “vgg”, “darknet”, “googlenet”, “mobilenet_v1”, “mobilenet_v2” and | string | resnet | | | “squeezenet”, "efficientnet_b0" are supported. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | nlayers | Number of conv layers in specific arch. For “resnet”, 10, 18, 34, 50 and 101 are supported. For “vgg”, 16 and 19 are | Unsigned int | -- | | | supported. For “darknet”, 19 and 53 are supported. All other networks don’t have this configuration and users should | | | | | just delete this config from the config file. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | freeze_bn | Whether to freeze all batch normalization layers during training. | boolean | False | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | freeze_blocks | The list of block IDs to be frozen in the model during training. You can choose to freeze some of the CNN blocks in the model | list(repeated integers) | -- | | | to make the training more stable and/or easier to converge. The definition of a block is heuristic for a specific architecture. | | | | | For example, by stride or by logical blocks in the model, etc. However, the block ID numbers identify the blocks in the model | • ResNet series. For the ResNet series, the block IDs valid | | | | in a sequential order so you don't have to know the exact locations of the blocks when you do training. A general principle to | for freezing is any subset of [0, 1, 2, 3] (inclusive) | | | | keep in mind is: the smaller the block ID, the closer it is to the model input; the larger the block ID, the closer it is to | • VGG series. For the VGG series, the block IDs valid for | | | | the model output. | freezing is any subset of[1, 2, 3, 4, 5] (inclusive) | | | | | • GoogLeNet. For the GoogLeNet, the block IDs valid for freezing | | | | | is any subset of[0, 1, 2, 3, 4, 5, 6, 7] (inclusive) | | | | | • MobileNet V1. For the MobileNet V1, the block IDs 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 IDs valid for freezing | | | | | is any subset of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] (inclusive) | | | | | • DarkNet. For the DarkNet 19 and DarkNet 53, the block IDs valid for freezing | | | | | is any subset of [0, 1, 2, 3, 4, 5] (inclusive) | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | n_kernels | This setting controls the number of convolutional layers in the RetinaNet subnets for classification and anchor box regression. | Unsigned int | 2 | | | A larger value generates a larger network and usually means the network is harder to train. | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | feature_size | This setting controls the number of channels of the convolutional layers in the RetinaNet subnets for classification and anchor | Unsigned int | 256 | | | box regression. A larger value gives a larger network and usually means the network is harder to train. | | | | | | | | | | Note that RetinaNet FPN generates 5 feature maps, thus the scales field requires a list of 6 scaling factors. The last number | | | | | is not used if two_boxes_for_ar1 is set to False. There are also three underlying scaling factors at each feature map level | | | | | (2^0, 2^⅓, 2^⅔ ). | | | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ | n_anchor_levels | Number of anchor levels between two adjacent scales. | Unsigned int | 1 | +----------------------+---------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+-------------------------------------------+ Focal loss is calculated as follows: .. image:: ../../content/focal_loss_formula.png Variances: .. image:: ../../content/variance_offset_calc.png Training the Model ------------------ .. _training_the_model_retinanet: Train the RetinaNet model using this command: .. code:: tlt retinanet train [-h] -e -r -k [--gpus ] [--gpu_index ] [--use_amp] [--log_file ] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-r, --results_dir`: Path to the folder where the experiment output is written. * :code:`-k, --key`: Provide the encryption key to decrypt the model. * :code:`-e, --experiment_spec_file`: Experiment specification file to set up the evaluation experiment. This should be the same as the training specification file. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`--gpus`: The number of GPUs to be used in the training in a multi-GPU scenario (default: 1). * :code:`--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. * :code:`--use_amp`: A flag to enable AMP training. * :code:`--log_file`: Path to the log file. Defaults to stdout. * :code:`-h, --help`: Show this help message and exit. Sample Usage ^^^^^^^^^^^^ Here's an example of using the train command on a RetinaNet model: .. code:: tlt retinanet train --gpus 2 -e /path/to/spec.txt -r /path/to/result -k $KEY Evaluating the Model -------------------- To run evaluation for a RetinaNet model use this command: .. code:: tlt retinanet evaluate [-h] -e -m -k [--gpu_index ] [--log_file ] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-e, --experiment_spec_file`: Experiment spec file to set up the evaluation experiment. This should be the same as the training specification file. * :code:`-m, --model`: Path to the model file to use for evaluation (support both TLT model and TensorRT engine). * :code:`-k, --key`: Provide the key to load the TLT model (it's not needed if a TensorRT engine is used). Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`--gpu_index`: The GPU index used to run the evaluation. We can specify the GPU index used to run evaluation when the machine has multiple GPUs installed. Note that evaluation can only run on a single GPU. * :code:`--log_file`: Path to the log file. Defaults to stdout. * :code:`-h, --help`: Show this help message and exit. Sample Usage ^^^^^^^^^^^^ Here's an example of using the evaluate command on a RetinaNet model: .. code:: tlt retinanet evaluate -e /path/to/spec.txt -m /path/to/model.tlt -k $KEY Running Inference on a RetinaNet Model -------------------------------------- The inference tool for RetinaNet networks can be used to visualize bboxes, or generate frame by frame KITTI format labels on a directory of images. Two modes are supported, namely TLT model model and TensorRT engine mode. You can execute the TLT model mode using the following command: .. code:: tlt retinanet inference [-h] -i -o -e -m -k [-l ] [-t ] [--gpu_index ] [--log_file ] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-m, --model`: Path to the pretrained model (supports both TLT model and TensorRT engine). * :code:`-i, --in_image_dir`: The directory of input images for inference. * :code:`-o, --out_image_dir`: The directory path to output annotated images. * :code:`-k, --key`: Key to load a TLT model (it's not needed if a TensorRT engine is used). * :code:`-e, --config_path`: Path to an experiment spec file for training. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-t, --threshold`: Threshold for drawing a bbox. default: 0.3 * :code:`-l, --out_label_dir`: The directory to output KITTI labels. * :code:`--gpu_index`: The GPU index to run inference on. We can specify the GPU index used to run inference if the machine has multiple GPUs installed. Note that inference can only run on a single GPU. * :code:`--log_file`: Path to the log file. Defaults to stdout. * :code:`-h, --help`: Show this help message and exit Sample Usage ^^^^^^^^^^^^ Here's an example of using the inference command on a RetinaNet model: .. code:: tlt retinanet inference -e /path/to/spec.txt -m /path/to/model.tlt -k $KEY -o /path/to/output_dir -i /path/to/input_dir Pruning the Model ----------------- .. _pruning_the_model_retinanet: Pruning removes parameters from the model to reduce the model size without compromising the integrity of the model itself using the :code:`tlt retinanet prune` command. The :code:`tlt retinanet prune` command includes these parameters: .. code:: tlt retinanet prune [-h] -m -o -k [-n ] [-eq ] [-pg ] [-pth ] [-nf ] [-el [] [--gpu_index ] [--log_file ] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-m, --model`: Path to a pretrained RetinaNet model. * :code:`-o, --output_file`: Path to output checkpoints. * :code:`-k, --key`: Key to load a :code`.tlt` model. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-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`) * :code:`-eq, --equalization_criterion`: Criteria to equalize the stats of inputs to an element wise op layer, or depth-wise convolutional layer. This parameter is useful for resnets and mobilenets. Options are :code:`arithmetic_mean`,:code:`geometric_mean`, :code:`union`, and :code:`intersection`. (default: :code:`union`) * :code:`-pg, -pruning_granularity`: Number of filters to remove at a time. (default:8) * :code:`-pth`: Threshold to compare normalized norm against. (default:0.1) .. Note:: NVIDIA recommends changing the threshold to keep the number of parameters in the model to within 10-20% of the original unpruned model. * :code:`-nf, --min_num_filters`: Minimum number of filters to keep per layer (default:16) * :code:`-el, --excluded_layers`: List of excluded_layers. Examples: -i item1 item2 (default: []) * :code:`--gpu_index`: The GPU index to run pruning on. We can specify the GPU index used to run pruning if the machine has multiple GPUs installed. Note that pruning can only run on a single GPU. * :code:`--log_file`: Path to the log file. Defaults to stdout. * :code:`-h, --help`: Show this help message and exit. After pruning, the model needs to be retrained. See :ref:`Re-training the Pruned Model ` for more details. Using the Prune Command ^^^^^^^^^^^^^^^^^^^^^^^ Here's an example of using the :code:`tlt retinanet prune` command: .. code:: tlt retinanet 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 ---------------------------- .. _re-training_the_pruned_model_retinanet: Once 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 :code:`tlt retinanet train` command as documented in :ref:`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 RetinaNet to recover the accuracy when retraining a pruned model. You may do this by setting the regularizer type to NO_REG as mentioned :code:`Training config`. All the other parameters may be retained in the spec file from the previous training. Exporting the Model ------------------- .. _exporting_the_model_retinanet: 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 :code:`.etlt`. Like :code:`.tlt`, the :code:`.etlt` model format is also a encrypted model format with the same key of the :code:`.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 :code:`tlt retinanet export` is run with the :code:`--data_type` flag set to :code:`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 INT8 calibration cache by ingesting training data using either of these options: * **Option 1**: Using the training data loader to load the training images for INT8 calibration. This option is now the recommended approach to support multiple image directories by leveraging the training dataset loader. This also ensures two important aspects of data during calibration: * Data pre-processing in the INT8 calibration step is the same as in the training process. * The data batches are sampled randomly across the entire training dataset, thereby improving the accuracy of the INT8 model. * **Option 2**: Pointing the tool to a directory of images that you want to use to calibrate the model. For this option, make sure to create a sub-sampled directory of random images that best represent your training dataset. FP16/FP32 Model ^^^^^^^^^^^^^^^ The :code:`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 :code:`.tlt` model from the training/retraining step to be converted into an :code:`.etlt`. Exporting the Model ^^^^^^^^^^^^^^^^^^^ Here's an example of the command line arguments of the :code:`tlt retinanet export` command: .. code:: tlt retinanet export [-h] -m --experiment_spec -k [-o ] [--cal_data_file ] [--cal_image_dir ] [--data_type ] [--batches ] [--max_batch_size ] [--max_workspace_size ] [--engine_file ] [--verbose Verbosity of the logger] [--strict_type_constraints ] [--force_ptq Flag to force PTQ] [--gpu_index ] [--log_file ] Required Arguments ****************** * :code:`-m, --model`: Path to the .tlt model file to be exported. * :code:`-k, --key`: Key used to save the :code:`.tlt` model file. * :code:`-e, --experiment_spec`: Path to the spec file. Optional Arguments ****************** * :code:`-o, --output_file`: Path to save the exported model to. The default is :code:`./.etlt`. * :code:`--data_type`: Desired engine data type, generates calibration cache if in INT8 mode. The options are: {:code:`fp32`, :code:`fp16`, :code:`int8`} The default value is :code:`fp32`. If using INT8, the following INT8 arguments are required. * :code:`-s, --strict_type_constraints`: A Boolean flag to indicate whether or not to apply the TensorRT strict type constraints when building the TensorRT engine. * :code:`--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. * :code:`--log_file`: Path to the log file. Defaults to stdout. * :code:`-h, --help`: Show this help message and exit. INT8 Export Mode Required Arguments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * :code:`--cal_data_file`: tensorfile generated for calibrating the engine. This can also be an output file if used with :code:`--cal_image_dir`. * :code:`--cal_image_dir`: Directory of images to use for calibration. .. Note:: :code:`--cal_image_dir` parameter for images and applies the necessary preprocessing to generate a tensorfile at the path mentioned in the :code:`--cal_data_file` parameter, which is in turn used for calibration. The number of batches in the tensorfile generated is obtained from the value set to the :code:`--batches` parameter, and the :code:`batch_size` is obtained from the value set to the :code:`--batch_size` parameter. Be sure that the directory mentioned in :code:`--cal_image_dir` has at least :code:`batch_size * batches` number of images in it. The valid image extensions are .jpg, .jpeg, and .png. In this case, the :code:`input_dimensions` of the calibration tensors are derived from the input layer of the :code:`.tlt` model. INT8 Export Optional Arguments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * :code:`--cal_cache_file`: Path to save the calibration cache file. The default value is :code:`./cal.bin`. * :code:`--batches`: Number of batches to use for calibration and inference testing. The default value is 10. * :code:`--batch_size`: Batch size to use for calibration. The default value is 8. * :code:`--max_batch_size`: Maximum batch size of TensorRT engine. The default value is 16. * :code:`--max_workspace_size`: Maximum workspace size of TensorRT engine. The default value is: 1073741824 = 1<<30) * :code:`--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. * :code:`--force_ptq`: A boolean flag to force post training quantization on the exported etlt model. .. Note:: When exporting a model trained with 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 :code:`cal_cache_file` argument. However, note that the current version of QAT doesn’t natively support DLA int8 deployment in the Jetson. In order to deploy this model on a Jetson with DLA :code:`int8`, use the :code:`--force_ptq` flag to use TensorRT post training quantization to generate the calibration cache file. Sample usage ^^^^^^^^^^^^ Here's a sample command to export a RetinaNet model in INT8 mode. .. code:: tlt retinanet export -m /ws/retinanet_resnet18_epoch_100.tlt \ -o /ws/retinanet_resnet18_epoch_100_int8.etlt \ -e /ws/retinanet_retrain_resnet18_kitti.txt \ -k $KEY \ --cal_image_dir /ws/data/training/image_2 \ --data_type int8 \ --batch_size 1 \ --batches 10 \ --cal_cache_file /export/cal.bin \ --cal_data_file /export/cal.tensorfile Deploying to DeepStream ----------------------- .. _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: https://developer.nvidia.com/deepstream-sdk DeepStream SDK is a streaming analytic toolkit to accelerate building AI-based video analytic applications. This section will describe how to deploy a TLT RetinaNet model to DeepStream SDK. .. _here: https://docs.nvidia.com/metropolis/deepstream/dev-guide/index.html To deploy a model trained by TLT to DeepStream we have two options: * **Option 1**: Integrate the :code:`.etlt` model directly in the DeepStream app. The model file is generated by export. * **Option 2**: Generate a device specific optimized TensorRT engine, using :code:`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 straightforward. The :code:`.etlt` file and calibration cache are directly used by DeepStream. DeepStream will automatically generate TensorRT engine file and then run inference. The generation of TensorRT engine can take some time depending on size of the model and type of hardware. The generation of TensorRT engine can be done ahead of time with option 2. With option 2, use :code:`tlt-converter` to convert the :code:`.etlt` file to TensorRT engine and then provide the engine file directly to DeepStream. For RetinaNet there are some steps that need to be completed before the models will work with DeepStream. Here are the steps with detailed instructions in the following sections. * **Step 1**: Build TensorRT Open source software (OSS). This is required because several TensorRT plugins that are required by these models are only available in TensorRT open source repo and not in the general TensorRT release. For more information and instructions, see the TensorRT Open Source Software section. * **Step 2**: Build custom parsers for DeepStream. The parsers are required to convert the raw tensor data from the inference to (x,y) location of bounding boxes around the detected object. For RetinaNet, we have to apply some custom post-processings to parse the model output. TensorRT Open Source Software (OSS) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TensorRT OSS build is required for RetinaNet models. This is required because several TensorRT plugins that are required by these models are only available in TensorRT open source repo and not in the general TensorRT release. Specifically, for RetinaNet, we need the :code:`batchTilePlugin` and :code:`NMSPlugin`. If the deployment platform is x86 with NVIDIA GPU, follow instructions for x86; if your deployment is on NVIDIA Jetson platform, follow instructions for Jetson. TensorRT OSS on x86 ******************* .. _tensorrt_oss_on_x86: Building TensorRT OSS on x86: 1. Install Cmake (>=3.13). .. Note:: TensorRT OSS requires cmake >= v3.13, so install cmake 3.13 if your cmake version is lower than 3.13c .. code:: sudo apt remove --purge --auto-remove cmake wget https://github.com/Kitware/CMake/releases/download/v3.13.5/cmake-3.13.5.tar.gz tar xvf cmake-3.13.5.tar.gz cd cmake-3.13.5/ ./configure make -j$(nproc) sudo make install sudo ln -s /usr/local/bin/cmake /usr/bin/cmake 2. Get GPU architecture. The :code:`GPU_ARCHS` value can be retrieved by the :code:`deviceQuery` CUDA sample: .. code:: cd /usr/local/cuda/samples/1_Utilities/deviceQuery sudo make ./deviceQuery If the :code:`/usr/local/cuda/samples` doesn’t exist in your system, you could download :code:`deviceQuery.cpp` from this repo. Compile and run :code:`deviceQuery`. .. code:: nvcc deviceQuery.cpp -o deviceQuery ./deviceQuery This command will output something like this, which indicates the :code:`GPU_ARCHS` is :code:`75` based on CUDA Capability major/minor version. .. code:: Detected 2 CUDA Capable device(s) Device 0: "Tesla T4" CUDA Driver Version / Runtime Version 10.2 / 10.2 CUDA Capability Major/Minor version number: 7.5 3. Build TensorRT OSS: .. code:: git clone -b release/7.0 https://github.com/nvidia/TensorRT cd TensorRT/ git submodule update --init --recursive export TRT_SOURCE=`pwd` cd $TRT_SOURCE mkdir -p build && cd build .. Note:: Make sure your :code:`GPU_ARCHS` from step 2 is in TensorRT OSS :code:`CMakeLists.txt`. If GPU_ARCHS is not in TensorRT OSS :code:`CMakeLists.txt`, add :code:`-DGPU_ARCHS=` as below, where :code:`` represents :code:`GPU_ARCHS` from step 2. .. code:: /usr/local/bin/cmake .. -DGPU_ARCHS=xy -DTRT_LIB_DIR=/usr/lib/aarch64-linux-gnu/ -DCMAKE_C_COMPILER=/usr/bin/gcc -DTRT_BIN_DIR=`pwd`/out make nvinfer_plugin -j$(nproc) After building ends successfully, :code:`libnvinfer_plugin.so*` will be generated under :code:`\`pwd\`/out/.` 4. Replace the original :code:`libnvinfer_plugin.so*`: .. code:: sudo mv /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so.7.x.y ${HOME}/libnvinfer_plugin.so.7.x.y.bak // backup original libnvinfer_plugin.so.x.y sudo cp $TRT_SOURCE/`pwd`/out/libnvinfer_plugin.so.7.m.n /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so.7.x.y sudo ldconfig TensorRT OSS on Jetson (ARM64) ****************************** .. _tensorrt_oss_on_jetson_arm64: 1. Install Cmake (>=3.13) .. Note:: TensorRT OSS requires cmake >= v3.13, while the default cmake on Jetson/Ubuntu 18.04 is cmake 3.10.2. Upgrade TensorRT OSS using: .. code:: sudo apt remove --purge --auto-remove cmake wget https://github.com/Kitware/CMake/releases/download/v3.13.5/cmake-3.13.5.tar.gz tar xvf cmake-3.13.5.tar.gz cd cmake-3.13.5/ ./configure make -j$(nproc) sudo make install sudo ln -s /usr/local/bin/cmake /usr/bin/cmake 2. Get GPU architecture based on your platform. The :code:`GPU_ARCHS` for different Jetson platform are given in the following table. +----------------------+---------------+ | **Jetson Platform** | **GPU_ARCHS** | +----------------------+---------------+ | Nano/Tx1 | 53 | +----------------------+---------------+ | Tx2 | 62 | +----------------------+---------------+ | AGX Xavier/Xavier NX | 72 | +----------------------+---------------+ 3. Build TensorRT OSS: .. code:: git clone -b release/7.0 https://github.com/nvidia/TensorRT cd TensorRT/ git submodule update --init --recursive export TRT_SOURCE=`pwd` cd $TRT_SOURCE mkdir -p build && cd build .. Note:: The :code:`-DGPU_ARCHS=72` below is for Xavier or NX, for other Jetson platform, change :code:`72` referring to :code:`GPU_ARCHS` from step 2. .. code:: /usr/local/bin/cmake .. -DGPU_ARCHS=72 -DTRT_LIB_DIR=/usr/lib/aarch64-linux-gnu/ -DCMAKE_C_COMPILER=/usr/bin/gcc -DTRT_BIN_DIR=`pwd`/out make nvinfer_plugin -j$(nproc) After building ends successfully, :code:`libnvinfer_plugin.so*` will be generated under :code:`‘pwd’/out/.` 4. Replace :code:`"libnvinfer_plugin.so*"` with the newly generated. .. code:: sudo mv /usr/lib/aarch64-linux-gnu/libnvinfer_plugin.so.7.x.y ${HOME}/libnvinfer_plugin.so.7.x.y.bak // backup original libnvinfer_plugin.so.x.y sudo cp `pwd`/out/libnvinfer_plugin.so.7.m.n /usr/lib/aarch64-linux-gnu/libnvinfer_plugin.so.7.x.y sudo ldconfig Generating an Engine Using tlt-converter ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. _generating_an_engine_using_tlt-converter: This is part of option 2 from the DeepStream deployment table above. The :code:`tlt-converter` is a tool that is provided with the Transfer Learning Toolkit to facilitate the deployment of TLT trained models on TensorRT and/or Deepstream. For deployment platforms with an x86 based CPU and discrete GPUs, the :code:`tlt-converter` is distributed within the TLT docker. Therefore, it is suggested to use 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 TLT docker includes TensorRT version 7.1. In order to use the engine with a different minor version of TensorRT, copy the converter from :code:`/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 ******************** 1. Copy :code:`/opt/nvidia/tools/tlt-converter` to the target machine. 2. Install `TensorRT 7.0+`_ for the respective target machine. 3. For RetinaNet, we need to build `TensorRT Open source software`_ on the machine. Instructions to build TensorRT OSS on x86 can be found in :ref:`TensorRT OSS on x86` section above or in this `GitHub repo`_. 4. Run :code:`tlt-converter` using the sample command below and generate the engine. .. _TensorRT 7.0+: https://developer.nvidia.com/tensorrt .. _TensorRT Open source software: https://github.com/NVIDIA/TensorRT .. _GitHub repo: https://github.com/NVIDIA-AI-IOT/deepstream_tlt_apps Instructions for Jetson *********************** For the Jetson platform, the :code:`tlt-converter` is available to download in the `dev zone`_. Once the :code:`tlt-converter` is downloaded, please follow the instructions below to generate a TensorRT engine. .. _dev zone: https://developer.nvidia.com/tlt-converter-trt71 1. Unzip :code:`tlt-converter-trt7.1.zip` on the target machine. 2. Install the open ssl package using the command: .. code:: sudo apt-get install libssl-dev 3. Export the following environment variables: .. code:: $ export TRT_LIB_PATH=”/usr/lib/aarch64-linux-gnu” $ export TRT_INC_PATH=”/usr/include/aarch64-linux-gnu” 4. For Jetson devices, TensorRT 7.1 comes pre-installed with `Jetpack`_. If you are using older JetPack, upgrade to JetPack 4.4. 5. For RetinaNet, instructions to build TensorRT OSS on Jetson can be found in :ref:`TensorRT OSS on Jetson (ARM64) ` section above or in this `GitHub repo`_. 6. Run the :code:`tlt-converter` using the sample command below and generate the engine. .. Note:: Make sure to follow the output node names as mentioned in :ref:`Exporting the Model`. .. _Jetpack: https://developer.nvidia.com/embedded/jetpack Using the tlt-converter *********************** .. code:: tlt-converter [-h] -k -d -o [-c ] [-e ] [-b ] [-m ] [-t ] [-w ] [-i ] [-p ] [-s] [-u ] input_file Required Arguments ~~~~~~~~~~~~~~~~~~ * :code:`input_file`: Path to the :code:`.etlt` model exported using :code:`tlt retinanet export`. * :code:`-k`: The key used to encode the :code:`.tlt` model when doing the training. * :code:`-d`: Comma-separated list of input dimensions that should match the dimensions used for :code:`tlt retinanet export`. * :code:`-o`: Comma-separated list of output blob names that should match the output configuration used for :code:`tlt retinanet export`. For RetinaNet, set this argument to :code:`NMS`. Optional Arguments ~~~~~~~~~~~~~~~~~~ * :code:`-e`: Path to save the engine to. (default: :code:`./saved.engine`) * :code:`-t`: Desired engine data type, generates calibration cache if in INT8 mode. The default value is :code:`fp32`. The options are {:code:`fp32`, :code:`fp16`, :code:`int8`}. * :code:`-w`: Maximum workspace size for the TensorRT engine. The default value is :code:`1073741824(1<<30)`. * :code:`-i`: Input dimension ordering, all other TLT commands use NCHW. The default value is :code:`nchw`. The options are {:code:`nchw`, :code:`nhwc`, :code:`nc`}. For RetinaNet, we can omit it(defaults to :code:`nchw`). * :code:`-p`: Optimization profiles for :code:`.etlt` models with dynamic shape. Comma separated list of optimization profile shapes in the format :code:`,,,`, where each shape has the format: :code:`xxx`. Can be specified multiple times if there are multiple input tensors for the model. This is only useful for new models introduced in TLT 3.0. This parameter is not required for models that are already existed in TLT 2.0. * :code:`-s`: TensorRT strict type constraints. A Boolean to apply TensorRT strict type constraints when building the TensorRT engine. * :code:`-u`: Use DLA core. Specifying DLA core index when building the TensorRT engine on Jetson devices. INT8 Mode Arguments ~~~~~~~~~~~~~~~~~~~ * :code:`-c`: Path to calibration cache file, only used in INT8 mode. The default value is :code:`./cal.bin`. * :code:`-b`: Batch size used during the export step for INT8 calibration cache generation. (default: :code:`8`). * :code:`-m`: Maximum batch size for TensorRT engine.(default: :code:`16`). If meet with out-of-memory issue, decrease the batch size accordingly. This parameter is not required for :code:`.etlt` models generated with dynamic shape. (This is only possible for new models introduced in TLT 3.0.) Sample Output Log ~~~~~~~~~~~~~~~~~ Here is a sample log for exporting a RetinaNet model. .. code:: tlt-converter -k $KEY \ -d 3,384,1248 \ -o NMS \ -e /export/trt.fp16.engine \ -t fp16 \ -i nchw \ -m 1 \ /ws/retinanet_resnet18_epoch_100.etlt .. [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 2 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 :code:`tlt retinanet export`. * **Option 2**: Generate a device specific optimized TensorRT engine, using tlt-converter. The TensorRT engine file can also be ingested by DeepStream. For RetinaNet, we will need to build TensorRT Open source plugins and custom bounding box parser. The instructions are provided below in the TensorRT OSS section above and the required code can be found in this `GitHub repo`_. .. _GitHub repo: https://github.com/NVIDIA-AI-IOT/deepstream_tlt_apps 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 :code:`.etlt` model file and optional calibration cache for INT8 precision. 3. `TensorRT 7+ OSS Plugins`_ . 4. A :code:`labels.txt` file containing the labels for classes in the order in which the networks produces outputs. 5. A sample :code:`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. .. _Download: https://developer.nvidia.com/deepstream-download .. _DeepStream Development Guide: https://docs.nvidia.com/metropolis/deepstream/dev-guide/index.html .. _TensorRT 7+ OSS Plugins : https://github.com/NVIDIA/TensorRT/tree/release/7.0 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 :code:`deepstream-app`. The graphic below shows the architecture of the reference application. .. image:: ../../content/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 :code:`samples/configs/deepstream-app` or :code:`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 :code:`samples/configs/deepstream-app` for your reference. * :code:`source4_1080p_dec_infer-resnet_tracker_sgie_tiled_display_int8.txt`: Main config file * :code:`config_infer_primary.txt`: Supporting config file for primary detector in the pipeline above * :code:`config_infer_secondary_*.txt`: Supporting config file for secondary classifier in the pipeline above The :code:`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. User will only have to modify or create :code:`config_infer_primary.txt` and :code:`config_infer_secondary_*.txt`. Integrating a RetinaNet Model ****************************** To run a RetinaNet model in DeepStream, you need a label file and a DeepStream configuration file. In addition, you need to compile the TensorRT 7+ Open source software and SSD bounding box parser for DeepStream. A DeepStream sample with documentation on how to run inference using the trained RetinaNet models from TLT is provided on GitHub here_. Prerequisite for RetinaNet Model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. RetinaNet requires batchTilePlugin and NMS_TRT. This plugin is available in the TensorRT open source repo, but not in TensorRT 7.0. Detailed instructions to build TensorRT OSS can be found in `TensorRT Open Source Software (OSS)`. 2. RetinaNet requires custom bounding box parsers that are not built-in inside the DeepStream SDK. The source code to build custom bounding box parsers for RetinaNet is available here_. The following instructions can be used to build bounding box parser: **Step1**: Install git-lfs_ (git >= 1.8.2) .. _git-lfs: https://github.com/git-lfs/git-lfs/wiki/Installation .. code:: curl -s https://packagecloud.io/install/repositories/github/git-lfs/ script.deb.sh | sudo bash sudo apt-get install git-lfs git lfs install **Step 2**: Download Source Code with SSH or HTTPS .. code:: git clone -b release/tlt3.0 https://github.com/NVIDIA-AI-IOT/deepstream_tlt_apps **Step 3**: Build .. code:: // or Path for DS installation export CUDA_VER=10.2 // CUDA version, e.g. 10.2 make This generates :code:`libnvds_infercustomparser_tlt.so` in the directory :code:`post_processor`. Label File ^^^^^^^^^^ The label file is a text file containing the names of the classes that the RetinaNet model is trained to detect. The order in which the classes are listed here must match the order in which the model predicts the output. During the training, TLT RetinaNet will specify all class names in lower case and sort them in alphabetical order. For example, if the `dataset_config` is: .. code:: dataset_config { data_sources: { label_directory_path: "/workspace/tlt-experiments/data/training/label_2" image_directory_path: "/workspace/tlt-experiments/data/training/image_2" } target_class_mapping { key: "car" value: "car" } target_class_mapping { key: "person" value: "person" } target_class_mapping { key: "bicycle" value: "bicycle" } validation_data_sources: { label_directory_path: "/workspace/tlt-experiments/data/val/label" image_directory_path: "/workspace/tlt-experiments/data/val/image" } } Then the corresponding `retinanet_labels.txt` file would be: .. code:: bicycle car person DeepStream Configuration File ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The detection model is typically used as a primary inference engine. It can also be used as a secondary inference engine. To run this model in the sample :code:`deepstream-app`, you must modify the existing :code:`config_infer_primary.txt` file to point to this model. .. image:: ../../content/dstream_deploy_options2.png **Option 1**: Integrate the model (:code:`.etlt`) directly in the DeepStream app. For this option, users will need to add the following parameters in the configuration file. The :code:`int8-calib-file` is only required for INT8 precision. .. code:: tlt-encoded-model= tlt-model-key= int8-calib-file= The :code:`tlt-encoded-model` parameter points to the exported model (:code:`.etlt`) from TLT. The :code:`tlt-model-key` is the encryption key used during model export. **Option 2**: Integrate TensorRT engine file with DeepStream app. **Step 1**: Generate TensorRT engine using tlt-converter. Detail instructions are provided in the :ref:`Generating an engine using tlt-converter ` section above. **Step 2**: Once the engine file is generated successfully, modify the following parameters to use this engine with DeepStream. .. code:: model-engine-file= All other parameters are common between the two approaches. To use the custom bounding box parser instead of the default parsers in DeepStream, modify the following parameters in [property] section of primary infer configuration file: .. code:: parse-bbox-func-name=NvDsInferParseCustomNMSTLT custom-lib-path= Add the label file generated above using: .. code:: labelfile-path= For all the options, see the sample configuration file below. To learn about what all the parameters are used for, refer to the `DeepStream Development Guide`_. .. _DeepStream Development Guide: https://docs.nvidia.com/metropolis/deepstream/dev-guide/index.html .. code:: [property] gpu-id=0 net-scale-factor=1.0 offsets=103.939;116.779;123.68 model-color-format=1 labelfile-path= tlt-encoded-model= tlt-model-key= uff-input-dims=3;384;1248;0 uff-input-blob-name=Input batch-size=1 ## 0=FP32, 1=INT8, 2=FP16 mode network-mode=0 num-detected-classes=3 interval=0 gie-unique-id=1 is-classifier=0 #network-type=0 output-blob-names=NMS parse-bbox-func-name=NvDsInferParseCustomNMSTLT custom-lib-path= [class-attrs-all] threshold=0.3 roi-top-offset=0 roi-bottom-offset=0 detected-min-w=0 detected-min-h=0 detected-max-w=0 detected-max-h=0