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

Multitask classification training uses the experiment specification described above and supports multi-GPU training as well as AMP.

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 multitask_classification app computes per-task evaluation loss and accuracy as metrics.

Generating Confusion Matrix#

Inferencing models on a labeled dataset can give confusion matrices from which you can see where the model makes mistakes. TAO supports generating confusion matrices for all tasks.

Running Inference on a Model#

Inference may be run on a single image with a trained multitask classification model. A class mapping JSON file (a by-product of training) is required to translate class indices to labels.

Pruning the Model#

Pruning removes parameters from the model to reduce the model size without compromising the integrity of the model itself.

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, with an updated specification 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 specification 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.

Deploying to DeepStream#

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