Multitask Image Classification
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:
|--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.
Here is an example of a specification file for multitask classification:
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
The table below describes the configurable parameters in the model_config
.
Parameter |
Datatype |
Default |
Description |
Supported Values |
|
bool |
|
For templates with shortcut connections, this parameter defines whether or not all shortcuts should be instantiated with 1x1 projection layers irrespective of whether there is a change in stride across the input and output. |
True or False (only to be used in ResNet templates) |
|
string |
|
This defines the architecture of the back bone feature extractor to be used to train. |
|
|
int |
|
Depth of the feature extractor for scalable templates. |
|
|
Boolean |
|
Choose between using strided convolutions or MaxPooling while downsampling. When True, MaxPooling is used to down sample, however for the object detection network, NVIDIA recommends setting this to False and using strided convolutions. |
True or False |
|
Boolean |
|
Boolean variable to use batch normalization layers or not. |
True or False |
|
float (repeated) |
– |
This parameter defines which blocks may be frozen from the instantiated feature extractor template, and is different for different feature extractor templates. |
|
|
Boolean |
|
You can choose to freeze the Batch Normalization layers in the model during training. |
True or False |
|
String |
|
The dimension of the input layer of the model. Images in the dataset will be resized to this shape by the dataloader when fed to the model for training. |
3,X,Y, where X,Y >=16 and X,Y are integers. |
|
enum |
|
The interpolation method for resizing the input images. |
BILINEAR, BICUBIC |
|
Boolean |
|
Whether or not to use the header layers as in the original implementation on ImageNet. Set this to True to reproduce the 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. |
True or False |
|
float |
|
Dropout rate for Dropout layers in the model. This is only valid for VGG and SqueezeNet. |
Float in the interval [0, 1) |
|
proto message |
– |
Parameters for BatchNormalization layers. |
– |
|
proto message |
– |
Parameters for the activation functions in the model. |
– |
BatchNormalization Parameters
The parameter batch_norm_config
defines parameters for BatchNormalization layers in the model (momentum and epsilon).
Parameter |
Datatype |
Default |
Description |
Supported Values |
|
float |
|
Momentum of BatchNormalization layers. |
float in the interval (0, 1), usually close to 1.0. |
|
float |
|
Epsilon to avoid zero division. |
float that is close to 0.0. |
Activation functions
The parameter activation
defines the parameters for activation functions in the model.
Parameter |
Datatype |
Default |
Description |
Supported Values |
|
String |
– |
Type of the activation function. |
Only |
Training Config
The training configuration (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 |
– |
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 |
This parameter supports one
|
Message type |
– |
regularizer |
This parameter configures the regularizer to use while training and contains the following nested parameters:
|
Message type |
L1 (Note: NVIDIA suggests using the L1 regularizer when training a network before pruning, as L1 regularization makes the network weights more prunable.) |
optimizer |
The optimizer can be
The optimizer parameters are the same as those in Keras. |
Message type |
– |
pretrain_model_path |
The path to the pretrained model, if any At most, one |
String |
– |
resume_model_path |
The path to the TAO checkpoint model to resume training, if any At most, one |
String |
– |
pruned_model_path |
The path to the TAO pruned model for re-training, if any At most, one |
String |
– |
The learning rate is automatically scaled with the number of GPUs used during training, or the effective learning rate is learning_rate * n_gpu
.
Dataset Config
Parameter |
Datatype |
Description |
|
string |
Path to the image directory |
|
string |
Path to the training CSV file |
|
string |
Path to the validation CSV file |
Use the tao multitask_classification train
command to tune a pre-trained model:
tao multitask_classification train -e <spec file>
-k <encoding key>
-r <result directory>
[--gpus <num GPUs>]
[--gpu_index <gpu_index>]
[--use_amp]
[--log_file <log_file_path>]
[-h]
Required Arguments
-r, --results_dir
: Path to a folder where the experiment outputs should be written.-k, --key
: User specific encoding key to save or load a.tlt
model.-e, --experiment_spec_file
: Path to the experiment spec file.
Optional Arguments
--gpus
: Number of GPUs to use and processes to launch for training. The default value is 1.--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.--use_amp
: A flag to enable AMP training.--log_file
: Path to the log file. Defaults to stdout.-h, --help
: Print the help message.
See the Specification File for Multitask Classification section for more details.
Here’s an example of using the tao multitask_classification train
command:
tao multitask_classification train -e /workspace/tlt_drive/spec/spec.cfg -r /workspace/output -k $YOUR_KEY
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 TAO Toolkit includes the tao 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 tao multitask_classification evaluate
command:
tao multitask_classification evaluate -e <experiment_spec_file>
-k <key>
-m <model>
[--gpu_index <gpu_index>]
[--log_file <log_file>]
[-h]
Required Arguments
-e, --experiment_spec_file
: Path to the experiment spec file.-k, --key
: Provide the encryption key to decrypt the model.-m, --model
: Provide path to the trained model.
Optional Arguments
-h, --help
: Show this help message and exit.--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.--log_file
: Path to the log file. Defaults to stdout.
Inferencing models on a labeled dataset can give confusion matrices from which you can see where the model makes mistakes.
TAO offers a command to easily generate confusion matrices for all tasks:
tao multitask_classification confmat -i <img_root>
-l <target_csv>
-k <key>
-m <model>
[--gpu_index <gpu_index>]
[--log_file <log_file>]
[-h]
Required Arguments
-i, --img_root
: Path to the image directory.-l, --target_csv
: Path to the ground truth label CSV file.-k, --key
: Provide the encryption key to decrypt the model.-m, --model
: Provide path to the trained model.
Optional Arguments
-h, --help
: Show this help message and exit.--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.--log_file
: Path to the log file. Defaults to stdout.
The tao multitask_classification inference
command runs the inference on a specified image.
Execute tao multitask_classification inference
on a multitask classification model trained
on TAO Toolkit.
tao multitask_classification inference -m <model> -i <image> -k <key> -cm <classmap> [--gpu_index <gpu_index>] [--log_file <log_file>] [-h]
Here are the arguments of the tao multitask_classification inference
tool:
Required arguments
-m, --model
: Path to the pretrained model (TAO model).-i, --image
: A single image file for inference.-k, --key
: Key to load model.-cm, --class_map
: The json file that specifies the class index and label mapping for each task.
Optional arguments
-h, --help
: Show this help message and exit.--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.--log_file
: Path to the log file. Defaults to stdout.
A classmap (-cm
) is required, which
should be a byproduct (class_mapping.json
) of your training process.
Pruning removes parameters from the model to reduce the model size without compromising the
integrity of the model itself using the tao multitask_classification prune
command.
The tao multitask_classification prune
command includes these parameters:
tao multitask_classification prune -m <model>
-o <output_file>
-k <key>
[-n <normalizer>
[-eq <equalization_criterion>]
[-pg <pruning_granularity>]
[-pth <pruning threshold>]
[-nf <min_num_filters>]
[-el <excluded_list>]
[--gpu_index <gpu_index>]
[--log_file <log_file>]
[-h]
Required Arguments
-m, --model
: Path to pretrained model-o, --output_file
: Path to output checkpoints-k, --key
: Key to load a .tlt model
Optional Arguments
-h, --help
: Show this help message and exit.-n, –normalizer
:max
to normalize by dividing each norm by the maximum norm within a layer;L2
to normalize by dividing by the L2 norm of the vector comprising all kernel norms. (default:max
)-eq, --equalization_criterion
: Criteria to equalize the stats of inputs to an elementwise op layer, or depth-wise convolutional layer. This parameter is useful for ResNet and MobileNet. Options arearithmetic_mean
,geometric_mean
,union
, andintersection
. (default:union
)-pg, -pruning_granularity
: Number of filters to remove at a time (default: 8)-pth
: Threshold to compare normalized norm against (default: 0.1)-nf, --min_num_filters
: Minimum number of filters to keep per layer (default: 16)-el, --excluded_layers
: List of excluded_layers. Examples: -i item1 item2 (default: [])--gpu_index
: The GPU indices used to run the pruning. We can specify the GPU indices used to run training when the machine has multiple GPUs installed.--log_file
: Path to the log file. Defaults to stdout.
After pruning, the model needs to be retrained. See Re-training the Pruned Model for more details.
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 tao multitask_classification train
command as documented in 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 NO_REG
. All the other parameters may be retained in the spec file from the previous training.
Exporting the model decouples the training process from inference and allows conversion to
TensorRT engines outside the TAO environment. TensorRT engines are specific to each hardware
configuration and should be generated for each unique inference environment.
The exported model may be used universally across training and deployment hardware.
The exported model format is referred to as .etlt
. Like .tlt
, the .etlt
model
format is also an encrypted model format with the same key of the .tlt
model that it is
exported from. This key is required when deploying this model.
Exporting the Model
Here’s an example of the tao multitask_classification export
command:
tao multitask_classification export
-m <path to the .tlt model file generated by training>
-k <key>
-cm <classmap>
[-o <path to output file>]
[--gpu_index <gpu_index>]
[--log_file <log_file_path>]
Required Arguments
-m, --model
: Path to the.tlt
model file to be exported.-k, --key
: Key used to save the.tlt
model file.-cm, --class_map
: The json file that specifies the class index and label mapping for each task.
A classmap (-cm
) is required, which
should be a by product (class_mapping.json
) of your training process.
Optional Arguments
-o, --output_file
: Path to save the exported model to. The default is./<input_file>.etlt
.--gpu_index
: The index of (discrete) 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.--log_file
: Path to the log file. Defaults to stdout.-v, --verbose
: Verbose log.
For TensorRT engine generation, validation, and int8 calibration, refer to the TAO Deploy documentation.
Refer to the Integrating a Multitask Image Classification Model page for more information about deploying a classification model with DeepStream.