MaskRCNN

MaskRCNN supports the following tasks:

  • train

  • evaluate

  • inference

  • export

These tasks may be invoked from the TAO Toolkit Launcher using the following convention on the command line:

tao mask_rcnn <sub_task> <args_per_subtask>

where args_per_subtask are the command-line arguments required for a given subtask. Each of these subtasks are explained in detail below.

Creating a Configuration File

Below is a sample MaskRCNN spec file. It has three major components: top level experiment configs, data_config, and maskrcnn_config, explained below in detail. 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.

Here’s a sample of the MaskRCNN spec file:

seed: 123
use_amp: False
warmup_steps: 0
checkpoint: "/workspace/tao-experiments/maskrcnn/pretrained_resnet50/tlt_instance_segmentation_vresnet50/resnet50.hdf5"
learning_rate_steps: "[60000, 80000, 100000]"
learning_rate_decay_levels: "[0.1, 0.02, 0.002]"
total_steps: 120000
train_batch_size: 2
eval_batch_size: 4
num_steps_per_eval: 10000
momentum: 0.9
l2_weight_decay: 0.0001
l1_weight_decay: 0.0
warmup_learning_rate: 0.0001
init_learning_rate: 0.02
# pruned_model_path: "/workspace/tao-experiments/maskrcnn/pruned_model/model.tlt"

data_config{
        image_size: "(832, 1344)"
        augment_input_data: True
        eval_samples: 500
        training_file_pattern: "/workspace/tao-experiments/data/train*.tfrecord"
        validation_file_pattern: "/workspace/tao-experiments/data/val*.tfrecord"
        val_json_file: "/workspace/tao-experiments/data/annotations/instances_val2017.json"

        # dataset specific parameters
        num_classes: 91
        skip_crowd_during_training: True
        max_num_instances: 200
}

maskrcnn_config {
        nlayers: 50
        arch: "resnet"
        freeze_bn: True
        freeze_blocks: "[0,1]"
        gt_mask_size: 112

        # Region Proposal Network
        rpn_positive_overlap: 0.7
        rpn_negative_overlap: 0.3
        rpn_batch_size_per_im: 256
        rpn_fg_fraction: 0.5
        rpn_min_size: 0.

        # Proposal layer.
        batch_size_per_im: 512
        fg_fraction: 0.25
        fg_thresh: 0.5
        bg_thresh_hi: 0.5
        bg_thresh_lo: 0.

        # Faster-RCNN heads.
        fast_rcnn_mlp_head_dim: 1024
        bbox_reg_weights: "(10., 10., 5., 5.)"

        # Mask-RCNN heads.
        include_mask: True
        mrcnn_resolution: 28

        # training
        train_rpn_pre_nms_topn: 2000
        train_rpn_post_nms_topn: 1000
        train_rpn_nms_threshold: 0.7

        # evaluation
        test_detections_per_image: 100
        test_nms: 0.5
        test_rpn_pre_nms_topn: 1000
        test_rpn_post_nms_topn: 1000
        test_rpn_nms_thresh: 0.7

        # model architecture
        min_level: 2
        max_level: 6
        num_scales: 1
        aspect_ratios: "[(1.0, 1.0), (1.4, 0.7), (0.7, 1.4)]"
        anchor_scale: 8

        # localization loss
        rpn_box_loss_weight: 1.0
        fast_rcnn_box_loss_weight: 1.0
        mrcnn_weight_loss_mask: 1.0
}

Field

Description

Data Type and Constraints

Recommended/Typical Value

seed

The random seed for the experiment

Unsigned int

123

warmup_steps

The steps taken for learning rate to ramp up to the init_learning_rate

Unsigned int

warmup_learning_rate

The initial learning rate during the warmup phase

float

learning_rate_steps

A list of steps at which the learning rate decays by the factor specified in learning_rate_decay_levels

string

learning_rate_decay_levels

A list of decay factors. The length should match the length of learning_rate_steps.

string

total_steps

The total number of training iterations

Unsigned int

train_batch_size

The batch size during training

Unsigned int

4

eval_batch_size

The batch size during validation or evaluation

Unsigned int

8

num_steps_per_eval

Save a checkpoint and run evaluation every N steps.

Unsigned int

momentum

Momentum of the SGD optimizer

float

0.9

l1_weight_decay

L1 weight decay

float

0.0001

l2_weight_decay

L2 weight decay

float

0.0001

use_amp

Specifies whether to use Automatic Mixed Precision training

boolean

False

checkpoint

The path to a pretrained model

string

maskrcnn_config

The architecture of the model

message

data_config

The input data configuration

message

skip_checkpoint_variables

If specified, the weights of the layers with matching regular expressions will not be loaded. This is especially helpful for transfer learning.

string

pruned_model_path

The path to a pruned MaskRCNN model

string

Note

When using skip_checkpoint_variables, you can first find the model structure in the training log (Part of the MaskRCNN+ResNet50 model structure is shown below). If, for example, you want to retrain all prediction heads, you can set skip_checkpoint_variables to “head”. TAO Toolkit uses the Python re library to check whether “head” matches any layer name or re.search($skip_checkpoint_variables, $layer_name).

[MaskRCNN] INFO    : ================ TRAINABLE VARIABLES ==================
[MaskRCNN] INFO    : [#0001] conv1/kernel:0                                               => (7, 7, 3, 64)
[MaskRCNN] INFO    : [#0002] bn_conv1/gamma:0                                             => (64,)
[MaskRCNN] INFO    : [#0003] bn_conv1/beta:0                                              => (64,)
[MaskRCNN] INFO    : [#0004] block_1a_conv_1/kernel:0                                     => (1, 1, 64, 64)
[MaskRCNN] INFO    : [#0005] block_1a_bn_1/gamma:0                                        => (64,)
[MaskRCNN] INFO    : [#0006] block_1a_bn_1/beta:0                                         => (64,)
[MaskRCNN] INFO    : [#0007] block_1a_conv_2/kernel:0                                     => (3, 3, 64, 64)
[MaskRCNN] INFO    : [#0008] block_1a_bn_2/gamma:0                                        => (64,)
[MaskRCNN] INFO    : [#0009] block_1a_bn_2/beta:0                                         => (64,)
[MaskRCNN] INFO    : [#0010] block_1a_conv_3/kernel:0                                     => (1, 1, 64, 256)
[MaskRCNN] INFO    : [#0011] block_1a_bn_3/gamma:0                                        => (256,)
[MaskRCNN] INFO    : [#0012] block_1a_bn_3/beta:0                                         => (256,)
[MaskRCNN] INFO    : [#0110] block_3d_bn_3/gamma:0                                        => (1024,)
[MaskRCNN] INFO    : [#0111] block_3d_bn_3/beta:0                                         => (1024,)
[MaskRCNN] INFO    : [#0112] block_3e_conv_1/kernel:0                                     => (1, 1, 1024, [MaskRCNN] INFO    : [#0144] block_4b_bn_1/beta:0                                         => (512,)
                                …     …       …    …                                                                       ...
[MaskRCNN] INFO    : [#0174] post_hoc_d5/kernel:0                                     => (3, 3, 256, 256)
[MaskRCNN] INFO    : [#0175] post_hoc_d5/bias:0                                       => (256,)
[MaskRCNN] INFO    : [#0176] rpn/kernel:0                                        => (3, 3, 256, 256)
[MaskRCNN] INFO    : [#0177] rpn/bias:0                                          => (256,)
[MaskRCNN] INFO    : [#0178] rpn-class/kernel:0                                  => (1, 1, 256, 3)
[MaskRCNN] INFO    : [#0179] rpn-class/bias:0                                    => (3,)
[MaskRCNN] INFO    : [#0180] rpn-box/kernel:0                                    => (1, 1, 256, 12)
[MaskRCNN] INFO    : [#0181] rpn-box/bias:0                                      => (12,)
[MaskRCNN] INFO    : [#0182] fc6/kernel:0                                        => (12544, 1024)
[MaskRCNN] INFO    : [#0183] fc6/bias:0                                          => (1024,)
[MaskRCNN] INFO    : [#0184] fc7/kernel:0                                        => (1024, 1024)
[MaskRCNN] INFO    : [#0185] fc7/bias:0                                          => (1024,)
[MaskRCNN] INFO    : [#0186] class-predict/kernel:0                              => (1024, 91)
[MaskRCNN] INFO    : [#0187] class-predict/bias:0                                => (91,)
[MaskRCNN] INFO    : [#0188] box-predict/kernel:0                                => (1024, 364)
[MaskRCNN] INFO    : [#0189] box-predict/bias:0                                  => (364,)
[MaskRCNN] INFO    : [#0190] mask-conv-l0/kernel:0                              => (3, 3, 256, 256)
[MaskRCNN] INFO    : [#0191] mask-conv-l0/bias:0                                => (256,)
[MaskRCNN] INFO    : [#0192] mask-conv-l1/kernel:0                              => (3, 3, 256, 256)
[MaskRCNN] INFO    : [#0193] mask-conv-l1/bias:0                                => (256,)
[MaskRCNN] INFO    : [#0194] mask-conv-l2/kernel:0                              => (3, 3, 256, 256)
[MaskRCNN] INFO    : [#0195] mask-conv-l2/bias:0                                => (256,)
[MaskRCNN] INFO    : [#0196] mask-conv-l3/kernel:0                              => (3, 3, 256, 256)
[MaskRCNN] INFO    : [#0197] mask-conv-l3/bias:0                                => (256,)
[MaskRCNN] INFO    : [#0198] conv5-mask/kernel:0                                => (2, 2, 256, 256)
[MaskRCNN] INFO    : [#0199] conv5-mask/bias:0                                  => (256,)
[MaskRCNN] INFO    : [#0200] mask_fcn_logits/kernel:0                           => (1, 1, 256, 91)
[MaskRCNN] INFO    : [#0201] mask_fcn_logits/bias:0                             => (91,)

MaskRCNN Config

The MaskRCNN configuration (maskrcnn_config) defines the model structure. This model is used for training, evaluation, and inference. A detailed description is included in the table below. Currently, MaskRCNN only supports ResNet10/18/34/50/101 as its backbone.

Field

Description

Data Type and Constraints

Recommended/Typical Value

nlayers

The number of layers in ResNet arch

message

50

arch

The backbone feature extractor name

string

resnet

freeze_bn

Whether to freeze all BatchNorm layers in the backbone

boolean

False

freeze_blocks

A list of conv blocks in the backbone to freeze

string

ResNet: For the ResNet series, the block IDs valid for freezing are any subset of [0, 1, 2, 3] (inclusive)

gt_mask_size

The groundtruth mask size

Unsigned int

112

rpn_positive_overlap

The lower-bound threshold to assign positive labels for anchors

float

0.7

rpn_negative_overlap

The upper-bound threshold to assign negative labels for anchors

float

0.3

rpn_batch_size_per_im

The number of sampled anchors per image in RPN

Unsigned int

256

rpn_fg_fraction

The desired fraction of positive anchors in a batch

Unsigned int

0.5

rpn_min_size

The minimum proposal height and width

0

batch_size_per_im

The RoI minibatch size per image

Unsigned int

512

fg_fraction

The target fraction of RoI minibatch that is labeled as foreground

float

0.25

fast_rcnn_mlp_head_dim

The Fast-RCNN classification head dimension

Unsigned int

1024

bbox_reg_weights

The bounding-box regularization weights

string

“(10, 10, 5, 5)”

include_mask

Specifies whether to include a mask head

boolean

True

(currently only True is supported)

mrcnn_resolution

The mask-head resolution

Unsigned int

28

train_rpn_pre_nms_topn

The number of top-scoring RPN proposals to keep before applying NMS (per FPN level) during training

Unsigned int

2000

train_rpn_post_nms_topn

The number of top-scoring RPN proposals to keep after applying NMS (total number produced) during training

Unsigned int

1000

train_rpn_nms_threshold

The NMS IOU threshold in RPN during training

float

0.7

test_detections_per_image

The number of bounding box candidates after NMS

Unsigned int

100

test_nms

The NMS IOU threshold during test

float

0.5

test_rpn_pre_nms_topn

The number of top-scoring RPN proposals to keep before applying NMS (per FPN level) during test

Unsigned int

1000

test_rpn_post_nms_topn

The number of top scoring RPN proposals to keep after applying NMS (total number produced) during test

Unsigned int

1000

test_rpn_nms_threshold

The NMS IOU threshold in RPN during test

float

0.7

min_level

The minimum level of the output feature pyramid

Unsigned int

2

max_level

The maximum level of the output feature pyramid

Unsigned int

6

num_scales

The number of anchor octave scales on each pyramid level (e.g. if set to 3, the anchor scales are [2^0, 2^(1/3), 2^(2/3)])

Unsigned int

1

aspect_ratios

A list of tuples representing the aspect ratios of anchors on each pyramid level

string

“[(1.0, 1.0), (1.4, 0.7), (0.7, 1.4)]”

anchor_scale

Scale of the base-anchor size to the feature-pyramid stride

Unsigned int

8

rpn_box_loss_weight

The weight for adjusting RPN box loss in the total loss

float

1.0

fast_rcnn_box_loss_weight

The weight for adjusting FastRCNN box regression loss in the total loss

float

1.0

mrcnn_weight_loss_mask

The weight for adjusting mask loss in the total loss

float

1.0

Note

The min_level, max_level, num_scales, aspect_ratios, and anchor_scale are used to determine anchor generation for MaskRCNN. anchor_scale is the base anchor scale, while min_level and max_level set the range of the scales on different feature maps. For example, the actual anchor scale for the feature map at min_level will be anchor_scale * 2^min_level and the actual anchor scale for the feature map at max_level will be anchor_scale * 2^max_level. And it will generate anchors of different aspect_ratios based on the actual anchor scale.

Data Config

The data configuration (data_config) specifies the input data source and format. This is used for training, evaluation, and inference. A detailed description is summarized in the table below.

Field

Description

Data Type and Constraints

Recommended/Typical Value

image_size

The image dimension as a tuple within quote marks. “(height, width)” indicates the dimension of the resized and padded input.

string

“(832, 1344)”

augment_input_data

Specifies whether to augment the data

boolean

True

eval_samples

The number of samples for evaluation

Unsigned int

training_file_pattern

The TFRecord path for training

string

validation_file_pattern

The TFRecord path for validation

string

val_json_file

The annotation file path for validation

string

num_classes

The number of classes. If there are N categories in the annotation, num_classes should be N+1 (background class)

Unsigned int

skip_crowd_during_training

Specifies whether to skip crowd during training

boolean

True

prefetch_buffer_size

The prefetch buffer size used by tf.data.Dataset (default: AUTOTUNE)

Unsigned int

shuffle_buffer_size

The shuffle buffer size used by tf.data.Dataset (default: 4096)

Unsigned int

4096

n_workers

The number of workers to parse and preprocess data (default: 16)

Unsigned int

16

max_num_instances

The maximum number of object instances to parse (default: 200)

Unsigned int

200

Note

If an out-of-memory error occurs during training, try to set a smaller image_size or batch_size first. If the error persists, try reducing the n_workers, shuffle_buffer_size, and prefetch_buffer_size values. Lastly, if the original images have a very large resolution, resize the images offline and create new tfrecords to avoid loading large images to GPU memory.

Training the Model

Train the MaskRCNN model using this command:

tao mask_rcnn train [-h] -e <experiment_spec>
                         -d <output_dir>
                         -k <key>
                         [--gpus <num_gpus>]
                         [--gpu_index <gpu_index>]
                         [--log_file <log_file_path>]

Required Arguments

  • -d, --model_dir: The path to the folder where the experiment output is written.

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

  • -e, --experiment_spec_file: The experiment specification file to set up the evaluation. experiment. This should be the same as the training specification file.

Optional Arguments

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

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

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

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

Input Requirement

  • Input size: C * W * H (where C = 3, W >= 128, H >= 128 and W, H are multiples of 2^ max_level)

  • Image format: JPG

  • Label format: COCO detection

Sample Usage

Here’s an example of using the train command on a MaskRCNN model:

tao mask_rcnn train --gpus 2 -e /path/to/spec.txt -d /path/to/result -k $KEY

Evaluating the Model

To run evaluation for a MaskRCNN model, use this command:

tao mask_rcnn evaluate [-h] -e <experiment_spec_file>
                            -m <model_file>
                            -k <key>
                            [--gpu_index <gpu_index>]
                            [--log_file <log_file_path>]

Required Arguments

  • -e, --experiment_spec_file: The experiment spec file to set up the evaluation experiment. This should be the same as the training spec file.

  • -m, --model: The path to the model file to use for evaluation

  • -k, --key: The key to load the model. This argument is not required if -m is followed by a TensorRT engine.

Optional Arguments

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

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

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

Pruning the Model

Pruning removes parameters from the model to reduce the model size. Retraining is necessary to regain the performance of the unpruned model.

The prune command includes these parameters:

tao mask_rcnn prune [-h] -m <pretrained_model>
                         -o <output_dir>
                         -k <key>
                         [-n <normalizer>]
                         [-eq <equalization_criterion>]
                         [-pg <pruning_granularity>]
                         [-pth <pruning threshold>]
                         [-nf <min_num_filters>]
                         [-el [<excluded_list>]
                         [--gpu_index <gpu_index>]
                         [--log_file <log_file>]

Required Arguments

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

  • -o, --output_dir: The output directory which contains the pruned model, named as model.tlt.

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

Optional Arguments

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

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

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

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

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

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

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

  • --gpu_index: The index of the GPU to run evaluation (useful when the machine has multiple GPUs installed). Note that evaluation can only run on a single GPU.

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

Here’s an example of using the prune command:

tao mask_rcnn prune -m /workspace/model.step-100.tlt
                    -o /workspace/output
                    -eq union
                    -pth 0.7 -k $KEY

After pruning, the model needs to be retrained first before it can be used for inference or evaluation.

Re-training the Pruned Model

Once the model has been pruned, there might be a decrease in accuracy. This happens because some previously useful weights may have been removed. To regain accuracy, NVIDIA recommends that you retrain this pruned model over the same dataset. To do this, run the tao mask_rcnn train command with an updated spec file that points to the newly pruned model by setting pruned_model_path.

Users are advised to turn off the regularizer during retraining. You may do this by setting the regularizer weights to 0 for both l1_weight_decay and l2_weight_decay. The other parameters may be retained in the spec file from the previous training. train_batch_size and eval_batch_size must be kept unchanged.

Running Inference on the Model

The inference tool for MaskRCNN networks can be used to visualize bboxes or generate frame-by-frame COCO-format labels on a directory of images. Here’s an example of using this tool:

tao mask_rcnn inference [-h] -i <input directory>
                             -o <output annotated image directory>
                             -e <experiment spec file>
                             -m <model file>
                             -k <key>
                             [-l <label file>]
                             [-t <bbox confidence threshold>]
                             [--include_mask]
                             [--gpu_index <gpu_index>]
                             [--log_file <log_file_path>]

Required Arguments

  • -m, --model_path: The path to the trained MaskRCNN model (either a .tlt model or a converted TensorRT engine).

  • -i, --image_dir: The directory of input images for inference. Supported image formats include PNG, JPG and JPEG.

  • -e, --config_path: The path to an experiment spec file for training.

  • -o, --out_image_path: The directory path to output annotated images.

  • -k, --key: The key to load a .tlt model (not needed if TensorRT engine is used).

Optional Arguments

  • -t, --threshold: The threshold for drawing a bbox (default: 0.6)

  • -l, --out_label_path: The directory of predicted labels in COCO format (https://cocodataset.org/#format-results). This argument is only supported with the TensorRT engine.

  • --include_mask: Specifies whether to draw masks on the annotated output.

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

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

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

Exporting the Model

Exporting the model decouples the training process from inference and allows conversion to TensorRT engines outside the TAO environment. TensorRT engines are specific to each hardware configuration and should be generated for each unique inference environment. The exported model may be used universally across training and deployment hardware.

The exported model format is referred to as .etlt. Like the .tlt model format, .etlt is an encrypted model format, and it uses the same key as the .tlt model that it is exported from. This key is required when deploying this model.

INT8 Mode Overview

TensorRT engines can be generated in INT8 mode to improve performance, but require a calibration cache at engine creation-time. The calibration cache is generated using a calibration tensor file, if export is run with the --data_type flag set to int8. Pre-generating the calibration information and caching it removes the need for calibrating the model on the inference 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: Use 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: Point 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 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 .tlt model from the training/retraining step to be converted into .etlt format.

Exporting the MaskRCNN Model

Here’s an example of the command line arguments of the tao mask_rcnn export command:

tao mask_rcnn export [-h] -m <path to the .tlt model file generated by tao train>
                          -k <key>
                          [-o <path to output file>]
                          [--cal_data_file <path to tensor file>]
                          [--cal_image_dir <path to the directory images to calibrate the model]
                          [--cal_cache_file <path to output calibration file>]
                          [--data_type <Data type for the TensorRT backend during export>]
                          [--batches <Number of batches to calibrate over>]
                          [--max_batch_size <maximum trt batch size>]
                          [--max_workspace_size <maximum workspace size]
                          [--batch_size <batch size to TensorRT engine>]
                          [--experiment_spec <path to experiment spec file>]
                          [--engine_file <path to the TensorRT engine file>]
                          [--gen_ds_config <Flag to generate ds config and label file>]
                          [--verbose <Verbosity of the logger>]
                          [--force_ptq <Flag to force PTQ>]
                          [--strict_type_constraints <Flag to apply strict type constraints>]
                          [--gpu_index <gpu_index>]
                          [--log_file <log_file_path>]

Required Arguments

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

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

  • -e, --experiment_spec: The path to the spec file.

Optional Arguments

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

  • --data_type: The desired engine data type. The options are fp32, fp16, and int8. The default value is fp32. A calibration cache will be generated in INT8 mode. If using INT8, the following INT8 arguments are required.

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

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

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

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

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

INT8 Export Mode Required Arguments

  • --cal_data_file: The tensorfile generated for calibrating the engine. This can also be an output file if used with --cal_image_dir.

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

Note

The --cal_image_dir parameter applies the necessary preprocessing to generate a tensorfile at the path mentioned in the --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 --batches parameter, and the batch_size is obtained from the value set to the --batch_size parameter. Ensure that the directory mentioned in --cal_image_dir has at least batch_size * batches number of images in it. The valid image extensions are .jpg, .jpeg, and .png. In this case, the input_dimensions of the calibration tensors are derived from the input layer of the .tlt model.

INT8 Export Optional Arguments

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

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

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

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

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

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

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

Note

MaskRCNN does not support QAT.

Sample usage

Here’s a sample command to export a MaskRCNN model in INT8 mode:

tao mask_rcnn export -m /ws/model.step-25000.tlt \
                     -k nvidia_tlt \
                     -e /ws/maskrcnn_train_resnet50.txt \
                     --batch_size 1 \
                     --data_type int8 \
                     --cal_image_dir /raw-data/val2017 \
                     --batches 10 \
                     --cal_cache_file /export/maskrcnn.cal \
                     --cal_data_file /export/maskrcnn.tensorfile

Deploying to DeepStream

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

DeepStream SDK is a streaming analytic toolkit to accelerate building AI-based video analytic applications. This section will describe how to deploy your trained model to DeepStream SDK.

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

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

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

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

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

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

TensorRT Open Source Software (OSS)

For MaskRCNN, we need the generateDetectionPlugin, multilevelCropAndResizePlugin, resizeNearestPlugin and multilevelProposeROI 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 NVIDIA Jetson platform, follow the TensorRT OSS on Jetson (ARM64) instructions.

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

    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 GPU_ARCHS value can be retrieved by the deviceQuery CUDA sample:

    cd /usr/local/cuda/samples/1_Utilities/deviceQuery
    sudo make
    ./deviceQuery
    

    If the /usr/local/cuda/samples doesn’t exist in your system, you could download deviceQuery.cpp from this GitHub repo. Compile and run deviceQuery.

    nvcc deviceQuery.cpp -o deviceQuery
    ./deviceQuery
    

    This command will output something like this, which indicates the GPU_ARCHS is 75 based on CUDA Capability major/minor version.

    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:

    git clone -b 21.08 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 GPU_ARCHS from step 2 is in TensorRT OSS CMakeLists.txt. If GPU_ARCHS is not in TensorRT OSS CMakeLists.txt, add -DGPU_ARCHS=<VER> as below, where <VER> represents GPU_ARCHS from step 2.

    /usr/local/bin/cmake .. -DGPU_ARCHS=xy  -DTRT_LIB_DIR=/usr/lib/x86_64-linux-gnu/ -DCMAKE_C_COMPILER=/usr/bin/gcc -DTRT_BIN_DIR=`pwd`/out
    make nvinfer_plugin -j$(nproc)
    

    After building ends successfully, libnvinfer_plugin.so* will be generated under \`pwd\`/out/.

  4. Replace the original libnvinfer_plugin.so*:

    sudo mv /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so.8.x.y ${HOME}/libnvinfer_plugin.so.8.x.y.bak   // backup original libnvinfer_plugin.so.x.y
    sudo cp $TRT_SOURCE/`pwd`/out/libnvinfer_plugin.so.8.m.n  /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so.8.x.y
    sudo ldconfig
    

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:

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

    git clone -b 21.03 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 -DGPU_ARCHS=72 below is for Xavier or NX, for other Jetson platform, change 72 referring to GPU_ARCHS from step 2.

    /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, libnvinfer_plugin.so* will be generated under ‘pwd’/out/.

  4. Replace "libnvinfer_plugin.so*" with the newly generated.

    sudo mv /usr/lib/aarch64-linux-gnu/libnvinfer_plugin.so.8.x.y ${HOME}/libnvinfer_plugin.so.8.x.y.bak   // backup original libnvinfer_plugin.so.x.y
    sudo cp `pwd`/out/libnvinfer_plugin.so.8.m.n  /usr/lib/aarch64-linux-gnu/libnvinfer_plugin.so.8.x.y
    sudo ldconfig
    

Generating an Engine Using tao-converter

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

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

Instructions for x86

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

  1. Unzip the zip file on the target machine.

  2. Install the OpenSSL package using the command:

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

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

  2. Instructions to build TensorRT OSS on Jetson can be found in the TensorRT OSS on x86 section above or in this GitHub repo.

Note

Make sure to follow the output node names as mentioned in Exporting the Model section of the respective model.

Instructions for Jetson

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

  1. Unzip the zip file on the target machine.

  2. Install the OpenSSL package using the command:

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

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

  2. Instructions to build TensorRT OSS on Jetson can be found in the TensorRT OSS on Jetson (ARM64) section above or in this GitHub repo.

  3. Run the tao-converter using the sample command below and generate the engine.

Note

Make sure to follow the output node names as mentioned in Exporting the Model section of the respective model.

Using the tao-converter

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

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

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

  • -o: A comma-separated list of output blob names that should match the output configuration used for tao mask_rcnn export. For MaskRCNN, these should be generate_detections, mask_fcn_logits/BiasAdd.

Note

The output node names have been changed since Developer Preview. The node names in Developer Preview are generate_detections, mask_head/mask_fcn_logits/BiasAdd.

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

  • -t: The desired engine data type. The options are fp32, fp16, or int8. Selecting INT8 mode will generate a calibration cache.

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

  • -i: The input-dimension ordering. All other TAO commands use NCHW. The options are nchw, nhwc, and nc. The default value is nchw, so you can omit this argument for MaskRCNN.

  • -p: Optimization profiles for .etlt models with dynamic shape. Use a comma-separated list of optimization-profile shapes in the format <input_name>,<min_shape>,<opt_shape>,<max_shape>, where each shape has the format <n>x<c>x<h>x<w>. This can be specified multiple times if there are multiple input tensors for the model. This is only useful for new models introduced in TAO Toolkit 3.0. This parameter is not required for models that already exist in version 2.0.

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

  • -u: (only needed if using DLA core) Specify the DLA core index when building the TensorRT engine on Jetson devices.

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

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

  • -m: The maximum batch size for the TensorRT engine. The default value is 16. If out-of-memory issues occur, decrease the batch size accordingly. This parameter is not required for .etlt models generated with dynamic shape, which is only possible for new models introduced in TAO Toolkit 3.21.08.

Sample Output Log

Here is a sample log for exporting a MaskRCNN model:

tao-converter -d 3,576,960 \
              -k nvidia_tlt \
              -o generate_detections,mask_fcn_logits/BiasAdd \
              /workspace/tao-experiments/mask_rcnn/model.step-25000.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 with DeepStream

There are two options for integrating TAO models with DeepStream:

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

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

For MaskRCNN, you will need to build the TensorRT open source plugins and custom bounding-box parser. The instructions are provided in the TensorRT OSS section above, and the required code can be found in this GitHub repo.

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

  • The DeepStream SDK (download from the DeepStream SDK Download Page). The installation instructions for DeepStream are provided in the DeepStream Development Guide.

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

  • TensorRT 7+ OSS Plugins

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

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

DeepStream SDK ships with an end-to-end reference application that 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 deepstream-app. The graphic below shows the architecture of the reference application:

../../_images/arch_ref_appl1.png

Typically, two or more configuration files are used with this app. In the install directory, the config files are located in samples/configs/deepstream-app or sample/configs/tlt_pretrained_models. The main config file configures all the high-level parameters in the pipeline above. This 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 samples/configs/deepstream-app for reference:

  • source4_1080p_dec_infer-resnet_tracker_sgie_tiled_display_int8.txt: The main configuration file

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

  • config_infer_secondary_*.txt: The supporting configuration file for the secondary classifier in the pipeline above

The 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 DeepStream SDK with little to no change. You will only need to modify or create config_infer_primary.txt and config_infer_secondary_*.txt.

Integrating a MaskRCNN Model

To run a MaskRCNN 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 MaskRCNN output parser for DeepStream.

See here for a GitHub page containing a DeepStream sample with documentation on how to run inference using the trained MaskRCNN models from TAO Toolkit.

Prerequisites for MaskRCNN Model
  • MaskRCNN requires the generateDetectionPlugin, multilevelCropAndResizePlugin, resizeNearestPlugin and multilevelProposeROI plugins, which 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.

  • MaskRCNN requires custom output parsers that are not built-in inside the DeepStream SDK. The source code to build custom bounding box parsers for MaskRCNN is available here. The following instructions can be used to build bounding box parser:

    1. Install git-lfs (git >= 1.8.2):

      curl -s https://packagecloud.io/install/repositories/github/git-lfs/
      script.deb.sh | sudo bash
      sudo apt-get install git-lfs
      git lfs install
      
    2. Download Source Code with SSH or HTTPS:

      git clone -b release/tlt3.0 https://github.com/NVIDIA-AI-IOT/deepstream_tlt_apps
      
    3. Build the parser:

      // or Path for DS installation
      export CUDA_VER=10.2         // CUDA version, e.g. 10.2
      make
      

      This generates libnvds_infercustomparser_tlt.so in the directory post_processor.

Label File

If the COCO annotation file has the following in “categories”:

[{'supercategory': 'person', 'id': 1, 'name': 'person'},
 {'supercategory': 'car', 'id': 2, 'name': 'car'}]

Then the corresponding maskrcnn_labels.txt file will be as follows:

BG
person
car

Run deepstream-app as follows:

deepstream-app -c <deepstream-app config file>

Also, you can use deepstream-mrcnn-test to run the MaskRCNN model. See the README under $DS_TOP/source/apps/sample_apps/deepstream-mrcnn-test/.

DeepStream Configuration File

The configuration file is used by deepstream-app (see the Deepstream Configuration Guide for more details). You need to enable the display-mask under the osd group to see the mask visual view:

[osd]
enable=1
gpu-id=0
border-width=3
text-size=15
text-color=1;1;1;1;
text-bg-color=0.3;0.3;0.3;1
font=Serif
display-mask=1
display-bbox=0
display-text=0
Nvinfer config file

The Nvinfer configuration file is used in the nvinfer plugin; see the Deepstream plugin manual for more details. The following are key parameters for running the MaskRCNN model:

tlt-model-key=<tlt_encode or TLT Key used during model export>
tlt-encoded-model=<Path to TLT model>
parse-bbox-instance-mask-func-name=<post process parser name>
custom-lib-path=<path to post process parser lib>
network-type=3 ## 3 is for instance segmentation network
output-instance-mask=1
labelfile-path=<Path to label file>
int8-calib-file=<Path to optional INT8 calibration cache>
infer-dims=<Inference resolution if different than provided>
num-detected-classes=<# of classes if different than default>

Here’s an example:

[property]
gpu-id=0
net-scale-factor=0.017507
offsets=123.675;116.280;103.53
model-color-format=0
tlt-model-key=<tlt_encode or TLT Key used during model export>
tlt-encoded-model=<Path to TLT model>
parse-bbox-instance-mask-func-name=NvDsInferParseCustomMrcnnTLT
custom-lib-path=<path to post process parser lib>
network-type=3 ## 3 is for instance segmentation network
labelfile-path=<Path to MaskRCNN label file>
int8-calib-file=<Path to optional INT8 calibration cache>
infer-dims=<Inference resolution if different than provided>
num-detected-classes=3
uff-input-blob-name=Input
output-blob-names=generate_detections;mask_fcn_logits/BiasAdd
batch-size=1
## 0=FP32, 1=INT8, 2=FP16 mode
network-mode=2
interval=0
gie-unique-id=1
#no cluster
## 0=Group Rectangles, 1=DBSCAN, 2=NMS, 3= DBSCAN+NMS Hybrid, 4 = None(No clustering)
## MRCNN supports only cluster-mode=4; Clustering is done by the model itself
cluster-mode=4
output-instance-mask=1

[class-attrs-all]
pre-cluster-threshold=0.8