Image Classification ==================== .. _image_classification: Preparing the Input Data Structure ---------------------------------- See the :ref:`Data Annotation Format ` page for more information about the data format for image classification. Creating an Experiment Spec File - Specification File for Classification ------------------------------------------------------------------------ .. _specification_file_for_classification: Here is an example of a specification file for model classification: .. code:: model_config { # Model Architecture can be chosen from: # ['resnet', 'vgg', 'googlenet', 'alexnet'] arch: "resnet" # for resnet --> n_layers can be [10, 18, 50] # for vgg --> n_layers can be [16, 19] n_layers: 101 use_batch_norm: True use_bias: False all_projections: False use_pooling: True use_imagenet_head: True resize_interpolation_method: BICUBIC # if you want to use the pretrained model, # image size should be "3,224,224" # otherwise, it can be "3, X, Y", where X,Y >= 16 input_image_size: "3,224,224" } train_config { train_dataset_path: "/path/to/your/train/data" val_dataset_path: "/path/to/your/val/data" pretrained_model_path: "/path/to/your/pretrained/model" # Only ['sgd', 'adam'] are supported for optimizer optimizer { sgd { lr: 0.01 decay: 0.0 momentum: 0.9 nesterov: False } } batch_size_per_gpu: 50 n_epochs: 150 # Number of CPU cores for loading data n_workers: 16 # regularizer reg_config { # regularizer type can be "L1", "L2" or "None". type: "L2" # if the type is not "None", # scope can be either "Conv2D" or "Dense" or both. scope: "Conv2D,Dense" # 0 < weight decay < 1 weight_decay: 0.000015 } # learning_rate lr_config { cosine { learning_rate: 0.04 soft_start: 0.0 } } enable_random_crop: True enable_center_crop: True enable_color_augmentation: True mixup_alpha: 0.2 label_smoothing: 0.1 preprocess_mode: "caffe" image_mean { key: 'b' value: 103.9 } image_mean { key: 'g' value: 116.8 } image_mean { key: 'r' value: 123.7 } } The classification experiment specification consists of three main components: * :code:`model_config` * :code:`eval_config` * :code:`train_config` Model Config ^^^^^^^^^^^^ .. _spec_file_model_config: The table below describes the configurable parameters in the :code:`model_config`. +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Typical value** | **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 | | | | | | * efficientnet_b0 | | | | | | * efficientnet_b1 | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`n_layers` | int | :code:`18` | Depth of the feature extractor for scalable templates. | | | | | | | * resnets: 10, 18, 34, 50, 101 | | | | | | * vgg: 16, 19 | | | | | | * darknet: 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/B1**: 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 | `C,X,Y`, where `C=1` or `C=3` and `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** | **Typical value** | **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. | +---------------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ Eval Config ^^^^^^^^^^^^ .. _spec_file_eval_config: The table below defines the configurable parameters for evaluating a classification model. +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Typical value** | **Description** | **Supported Values** | +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`eval_dataset_path` | string | | UNIX format path to the root directory of the evaluation dataset. | UNIX format path. | +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`model_path` | string | | UNIX format path to the root directory of the model file you would like to evaluate. | UNIX format path. | +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`top_k` | int | :code:`5` | The number elements to look at when calculating the top-K classification categorical accuracy metric. | 1, 3, 5 | +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`batch_size` | int | :code:`256` | Number of images per batch when evaluating the model. | >1 (bound by the number of images that can be fit in the GPU memory) | +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`n_workers` | int | :code:`8` | Number of workers fetching batches of images in the evaluation dataloader. | >1 | +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | :code:`enable_center_crop` | Boolean | :code:`True` | Enable center crop for input images or not. Usually this parameter is set to :code:`True` to achieve better accuracy. | `True` or `False` | +-------------------------------+------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ Training Config ^^^^^^^^^^^^^^^ .. _spec_file_training_config: This section defines the configurable parameters for the classification model trainer. +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Default** | **Description** | **Supported Values** | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`val_dataset_path` | string | | UNIX format path to the root directory of the validation dataset. | UNIX format path. | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`train_dataset_path` | string | | UNIX format path to the root directory of the training dataset. | UNIX format path. | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`pretrained_model_path` | string | | UNIX format path to the model file containing the pretrained weights to initialize the model from. | UNIX format path. | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`batch_size_per_gpu` | int | :code:`32` | This parameter defines the number of images per batch per gpu. | >1 | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`n_epochs` | int | :code:`120` | This parameter defines the total number of epochs to run the experiment. | | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`n_workers` | int | :code:`10` | Number of workers fetching batches of images in the training/validation dataloader. | >1 | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`lr_config` | proto message | -- | The parameters for learning rate scheduler. | -- | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`reg_config` | proto message | -- | The parameters for regularizers. | -- | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`optimizer` | proto message | -- | This parameter defines which optimizer to use for training. Can be choosen from :code:`sgd`, :code:`adam`, or :code:`rmsprop` | -- | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`random_seed` | int | -- | Random seed for training. | -- | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`enable_random_crop` | Boolean | :code:`True` | A flag to enable random crop during training. | `True` or `False` | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`enable_center_crop` | Boolean | :code:`True` | A flag to enable center crop during validation. | `True` or `False` | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`enable_color_augmentation` | Boolean | :code:`True` | A flag to enable color augmentation during training. | `True` or `False` | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`disable_horizontal_flip` | Boolean | :code:`False` | A flag to disable horizontal flip. | `True` or `False` | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`label_smoothing` | float | :code:`0.1` | A factor used for label smoothing. | in the interval (0, 1) | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`mixup_alpha` | float | :code:`0.2` | A factor used for mixup augmentation. | in the interval (0, 1) | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`preprocess_mode` | string | :code:`'caffe'` | Mode for input image preprocessing. Defaults to 'caffe'. | 'caffe', 'torch', 'tf' | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`model_parallelism` | repeated float | -- | List of fractions to indicate how we split the model on multiple GPUs for model parallelism. | -- | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`image_mean` | dict | 'b': 103.939 | A key/value pair to specify image mean values. It's only applicable when preprocess_mode is :code:`caffe`. | -- | | | | 'g': 116.779 | If omitted, ImageNet mean will be used for image preprocessing. | | | | | 'r': 123.68 | If set, depending on `output_channel`, either 'r/g/b' or 'l' | | | | | | key/value pair must be configured. | | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ Learning Rate Scheduler *********************** The parameter :code:`lr_config` defines the parameters for learning rate scheduler The learning rate scheduler can be either :code:`step`, :code:`soft_anneal` or :code:`cosine`. Step ~~~~ The parameter :code:`step` defines the step learning rate scheduler. +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Typical value** | **Description** | **Supported Values** | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`learning_rate` | float | -- | The base(maximum) learning rate value. | Positive, usually in the interval (0, 1). | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`step_size` | int | -- | The progress (percentage of the entire training duration) after which the learning rate will be decreased. | Less than 100. | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`gamma` | float | -- | The multiplicative factor used to decrease the learning rate. | In the interval (0, 1). | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ .. 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`. Soft Annealing ~~~~~~~~~~~~~~ The parameter :code:`soft_anneal` defines the soft annealing learning rate scheduler. +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Typical value** | **Description** | **Supported Values** | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`learning_rate` | float | -- | The base (maximum) learning rate value. | Positive, usually in the interval (0, 1). | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`soft_start` | float | -- | The progress at which learning rate achieves the base learning rate. | In the interval (0, 1). | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`annealing_divider` | float | -- | The divider by which the learning rate will be scaled down. | Greater than 1.0. | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`annealing_points` | repeated float | -- | Points of progress at which the learning rate will be decreased. | List of floats. Each will be in the interval (0, 1). | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ Cosine ~~~~~~ The parameter :code:`cosine` defines the cosine learning rate scheduler. +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | **Parameter** | **Datatype** | **Typical value** | **Description** | **Supported Values** | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`learning_rate` | float | -- | The base (maximum) learning rate. | Usually less than 1.0 | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`min_lr_ratio` | float | -- | The ratio of minimum learning rate to the base learning rate. | Less than 1.0 | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | :code:`soft_start` | float | -- | The progress at which learning rate achieves the base learning rate. | In the interval (0, 1). | +-----------------------------------+-------------------------------+---------------------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ Training the model ------------------------------- Use the :code:`tlt classification train` command to tune a pre-trained model: .. code:: tlt classification train [-h] -e -k -r [--gpus ] [--num_processes ] [--gpu_index ] [--use_amp] [--log_file ] 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:`--num_processes, -np`: Number of processes to be spawned for training. It defaults to be -1(equal to :code:`--gpus`, for the use case of data parallelism). In the case of model parallelism, this argument should be explicitly set to 1 or more, depending on the actual scenario. Setting :code:`--gpus` to be larger than 1 and :code:`--num_processes` to 1 correspoinding to the model parallelism use case; while setting both :code:`--gpus` and :code:`num_processes` to be larger than 1 corresponding to the case of enabling both model parallelism and data parallelism. For example, :code:`--gpus=4` and :code:`--num_processes=2` means 2 horovod processes will be spawned and each of them will occupy 2 GPUs for model parallelism. * :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 Classification ` section for more details. Input Requirement ^^^^^^^^^^^^^^^^^ * **Input size**: 3 * H * W (W, H >= 32) * **Input format**: JPG, JPEG, PNG .. Note:: Classification input images do not need to be manually resized. The input dataloader automatically resizes images to :code:`input size`. Sample Usage ^^^^^^^^^^^^ Here's an example of using the :code:`tlt classification train` command: .. code:: tlt classification train -e /workspace/tlt_drive/spec/spec.cfg -r /workspace/output -k $YOUR_KEY Model parallelism ^^^^^^^^^^^^^^^^^ Image classification supports model parallelism. Model parallelism is a technique that we split the entire model on multiple GPUs and each GPU will hold a part of the model. A model is splitted by layers. For example, if a model has 100 layers, then we can place the layer 0-49 on GPU 0 and layer 50-99 on GPU 1. Model parallelism will be useful when the model is huge and cannot fit into a single GPU even with batch size 1. Model parallelism is also useful if we want to increase the batch size that is seen by BatchNormalization layers and hence potentially improve the accuracy. This feature can be enabled by setting :code:`model_parallelism` in :code:`training_config`. For example, .. code:: model_parallelism: 0.3 model_parallelism: 0.7 will enable a 2-GPU model parallelism where the first GPU will hold 30% of the model layers and the second GPU will hold 70% of the model layers. The percentage of model layers can be adjusted with some trial-and-error so all GPUs consumes almost the same GPU memory size and in that case we can use the largest batch size for this model-parallelised training. Model parallelism can be enabled jointly with data parallelism. For example, in above case we enabled a 2-GPU model parallelism, at the same time we can also enable 4 horovod processes for it. In this case, we have 4 horovod processes for data parallelism and each process will have the model splitted on 2 GPUs. 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 classification evaluate` command to do this. The classification app computes evaluation loss, Top-k accuracy, precision, and recall as metrics. When training is complete, the model is stored in the output directory of your choice in $OUTPUT_DIR. Evaluate a model using the :code:`tlt classification evaluate` command: .. code:: tlt classification evaluate [-h] -e -k [--gpu_index ] [--log_file ] Required Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-e, --experiment_spec_file`: Path to the experiment spec file. * :code:`-k, –key`: Provide the encryption key to decrypt the model. Optional Arguments ^^^^^^^^^^^^^^^^^^ * :code:`-h, --help`: Show this help message and exit. * :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:`--log_file`: Path to the log file. Defaults to `stdout`. If you followed the example in training a classification model, run the evaluation: .. code:: tlt classification evaluate -e classification_spec.cfg -k $YOUR_KEY TLT evaluates for classification and produces the following metrics: * Loss * Top-K accuracy * Precision (P): TP / (TP + FP) * Recall (R): TP / (TP + FN) * Confusion Matrix Running Inference on a Model ---------------------------- The :code:`tlt classification inference` command runs the inference on a specified set of input images. For classification, :code:`tlt classification inference` provides class label output over the command-line for a single image or a `csv` file containing the image path and the corresponding labels for multiple images. TensorRT Python inference can also be enabled. Execute :code:`tlt classification inference` on a classification model trained on TLT. .. code:: tlt classification inference [-h] -m -i -d -k -cm -e [-b ] [--gpu_index ] [--log_file ] Here are the arguments of the :code:`tlt 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:`-d, --image_dir`: The directory of input images for inference. * :code:`-k, --key`: Key to load model. * :code:`-cm, --class_map`: The `json` file that specifies the class index and label mapping. * :code:`-e, --experiment_spec_file`: Path to the experiment spec file. Optional arguments ^^^^^^^^^^^^^^^^^^ * :code:`--batch_size`: Inference batch size, default: `1` * :code:`-h, --help`: Show this help message and exit. * :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:`--log_file`: Path to the log file. Defaults to `stdout`. .. Note:: The inference tool requires a `cluster_params.json` file to configure the post processing block. When executing with :code:`-d`, or directory mode, a :code:`result.csv` file is created and stored in the directory you specify using :code:`-d`. The :code:`result.csv` has the file path in the first column and predicted labels in the second. .. Note:: In both single image and directory modes, a classmap (:code:`-cm`) is required, which should be a by product (:code:`-classmap.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 classification prune` command. The :code:`tlt classification prune` command includes these parameters: .. code:: tlt classification prune [-h] -m -o -k [-n [-eq ] [-pg ] [-pth ] [-nf ] [-el ] [--gpu_index ] [--log_file 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 training. 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. Using the Prune Command ^^^^^^^^^^^^^^^^^^^^^^^ Here's an example of using the :code:`tlt classification prune` command: .. code:: tlt classification prune -m /workspace/output/weights/resnet_003.tlt -o /workspace/output/weights/resnet_003_pruned.tlt -eq union -pth 0.7 -k $KEY Re-training the Pruned Model ---------------------------- .. _re-training_the_pruned_model: 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 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 a encrypted model format with the same key of the :code:`.tlt` model that it is exported from. This key is required when deploying this model. INT8 Mode Overview ^^^^^^^^^^^^^^^^^^ TensorRT engines can be generated in INT8 mode to improve performance, but require a calibration cache at engine creation-time. The calibration cache is generated using a calibration tensor file, if export is run with the :code:`--data_type` flag set to :code:`int8`. Pre-generating the calibration information and caching it removes the need for calibrating the model on the inference device. 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 calibration data and the model itself. The export tool can generate INT8 calibration cache by ingesting calibration dataset generated by the command :code:`tlt classification calibration_tensorfile`. Here is an example of the :code:`tlt calibration_tensorfile` command: .. code:: tlt classification calibration_tensorfile -e -o [-m ] [--use_validation_set] [-v] Required Arguments ****************** * :code:`-o, --output`: Path to output tensorfile. * :code:`-e, --experiment_spec`: Path to the spec file. Optional Arguments ****************** * :code:`-m, --max_batches`: Number of batches of calibration data. The batch size is the training batch size as in spec file. * :code:`--use_validation_set`: Use validation dataset only if this flag is set. * :code:`-v, --verbose`: Set verbosity of the log. FP16/FP32 Model ^^^^^^^^^^^^^^^ The :code:`calibration.bin` is only required if you need to run inference at INT8 precision. For FP16/FP32 based inference, the export step is much simpler. All that is required is to provide a :code:`.tlt` model from the training/retraining step to be converted into an :code:`.etlt`. Exporting the Model ^^^^^^^^^^^^^^^^^^^ Here's an example of the :code:`tlt classification export` command: .. code:: tlt classification export [-h] -m -k [-o ] [--cal_data_file ] [--cal_cache_file ] [--data_type ] [--batches ] [--max_batch_size ] [--max_workspace_size ] [--strict_type_constraints ] [--gen_ds_config] ] [--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. 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:`--gen_ds_config`: A Boolean flag indicating whether to generate the template DeepStream related configuration ("nvinfer_config.txt") as well as a label file ("labels.txt") in the same directory as the :code:`output_file`. Note that the config file is NOT a complete configuration file and requires the user to update the sample config files in DeepStream with the parameters generated. * :code:`--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 input tensorfile for calibration. INT8 Export Optional Arguments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * :code:`--cal_cache_file`: Path to save the calibration cache file. The default value is :code:`./cal.bin`. * :code:`--batches`: Number of batches to use for calibration and inference testing. The default value is :code:`10`. * :code:`--batch_size`: Batch size to use for calibration. The default value is :code:`8`. * :code:`--max_batch_size`: Maximum batch size of TensorRT engine. The default value is :code:`16`. * :code:`--max_workspace_size`: Maximum workspace size of TensorRT engine. The default value is: :code:`1073741824(1<<30)`. * :code:`--engine_file`: Path to the serialized TensorRT engine file. Note that this file is hardware specific and cannot be generalized across GPUs. Useful to quickly test your model accuracy using TensorRT on the host. As TensorRT engine file is hardware specific, you cannot use this engine file for deployment unless the deployment GPU is identical to training GPU. * :code:`--force_ptq`: A boolean flag to force post training quantization on the exported etlt model. .. Note:: When exporting a model trained with Quantization Aware Training (QAT) enabled, the tensor scale factors to calibrate the activations are peeled out of the model and serialized to a TensorRT readable cache file defined by the :code:`cal_cache_file` argument. However, note that the current version of QAT doesn’t natively support DLA INT8 deployment in Jetson. In order to deploy this model on a Jetson with DLA INT8, use the :code:`--force_ptq` flag to use TensorRT post training quantization to generate the calibration cache file. Exporting a Model ^^^^^^^^^^^^^^^^^ Here's a sample command using the data loader for loading calibration data to calibrate a classification model. .. code:: tlt classification export -m /ws/output_retrain/weights/resnet_001.tlt -o /ws/export/final_model.etlt -k $KEY --cal_data_file /ws/export/calibration.tensor --data_type int8 --batches 10 --cal_cache_file /ws/export/final_model_int8_cache.bin Deploying to DeepStream ----------------------- .. _deploying_to_deepstream_image_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-converter [-h] -k -d -o [-c ] [-e ] [-b ] [-m ] [-t ] [-w ] [-i ] [-p ] [-s] [-u ] input_file Required Arguments ~~~~~~~~~~~~~~~~~~ * :code:`input_file`: Path to the :code:`.etlt` model exported using :code:`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 classification export`. Unlike :code:`tlt 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 output configuration used for :code:`tlt classification export`. This parameter is not required for new models introduced in TLT v3.0 (for example, LPRNet, UNet, GazeNet, etc). For classification, set this argument to :code:`predictions/Softmax`. 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. This parameter is not required for :code:`.etlt` models generated with dynamic shape. This is only possible for new models introduced in TLT v3.0. Sample Output Log ~~~~~~~~~~~~~~~~~ Here is a sample log for converting a classification model. .. code:: tlt-converter /ws/export/final_model.etlt -k $KEY -c /ws/export/final_model_int8_cache.bin -o predictions/Softmax -d 3,224,224 -i nchw -m 64 -t int8 -e /ws/export/final_model.trt -b 64 [INFO] Some tactics do not have sufficient workspace memory to run. Increasing workspace size may increase performance, please check verbose output. [INFO] Detected 1 inputs and 1 output network tensors. Integrating the model 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 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 Classification Model ********************************** See Exporting The Model for more details on how to export a TLT model. After the model has been generated, two extra files are required: 1. Label file 2. DeepStream configuration file Label File ~~~~~~~~~~ The label file is a text file, containing the names of the classes that the TLT model is trained to classify against. The order in which the classes are listed must match the order in which the model predicts the output. This order may be deduced from the :code:`classmap.json` file that is generated by TLT. This file is a simple dictionary containing the 'class_name' to 'index map'. For example, in the sample classification sample notebook file included with the TLT Docker, the :code:`classmap.json` file generated for Pascal Visual Object Classes (VOC) would look like this: .. code:: {"sheep": 16,"horse": 12,"bicycle": 1, "aeroplane": 0, "cow": 9, "sofa": 17, "bus": 5, "dog": 11, "cat": 7, "person": 14, "train": 18, "diningtable": 10, "bottle": 4, "car": 6, "pottedplant": 15, "tvmonitor": 19, "chair": 8, "bird": 2, "boat": 3, "motorbike": 13} The 0th index corresponds to :code:`aeroplane`, the 1st index corresponds to :code:`bicycle`, up to 19, which corresponds to :code:`tvmonitor`. Here is a sample :code:`classification_labels.txt` file, arranged in order of index: .. code:: aeroplane;bicycle;bird;boat;bottle;bus;....;tvmonitor DeepStream Configuration File ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A typical use case for video analytic is first to do an object detection and then crop the detected object and send it further for classification. This is supported by :code:`deepstream-app` and the app architecture can be seen above. For example, to classify models of cars on the road, first you will need to detect all the cars in a frame. Once you do detection, you perform classification on the cropped image of the car. In the sample DeepStream app, the classifier is configured as a secondary inference engine after the primary detection. If configured appropriately, :code:`deepstream-app` will automatically crop the detected image and send the frame to the secondary classifier. The :code:`config_infer_secondary_*.txt` is used to configure the classification model. .. image:: ../content/dstream_deploy_options2.png **Option 1**: Integrate the model (:code:`.etlt`) directly in the DeepStream app. For this option, users will need to add the following parameters in the configuration file. The :code:`int8-calib-file` is only required for INT8 precision. .. code:: tlt-encoded-model= tlt-model-key= int8-calib-file= **Option 2**: Integrate the TensorRT engine file with the DeepStream app. **Step 1**: Generate the TensorRT engine using `tlt-converter`. Detail instructions are provided in the :ref:`Generating an Engine Using tlt-converter ` section. **Step 2**: After the engine file is generated successfully, modify the following parameters to use this engine with DeepStream. .. code:: model-engine-file= All other parameters are common between the 2 approaches. Add the label file generated above using: .. code:: labelfile-path= For all the options, see the configuration file below. To learn about what all the parameters are used for, refer to `DeepStream Development Guide`_. .. code:: [property] gpu-id=0 # preprocessing parameters: These are the same for all classification models generated by TLT. net-scale-factor=1.0 offsets=103.939;116.779;123.68 model-color-format=1 batch-size=30 # Model specific paths. These need to be updated for every classification model. int8-calib-file= labelfile-path= tlt-encoded-model= tlt-model-key= infer-dims=c;h;w # where c = number of channels, h = height of the model input, w = width of model input uff-input-blob-name=input_1 uff-input-order=0 output-blob-names=predictions/Softmax ## 0=FP32, 1=INT8, 2=FP16 mode network-mode=0 # process-mode: 2 - inferences on crops from primary detector, 1 - inferences on whole frame process-mode=2 interval=0 network-type=1 # defines that the model is a classifier. gie-unique-id=1 classifier-threshold=0.2