Main Content

Code Generation for Quantized Deep Learning Networks

Deep learning uses neural network architectures that contain many processing layers, including convolutional layers. Deep learning models typically work on large sets of labeled data. Training these models and performing inference is computationally intensive, consuming significant amount of memory. Neural networks use memory to store input data, parameters (weights), and activations from each layer as the input propagates through the network. The majority of the pretrained neural networks and neural networks trained by using Deep Learning Toolbox™ use single-precision floating point data types. Even networks that are small in size require a considerable amount of memory and hardware to perform these floating-point arithmetic operations. These restrictions can inhibit deployment of deep learning models to devices that have low computational power and smaller memory resources. By using a lower precision to store the weights and activations, you can reduce the memory requirements of the network.

You can use Deep Learning Toolbox in tandem with the Deep Learning Toolbox Model Quantization Library support package to reduce the memory footprint of a deep neural network by quantizing the weights, biases, and activations of convolution layers to 8-bit scaled integer data types. Then, you can use GPU Coder™ to generate optimized CUDA® code for the quantized network. The generated code takes advantage of NVIDIA® CUDA deep neural network library (cuDNN) or the TensorRT™ high performance inference library. the generated code can be integrated into your project as source code, static or dynamic libraries, or executables that you can deploy to a variety of NVIDIA GPU platforms.

Example: Classify Images Using SqueezeNet

In this example, you use GPU Coder to generate CUDA code for a quantized deep convolutional neural network and classify an image. The example uses the pretrained squeezenet (Deep Learning Toolbox) convolutional neural network to demonstrate transfer learning, quantization, and CUDA code generation for the quantized network.

SqueezeNet has been trained on over a million images and can classify images into 1000 object categories (such as keyboard, coffee mug, pencil, and many animals). The network has learned rich feature representations for a wide range of images. The network takes an image as input and outputs a label for the object in the image together with the probabilities for each of the object categories.



This example generates CUDA MEX that has the following additional requirements.

  1. Deep Learning Toolbox.

  2. Deep Learning Toolbox Model for SqueezeNet Network support package.

  3. GPU Coder Interface for Deep Learning Libraries support package.

  4. Deep Learning Toolbox Model Quantization Library support package. To install the support packages, select the support package from the MATLAB® Add-Ons menu.

  5. CUDA enabled NVIDIA GPU and a compatible driver. For 8-bit integer precision, the CUDA GPU must have a compute capability of 6.1, 6.3 or higher.


For non-MEX builds such as static, dynamic libraries, or executables, this example has the following additional requirements.

  1. CUDA toolkit, cuDNN, and TensorRT libraries. For information on the supported versions of the compilers and libraries, see Installing Prerequisite Products.

  2. Environment variables for the compilers and libraries. For more information, see Environment Variables.

Transfer Learning Using SqueezeNet

To perform classification on a new set of images, you fine-tune a pretrained SqueezeNet convolutional neural network by transfer learning. In transfer learning, you can take a pretrained network and use it as a starting point to learn a new task. Fine-tuning a network with transfer learning is usually much faster and easier than training a network with randomly initialized weights from scratch. You can quickly transfer learned features to a new task using a smaller number of training images.

Load Training Data

Unzip and load the new images as an image datastore. The imageDatastore function automatically labels the images based on folder names and stores the data as an ImageDatastore object. An image datastore enables you to store large image data, including data that does not fit in memory, and efficiently read batches of images during training of a convolutional neural network. Divide the data into training and validation data sets. Use 70% of the images for training and 30% for validation. splitEachLabel splits the imds datastore into two new datastores.

imds = imageDatastore('MerchData', ...
    'IncludeSubfolders',true, ...
[imdsTrain,imdsValidation] = splitEachLabel(imds,0.7,'randomized');

numTrainImages = numel(imdsTrain.Labels);
idx = randperm(numTrainImages,4);
img = imtile(imds, 'Frames', idx);

title('Random Images from Training Dataset');

Random images from the training dataset

Load Pretrained Network

  1. Load the pretrained SqueezeNet network. If you do not have the required support packages installed, the software provides a download link.

    net = squeezenet;

  2. The object net contains the DAGNetwork object. The first layer, the image input layer, requires input images of size 227-by-227-by-3, where 3 is the number of color channels. You can use the analyzeNetwork (Deep Learning Toolbox) function to display an interactive visualization of the network architecture, to detect errors and issues in the network, and to display detailed information about the network layers. The layer information includes the sizes of layer activations and learnable parameters, the total number of learnable parameters, and the sizes of state parameters of recurrent layers.

    inputSize = net.Layers(1).InputSize;

Replace Final Layers

  1. The convolutional layers of the network extract image features that the last learnable layer and the final classification layer use to classify the input image. These two layers, 'conv10' and 'ClassificationLayer_predictions' in SqueezeNet, contain information on how to combine the features that the network extracts into class probabilities, a loss value, and predicted labels.

  2. To retrain a pretrained network to classify new images, replace these two layers with new layers adapted to the new data set. You can do this manually or use the helper function findLayersToReplace to find these layers automatically.

    lgraph = layerGraph(net); 
    [learnableLayer,classLayer] = findLayersToReplace(lgraph);
    numClasses = numel(categories(imdsTrain.Labels));
    newConvLayer =  convolution2dLayer([1, 1],numClasses,'WeightLearnRateFactor',...
    lgraph = replaceLayer(lgraph,'conv10',newConvLayer);
    newClassificatonLayer = classificationLayer('Name','new_classoutput');
    lgraph = replaceLayer(lgraph,'ClassificationLayer_predictions',newClassificatonLayer);
  3. The findLayersToReplace.m Helper Function


Train Network

  1. The network requires input images of size 227-by-227-by-3, but the images in the image datastores have different sizes. Use an augmented image datastore to automatically resize the training images. Specify additional augmentation operations to perform on the training images: randomly flip the training images along the vertical axis, and randomly translate them up to 30 pixels horizontally and vertically. Data augmentation helps prevent the network from over-fitting and memorizing the exact details of the training images.

    pixelRange = [-30 30];
    imageAugmenter = imageDataAugmenter( ...
        'RandXReflection',true, ...
        'RandXTranslation',pixelRange, ...
    augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain, ...
  2. To automatically resize the validation images without performing further data augmentation, use an augmented image datastore without specifying any additional preprocessing operations.

    augimdsValidation = augmentedImageDatastore(inputSize(1:2),imdsValidation);
  3. Specify the training options. For transfer learning, keep the features from the early layers of the pretrained network (the transferred layer weights). To slow down learning in the transferred layers, set the initial learning rate to a small value. In the previous step, you increased the learning rate factors for the convolutional layer to speed up learning in the new final layers. This combination of learning rate settings results in fast learning only in the new layers and slower learning in the other layers. When performing transfer learning, you do not need to train for as many epochs. An epoch is a full training cycle on the entire training data set. Specify the mini-batch size to be 11 so that in each epoch you consider all of the data. The software validates the network every ValidationFrequency iterations during training.

    options = trainingOptions('sgdm', ...
        'MiniBatchSize',11, ...
        'MaxEpochs',7, ...
        'InitialLearnRate',2e-4, ...
        'Shuffle','every-epoch', ...
        'ValidationData',augimdsValidation, ...
        'ValidationFrequency',3, ...
        'Verbose',false, ...
  4. Train the network that consists of the transferred and new layers.

    netTransfer = trainNetwork(augimdsTrain,lgraph,options);
    classNames = netTransfer.Layers(end).Classes;

Quantize the Network

  1. Create a dlquantizer object and specify the network to quantize.

    quantObj = dlquantizer(net);
  2. Define a metric function to use to compare the behavior of the network before and after quantization. Save this function in a local file.

    function accuracy = hComputeModelAccuracy(predictionScores, net, dataStore)
    %% Computes model-level accuracy statistics
        % Load ground truth
        tmp = readall(dataStore);
        groundTruth = tmp.response;
        % Compare with predicted label with actual ground truth 
        predictionError = {};
        for idx=1:numel(groundTruth)
            [~, idy] = max(predictionScores(idx,:)); 
            yActual = net.Layers(end).Classes(idy);
            predictionError{end+1} = (yActual == groundTruth(idx)); %#ok
        % Sum all prediction errors.
        predictionError = [predictionError{:}];
        accuracy = sum(predictionError)/numel(predictionError);
  3. Specify the metric function in a dlquantizationOptions object.

    quantOpts = dlquantizationOptions('MetricFcn', ...
  4. Use the calibrate function to exercise the network with sample inputs and collect range information. The calibrate function exercises the network and collects the dynamic ranges of the weights and biases in the convolution and fully connected layers of the network and the dynamic ranges of the activations in all layers of the network. The function returns a table. Each row of the table contains range information for a learnable parameter of the optimized network.

    calResults = calibrate(quantObj,augimdsTrain);
  5. You can use the validate function to quantize the learnable parameters in the convolution layers of the network and exercise the network. The function uses the metric function defined in the dlquantizationOptions object to compare the results of the network before and after quantization.

    valResults = validate(quantObj,augimdsValidation,quantOpts);

Create an Entry-Point Function

  1. Write an entry-point function in MATLAB that:

    1. Uses the coder.loadDeepLearningNetwork function to load a deep learning model and to construct and set up a CNN class. For more information, see Load Pretrained Networks for Code Generation.

    2. Calls predict (Deep Learning Toolbox) to predict the responses.

  2. For example:

    function out = predict_int8(netFile, in)
        persistent mynet;
        if isempty(mynet)
            net = coder.loadDeepLearningNetwork(netFile);
        out = predict(mynet,in);

    A persistent object mynet loads the DAGNetwork object. At the first call to the entry-point function, the persistent object is constructed and set up. On subsequent calls to the function, the same object is reused to call predict on inputs, avoiding reconstructing and reloading the network object.


    Ensure that all the preprocessing operations performed in the calibration and validation steps are included in the design file.

Code Generation by Using codegen

  1. To configure build settings such as output file name, location, and type, you create coder configuration objects. To create the objects, use the coder.gpuConfig function. For example, when generating CUDA MEX using the codegen command, use cfg = coder.gpuConfig('mex');

  2. To specify code generation parameters for cuDNN, set the DeepLearningConfig property to a coder.CuDNNConfig object that you create by using coder.DeepLearningConfig.

    cfg = coder.gpuConfig('mex');
    cfg.TargetLang = 'C++';
    cfg.GpuConfig.ComputeCapability = '6.1';
    cfg.DeepLearningConfig = coder.DeepLearningConfig('cudnn');
    cfg.DeepLearningConfig.AutoTuning = true;
    cfg.DeepLearningConfig.CalibrationResultFile = 'squeezenetQuantObj.mat';
    cfg.DeepLearningConfig.DataType = 'int8';

    Specify the location of the MAT-file containing the calibration data.

    Specify the precision of the inference computations in supported layers by using the DataType property. For 8-bit integer, use 'int8'. INT8 precision requires a CUDA GPU with a compute capability of 6.1, 6.3 or higher. Use the ComputeCapability property of the GpuConfig object to set the appropriate compute capability value.

  3. Run the codegen command. The codegen command generates CUDA code from the predict_int8.m MATLAB entry-point function.

    codegen -config cfg -args {coder.Constant('mySqueezenet.mat'),...
    ones(inputSize} predict_int8 -d codegen_int8

  4. When code generation is successful, you can view the resulting code generation report by clicking View Report in the MATLAB Command Window. The report is displayed in the Report Viewer window. If the code generator detects errors or warnings during code generation, the report describes the issues and provides links to the problematic MATLAB code. See Code Generation Reports.

    Code generation successful: View report

Run the Generated MEX

  1. The image that you want to classify must have the same size as the input size of the network. Read the image that you want to classify and resize it to the input size of the network. This resizing slightly changes the aspect ratio of the image.

    testImage = imread("MerchDataTest.jpg");
    testImage = imresize(testImage,inputSize(1:2));
  2. Call SqueezeNet predict on the input image.

    predictScores(:,1) =  predict(netTransfer,testImage)';
    predictScores(:,2) = predict_int8_mex('mySqueezenet.mat',testImage);
  3. Display the predicted labels and their associated probabilities as a histogram.

    h = figure;
    h.Position(3) = 2*h.Position(3);
    ax1 = subplot(1,2,1);
    ax2 = subplot(1,2,2);
    ax2.XLim = [0 1.1];
    ax2.YAxisLocation = 'left';
    legend('Matlab Single','cuDNN 8-bit integer');
    sgtitle('Predictions using Squeezenet')

    Prediction outputs from the MATLAB and generated code. Input test image is MathWorks cube. Predicted result is MathWorks cube with 100% probability.


The following layers are not supported for 8-bit integer quantization when targeting the NVIDIA CUDA deep neural network library (cuDNN) library.

  • leakyReluLayer

  • clippedReluLayer

  • averagePooling2dLayer

  • globalAveragePooling2dLayer

See Also




Related Topics