YOLOv3 ======= .. _yolo_v3: YOLOv3 is an object detection model that is included in the Transfer Learning Toolkit. YOLOv3 supports the following tasks: * kmeans * train * evaluate * inference * prune * export These tasks can be invoked from the TLT launcher using the following convention on the command line: .. code:: tlt yolo_v3 where :code:`args_per_subtask` are the command line arguments required for a given subtask. Each subtask is explained in detail below. Creating a Configuration File ----------------------------- .. _creating_a_configuration_file_yolo_v3: Below is a sample for the YOLOv3 spec file. It has six major components: :code:`yolov3_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 yolov3_config { big_anchor_shape: "[(116,90), (156,198), (373,326)]" mid_anchor_shape: "[(30,61), (62,45), (59,119)]" small_anchor_shape: "[(10,13), (16,30), (33,23)]" matching_neutral_box_iou: 0.5 arch: "darknet" nlayers: 53 arch_conv_blocks: 2 loss_loc_weight: 0.8 loss_neg_obj_weights: 100.0 loss_class_weights: 1.0 freeze_bn: false freeze_blocks: 0 freeze_blocks: 1 force_relu: false } training_config { batch_size_per_gpu: 16 checkpoint_interval: 10 num_epochs: 80 enable_qat: false learning_rate { soft_start_annealing_schedule { min_learning_rate: 5e-5 max_learning_rate: 2e-2 soft_start: 0.15 annealing: 0.8 } } regularizer { type: L1 weight: 3e-5 } optimizer { adam { epsilon: 1e-7 beta1: 0.9 beta2: 0.999 amsgrad: false } } pretrain_model_path: "EXPERIMENT_DIR/darknet_53.hdf5" } eval_config { average_precision_mode: SAMPLE batch_size: 16 matching_iou_threshold: 0.5 } nms_config { confidence_threshold: 0.01 clustering_iou_threshold: 0.6 top_k: 200 } augmentation_config { hue: 0.1 saturation: 1.5 exposure:1.5 vertical_flip:0 horizontal_flip: 0.5 jitter: 0.3 output_width: 1248 output_height: 384 output_channel: 3 randomize_input_shape_period: 0 image_mean { key: 'b' value: 103.9 } image_mean { key: 'g' value: 116.8 } image_mean { key: 'r' value: 123.7 } } dataset_config { data_sources: { label_directory_path: "/workspace/tlt-experiments/data/training/label_2" image_directory_path: "/workspace/tlt-experiments/data/training/image_2" } include_difficult_in_training: true 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 | Unsigned int, positive | -- | | | batch_size_per_gpu * num_gpus | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | checkpoint_interval | The number of training epochs per model checkpoint / validation that should run | Unsigned int, positive | 10 | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | num_epochs | The number of epochs to train the network | Unsigned int, positive. | -- | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | enable_qat | Whether to use quantization-aware training | Boolean | **Note**: YOLOv3 does not support loading a pruned QAT model and retraining | | | | | it with QAT disabled, or vice versa. For example, to get a pruned QAT model, | | | | | perform the initial training with QAT enabled or :code:`enable_qat=True`. | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | learning_rate | Only "soft_start_annealing_schedule" with these nested parameters is supported: | Message type. | -- | | | | | | | | 1. min_learning_rate: Minimum learning rate during the entire experiment | | | | | 2. max_learning_rate: Maximum learning during the entire experiment | | | | | 3. soft_start: Time to lapse 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 before | | | the following nested parameters: | | 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 regularizer weight as a floating point value | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | optimizer | Can be one of "adam", "sgd", or "rmsprop". Each type has the following parameters: | Message type. | -- | | | | | | | | 1. adam: epsilon, beta1, beta2, amsgrad | | | | | 2. sgd: momentum, nesterov | | | | | 3. rmsprop: rho, momentum, epsilon, centered | | | | | | | | | | The parameters are same as those in Keras_. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | pretrain_model_path | The path to the pretrained model, if any | String | -- | | | | | | | | At most one of pretrain_model_path, resume_model_path, or pruned_model_path may | | | | | present. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | resume_model_path | The path to a TLT checkpoint model to resume training, if any | String | -- | | | | | | | | At most one of pretrain_model_path, resume_model_path, or pruned_model_path may | | | | | present. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | pruned_model_path | The path to a TLT pruned model for re-training, if any | String | -- | | | | | | | | At most one of pretrain_model_path, resume_model_path, or pruned_model_path may | | | | | present. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | max_queue_size | The number of prefetch batches in data loading | Unsigned int, positive | -- | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | n_workers | The number of workers for data loading per GPU | Unsigned int, positive | -- | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | use_multiprocessing | Whether to use multiprocessing mode of keras sequence data loader | Boolean | true (in case of deadlock, restart training and use False) | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ .. 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`. .. _Keras: keras.io/api/optimizers Evaluation Config ^^^^^^^^^^^^^^^^^ The evaluation configuration (:code:`eval_config`) defines the parameters needed for evaluation either during training or as a standalone procedure. Details are summarized in the table below. +-----------------------------------+-----------------------------------------------------------------------------+----------------------------------+-------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +-----------------------------------+-----------------------------------------------------------------------------+----------------------------------+-------------------------------+ | average_precision_mode | Average Precision (AP) calculation mode can be either SAMPLE or INTEGRATE. | ENUM type ( SAMPLE or INTEGRATE) | SAMPLE | | | SAMPLE is 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 | float | 0.5 | | | a match. | | | +-----------------------------------+-----------------------------------------------------------------------------+----------------------------------+-------------------------------+ 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 applying NMS.| float | 0.01 | +------------------------------------------+------------------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ | cluster_iou_threshold | The IoU threshold below which boxes will go through the NMS process. | float | 0.6 | +------------------------------------------+------------------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ | top_k | top_k boxes will be output after the NMS keras layer. If the number of valid boxes is less | Unsigned int | 200 | | | than k, the returned array will be padded with boxes whose confidence score is 0. | | | +------------------------------------------+------------------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ | infer_nms_score_bits | The number of bits to represent the score values in NMS plugin in TensorRT OSS. The valid range| int. In the interval [1, 10]. | 0 | | | is integers in [1, 10]. Setting it to any other values will make it fall back to ordinary NMS. | | | | | Currently this optimized NMS plugin is only avaible in FP16 but it should also be selected by | | | | | INT8 data type as there is no INT8 NMS in TensorRT OSS and hence this fastest implementation in| | | | | FP16 will be selected. If falling back to ordinary NMS, the actual data type when building the | | | | | engine will decide the exact precision(FP16 or FP32) to run at. | | | +------------------------------------------+------------------------------------------------------------------------------------------------+-------------------------------+-------------------------------+ Augmentation Config ^^^^^^^^^^^^^^^^^^^ The augmentation configuration (:code:`augmentation_config`) defines the parameters needed for online data augmentation. Details are summarized in the table below. +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | hue | Image hue to be changed within [-hue, hue] * 180.0 | float of [0, 1] | 0.1 | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | saturation | Image saturation to be changed within [1.0 / saturation, saturation] | float >= 1.0 | 1.5 | | | times | | | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | exposure | Image exposure to be changed within [1.0 / exposure, exposure] times | float >= 1.0 | 1.5 | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | vertical_flip | The probability of images to be vertically flipped | float of [0, 1] | 0 | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | horizontal_flip | The probability of images to be horizontally flipped | float of [0, 1] | 0.5 | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | jitter | The maximum jitter allowed in augmentation. Jitter here refers | float of [0, 1] | 0.3 | | | to jitter augmentation in YOLO networks | | | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | output_width | The base output image width of augmentation pipeline. | integer, multiple of 32 | -- | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | output_height | The base output image height of augmentation pipeline | integer, multiple of 32 | -- | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | output_channel | The number of output channels of augmentation pipeline | 1 or 3 | -- | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | randomize_input_shape_period | The batch interval to randomly change the output width and height. | non-negative integer | 10 | | | For value K, the augmentation pipeline will adjust the output shape | | | | | per K batches and the adjusted output width/height will be within | | | | | 0.6 to 1.5 times of base width/height. | | | | | | | | | | Note: if K=0, the output width/height will always match the | | | | | base width/height as configured and training will be much faster, | | | | | but the accuracy of trained network might not be as good. | | | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ | image_mean | A key/value pair to specify image mean values. | dict | -- | | | If omitted, ImageNet mean will be used for image preprocessing. | | | | | If set, depending on `output_channel`, either 'r/g/b' or 'l' | | | | | key/value pair must be configured. | | | +------------------------------+----------------------------------------------------------------------+-------------------------------+-------------------------------+ Dataset Config ^^^^^^^^^^^^^^ The following is an example :code:`dataset_config` element: .. 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" } data_sources: { label_directory_path: "/workspace/tlt-experiments/data/training/label_3" image_directory_path: "/workspace/tlt-experiments/data/training/image_3" } include_difficult_in_training: true 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_1" image_directory_path: "/workspace/tlt-experiments/data/val/image_1" } } The YOLOv3 dataloader assumes the training/validation split is already done and data is prepared in KITTI format: images and labels are in two separate folders and each image file has a corresponding txt label file in the label folder with the same filename. The label file content should also follow KITTI format. 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`: Specifies 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 is 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`. Like :code:`data_sources`, this field contains two parameters. .. 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. YOLOv3 Config ^^^^^^^^^^^^^ The YOLOv3 configuration (:code:`yolov3_config`) defines the parameters needed for building the YOLOv3 model. Details are summarized in the table below. +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | **Field** | **Description** | **Data Type and Constraints** | **Recommended/Typical Value** | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | big_anchor_shape, mid_anchor_shape, and small_anchor_shape | These settings should be 1-d arrays inside quotation marks. The elements of these arrays | string | Use `tlt yolo_v3 kmeans` command to generate those | | | are tuples representing the pre-defined anchor shape in the order of width, height. | | shapes | | | | | | | | By default, YOLOv3 has nine predefined anchor shapes, divided into three groups | | | | | corresponding to big, medium, and small objects. The detection output corresponding to | | | | | different groups are from different depths in the network. Users should run the kmeans | | | | | command (:code:`tlt yolo_v3 kmeans`) to determine the best anchor shapes for their own | | | | | dataset and put those anchor shapes in the spec file. Note that the number of | | | | | anchor shapes for any field is not limited to 3. Users only need to specify at least one anchor | | | | | shape in each of those three fields. | | | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | matching_neutral_box_iou | This field should be a float number between 0 and 1. Any anchor not matching to ground truth | float | 0.5 | | | boxes, but with IOU higher than this float value with any ground truth box, will not have their | | | | | objectiveness loss back-propagated during training. This is to reduce false negatives. | | | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | arch_conv_blocks | Supported values are 0, 1 and 2. This value controls how many convolutional blocks are present | 0, 1 or 2 | 2 | | | among detection output layers. Setting this value to 2 if you want to reproduce the meta | | | | | architecture of the original YOLOv3 model coming with DarkNet 53. Please note this config setting | | | | | only controls the size of the YOLO meta architecture and the size of the feature extractor has | | | | | nothing to do with this config field. | | | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | loss_loc_weight, loss_neg_obj_weights, and loss_class_weights | Those loss weights can be configured as float numbers. | float | loss_loc_weight: 5.0 | | | | | loss_neg_obj_weights: 50.0 | | | The YOLOv3 loss is a summation of localization loss, negative objectiveness loss, positive | | loss_class_weights: 1.0 | | | objectiveness loss and classification loss. The weight of positive objectiveness loss is set to | | | | | 1 while the weights of other losses are read from config file. | | | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | arch | Backbone for feature extraction. Currently, “resnet”, “vgg”, “darknet”, “googlenet”, “mobilenet_v1”, | string | resnet | | | “mobilenet_v2” and “squeezenet” are supported. | | | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | nlayers | Number of conv layers in specific arch. For “resnet”, 10, 18, 34, 50 and 101 are supported. For “vgg”, | Unsigned int | -- | | | 16 and 19 are 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 | list(repeated integers) | -- | | | CNN blocks in the model 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 | • ResNet series. For the ResNet series, the block IDs valid for | | | | model, etc. However, the block ID numbers identify the blocks in the model in a sequential order so you | freezing is any subset of [0, 1, 2, 3] (inclusive) | | | | don't have to know the exact locations of the blocks when you do training. A general principle to keep | • VGG series. For the VGG series, the block IDs valid for freezing | | | | in mind is: the smaller the block ID, the closer it is to the model input; the larger the block ID, the | is any subset of[1, 2, 3, 4, 5] (inclusive) | | | | closer it is to the model output. | • GoogLeNet. For the GoogLeNet, the block IDs valid for freezing | | | | | is any subset of[0, 1, 2, 3, 4, 5, 6, 7] (inclusive) | | | | You can divide the whole model into several blocks and optionally freeze a subset of it. Note that for | • MobileNet V1. For the MobileNet V1, the block IDs valid for freezing | | | | FasterRCNN you can only freeze the blocks that are before the ROI pooling layer. Any layer after the ROI | is any subset of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11](inclusive) | | | | pooling layer will not be frozen any way. For different backbones, the number of blocks and the block ID | • MobileNet V2. For the MobileNet V2, the block IDs valid for freezing | | | | for each block are different. It deserves some detailed explanations on how to specify the block ID's for | is any subset of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13](inclusive) | | | | each backbone. | • 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) | | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ | force_relu | Whether to replace all activation functions with ReLU. This is useful for training models for NVDLA. | boolean | False | +---------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------+ Generate the Anchor Shape ------------------------- The anchor shape should match most ground truth boxes in the dataset to help the network learn bounding boxes. You can use the kmeans algorithm to generate the anchor shapes. The algorithm is implemented in TLT as the :code:`tlt yolo_v3 kmeans` command. You can use the output of the algorithm as the anchor shape in the :code:`yolov3_config` spec file. .. code:: tlt yolo_v3 kmeans [-h] -l -i -x -y [-n ] [--max_steps ] [--min_x ] [--min_y ] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-l`: The paths to the training label folders. Multiple folder paths should be separated with spaces. * :code:`-i`: The paths to corresponding training image folders. Folder counts and orders must match label folders. * :code:`-x`: The base network input width, which should be `output_width` in the augmentation config section of your spec file. * :code:`-y`: The base network input height, which should be `output_height` in the augmentation config section of your spec file. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-n`: The number of shape clusters. This defines how many shape centers the command will output. The default is 9 (3 per group, with 3 groups) * :code:`--max_steps`: The maximum number of steps the kmeans algorithm should run. If the algorithm does not converge at this step, a suboptimal result will be returned. The default value is 10000. * :code:`--min_x`: Ignore ground-truth boxes with width less than this value in the reshaped image (images are first reshaped to the network base shape as `-x`, `-y`) * :code:`--min_y`: Ignore ground-truth boxes with height less than this value in the reshaped image (images are first reshaped to the network base shape as `-x`, `-y`) * :code:`-h, --help`: Show this help message and exit. Training the Model ------------------ .. _training_the_model_yolo_v3: Train the YOLOv3 model using this command: .. code:: tlt yolo_v3 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 for training in a multi-GPU scenario (the default value is 1). * :code:`--gpu_index`: The GPU indices used to run training. You can use GPU indicies to specify the GPU(s) to use for training when the machine has multiple GPUs installed. * :code:`--use_amp`: A flag to enable AMP training. * :code:`--log_file`: The path to the log file. The default path is "stdout". * :code:`-h, --help`: Show this help message and exit. Input Requirement ^^^^^^^^^^^^^^^^^ * **Input size**: C * W * H (where C = 1 or 3, W >= 128, H >= 128, W, H are multiples of 32) * **Image format**: JPG, JPEG, PNG * **Label format**: KITTI detection Sample Usage ^^^^^^^^^^^^ Here's an example of using the train command on a YOLOv3 model: .. code:: tlt yolo_v3 train --gpus 2 -e /path/to/spec.txt -r /path/to/result -k $KEY Evaluating the Model -------------------- To run evaluation for a YOLOv3 model use this command: .. code:: tlt yolo_v3 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. Model can be either .tlt model file or TensorRT engine. * :code:`-k, --key`: Provide the key to load the model (not needed if model is a TensorRT engine). Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-h, --help`: show this help message and exit. * :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. Running Inference on a YOLOv3 Model ----------------------------------- .. _running_inference_on_a_yolo_v3_model: The inference tool for YOLOv3 networks may be used to visualize bboxes or generate frame-by-frame KITTI-format labels on a single image or a directory of images. An example of the command for this tool is shown here: .. code:: tlt yolo_v3 inference [-h] -i -o -e -m -k [-l ] [-t ] [--gpu_index ] [--log_file ] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-m, --model`: Path to the trained model (TLT model) or 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 model (not needed if model is a TensorRT engine). * :code:`-e, --config_path`: Path to an experiment spec file for training. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-t, --draw_conf_thres`: The threshold for drawing a bbox. The default value is 0.3. * :code:`-h, --help`: Show this help message and exit. * :code:`-l, --out_label_dir`: The directory to output KITTI labels. * :code:`--gpu_index`: The GPU index used to run inference. You can specify the index of the GPU to run evaluation when the machine has multiple GPUs installed. Note that evaluation can only run on a single GPU. * :code:`--log_file`: The path to the log file. The default path is "stdout". Pruning the Model ----------------- .. _pruning_the_model_yolo_v3: Pruning removes parameters from the model to reduce the model size without compromising the integrity of the model itself using the :code:`tlt yolo_v3 prune` command. The :code:`tlt yolo_v3 prune` command includes these parameters: .. code:: tlt yolo_v3 prune [-h] -m -o -k [-n ] [-eq ] [-pg ] [-pth ] [-nf ] [-el [] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-m, --model`: Path to pretrained YOLOv3 model. * :code:`-o, --output_file`: Path to output checkpoints. * :code:`-k, --key`: Key to load a .tlt model. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-h, --help`: Show this help message and exit. * :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: []). 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 yolo_v3 prune` command: .. code:: tlt yolo_v3 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_yolo_v3: Once the model has been pruned, there might be a slight decrease in accuracy because some previously useful weights may be removed. To regain accuracy, NVIDIA recommends that you retrain this pruned model over the same dataset. To do this, use the :code:`tlt yolo_v3 train` command as documented in :ref:`Training the model `, with an updated spec file that points to the newly pruned model as the :code:`pruned_model_path`. We recommend turning off the regularizer in the :code:`training_config` for detectnet to recover the accuracy when retraining a pruned model. To do this, set the regularizer type to :code:`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_yolo_v3: 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 the :code:`.tlt` model format, :code:`.etlt` is an encrypted model format, and it uses the same key as 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 yolo_v3 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 the INT8 calibration cache by ingesting training data using one 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 you need to do is provide a :code:`.tlt` model from the training/retraining step to be converted into :code:`.etlt` format. Exporting the Model ^^^^^^^^^^^^^^^^^^^ Here's an example of the command line arguments of the :code:`tlt yolo_v3 export` command: .. code:: tlt yolo_v3 export [-h] -m -k [-o ] [--cal_data_file ] [--cal_image_dir ] [--data_type ] [--batches ] [--max_batch_size ] [--max_workspace_size ] [--experiment_spec ] [--engine_file ] [--gen_ds_config] [--verbose] [--strict_type_constraints] [--force_ptq] [--gpu_index ] [--log_file ] Required Arguments ****************** * :code:`-m, --model`: The path to the :code:`.tlt` model file to be exported. * :code:`-k, --key`: The key used to save the :code:`.tlt` model file. * :code:`-e, --experiment_spec`: The path to the spec file. Optional Arguments ****************** * :code:`-h, --help`: Show this help message and exit. * :code:`-o, --output_file`: The path to save the exported model to. The default path is :code:`./.etlt`. * :code:`--data_type`: The desired engine data type. The options are :code:`fp32`, :code:`fp16`, :code:`int8`. The default value is :code:`fp32`. A calibration cache will be generated in INT8 mode. If using INT8, the following INT8 arguments are required. * :code:`--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 :code:`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. * :code:`-s, --strict_type_constraints`: A Boolean flag indicating whether to apply the TensorRT strict type constraints when building the TensorRT engine. * :code:`--gpu_index`: The index of (discrete) GPUs used for exporting the model. You can specify the index of the GPU to run export if the machine has multiple GPUs installed. Note that export can only run on a single GPU. * :code:`--log_file`: The path to the log file. The default path is "stdout". 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`: The path to save the calibration cache file to. 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 YOLOv3 model in INT8 mode: .. code:: tlt yolo_v3 export -m /workspace/yolov3_resnet18_epoch_100.tlt \ -o /workspace/yolov3_resnet18_epoch_100_int8.etlt \ -e /workspace/yolov3_retrain_resnet18_kitti.txt \ -k $KEY \ --cal_image_dir /workspace/data/training/image_2 \ --data_type int8 \ --batch_size 8 \ --batches 10 \ --cal_cache_file /export/cal.bin \ --cal_data_file /export/cal.tensorfile Deploying to DeepStream ----------------------- .. _deploying_to_deepstream_yolov3: .. include:: ../excerpts/deploying_to_deepstream.rst TensorRT Open Source Software (OSS) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ For YOLOv3, we need the :code:`batchTilePlugin` and :code:`batchedNMSPlugin` plugins from the TensorRT OSS build. If the deployment platform is x86 with an NVIDIA GPU, follow the **TensorRT OSS on x86** instructions. On the other hand, if your deployment is on the NVIDIA Jetson platform, follow the **TensorRT OSS on Jetson (ARM64)** instructions. TensorRT OSS on x86 ******************* .. _tensorrt_oss_on_x86: Building TensorRT OSS on x86: 1. Install Cmake (>=3.13). .. Note:: TensorRT OSS requires cmake version v3.13 or greater, 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 your 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 that the :code:`GPU_ARCHS` is :code:`75` based on the 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 :code:`GPU_ARCHS` is not in TensorRT OSS :code:`CMakeLists.txt`, add :code:`-DGPU_ARCHS=` as below, where :code:`` represents the :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 version v3.13 or greater, while the default version of cmake on Jetson/Ubuntu 18.04 is cmake 3.10.2. Upgrade TensorRT OSS as follows: .. 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 the GPU architecture for your platform. The :code:`GPU_ARCHS` for different Jetson platforms 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 Jetson Xavier or NX; for other Jetson platforms, change :code:`72` to the :code:`GPU_ARCHS` number shown in 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 completes successfully, :code:`libnvinfer_plugin.so*` will be generated under :code:`‘pwd’/out/.` 4. Replace :code:`"libnvinfer_plugin.so*"` with the newly generated version: .. 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: .. include:: ../excerpts/generating_an_engine_using_tlt-converter.rst 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 YOLOv3, you 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 this 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 an older version of JetPack, upgrade to JetPack 4.4. 5. For YOLOv3, instructions to build TensorRT OSS on Jetson can be found in the :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`: The path to the :code:`.etlt` model exported using :code:`tlt yolo_v3 export`. * :code:`-k`: The key used to encode the :code:`.tlt` model when doing the training. * :code:`-d`: A comma-separated list of input dimensions that should match the dimensions used for :code:`tlt yolo_v3 export`. * :code:`-o`: A comma-separated list of output blob names that should match the output configuration. used for :code:`tlt yolo_v3 export`. For YOLOv3, set this argument to :code:`BatchedNMS`. * :code:`-p`: Optimization profiles for :code:`.etlt` models with dynamic shape. Use a comma-separated list of optimization profile shapes in the format :code:`,,,`, where each shape has the format: :code:`xxx`. The input name for YOLOv3 is :code:`Input` Optional Arguments ~~~~~~~~~~~~~~~~~~ * :code:`-e`: The path to save the engine to. The default path is :code:`./saved.engine`. * :code:`-t`: The desired engine data type. The options are :code:`fp32`, :code:`fp16`, or :code:`int8`. Selecting INT8 mode will generate a calibration cache. * :code:`-w`: The maximum workspace size for the TensorRT engine. The default value is :code:`1073741824(1<<30)`. * :code:`-i`: The input-dimension ordering. All other TLT commands use NCHW. The options are :code:`nchw`, :code:`nhwc`, and :code:`nc`. The default value is :code:`nchw`, so you can omit this argument for YOLOv3. * :code:`-s`: A Boolean value specifying wheter to apply TensorRT strict-type constraints when building the TensorRT engine. * :code:`-u`: Only needed if use DLA core. Specifying DLA core index when building the TensorRT engine on Jetson devices. INT8 Mode Arguments ~~~~~~~~~~~~~~~~~~~ * :code:`-c`: The path to calibration cache file (only used in INT8 mode). The default value is :code:`./cal.bin`. * :code:`-b`: The batch size used during the export step for INT8 calibration cache generation (default: :code:`8`). * :code:`-m`: The maximum batch size for the TensorRT engine. The default value is :code:`16`. If out-of-memory issues occur, decrease the batch size accordingly. This parameter is not required for :code:`.etlt` models generated with dynamic shape, which is only possible for new models introduced in TLT 3.0. Sample Output Log ~~~~~~~~~~~~~~~~~ Here is a sample log for exporting a YOLOv3 model. .. code:: tlt-converter -k $KEY \ -d 3,384,1248 \ -o BatchedNMS \ -e /export/trt.fp16.engine \ -t fp16 \ -i nchw \ -m 8 \ /ws/yolov3_resnet18_epoch_100.etlt Integrating the model to DeepStream ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To integrate a model trained by TLT with DeepStream, you shoud generate a device-specific optimized TensorRT engine using :code:`tlt-converter`. The generated TensorRT engine file can then be ingested by DeepStream (Currently, YOLOv3 etlt files are not supported by DeepStream). For YOLOv3, you will need to build the TensorRT open source plugins and custom bounding-box parser. The instructions to build TensorRT open source plugins are provided in the TensorRT OSS section above. The instructions to build custom bounding-box parser is provided below in prerequisite section and the required code can be found in this `GitHub repo`_. .. _GitHub repo: https://github.com/NVIDIA-AI-IOT/deepstream_tlt_apps To integrate the models with DeepStream, you will need the following: 1. The DeepStream SDK (download from the `DeepStream SDK Download Page`_). 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 produce 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. .. _DeepStream SDK Download Page: 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, the 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 Typically, two or more configuration files 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 will 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 configuration files are used to specify the models, inference resolution, batch size, number of classes, and other customizations. The main configuration file will call all the supporting configuration files. Here are some configuration files in :code:`samples/configs/deepstream-app` for reference: * :code:`source4_1080p_dec_infer-resnet_tracker_sgie_tiled_display_int8.txt`: The main configuration file. * :code:`config_infer_primary.txt`: The supporting configuration file for the primary detector in the pipeline above. * :code:`config_infer_secondary_*.txt`: The supporting configuration file for the secondary classifier in the pipeline above. The :code:`deepstream-app` will only work with the main configuration 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. You will only have to modify or create :code:`config_infer_primary.txt` and :code:`config_infer_secondary_*.txt`. Integrating a YOLOv3 Model ****************************** To run a YOLOv3 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 YOLOv3 bounding box parser for DeepStream. A DeepStream sample with documentation on how to run inference using the trained YOLOv3 models from TLT is provided on `GitHub repo`_. Prerequisite for YOLOv3 Model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. YOLOv3 requires the batchTilePlugin, resizeNearestPlugin and batchedNMSPlugin. These plugins are available in the TensorRT open source repo, but not in TensorRT 7.0. Detailed instructions to build TensorRT OSS can be found in the **TensorRT Open Source Software (OSS)** section. 2. YOLOv3 requires custom bounding box parsers that are not built in to the DeepStream SDK. The source code to build custom bounding box parsers for YOLOv3 is available in `GitHub repo`_. The following instructions can be used to build the bounding-box parser: a. Install git-lfs_ (git >= 1.8.2) .. 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 .. _git-lfs: https://github.com/git-lfs/git-lfs/wiki/Installation b. Download the source code with SSH or HTTPS: .. code:: git clone -b release/tlt3.0 https://github.com/NVIDIA-AI-IOT/deepstream_tlt_apps c. Build the parser: .. 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 YOLOv3 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 YOLOv3 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 `yolov3_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 **Integrate the TensorRT engine file with the DeepStream app** 1. Generate the TensorRT engine using tlt-converter. Detailed instructions are provided in the :ref:`Generating an engine using tlt-converter ` section above. 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 the :code:`[property]` section of the primary infer configuration file: .. code:: parse-bbox-func-name=NvDsInferParseCustomBatchedNMSTLT custom-lib-path= Add the label file generated above using the following: .. code:: labelfile-path= For all the options, see the configuration file below. To learn more about all the parameters, refer to the `DeepStream Development Guide`_. .. _DeepStream Development Guide: https://docs.nvidia.com/metropolis/deepstream/dev-guide/index.html Here’s a sample config file, `pgie_yolov3_config.txt`: .. code:: [property] gpu-id=0 net-scale-factor=1.0 offsets=103.939;116.779;123.68 model-color-format=1 labelfile-path= model-engine-file= tlt-model-key= infer-dims=3;384;1248 maintain-aspect-ratio=1 uff-input-order=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 #no cluster cluster-mode=3 output-blob-names=BatchedNMS parse-bbox-func-name=NvDsInferParseCustomBatchedNMSTLT custom-lib-path= [class-attrs-all] pre-cluster-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