quantize a deep neural network to 8-凯发k8网页登录
quantize a deep neural network to 8-bit scaled integer data types
since r2020a
description
use the deep network quantizer app to reduce the memory requirement of a deep neural network by quantizing weights, biases, and activations of convolution layers to 8-bit scaled integer data types. using this app you can:
visualize the dynamic ranges of convolution layers in a deep neural network.
select individual network layers to quantize.
assess the performance of a quantized network.
generate gpu code to deploy the quantized network using gpu coder™.
generate hdl code to deploy the quantized network to an fpga using deep learning hdl toolbox™.
generate c code to deploy the quantized network to an arm cortex-a microcontroller using matlab® coder™.
generate a simulatable quantized network that you can explore in matlab without generating code or deploying to hardware.
this app requires . to learn about the products required to quantize a deep neural network, see .
open the deep network quantizer app
matlab command prompt: enter
deepnetworkquantizer
.matlab toolstrip: on the apps tab, under machine learning and deep learning, click the app icon.
examples
quantize a network for gpu deployment
this example uses:
to explore the behavior of a neural network with quantized convolution layers, use the deep network quantizer app. this example quantizes the learnable parameters of the convolution layers of the squeezenet
neural network after retraining the network to classify new images according to the example.
this example uses a dag network with the gpu execution environment.
load the network to quantize into the base workspace.
load squeezenetmerch
net
net = dagnetwork with properties: layers: [68×1 nnet.cnn.layer.layer] connections: [75×2 table] inputnames: {'data'} outputnames: {'new_classoutput'}
define calibration and validation data.
the app uses calibration data to exercise the network and collect 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. for the best quantization results, the calibration data must be representative of inputs to the network.
the app uses the validation data to test the network after quantization to understand the effects of the limited range and precision of the quantized learnable parameters of the convolution layers in the network.
in this example, use the images in the merchdata
data set. define an augmentedimagedatastore
object to resize the data for the network. then, split the data into calibration and validation data sets.
unzip('merchdata.zip'); imds = imagedatastore('merchdata', ... 'includesubfolders',true, ... 'labelsource','foldernames'); [caldata, valdata] = spliteachlabel(imds, 0.7, 'randomized'); aug_caldata = augmentedimagedatastore([227 227], caldata); aug_valdata = augmentedimagedatastore([227 227], valdata);
at the matlab command prompt, open the app.
deepnetworkquantizer
in the app, click new and select quantize a network
.
the app verifies your execution environment. for more information, see .
in the dialog, select the execution environment and the network to quantize from the base workspace. for this example, select a gpu execution environment and the dag network, net
.
the app displays the layer graph of the selected network.
in the calibrate section of the toolstrip, under calibration data, select the augmentedimagedatastore
object from the base workspace containing the calibration data, aug_caldata
. select calibrate.
the deep network quantizer uses the calibration data to exercise the network and collect range information for the learnable parameters in the network layers.
when the calibration is complete, the app displays a table containing 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 and their minimum and maximum values during the calibration. to the right of the table, the app displays histograms of the dynamic ranges of the parameters. the gray regions of the histograms indicate data that cannot be represented by the quantized representation. for more information on how to interpret these histograms, see quantization of deep neural networks.
in the quantize column of the table, indicate whether to quantize the learnable parameters in the layer. layers that are not quantized remain in single-precision after quantization.
in the validate section of the toolstrip, under validation data, select the augmentedimagedatastore
object from the base workspace containing the validation data, aug_valdata
.
in the validate section of the toolstrip, under quantization options, select the default metric function and minmax exponent scheme. select quantize and validate.
the deep network quantizer quantizes the weights, activations, and biases of convolution layers in the network to scaled 8-bit integer data types and uses the validation data to exercise the network. the app determines a default metric function to use for the validation based on the type of network that is being quantized. for a classification network, the app uses top-1 accuracy.
when the validation is complete, the app displays the results of the validation, including:
metric function used for validation
result of the metric function before and after quantization
memory requirement of the network before and after quantization (mb)
if you want to use a different metric function for validation, for example to use the top-5 accuracy metric function instead of the default top-1 accuracy metric function, you can define a custom metric function. 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 end % sum all prediction errors. predictionerror = [predictionerror{:}]; accuracy = sum(predictionerror)/numel(predictionerror); end
to revalidate the network using this custom metric function, under quantization options, enter the name of the custom metric function, hcomputemodelaccuracy
. select add to add hcomputemodelaccuracy
to the list of metric functions available in the app. select hcomputemodelaccuracy
as the metric function to use.
the custom metric function must be on the path. if the metric function is not on the path, this step will produce an error.
select quantize and validate.
the app quantizes the network and displays the validation results for the custom metric function.
the app displays only scalar values in the validation results table. to view the validation results for a custom metric function with non-scalar output, export the dlquantizer
object as described below, then validate using the function at the matlab command window.
if the performance of the quantized network is not satisfactory, you can choose to not quantize some layers by deselecting the layer in the table. you can also explore the effects of choosing a different exponent selection scheme for quantization in the quantization options menu. to see the effects of these changes, select quantize and validate again.
after calibrating the network, you can choose to export the quantized network or the dlquantizer
object. select the export button. in the drop down, select from the following options:
export quantized network - add the quantized network to the base workspace. this option exports a simulatable quantized network that you can explore in matlab without deploying to hardware.
export quantizer - add the
dlquantizer
object to the base workspace. you can save thedlquantizer
object and use it for further exploration in the deep network quantizer app or at the command line, or use it to generate code for your target hardware.generate code - open the gpu coder app and generate gpu code from the quantized neural network. generating gpu code requires a gpu coder™ license.
quantize a network for cpu deployment
this example uses:
to explore the behavior of a neural network with quantized convolution layers, use the deep network quantizer app. this example quantizes the learnable parameters of the convolution layers of the squeezenet
neural network after retraining the network to classify new images according to the example.
this example uses a dag network with the cpu execution environment.
load the network to quantize into the base workspace.
load squeezenetmerch
net
net = dagnetwork with properties: layers: [68×1 nnet.cnn.layer.layer] connections: [75×2 table] inputnames: {'data'} outputnames: {'new_classoutput'}
define calibration and validation data.
the app uses calibration data to exercise the network and collect 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. for the best quantization results, the calibration data must be representative of inputs to the network.
the app uses the validation data to test the network after quantization to understand the effects of the limited range and precision of the quantized learnable parameters of the convolution layers in the network.
in this example, use the images in the merchdata
data set. define an augmentedimagedatastore
object to resize the data for the network. then, split the data into calibration and validation data sets.
unzip('merchdata.zip'); imds = imagedatastore('merchdata', ... 'includesubfolders',true, ... 'labelsource','foldernames'); [caldata, valdata] = spliteachlabel(imds, 0.7, 'randomized'); aug_caldata = augmentedimagedatastore([227 227], caldata); aug_valdata = augmentedimagedatastore([227 227], valdata);
at the matlab command prompt, open the app.
deepnetworkquantizer
in the app, click new and select quantize a network
.
the app verifies your execution environment. for more information, see .
in the dialog, select the execution environment and the network to quantize from the base workspace. for this example, select a cpu execution environment and the dag network, net
.
the app displays the layer graph of the selected network.
in the calibrate section of the toolstrip, under calibration data, select the augmentedimagedatastore
object from the base workspace containing the calibration data, aug_caldata
. select calibrate.
the deep network quantizer uses the calibration data to exercise the network and collect range information for the learnable parameters in the network layers.
when the calibration is complete, the app displays a table containing 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 and their minimum and maximum values during the calibration. to the right of the table, the app displays histograms of the dynamic ranges of the parameters. the gray regions of the histograms indicate data that cannot be represented by the quantized representation. for more information on how to interpret these histograms, see quantization of deep neural networks.
in the quantize column of the table, indicate whether to quantize the learnable parameters in the layer. layers that are not quantized remain in single-precision after quantization.
in the validate section of the toolstrip, under validation data, select the augmentedimagedatastore
object from the base workspace containing the validation data, aug_valdata
.
in the validate section of the toolstrip, under hardware settings, select raspberry pi as the simulation environment. the app auto-populates the target credentials from an existing connection or from the last successful connection. you can also use this option to create a new raspberry pi connection.
in the validate section of the toolstrip, under quantization options, select the default metric function and minmax exponent scheme. select quantize and validate.
the deep network quantizer quantizes the weights, activations, and biases of convolution layers in the network to scaled 8-bit integer data types and uses the validation data to exercise the network. the app determines a default metric function to use for the validation based on the type of network that is being quantized. for a classification network, the app uses top-1 accuracy.
when the validation is complete, the app displays the results of the validation, including:
metric function used for validation
result of the metric function before and after quantization
memory requirement of the network before and after quantization (mb)
if the performance of the quantized network is not satisfactory, you can choose to not quantize some layers by deselecting the layer in the table. you can also explore the effects of choosing a different exponent selection scheme for quantization in the quantization options menu. to see the effects of these changes, select quantize and validate again.
after calibrating the network, you can choose to export the quantized network or the dlquantizer
object. select the export button. in the drop down, select from the following options:
export quantized network - add the quantized network to the base workspace. this option exports a simulatable quantized network that you can explore in matlab without deploying to hardware.
export quantizer - add the
dlquantizer
object to the base workspace. you can save thedlquantizer
object and use it for further exploration in the deep network quantizer app or at the command line, or use it to generate code for your target hardware.generate code - open the matlab coder app and generate c code from the quantized neural network. generating c code requires a matlab coder™ license.
quantize a network for fpga deployment
to explore the behavior of a neural network that has quantized
convolution layers, use the deep network quantizer app. this example
quantizes the learnable parameters of the convolution layers of the
logonet
neural network for an fpga target.
for this example, you need the products listed under fpga
in .
load the pretrained network to quantize into the base workspace. create a file in
your current working folder called getlogonetwork.m
. in the file,
enter:
function net = getlogonetwork if ~isfile('logonet.mat') url = 'https://www.mathworks.com/supportfiles/gpucoder/cnn_models/logo_detection/logonet.mat'; websave('logonet.mat',url); end data = load('logonet.mat'); net = data.convnet; end
load the pretrained network.
snet = getlogonetwork;
snet = seriesnetwork with properties: layers: [22×1 nnet.cnn.layer.layer] inputnames: {'imageinput'} outputnames: {'classoutput'}
define calibration and validation data to use for quantization.
the deep network quantizer app uses calibration data to exercise the network and collect the dynamic ranges of the weights and biases in the convolution and fully connected layers of the network. the app also exercises the dynamic ranges of the activations in all layers of the logonet network. for the best quantization results, the calibration data must be representative of inputs to the logonet network.
after quantization, the app uses the validation data set to test the network to understand the effects of the limited range and precision of the quantized learnable parameters of the convolution layers in the network.
in this example, use the images in the logos_dataset
data set
to calibrate and validate the logonet network. define an
imagedatastore
object, then split the data into calibration and
validation data sets.
expedite the calibration and validation process for this example by using a subset
of the calibration and validation data. store the new reduced calibration data set
in caldata_concise
and the new reduced validation data set in
valdata_concise
.
currentdir = pwd; openexample('deeplearning_shared/quantizenetworkforfpgadeploymentexample') unzip('logos_dataset.zip'); imds = imagedatastore(fullfile(currentdir,'logos_dataset'),... 'includesubfolders',true,'fileextensions','.jpg','labelsource','foldernames'); [caldata,valdata] = spliteachlabel(imds,0.7,'randomized'); caldata_concise = caldata.subset(1:20); valdata_concise = valdata.subset(1:6);
open the deep network quantizer app.
deepnetworkquantizer
click new and select quantize a
network
.
set the execution environment to fpga and select snet -
seriesnetwork
as the network to quantize.
the app displays the layer graph of the selected network.
under calibration data, select the caldata_concise -
imagedatastore
object from the base workspace containing the
calibration data.
click calibrate. by default, the app uses the host gpu to collect calibration data, if one is available. otherwise, the host cpu is used. you can use the calibrate drop down menu to select the calibration environment.
the deep network quantizer app uses the calibration data to exercise the network and collect range information for the learnable parameters in the network layers.
when the calibration is complete, the app displays a table containing the weights and biases in the convolution and fully connected layers of the network. also displayed are the dynamic ranges of the activations in all layers of the network and their minimum and maximum values recorded during the calibration. the app displays histograms of the dynamic ranges of the parameters. the gray regions of the histograms indicate data that cannot be represented by the quantized representation. for more information on how to interpret these histograms, see quantization of deep neural networks.
in the quantize layer column of the table, indicate whether to quantize the learnable parameters in the layer. layers that are not quantized remain in single-precision.
under validation data, select the valdata_concise -
imagedatastore
object from the base workspace containing the validation
data.
in the hardware settings section of the toolstrip, select the environment to use for validation of the quantized network. for more information on these options, see hardware settings.
for this example, select xilinx zc706 (zc706_int8) and jtag.
under quantization options, select the default metric function and minmax exponent scheme. for more information on these options, see quantization options.
click quantize and validate.
the deep network quantizer app quantizes the weights, activations, and biases of convolution layers in the network to scaled 8-bit integer data types and uses the validation data to exercise the network. the app determines a default metric function to use for the validation based on the type of network that is being quantized. for more information, see quantization options.
when the validation is complete, the app displays the validation results.
after quantizing and validating the network, you can choose to export the quantized network.
click the export button. in the drop-down list, select
export quantizer to create a
dlquantizer
object in the base workspace. you can deploy the
quantized network to your target fpga board and retrieve the prediction results by
using matlab. for an example, see classify images on fpga using quantized neural network (deep learning hdl toolbox).
import a dlquantizer
object into the deep network quantizer app
this example shows you how to import a dlquantizer
object from the base workspace into the deep network quantizer app. this allows you to begin quantization of a deep neural network using the command line or the app, and resume your work later in the app.
open the deep network quantizer app.
deepnetworkquantizer
in the app, click new and select import dlquantizer object
.
in the dialog, select the dlquantizer
object to import from the
base workspace. for this example, use quantobj
that you create in
the above example quantize a neural network for gpu target.
the app imports any data contained in the dlquantizer
object that
was collected at the command line. this data can include the network to quantize,
calibration data, validation data, and calibration statistics.
the app displays a table containing the calibration data contained in the imported
dlquantizer
object, quantobj
. to the right
of the table, the app displays histograms of the dynamic ranges of the parameters.
the gray regions of the histograms indicate data that cannot be represented by the
quantized representation. for more information on how to interpret these histograms,
see quantization of deep neural networks.
related examples
parameters
execution environment
— execution environment
gpu
(default) | fpga
| cpu
| matlab
when you select new > quantize a network, the app allows you to choose the execution environment for the quantized network. how the network is quantized depends on the choice of execution environment.
when you select the matlab
execution environment, the app
performs target-agnostic quantization of the neural network. this option does not
require you to have target hardware in order to explore the quantized network in
matlab.
hardware settings
— hardware settings
simulation environment | target
specify hardware settings based on your execution environment.
gpu execution environment
select from the following simulation environments:
simulation environment action gpu
simulate on host gpu
deploys the quantized network to the host gpu. validates the quantized network by comparing performance to single-precision version of the network.
matlab
simulate in matlab
simulates the quantized network in matlab. validates the quantized network by comparing performance to single-precision version of the network.
fpga execution environment
select from the following simulation environments:
simulation environment action co-simulation
simulate with dlhdl.simulator
simulates the quantized network in matlab using (deep learning hdl toolbox). validates the quantized network by comparing performance to single-precision version of the network. intel arria 10 soc
arria10soc_int8
deploys the quantized network to an intel® arria® 10 soc board by using the
arria10soc_int8
bitstream. validates the quantized network by comparing performance to single-precision version of the network.xilinx zcu102
zcu102_int8
deploys the quantized network to a xilinx® zynq® ultrascale ™ mpsoc zcu102 10 soc board by using the
zcu102_int8
bitstream. validates the quantized network by comparing performance to single-precision version of the network.xilinx zc706
zc706_int8
deploys the quantized network to a xilinx zynq-7000 zc706 board by using the
zc706_int8
bitstream. validates the quantized network by comparing performance to single-precision version of the network.when you select the intel arria 10 soc, xilinx zcu102, or xilinx zc706 option, additionally select the interface to use to deploy and validate the quantized network.
target option action jtag programs the target fpga board selected under simulation environment by using a jtag cable. for more information, see (deep learning hdl toolbox). ethernet programs the target fpga board selected in simulation environment through the ethernet interface. specify the ip address for your target board in the ip address field. cpu execution environment
select from the following simulation environments:
simulation environment action raspberry pi
deploys the quantized network to the raspberry pi board. validates the quantized network by comparing performance to single-precision version of the network.
when you select the raspberry pi option, additionally specify the following details for the
raspi
connection.target option description hostname hostname of the board, specified as a string. username linux® username, specified as a string. password linux user password, specified as a string.
quantization options
— options for quantization and validation
metric function | exponent scheme
by default, the deep network quantizer app determines a metric function to use for the validation based on the type of network that is being quantized.
type of network | metric function |
---|---|
classification | top-1 accuracy – accuracy of the network |
object detection | average precision – average precision over all detection results. see (computer vision toolbox). |
regression | mse – mean squared error of the network |
semantic segmentation | weightediou – average iou of each class, weighted by the number of pixels in that class. see (computer vision toolbox). |
you can also specify a custom metric function to use for validation.
you can select the exponent selection scheme to use for quantization of the network:
minmax — (default) evaluate the exponent based on the range information in the calibration statistics and avoid overflows.
histogram — distribution-based scaling which evaluates the exponent to best fit the calibration data.
export
— options for exporting quantized network
export quantized network
| export quantizer
| generate code
export quantized network — after calibrating the network, quantize and add the quantized network to the base workspace. this option exports a simulatable quantized network,
quantizednet
, that you can explore in matlab without deploying to hardware. this option is equivalent to using at the command line.code generation is not supported for the exported quantized network,
quantizednet
.export quantizer — add the object to the base workspace. you can save the
dlquantizer
object and use it for further exploration in the deep network quantizer app or at the command line, or use it to generate code for your target hardware.generate code
execution environment code generation gpu open the gpu coder app and generate gpu code from the quantized and validated neural network. generating gpu code requires a gpu coder license. cpu open the matlab coder app and generate c code from the quantized and validated neural network. generating c code requires a matlab coder license.
version history
introduced in r2020ar2023a: specify raspberry pi connection in hardware settings
you can now validate the quantized network on a raspberry pi® board by selecting raspberry pi in
hardware settings
and specifying target credentials for a
raspi
object in the validation step.
r2022b: calibrate on host gpu or host cpu
you can now choose whether to calibrate your network using the host gpu or host cpu. by
default, the calibrate
function and the deep network
quantizer app will calibrate on the host gpu if one is available.
in previous versions, it was required that the execution environment be the same as the instrumentation environment used for the calibration step of quantization.
r2022b: dlnetwork
support
the deep network quantizer app now supports calibration and validation for
dlnetwork
objects.
r2022a: validate the performance of quantized network for cpu target
the deep network quantizer app now supports the quantization and validation workflow for cpu targets.
r2022a: quantize neural networks without a specific target
specify matlab
as the execution environment
to
quantize your neural networks without generating code or committing to a specific target for
code deployment. this can be useful if you:
do not have access to your target hardware.
want to inspect your quantized network without generating code.
your quantized network implements int8
data instead of
single
data. it keeps the same layers and connections as the original
network, and it has the same inference behavior as it would when running on hardware.
once you have quantized your network, you can use the
quantizationdetails
function to inspect your quantized network.
additionally, you also have the option to deploy the code to a gpu target.
see also
functions
- | | | | | |
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)