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:

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

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

all_projections

bool

False

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)

arch

string

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

n_layers

int

18

Depth of the feature extractor for scalable templates.

  • resnets: 10, 18, 34, 50, 101

  • vgg: 16, 19

  • darknet / cspdarknet: 19, 53

use_pooling

Boolean

False

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

use_batch_norm

Boolean

False

Boolean variable to use batch normalization layers or not.

True or False

freeze_blocks

float (repeated)

This parameter defines which blocks may be frozen from the instantiated feature extractor template, and is different for different feature extractor templates.

  • ResNet series: For the ResNet series, the block ID’s valid for freezing is any subset of {0, 1, 2, 3}(inclusive)

  • 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)

freeze_bn

Boolean

False

You can choose to freeze the Batch Normalization layers in the model during training.

True or False

input_image_size

String

"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 when fed to the model for training.

3,X,Y, where X,Y >=16 and X,Y are integers.

resize_interpolation_method

enum

BILEANER

The interpolation method for resizing the input images.

BILINEAR, BICUBIC

use_imagenet_head

Boolean

False

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

dropout

float

0.0

Dropout rate for Dropout layers in the model. This is only valid for VGG and SqueezeNet.

Float in the interval [0, 1)

batch_norm_config

proto message

Parameters for BatchNormalization layers.

activation

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

momentum

float

0.9

Momentum of BatchNormalization layers.

float in the interval (0, 1), usually close to 1.0.

epsilon

float

1e-5

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

activation_type

String

Type of the activation function.

Only relu and swish are supported.

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 batch_size_per_gpu * num_gpus

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 soft_start_annealing_schedule and soft_start_cosine_annealing_schedule with the following nested parameters:

  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

Message type

regularizer

This parameter configures the regularizer to use while training and contains the following nested parameters:

  1. type: The type of regularizer to use. NVIDIA supports NO_REG, L1, or L2.

  2. weight: The floating point value for regularizer weight

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 adam, sgd, or rmsprop. Each type has the following parameters:

  1. adam: epsilon, beta1, beta2, amsgrad

  2. sgd: momentum, nesterov

  3. rmsprop: rho, momentum, epsilon, centered

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 pretrain_model_path, resume_model_path, and pruned_model_path may be present.

String

resume_model_path

The path to the TAO checkpoint model to resume training, if any

At most, one pretrain_model_path, resume_model_path, and pruned_model_path may be present.

String

pruned_model_path

The path to the TAO pruned model for re-training, if any

At most, one pretrain_model_path, resume_model_path, and pruned_model_path may be present.

String

Note

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

image_directory_path

string

Path to the image directory

train_csv_path

string

Path to the training CSV file

val_csv_path

string

Path to the validation CSV file

Training the model

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.

Note

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

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

Generating Confusion Matrix

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.

Running Inference on a Model

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.

Note

A classmap (-cm) is required, which should be a byproduct (class_mapping.json) of your training process.

Pruning the Model

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 are arithmetic_mean, geometric_mean, union, and intersection. (default: union)

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

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

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

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

  • --gpu_index: The 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.

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

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.

Note

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.

TensorRT Engine Generation, Validation, and int8 Calibration

For TensorRT engine generation, validation, and int8 calibration, refer to the TAO Deploy documentation.

Deploying to DeepStream

Refer to the Integrating a Multitask Image Classification Model page for more information about deploying a classification model with DeepStream.