%% Deploy Quantized Network Example
% This example shows how to train, compile, and deploy a dlhdl.Workflow object that has quantized Alexnet as the network object by using the Deep Learning HDL Toolbox™ Support Package for Xilinx FPGA and SoC. Quantization helps reduce the memory requirement of a deep neural network by quantizing weights, biases and activations of network layers to 8-bit scaled integer data types. Use MATLAB® to retrieve the prediction results from the target device.
%% Required Products
% For this example, you need:
% Deep Learning Toolbox ™
% Deep Learning HDL Toolbox ™
% Deep Learning Toolbox Model Quantization Library
% Deep Learning HDL Toolbox Support Package for Xilinx FPGA and SoC Devices
% MATLAB Coder Interface for Deep Learning Libraries.
%
%
%% Load Pretrained SeriesNetwork
% To load the pretrained series network AlexNet, enter:

snet = alexnet;

% To view the layers of the pretrained series network, enter:

analyzeNetwork(snet);

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

inputSize = snet.Layers(1).InputSize;

% inputSize = 1×3
%    227   227     3
%
%% Define Training and Validation Data Sets
% This example uses the logos_dataset data set. The data set consists of 320 images. Create an augmentedImageDatastore object to use for training and validation.

curDir = pwd;
newDir = fullfile(matlabroot,'examples','deeplearning_shared','data','logos_dataset.zip');
copyfile(newDir,curDir,'f');

unzip('logos_dataset.zip');

imds = imageDatastore('logos_dataset', ...
    'IncludeSubfolders',true, ...
    'LabelSource','foldernames');

[imdsTrain,imdsValidation] = splitEachLabel(imds,0.7,'randomized');

%
%% Replace Final Layers
% The last three layers of the pretrained network net are configured for 1000 classes. These three layers must be fine-tuned  for the new classification problem. Extract all the layers, except the last  three layers, from the pretrained network.

layersTransfer = snet.Layers(1:end-3);

% Transfer the layers to the new classification task by replacing the last three  layers with a fully connected layer, a softmax layer, and a  classification output layer. Set the fully connected layer to have the same size as the number of classes in the new data.

numClasses = numel(categories(imdsTrain.Labels));

% numClasses = 32

layers = [
    layersTransfer
    fullyConnectedLayer(numClasses,'WeightLearnRateFactor',20,'BiasLearnRateFactor',20)
    softmaxLayer
    classificationLayer];

%
%
%% Train Network
% 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, such as  randomly flipping the training images along the vertical axis and randomly  translating them up to 30 pixels horizontally and vertically. Data  augmentation helps prevent the network from overfitting and memorizing  the exact details of the training images.


pixelRange = [-30 30];
imageAugmenter = imageDataAugmenter( ...
    'RandXReflection',true, ...
    'RandXTranslation',pixelRange, ...
    'RandYTranslation',pixelRange);
augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain, ...
    'DataAugmentation',imageAugmenter);

% 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);

% 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. Specify the mini-batch size and  validation data. The software validates the network every ValidationFrequency iterations during training.


options = trainingOptions('sgdm', ...
    'MiniBatchSize',10, ...
    'MaxEpochs',6, ...
    'InitialLearnRate',1e-4, ...
    'Shuffle','every-epoch', ...
    'ValidationData',augimdsValidation, ...
    'ValidationFrequency',3, ...
    'Verbose',false, ...
    'Plots','training-progress');

% Train the network that consists of the transferred and new layers. By default, trainNetwork uses a GPU if one is available (requires Parallel Computing Toolbox™  and a supported GPU device. For more information, see GPU Support by Release).  Otherwise, the network uses a CPU (requires MATLAB Coder Interface for Deep learning Libraries™). You can also specify the execution environment by using the 'ExecutionEnvironment' name-value argument of trainingOptions.
%

netTransfer = trainNetwork(augimdsTrain,layers,options);

%
%% Create dlquantizer Object
% Create a dlquantizer object and specify the network to quantize. Specify the execution environment as FPGA.

dlQuantObj = dlquantizer(netTransfer,'ExecutionEnvironment','FPGA');

%
%% Calibrate Quantized Network
% The dlquantizer object uses calibration data to collect dynamic ranges for the learnable parameters of the convolution and fully connected layers of the network.
% For best quantization results, the calibration data must be a representative of actual inputs predicted by the LogoNet network. Expedite the calibration process by reducing the calibration data set to 20 images.

imageData = imageDatastore(fullfile(curDir,'logos_dataset'),...
 'IncludeSubfolders',true,'FileExtensions','.JPG','LabelSource','foldernames');
imageData_reduced = imageData.subset(1:20);
dlQuantObj.calibrate(imageData_reduced)

%
%% Create Target Object
% Create a target object with a custom name for your target device and an interface to connect your target device to the host computer. Interface options are JTAG and Ethernet. To use JTAG, install Xilinx™ Vivado™ Design Suite 2020.1. To set the Xilinx Vivado toolpath, enter:

% hdlsetuptoolpath('ToolName', 'Xilinx Vivado', 'ToolPath', 'C:\Xilinx\Vivado\2020.1\bin\vivado.bat');

% To create the target object, enter:

hTarget = dlhdl.Target('Xilinx','Interface','Ethernet');

% Alternatively, you can also use the JTAG interface.

% hTarget = dlhdl.Target('Xilinx', 'Interface', 'JTAG');

%
%% Create Workflow Object
% Create an object of the dlhdl.Workflow class. When you create the class, an instance of the dlquantizer object, the bitstream name, and the target information are specified. Specify dlQuantObj as the network. Make sure that the bitstream name matches the data type and the FPGA board that you are targeting. In this example, the target FPGA board is the Xilinx ZCU102 SOC board and the bitstream uses the int8 data type.

hW = dlhdl.Workflow('Network', dlQuantObj, 'Bitstream', 'zcu102_int8','Target',hTarget);

%
%
%% Compile the Quantized Series Network
% To compile the quantized AlexNet series network, run the compile function of the dlhdl.Workflow object.

dn = hW.compile

%
%
%% Program Bitstream onto FPGA and Download Network Weights
% To deploy the network on the Xilinx ZCU102 SoC hardware, run the deploy function of the dlhdl.Workflow object. This function uses the output of the compile function to program the FPGA board by using the programming file. It also downloads the network weights and biases. The deploy function starts programming the FPGA device, displays progress messages, and the time it takes to deploy the network.

hW.deploy

%
%% Load Example Images and Run the Prediction
% To load the example image, execute the predict function of the dlhdl.Workflow object, and then display the FPGA result, enter:

idx = randperm(numel(imdsValidation.Files),4);
figure
for i = 1:4
    subplot(2,2,i)
    I = readimage(imdsValidation,idx(i));
    imshow(I)
    [prediction, speed] = hW.predict(single(I),'Profile','on');
    [val, index] = max(prediction);
    netTransfer.Layers(end).ClassNames{index}
    label = netTransfer.Layers(end).ClassNames{index}
    title(string(label));
end

%
%
%% See Also
% dlquantizer
% calibrate
% dlhdl.Workflow
% Quantization of Deep Neural Networks
% Prototype Deep learning Networks on FPGAs and SOCs
%
%
% Copyright 2020 The MathWorks, Inc.