Multitask Image Classification ============================== Preparing the Input Data Structure ---------------------------------- Multitask classification expects a directory of images and two CSVs for training labels and validation labels. The image directory should contain all images for both training and validation (but it can contain additional images). Only images specified in training CSV file will be used during training and same for validation. The data structure should look like following: .. code:: |--dataset_root: |--images |--1.jpg |--2.jpg |--3.jpg |--4.jpg |--5.jpg |--6.jpg |--train.csv |--val.csv Training and validation CSV files contain the labels for training and validation images. Both CSVs should have same format: the first column of the CSV must be `fname`, standing for the filename of the image. If you have `N` tasks, you need additional `N` columns, each with the task name as column name. For each image (row entry in CSV), there must be one and only one label for each task cell. An example for train.csv with 3 classification tasks (color, type and size) is like following: +-------+-------+------+-------+ | fname | color | type | size | +-------+-------+------+-------+ | 1.jpg | Blue | 1 | Big | +-------+-------+------+-------+ | 2.jpg | Red | 1 | Small | +-------+-------+------+-------+ | 3.jpg | Red | 0 | Small | +-------+-------+------+-------+ Note: currently, multitask image classification only supports RGB training. The trained model will always have 3 input channels. For inferencing on grayscale images, user should load the image as RGB with same values in all channels. This is also how the training script handles grayscale training images. Creating an Experiment Spec File - Specification File for Multitask Classification ---------------------------------------------------------------------------------- .. _specification_file_for_multitask_classification: Here is an example of a specification file for multitask classification: .. code:: random_seed: 42 model_config { arch: "resnet" n_layers: 101 use_batch_norm: True use_bias: False all_projections: False use_pooling: True use_imagenet_head: True resize_interpolation_method: BICUBIC input_image_size: "3,224,224" } 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/resnet_101.hdf5" } dataset_config { image_directory_path: "EXPERIMENT_DIR/data/images" train_csv_path: "EXPERIMENT_DIR/data/train.csv" val_csv_path: "EXPERIMENT_DIR/data/val.csv" } Model Config ^^^^^^^^^^^^ .. _spec_file_model_config: The table below describes the configurable parameters in the :code:`model_config`. +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Default** | **Description** | **Supported Values** | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`all_projections` | bool | :code:`False` | For templates with shortcut connections, this parameter defines whether or not all shortcuts should be instantiated with 1x1 | `True` or `False` (only to be used in ResNet templates) | | | | | projection layers irrespective of whether there is a change in stride across the input and output. | | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`arch` | string | :code:`resnet` | This defines the architecture of the back bone feature extractor to be used to train. | | | | | | | * resnet | | | | | | * vgg | | | | | | * mobilenet_v1 | | | | | | * mobilenet_v2 | | | | | | * googlenet | | | | | | * darknet | | | | | | * cspdarknet | | | | | | * squeezenet | | | | | | * efficientnet_b0 | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`n_layers` | int | :code:`18` | Depth of the feature extractor for scalable templates. | | | | | | | * resnets: 10, 18, 34, 50, 101 | | | | | | * vgg: 16, 19 | | | | | | * darknet / cspdarknet: 19, 53 | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`use_pooling` | Boolean | :code:`False` | Choose between using strided convolutions or MaxPooling while downsampling. When `True`, MaxPooling is used to down sample, however | `True` or `False` | | | | | for the object detection network, NVIDIA recommends setting this to `False` and using strided convolutions. | | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`use_batch_norm` | Boolean | :code:`False` | Boolean variable to use batch normalization layers or not. | `True` or `False` | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`freeze_blocks` | float | -- | This parameter defines which blocks may be frozen from the instantiated feature extractor template, and is different for different | * **ResNet series**: For the ResNet series, the block ID's valid for freezing is any subset of {0, 1, 2, 3}(inclusive) | | | (repeated) | | feature extractor templates. | * **VGG series**: For the VGG series, the block ID's valid for freezing is any subset of {1, 2, 3, 4, 5}(inclusive) | | | | | | * **MobileNet V1**: For the MobileNet V1, the block ID's valid for freezing is any subset of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}(inclusive) | | | | | | * **MobileNet V2**: For the MobileNet V2, the block ID's valid for freezing is any subset of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}(inclusive) | | | | | | * **GoogLeNet**: For the GoogLeNet, the block ID's valid for freezing is any subset of {0, 1, 2, 3, 4, 5, 6, 7}(inclusive) | | | | | | * **DarkNet**: For DarkNet, the valid blocks IDs is any subset of {0, 1, 2, 3, 4, 5}(inclusive) | | | | | | * **EfficientNet B0**: For EfficientNet, the valid block IDs is any subset of {0, 1, 2, 3, 4, 5, 6, 7}(inclusive) | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`freeze_bn` | Boolean | :code:`False` | You can choose to freeze the Batch | `True` or `False` | | | | | Normalization layers in the model during training. | | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`input_image_size` | String | :code:`"3,224,224"` | The dimension of the input layer of the model. Images in the dataset will be resized to this shape by the dataloader | `3,X,Y`, where `X,Y >=16` and `X,Y` are integers. | | | | | when fed to the model for training. | | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`resize_interpolation_method` | enum | :code:`BILEANER` | The interpolation method for resizing the input images. | BILINEAR, BICUBIC | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`use_imagenet_head` | Boolean | :code:`False` | Whether or not to use the header layers as in the original implementation on ImageNet. Set this to `True` to reproduce the | `True` or `False` | | | | | accuracy on ImageNet as in the literature. If set to False, a Dense layer will be used for header, which can be different from the literature. | | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`dropout` | float | :code:`0.0` | Dropout rate for Dropout layers in the model. This is only valid for VGG and SqueezeNet. | Float in the interval [0, 1) | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`batch_norm_config` | proto message | -- | Parameters for BatchNormalization layers. | -- | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`activation` | proto message | -- | Parameters for the activation functions in the model. | -- | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ BatchNormalization Parameters ***************************** The parameter :code:`batch_norm_config` defines parameters for BatchNormalization layers in the model (momentum and epsilon). +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Default** | **Description** | **Supported Values** | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`momentum` | float | :code:`0.9` | Momentum of BatchNormalization layers. | float in the interval (0, 1), usually close to 1.0. | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`epsilon` | float | :code:`1e-5` | Epsilon to avoid zero division. | float that is close to 0.0. | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ Activation functions ******************** The parameter :code:`activation` defines the parameters for activation functions in the model. +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Default** | **Description** | **Supported Values** | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`activation_type` | String | -- | Type of the activation function. | Only :code:`relu` and :code:`swish` are supported. | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ Training Config ^^^^^^^^^^^^^^^ .. _training_config_multitask_classification: The training configuration (:code:`training_config`) defines the parameters needed for 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; the effective batch size is | Unsigned int, positive | -- | | | batch_size_per_gpu * num_gpus | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | checkpoint_interval | The number of training epochs per one model checkpoint/validation | Unsigned int, positive | 10 | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | num_epochs | The number of epochs to train the network | Unsigned int, positive. | -- | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | enable_qat | A flag to enable/disable quantization-aware training | Boolean | -- | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | learning_rate | One soft_start_annealing_schedule and soft_start_cosine_annealing_schedule with | Message type | -- | | | the following nested parameters are supported: | | | | | | | | | | 1. min_learning_rate: The minimum learning late during the entire experiment | | | | | 2. max_learning_rate: The maximum learning rate during the entire experiment | | | | | 3. soft_start: The time to lapse before warm up (expressed as a percentage of | | | | | progress between 0 and 1) | | | | | 4. annealing: (**only for soft_start_annealing_schedule**) The time to start | | | | | annealing the learning rate | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | regularizer | This parameter configures the regularizer to use while training and contains | Message type | L1 (Note: NVIDIA suggests using the L1 regularizer when training a network | | | the following nested parameters: | | before pruning, as L1 regularization makes the network weights more | | | | | prunable.) | | | 1. type: The type of regularizer to use. NVIDIA supports NO_REG, L1, or L2. | | | | | 2. weight: The floating point value for regularizer weight | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | optimizer | The optimizer can be one of adam, sgd, and rmsprop. Each type has the | Message type | -- | | | following parameters: | | | | | | | | | | 1. adam: epsilon, beta1, beta2, amsgrad | | | | | 2. sgd: momentum, nesterov | | | | | 3. rmsprop: rho, momentum, epsilon, centered | | | | | | | | | | The meanings of above parameters are same as those in Keras_. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | pretrain_model_path | The path to the pretrained model, if any | String | -- | | | | | | | | At most, one pretrain_model_path, resume_model_path, and pruned_model_path may be | | | | | present. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | resume_model_path | The path to the TLT checkpoint model to resume training, if any | String | -- | | | | | | | | At most, one pretrain_model_path, resume_model_path, and pruned_model_path may be | | | | | present. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ | pruned_model_path | The path to the TLT pruned model for re-training, if any | String | -- | | | | | | | | At most, one pretrain_model_path, resume_model_path, and pruned_model_path may be | | | | | present. | | | +---------------------+---------------------------------------------------------------------------------------+-------------------------------+-------------------------------------------------------------------------------+ .. 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 Dataset Config ^^^^^^^^^^^^^^ .. _spec_file_dataset_config: +------------------------------+--------------+---------------------------------+ | **Parameter** | **Datatype** | **Description** | +------------------------------+--------------+---------------------------------+ | :code:`image_directory_path` | string | Path to the image directory | +------------------------------+--------------+---------------------------------+ | :code:`train_csv_path` | string | Path to the training CSV file | +------------------------------+--------------+---------------------------------+ | :code:`val_csv_path` | string | Path to the validation CSV file | +------------------------------+--------------+---------------------------------+ Training the model ------------------------------- Use the :code:`tlt multitask_classification train` command to tune a pre-trained model: .. code:: tlt multitask_classification train -e -k -r [--gpus ] [--gpu_index ] [--use_amp] [--log_file ] [-h] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-r, --results_dir`: Path to a folder where the experiment outputs should be written. * :code:`-k, --key`: User specific encoding key to save or load a :code:`.tlt` model. * :code:`-e, --experiment_spec_file`: Path to the experiment spec file. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`--gpus`: Number of GPUs to use and processes to launch for training. The default value is `1`. * :code:`--gpu_index`: The GPU indices used to run the training. We can specify the GPU indices used to run training when the machine has multiple GPUs installed. * :code:`--use_amp`: A flag to enable AMP training. * :code:`--log_file`: Path to the log file. Defaults to `stdout`. * :code:`-h, --help`: Print the help message. .. Note:: See the :ref:`Specification File for Multitask Classification ` section for more details. Here's an example of using the :code:`tlt multitask_classification train` command: .. code:: tlt multitask_classification train -e /workspace/tlt_drive/spec/spec.cfg -r /workspace/output -k $YOUR_KEY Evaluating the Model -------------------- .. _evaluating_the_model: After the model has been trained, using the experiment config file, and by following the steps to train a model, the next step is to evaluate this model on a test set to measure the accuracy of the model. The TLT toolkit includes the :code:`tlt multitask_classification evaluate` command to do this. The multitask_classification app computes per-task evaluation loss and accuracy as metrics. When training is complete, the model is stored in the output directory of your choice in $OUTPUT_DIR. Evaluate a model using the :code:`tlt multitask_classification evaluate` command: .. code:: tlt multitask_classification evaluate -e -k -m [--gpu_index ] [--log_file ] [-h] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-e, --experiment_spec_file`: Path to the experiment spec file. * :code:`-k, --key`: Provide the encryption key to decrypt the model. * :code:`-m, --model`: Provide path to the trained model. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-h, --help`: Show this help message and exit. * :code:`--gpu_index`: The GPU indices used to run the evaluation. We can specify the GPU indices used to run training when the machine has multiple GPUs installed. * :code:`--log_file`: Path to the log file. Defaults to `stdout`. Generating Confusion Matrix --------------------------- Inferencing models on a labeled dataset can give confusion matrices from which you can see where the model makes mistakes. TLT offers a command to easily generate confusion matrices for all tasks: .. code:: tlt multitask_classification confmat -i -l -k -m [--gpu_index ] [--log_file ] [-h] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-i, --img_root`: Path to the image directory. * :code:`-l, --target_csv`: Path to the ground truth label CSV file. * :code:`-k, --key`: Provide the encryption key to decrypt the model. * :code:`-m, --model`: Provide path to the trained model. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-h, --help`: Show this help message and exit. * :code:`--gpu_index`: The GPU indices used to run the confmat. We can specify the GPU indices used to run training when the machine has multiple GPUs installed. * :code:`--log_file`: Path to the log file. Defaults to `stdout`. Running Inference on a Model ---------------------------- The :code:`tlt multitask_classification inference` command runs the inference on a specified image. Execute :code:`tlt multitask_classification inference` on a multitask classification model trained on TLT. .. code:: tlt multitask_classification inference -m -i -k -cm [--gpu_index ] [--log_file ] [-h] Here are the arguments of the :code:`tlt multitask_classification inference` tool: Required arguments ^^^^^^^^^^^^^^^^^^ * :code:`-m, --model`: Path to the pretrained model (TLT model). * :code:`-i, --image`: A single image file for inference. * :code:`-k, --key`: Key to load model. * :code:`-cm, --class_map`: The `json` file that specifies the class index and label mapping for each task. Optional arguments ^^^^^^^^^^^^^^^^^^ * :code:`-h, --help`: Show this help message and exit. * :code:`--gpu_index`: The GPU indices used to run the inference. We can specify the GPU indices used to run training when the machine has multiple GPUs installed. * :code:`--log_file`: Path to the log file. Defaults to `stdout`. .. Note:: A classmap (:code:`-cm`) is required, which should be a byproduct (:code:`class_mapping.json`) of your training process. Pruning the Model ----------------- .. _pruning_the_model: Pruning removes parameters from the model to reduce the model size without compromising the integrity of the model itself using the :code:`tlt multitask_classification prune` command. The :code:`tlt multitask_classification prune` command includes these parameters: .. code:: tlt multitask_classification prune -m -o -k [-n [-eq ] [-pg ] [-pth ] [-nf ] [-el ] [--gpu_index ] [--log_file ] [-h] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-m, --model`: Path to pretrained 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 elementwise op layer, or depth-wise convolutional layer. This parameter is useful for ResNet and MobileNet. Options are :code:`arithmetic_mean`, :code:`geometric_mean`, :code:`union`, and :code:`intersection`. (default: :code:`union`) * :code:`-pg, -pruning_granularity`: Number of filters to remove at a time (default: `8`) * :code:`-pth`: Threshold to compare normalized norm against (default: `0.1`) .. Note: NVIDIA recommends changing the threshold to keep the number of parameters in the model to within 10-20% of the original unpruned model. * :code:`-nf, --min_num_filters`: Minimum number of filters to keep per layer (default: `16`) * :code:`-el, --excluded_layers`: List of excluded_layers. Examples: `-i item1 item2` (default: `[]`) * :code:`--gpu_index`: The GPU indices used to run the pruning. We can specify the GPU indices used to run training when the machine has multiple GPUs installed. * :code:`--log_file`: Path to the log file. Defaults to stdout. After pruning, the model needs to be retrained. See :ref:`Re-training the Pruned Model ` for more details. Re-training the Pruned Model ---------------------------- .. _re-training_the_pruned_model: After the model has been pruned, there might be a slight decrease in accuracy. This happens because some previously useful weights may have been removed. In order to regain the accuracy, NVIDIA recommends that you retrain this pruned model over the same dataset. To do this, use the :code:`tlt multitask_classification train` command as documented in :ref:`Training the model `, with an updated spec file that points to the newly pruned model as the pretrained model file. Users are advised to turn off the regularizer in the `training_config` for classification to recover the accuracy when retraining a pruned model. You may do this by setting the regularizer type to :code:`NO_REG`. All the other parameters may be retained in the spec file from the previous training. Exporting the model ------------------- .. _exporting_the_model: Exporting the model decouples the training process from inference and allows conversion to TensorRT engines outside the TLT environment. TensorRT engines are specific to each hardware configuration and should be generated for each unique inference environment. The exported model may be used universally across training and deployment hardware. The exported model format is referred to as :code:`.etlt`. Like :code:`.tlt`, the :code:`.etlt` model format is also an encrypted model format with the same key of the :code:`.tlt` model that it is exported from. This key is required when deploying this model. Exporting the Model ^^^^^^^^^^^^^^^^^^^ Here's an example of the :code:`tlt multitask_classification export` command: .. code:: tlt multitask_classification export -m -k -cm [-o ] [--cal_data_file ] [--cal_cache_file ] [--data_type ] [--batches ] [--max_batch_size ] [--max_workspace_size ] [--engine_file ] [--verbose] [--force_ptq] [--gpu_index ] [--log_file ] Required Arguments ****************** * :code:`-m, --model`: Path to the :code:`.tlt` model file to be exported. * :code:`-k, --key`: Key used to save the :code:`.tlt` model file. * :code:`-cm, --class_map`: The `json` file that specifies the class index and label mapping for each task. .. Note:: A classmap (:code:`-cm`) is required, which should be a by product (:code:`class_mapping.json`) of your training process. Optional Arguments ****************** * :code:`-o, --output_file`: Path to save the exported model to. The default is :code:`./.etlt`. * :code:`--data_type`: Desired engine data type, generates calibration cache if in INT8 mode. The options are: {:code:`fp32`, :code:`fp16`, :code:`int8`} The default value is :code:`fp32`. If using INT8, the following INT8 arguments are required. * :code:`-s, --strict_type_constraints`: A Boolean flag to indicate whether or not to apply the TensorRT strict type constraints when building the TensorRT engine. * :code:`--gpu_index`: The index of (descrete) GPUs used for exporting the model. We can specify the GPU index to run export if the machine has multiple GPUs installed. Note that export can only run on a single GPU. * :code:`--log_file`: Path to the log file. Defaults to `stdout`. * :code:`-v, --verbose`: Verbose log. INT8 Export Mode Required Arguments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * :code:`--cal_data_file`: The tensorfile generated for calibrating the engine. This can also be an output file if used with :code:`--cal_image_dir`. * :code:`--cal_image_dir`: A directory of images to use for calibration. .. Note:: The :code:`--cal_image_dir` parameter for images 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 generated batches in the tensorfile is obtained from the :code:`--batches` parameter value, and the :code:`batch_size` is obtained from the :code:`--batch_size` parameter value. Ensure 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 :code:`.jpg`, :code:`.jpeg`, and :code:`.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`: The number of batches to use for calibration and inference testing. The default value is 10. * :code:`--batch_size`: The batch size to use for calibration. The default value is 8. * :code:`--max_batch_size`: The maximum batch size of the TensorRT engine. The default value is 16. * :code:`--max_workspace_size`: The maximum workspace size of TensorRT engine. The default value is :code:`1073741824 = 1<<30` * :code:`--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 TensorRT engine file is hardware specific, you cannot use this engine file for deployment unless the deployment GPU is identical to the 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 on Jetson. To deploy this model on a Jetson with DLA :code:`int8`, use the :code:`--force_ptq` flag for TensorRT post-training quantization to generate the calibration cache file. Deploying to DeepStream ----------------------- .. _deploying_to_deepstream_multitask_classification: .. include:: excerpts/deploying_to_deepstream.rst Generating an Engine Using `tlt-converter` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. _generating_an_engine_using_tlt-converter: .. include:: excerpts/generating_an_engine_using_tlt-converter.rst Instructions for x86 ******************** .. include:: excerpts/instructions_for_x86.rst Instructions for Jetson *********************** .. include:: excerpts/instructions_for_jetson.rst Using the `tlt-converter` ************************* .. code:: tlt tlt-converter -k -d -o [-c ] [-e ] [-b ] [-m ] [-t ] [-w ] [-i ] [-p ] [-s] [-u ] [-h] input_file Required Arguments ~~~~~~~~~~~~~~~~~~ * :code:`input_file`: Path to the :code:`.etlt` model exported using :code:`export`. * :code:`-k`: The key used to encode the :code:`.tlt` model when doing the traning. * :code:`-d`: Comma-separated list of input dimensions that should match the dimensions used for :code:`tlt multitask_classification export`. Unlike :code:`tlt multitask_classification export` this cannot be inferred from calibration data. This parameter is not required for new models introduced in TLT v3.0 (for example, LPRNet, UNet, GazeNet, etc). * :code:`-o`: Comma-separated list of output blob names that should match the printout when using :code:`tlt multitask_classification export`. The number of the outputs equals to the number of tasks. Optional Arguments ~~~~~~~~~~~~~~~~~~ * :code:`-e`: Path to save the engine to. The default value is :code:`./saved.engine`. * :code:`-t`: Desired engine data type, generates calibration cache if in INT8 mode. The default value is :code:`fp32`. The options are {:code:`fp32`, :code:`fp16`, :code:`int8`}. * :code:`-w`: Maximum workspace size for the TensorRT engine. The default value is :code:`1073741824(1<<30)`. * :code:`-i`: Input dimension ordering, all other TLT commands use NCHW. The default value is :code:`nchw`. The options are {:code:`nchw`, :code:`nhwc`, :code:`nc`}. For classification, we can omit it (defaults to :code:`nchw`). * :code:`-p`: Optimization profiles for :code:`.etlt` models with dynamic shape. Comma separated list of optimization profile shapes in the format :code:`,,,`, where each shape has the format: :code:`xxx`. Can be specified multiple times if there are multiple input tensors for the model. This is only useful for new models introduced in TLT v3.0. This parameter is not required for models that are already existed in TLT v2.0. * :code:`-s`: TensorRT strict type constraints. A Boolean to apply TensorRT strict type constraints when building the TensorRT engine. * :code:`-u`: Use DLA core. Specifying DLA core index when building the TensorRT engine on Jetson devices. INT8 Mode Arguments ~~~~~~~~~~~~~~~~~~~ * :code:`-c`: Path to calibration cache file, only used in INT8 mode. The default value is :code:`./cal.bin`. * :code:`-b`: Batch size used during the export step for INT8 calibration cache generation. (default: :code:`8`). * :code:`-m`: Maximum batch size for TensorRT engine.(default: :code:`16`). If met with out-of-memory issue, decrease the batch size accordingly. Integrating the Model to DeepStream ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There are 2 options to integrate models from TLT with DeepStream: * **Option 1**: Integrate the model (.etlt) with the encrypted key directly in the DeepStream app. The model file is generated by :code:`tlt multitask_classification export`. * **Option 2**: Generate a device specific optimized TensorRT engine, using `tlt-converter`. The TensorRT engine file can also be ingested by DeepStream. In order to integrate the models with DeepStream, you need the following: 1. Download_ and install DeepStream SDK. The installation instructions for DeepStream are provided in the `DeepStream Development Guide`_. 2. An exported :code:`.etlt` model file and optional calibration cache for INT8 precision. 3. A :code:`labels.txt` file containing the labels for classes in the order in which the networks produces outputs. 4. A sample :code:`config_infer_*.txt` file to configure the nvinfer element in DeepStream. The nvinfer element handles everything related to TensorRT optimization and engine creation in DeepStream. .. _Download: https://developer.nvidia.com/deepstream-download .. _DeepStream Development Guide: https://docs.nvidia.com/metropolis/deepstream/dev-guide/index.html DeepStream SDK ships with an end-to-end reference application which is fully configurable. Users can configure input sources, inference model and output sinks. The app requires a primary object detection model, followed by an optional secondary classification model. The reference application is installed as :code:`deepstream-app`. The graphic below shows the architecture of the reference application. .. image:: ../content/arch_ref_appl.png There are typically 2 or more configuration files that are used with this app. In the install directory, the config files are located in :code:`samples/configs/deepstream-app` or :code:`sample/configs/tlt_pretrained_models`. The main config file configures all the high level parameters in the pipeline above. This would set input source and resolution, number of inferences, tracker and output sinks. The other supporting config files are for each individual inference engine. The inference specific config files are used to specify models, inference resolution, batch size, number of classes and other customization. The main config file will call all the supporting config files. Here are some config files in :code:`samples/configs/deepstream-app` for your reference. * :code:`source4_1080p_dec_infer-resnet_tracker_sgie_tiled_display_int8.txt`: Main config file * :code:`config_infer_primary.txt`: Supporting config file for primary detector in the pipeline above * :code:`config_infer_secondary_*.txt`: Supporting config file for secondary classifier in the pipeline above The :code:`deepstream-app` will only work with the main config file. This file will most likely remain the same for all models and can be used directly from the DeepStream SDK will little to no change. Users will only have to modify or create :code:`config_infer_primary.txt` and :code:`config_infer_secondary_*.txt`. Integrating a Multitask Image Classification Model ************************************************** See Exporting The Model for more details on how to export a TLT model. After the model has been generated, you can use the `DeepStream sample app`_ provided in GitHub repository to integrate the exported model. The GitHub repository also provides a README file for adjustments needed to integrate a custom model you trained on your own dataset. .. _DeepStream sample app: https://github.com/NVIDIA-AI-IOT/deepstream_tlt_apps