Image Classification (TF1)

See the Data Annotation Format page for more information about the data format for image classification.

Here is an example of a specification file for model classification:

Copy
Copied!
            

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 retain_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 } } eval_config { eval_dataset_path: "/path/to/your/test/data" model_path: "/workspace/tao-experiments/classification/weights/resnet_080.tlt" top_k: 3 batch_size: 256 n_workers: 8 enable_center_crop: True }

The classification experiment specification consists of three main components:

  • model_config

  • eval_config

  • train_config

Model Config

The table below describes the configurable parameters in the model_config.

Parameter Datatype Typical value 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
* efficientnet_b0
* efficientnet_b1
* cspdarknet_tiny

n_layers

int

18

Depth of the feature extractor for scalable templates.

* resnets: 10, 18, 34, 50, 101
* vgg: 16, 19
* darknet: 19, 53
* 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)
* CSPDarkNet: For CSPDarkNet, 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)
* CSPDarkNet-tiny: For CSPDarkNet-tiny, the valid blocks IDs is any subset of {0, 1, 2, 3, 4, 5}(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.

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

resize_interpolation_method enum BILEANER The interpolation method for resizing the input images. BILINEAR, BICUBIC

retain_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 Typical value 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.

Eval Config

The table below defines the configurable parameters for evaluating a classification model.

Parameter Datatype Typical value Description Supported Values
eval_dataset_path string UNIX format path to the root directory of the evaluation dataset. UNIX format path.
model_path string UNIX format path to the root directory of the model file you would like to evaluate. UNIX format path.
top_k int 5 The number elements to look at when calculating the top-K classification categorical accuracy metric. 1, 3, 5
batch_size int 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)
n_workers int 8 Number of workers fetching batches of images in the evaluation dataloader. >1
enable_center_crop Boolean True Enable center crop for input images or not. Usually this parameter is set to True to achieve better accuracy. True or False

Training Config

This section defines the configurable parameters for the classification model trainer.

Parameter Datatype Default Description Supported Values
val_dataset_path string UNIX format path to the root directory of the validation dataset. UNIX format path.
train_dataset_path string UNIX format path to the root directory of the training dataset. UNIX format path.
pretrained_model_path string UNIX format path to the model file containing the pretrained weights to initialize the model from. UNIX format path.
batch_size_per_gpu int 32 This parameter defines the number of images per batch per gpu. >1
n_epochs int 120 This parameter defines the total number of epochs to run the experiment.
n_workers int 10 Number of workers fetching batches of images in the training/validation dataloader. >1
lr_config proto message The parameters for learning rate scheduler.
reg_config proto message The parameters for regularizers.
optimizer proto message This parameter defines which optimizer to use for training. Can be chosen from sgd, adam, or rmsprop
random_seed int Random seed for training.
enable_random_crop Boolean True A flag to enable random crop during training. True or False
enable_center_crop Boolean True A flag to enable center crop during validation. True or False
enable_color_augmentation Boolean True A flag to enable color augmentation during training. True or False
disable_horizontal_flip Boolean False A flag to disable horizontal flip. True or False
label_smoothing float 0.1 A factor used for label smoothing. in the interval (0, 1)
mixup_alpha float 0.2 A factor used for mixup augmentation. in the interval (0, 1)
preprocess_mode string 'caffe' Mode for input image preprocessing. Defaults to ‘caffe’. ‘caffe’, ‘torch’, ‘tf’
model_parallelism repeated float List of fractions to indicate how we split the model on multiple GPUs for model parallelism.
image_mean dict ‘b’: 103.939 ‘g’: 116.779 ‘r’: 123.68 A key/value pair to specify image mean values. It’s only applicable when preprocess_mode is caffe. If omitted, ImageNet mean will be used for image preprocessing. If set, depending on output_channel, either ‘r/g/b’ or ‘l’ key/value pair must be configured.

Learning Rate Scheduler

The parameter lr_config defines the parameters for learning rate scheduler The learning rate scheduler can be either step, soft_anneal or cosine.

Step

The parameter step defines the step learning rate scheduler.

Parameter Datatype Typical value Description Supported Values
learning_rate float The base(maximum) learning rate value. Positive, usually in the interval (0, 1).
step_size int The progress (percentage of the entire training duration) after which the learning rate will be decreased. Less than 100.
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 learning_rate * n_gpu.

Soft Annealing

The parameter soft_anneal defines the soft annealing learning rate scheduler.

Parameter Datatype Typical value Description Supported Values
learning_rate float The base (maximum) learning rate value. Positive, usually in the interval (0, 1).
soft_start float The progress at which learning rate achieves the base learning rate. In the interval (0, 1).
annealing_divider float The divider by which the learning rate will be scaled down. Greater than 1.0.
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 cosine defines the cosine learning rate scheduler.

Parameter Datatype Typical value Description Supported Values
learning_rate float The base (maximum) learning rate. Usually less than 1.0
min_lr_ratio float The ratio of minimum learning rate to the base learning rate. Less than 1.0
soft_start float The progress at which learning rate achieves the base learning rate. In the interval (0, 1).
learning_rate_schedules.png

Optimizer

Three types of optimizers are supported: Adam, SGD and RMSProp. Only one type should be specified in the spec file. No matter which type is chosen, it will be wrapped in an optimizer proto, as shown in the following example:

Copy
Copied!
            

optimizer { sgd { lr: 0.01 decay: 0.0 momentum: 0.9 nesterov: False } }

The Adam optimizer parameters are summarized in the table below.

Parameter Description Data Type and Constraints Default/Suggested Value
lr The learning rate. This parameter is overridden by the learning rate scheduler and hence not useful. float 0.01
beta_1 The momentum for the means of the model parameters float 0.9
beta_2 The momentum for the variances of the model parameters float 0.999
decay Th decay factor for the learning rate. This parameter is not useful. float 0.0
epsilon A small constant for numerical stability float 1e-7

The SGD optimizer parameters are summarized in the table below.

Parameter Description Data Type and Constraints Default/Suggested Value
lr The learning rate. This parameter is overridden by the learning rate scheduler and hence not useful. float 0.01
momentum The momentum of SGD float 0.9
decay The decay factor of the learning rate. This parameter is not useful because it is overridden by the learning rate scheduler. float 0.0
nesterov A flag to enable Nesterov momentum for SGD Boolean False

The RMSProp optimizer parameters are summarized in the table below.

Parameter Description Data Type and Constraints Default/Suggested Value
lr The learning rate. This parameter is overridden by the learning rate scheduler and hence not useful. float 0.01

Use the tao model classification_tf1 train command to tune a pre-trained model:

Copy
Copied!
            

tao model classification_tf1 train [-h] -e <spec file> -k <encoding key> -r <result directory> [--gpus <num GPUs>] [--num_processes <number_of_processes>] [--gpu_index <gpu_index>] [--use_amp] [--log_file <log_file_path>]

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.

  • --num_processes, -np: Number of processes to be spawned for training. It defaults to be -1(equal to --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 --gpus to be larger than 1 and --num_processes to 1 corresponding to the model parallelism use case; while setting both --gpus and num_processes to be larger than 1 corresponding to the case of enabling both model parallelism and data parallelism. For example, --gpus=4 and --num_processes=2 means 2 horovod processes will be spawned and each of them will occupy 2 GPUs for model parallelism.

  • --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 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 input size.

Sample Usage

Here’s an example of using the tao model classification_tf1 train command:

Copy
Copied!
            

tao model classification_tf1 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 split 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 model_parallelism in training_config. For example,

Copy
Copied!
            

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 split on 2 GPUs.

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 model classification_tf1 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 tao model classification_tf1 evaluate command:

Copy
Copied!
            

tao model classification_tf1 evaluate [-h] -e <experiment_spec_file> -k <key> [--gpu_index <gpu_index>] [--log_file <log_file>]

Required Arguments

  • -e, --experiment_spec_file: Path to the experiment spec file.

  • -k, –key: Provide the encryption key to decrypt the model.

Optional Arguments

  • -h, --help: Show this help message and exit.

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

  • --log_file: Path to the log file. Defaults to stdout.

If you followed the example in training a classification model, run the evaluation:

Copy
Copied!
            

tao model classification_tf1 evaluate -e classification_spec.cfg -k $YOUR_KEY

TAO evaluates for classification and produces the following metrics:

  • Loss

  • Top-K accuracy

  • Precision (P): TP / (TP + FP)

  • Recall (R): TP / (TP + FN)

  • Confusion Matrix

The tao model classification_tf1 inference command runs the inference on a specified set of input images. For classification, tao model classification_tf1 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 tao model classification_tf1 inference on a classification model trained on TAO Toolkit.

Copy
Copied!
            

tao model classification_tf1 inference [-h] -m <model> -i <image> -d <image dir> -k <key> -cm <classmap> -e <experiment_spec_file> [-b <batch size>] [--gpu_index <gpu_index>] [--log_file <log_file>]

Here are the arguments of the tao model classification_tf1 inference tool:

Required arguments

  • -m, --model: Path to the pretrained model (TAO model).

  • -i, --image: A single image file for inference.

  • -d, --image_dir: The directory of input images for inference.

  • -k, --key: Key to load model.

  • -cm, --class_map: The json file that specifies the class index and label mapping.

  • -e, --experiment_spec_file: Path to the experiment spec file.

Optional arguments

  • --batch_size: Inference batch size, default: 1

  • -h, --help: Show this help message and exit.

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

  • --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 -d, or directory mode, a result.csv file is created and stored in the directory you specify using -d. The 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 (-cm) is required, which should be a by product (-classmap.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 model classification_tf1 prune command.

The tao model classification_tf1 prune command includes these parameters:

Copy
Copied!
            

tao model classification_tf1 prune [-h] -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>]

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

Using the Prune Command

Here’s an example of using the tao model classification_tf1 prune command:

Copy
Copied!
            

tao model classification_tf1 prune -m /workspace/output/weights/resnet_003.tlt -o /workspace/output/weights/resnet_003_pruned.tlt -eq union -pth 0.7 -k $KEY

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 model classification_tf1 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 a encrypted model format with the same key of the .tlt model that it is exported from. This key is required when deploying this model.

Here’s an example of the tao model classification_tf1 export command:

Copy
Copied!
            

tao model classification_tf1 export [-h] -m <path to the .tlt model file generated by training> -e <experiment_spec_file> [-k <key>] [-o <path to output file>] [--gen_ds_config <Flag to generate ds config and label file>] [--verbose] [--gpu_index <gpu_index>] [--log_file <log_file_path>] [--classmap_json CLASSMAP_JSON]

Required Arguments

  • -m, --model: Path to the .tlt model file to be exported.

  • -e, --experiment_spec_file: Path to the experiment spec file.

Optional Arguments

  • -k, --key: Key used to save the .tlt model file.

  • -o, --output_file: Path to save the exported model to. The default is ./<input_file>.etlt.

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

  • --classmap_json: Path to the classmap_json file. It is already generated in training result folder. This file is required if gen_ds_config is enabled.

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

Sample usage

Here’s a sample command.

Copy
Copied!
            

tao model classification_tf1 export -m /ws/output_retrain/weights/resnet_001.tlt -o /ws/export/final_model.etlt -k $KEY

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

Refer to the Integrating a Classification (TF1/TF2) Model page for more information about deploying a classification model with DeepStream.

Previous Data Annotation Format
Next Image Classification (TF2)
© Copyright 2024, NVIDIA. Last updated on Mar 18, 2024.