CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/main/prototype_source/numeric_suite_tutorial.py
Views: 494
# -*- coding: utf-8 -*-1"""2PyTorch Numeric Suite Tutorial3==============================45Introduction6------------78Quantization is good when it works, but it’s difficult to know what's wrong when it doesn't satisfy the accuracy we expect. Debugging the accuracy issue of quantization is not easy and time consuming.910One important step of debugging is to measure the statistics of the float model and its corresponding quantized model to know where are they differ most. We built a suite of numeric tools called PyTorch Numeric Suite in PyTorch quantization to enable the measurement of the statistics between quantized module and float module to support quantization debugging efforts. Even for the quantized model with good accuracy, PyTorch Numeric Suite can still be used as the profiling tool to better understand the quantization error within the model and provide the guidance for further optimization.1112PyTorch Numeric Suite currently supports models quantized through both static quantization and dynamic quantization with unified APIs.1314In this tutorial we will first use ResNet18 as an example to show how to use PyTorch Numeric Suite to measure the statistics between static quantized model and float model in eager mode. Then we will use LSTM based sequence model as an example to show the usage of PyTorch Numeric Suite for dynamic quantized model.1516Numeric Suite for Static Quantization17-------------------------------------1819Setup20^^^^^^21We’ll start by doing the necessary imports:22"""2324##############################################################################2526import numpy as np27import torch28import torch.nn as nn29import torchvision30from torchvision import models, datasets31import torchvision.transforms as transforms32import os33import torch.quantization34import torch.quantization._numeric_suite as ns35from torch.quantization import (36default_eval_fn,37default_qconfig,38quantize,39)4041##############################################################################42# Then we load the pretrained float ResNet18 model, and quantize it into qmodel. We cannot compare two arbitrary models, only a float model and the quantized model derived from it can be compared.434445float_model = torchvision.models.quantization.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1, quantize=False)46float_model.to('cpu')47float_model.eval()48float_model.fuse_model()49float_model.qconfig = torch.quantization.default_qconfig50img_data = [(torch.rand(2, 3, 10, 10, dtype=torch.float), torch.randint(0, 1, (2,), dtype=torch.long)) for _ in range(2)]51qmodel = quantize(float_model, default_eval_fn, [img_data], inplace=False)5253##############################################################################54# 1. Compare the weights of float and quantized models55# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^56# The first thing we usually want to compare are the weights of quantized model and float model.57# We can call ``compare_weights()`` from PyTorch Numeric Suite to get a dictionary ``wt_compare_dict`` with key corresponding to module names and each entry is a dictionary with two keys 'float' and 'quantized', containing the float and quantized weights.58# ``compare_weights()`` takes in floating point and quantized state dict and returns a dict, with keys corresponding to the59# floating point weights and values being a dictionary of floating point and quantized weights6061wt_compare_dict = ns.compare_weights(float_model.state_dict(), qmodel.state_dict())6263print('keys of wt_compare_dict:')64print(wt_compare_dict.keys())6566print("\nkeys of wt_compare_dict entry for conv1's weight:")67print(wt_compare_dict['conv1.weight'].keys())68print(wt_compare_dict['conv1.weight']['float'].shape)69print(wt_compare_dict['conv1.weight']['quantized'].shape)707172##############################################################################73# Once get ``wt_compare_dict``, users can process this dictionary in whatever way they want. Here as an example we compute the quantization error of the weights of float and quantized models as following.74# Compute the Signal-to-Quantization-Noise Ratio (SQNR) of the quantized tensor ``y``. The SQNR reflects the75# relationship between the maximum nominal signal strength and the quantization error introduced in the76# quantization. Higher SQNR corresponds to lower quantization error.7778def compute_error(x, y):79Ps = torch.norm(x)80Pn = torch.norm(x-y)81return 20*torch.log10(Ps/Pn)8283for key in wt_compare_dict:84print(key, compute_error(wt_compare_dict[key]['float'], wt_compare_dict[key]['quantized'].dequantize()))8586##############################################################################87# As another example ``wt_compare_dict`` can also be used to plot the histogram of the weights of floating point and quantized models.8889import matplotlib.pyplot as plt9091f = wt_compare_dict['conv1.weight']['float'].flatten()92plt.hist(f, bins = 100)93plt.title("Floating point model weights of conv1")94plt.show()9596q = wt_compare_dict['conv1.weight']['quantized'].flatten().dequantize()97plt.hist(q, bins = 100)98plt.title("Quantized model weights of conv1")99plt.show()100101102103##############################################################################104#105# 2. Compare float point and quantized models at corresponding locations106# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^107#108# The second tool allows for comparison of weights and activations between float and quantized models at corresponding locations for the same input as shown in the figure below. Red arrows indicate the locations of the comparison.109#110# .. figure:: /_static/img/compare_output.png111#112# We call ``compare_model_outputs()`` from PyTorch Numeric Suite to get the activations in float model and quantized model at corresponding locations for the given input data. This API returns a dict with module names being keys. Each entry is itself a dict with two keys 'float' and 'quantized' containing the activations.113data = img_data[0][0]114115# Take in floating point and quantized model as well as input data, and returns a dict, with keys116# corresponding to the quantized module names and each entry being a dictionary with two keys 'float' and117# 'quantized', containing the activations of floating point and quantized model at matching locations.118act_compare_dict = ns.compare_model_outputs(float_model, qmodel, data)119120print('keys of act_compare_dict:')121print(act_compare_dict.keys())122123print("\nkeys of act_compare_dict entry for conv1's output:")124print(act_compare_dict['conv1.stats'].keys())125print(act_compare_dict['conv1.stats']['float'][0].shape)126print(act_compare_dict['conv1.stats']['quantized'][0].shape)127128##############################################################################129# This dict can be used to compare and compute the quantization error of the activations of float and quantized models as following.130for key in act_compare_dict:131print(key, compute_error(act_compare_dict[key]['float'][0], act_compare_dict[key]['quantized'][0].dequantize()))132133##############################################################################134# If we want to do the comparison for more than one input data, we can do the following.135# Prepare the model by attaching the logger to both floating point module and quantized136# module if they are in the ``white_list``. Default logger is ``OutputLogger``, and default white_list137# is ``DEFAULT_NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_WHITE_LIST``138ns.prepare_model_outputs(float_model, qmodel)139140for data in img_data:141float_model(data[0])142qmodel(data[0])143144# Find the matching activation between floating point and quantized modules, and return a dict with key145# corresponding to quantized module names and each entry being a dictionary with two keys 'float'146# and 'quantized', containing the matching floating point and quantized activations logged by the logger147act_compare_dict = ns.get_matching_activations(float_model, qmodel)148149150##############################################################################151# The default logger used in above APIs is ``OutputLogger``, which is used to log the outputs of the modules. We can inherit from base ``Logger`` class and create our own logger to perform different functionalities. For example we can make a new ``MyOutputLogger`` class as below.152153class MyOutputLogger(ns.Logger):154r"""Customized logger class155"""156157def __init__(self):158super(MyOutputLogger, self).__init__()159160def forward(self, x):161# Custom functionalities162# ...163return x164165##############################################################################166# And then we can pass this logger into above APIs such as:167168data = img_data[0][0]169act_compare_dict = ns.compare_model_outputs(float_model, qmodel, data, logger_cls=MyOutputLogger)170171##############################################################################172# or:173174ns.prepare_model_outputs(float_model, qmodel, MyOutputLogger)175for data in img_data:176float_model(data[0])177qmodel(data[0])178act_compare_dict = ns.get_matching_activations(float_model, qmodel)179180181182##############################################################################183#184# 3. Compare a module in a quantized model with its float point equivalent, with the same input data185# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^186#187# The third tool allows for comparing a quantized module in a model with its float point counterpart, feeding both of them the same input and comparing their outputs as shown below.188#189# .. figure:: /_static/img/compare_stub.png190#191# In practice we call prepare_model_with_stubs() to swap the quantized module that we want to compare with the Shadow module, which is illustrated as below:192#193# .. figure:: /_static/img/shadow.png194#195# The Shadow module takes quantized module, float module and logger as input, and creates a forward path inside to make the float module to shadow quantized module sharing the same input tensor.196#197# The logger can be customizable, default logger is ``ShadowLogger`` and it will save the outputs of the quantized module and float module that can be used to compute the module level quantization error.198#199# Notice before each call of ``compare_model_outputs()`` and ``compare_model_stub()`` we need to have clean float and quantized model. This is because ``compare_model_outputs()`` and ``compare_model_stub()`` modify float and quantized model inplace, and it will cause unexpected results if call one right after another.200201float_model = torchvision.models.quantization.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1, quantize=False)202float_model.to('cpu')203float_model.eval()204float_model.fuse_model()205float_model.qconfig = torch.quantization.default_qconfig206img_data = [(torch.rand(2, 3, 10, 10, dtype=torch.float), torch.randint(0, 1, (2,), dtype=torch.long)) for _ in range(2)]207qmodel = quantize(float_model, default_eval_fn, [img_data], inplace=False)208209##############################################################################210# In the following example we call ``compare_model_stub()`` from PyTorch Numeric Suite to compare ``QuantizableBasicBlock`` module with its float point equivalent. This API returns a dict with key corresponding to module names and each entry being a dictionary with two keys 'float' and 'quantized', containing the output tensors of quantized and its matching float shadow module.211212data = img_data[0][0]213module_swap_list = [torchvision.models.quantization.resnet.QuantizableBasicBlock]214215# Takes in floating point and quantized model as well as input data, and returns a dict with key216# corresponding to module names and each entry being a dictionary with two keys 'float' and217# 'quantized', containing the output tensors of quantized module and its matching floating point shadow module.218ob_dict = ns.compare_model_stub(float_model, qmodel, module_swap_list, data)219220print('keys of ob_dict:')221print(ob_dict.keys())222223print("\nkeys of ob_dict entry for layer1.0's output:")224print(ob_dict['layer1.0.stats'].keys())225print(ob_dict['layer1.0.stats']['float'][0].shape)226print(ob_dict['layer1.0.stats']['quantized'][0].shape)227228##############################################################################229# This dict can be then used to compare and compute the module level quantization error.230231for key in ob_dict:232print(key, compute_error(ob_dict[key]['float'][0], ob_dict[key]['quantized'][0].dequantize()))233234##############################################################################235# If we want to do the comparison for more than one input data, we can do the following.236237ns.prepare_model_with_stubs(float_model, qmodel, module_swap_list, ns.ShadowLogger)238for data in img_data:239qmodel(data[0])240ob_dict = ns.get_logger_dict(qmodel)241242##############################################################################243# The default logger used in above APIs is ``ShadowLogger``, which is used to log the outputs of the quantized module and its matching float shadow module. We can inherit from base ``Logger`` class and create our own logger to perform different functionalities. For example we can make a new ``MyShadowLogger`` class as below.244245class MyShadowLogger(ns.Logger):246r"""Customized logger class247"""248249def __init__(self):250super(MyShadowLogger, self).__init__()251252def forward(self, x, y):253# Custom functionalities254# ...255return x256257##############################################################################258# And then we can pass this logger into above APIs such as:259260data = img_data[0][0]261ob_dict = ns.compare_model_stub(float_model, qmodel, module_swap_list, data, logger_cls=MyShadowLogger)262263##############################################################################264# or:265266ns.prepare_model_with_stubs(float_model, qmodel, module_swap_list, MyShadowLogger)267for data in img_data:268qmodel(data[0])269ob_dict = ns.get_logger_dict(qmodel)270271###############################################################################272# Numeric Suite for Dynamic Quantization273# --------------------------------------274#275# Numeric Suite APIs are designed in such as way that they work for both dynamic quantized model and static quantized model. We will use a model with both LSTM and Linear modules to demonstrate the usage of Numeric Suite on dynamic quantized model. This model is the same one used in the tutorial of dynamic quantization on LSTM word language model [1].276#277278#################################279# Setup280# ^^^^^^281# First we define the model as below. Notice that within this model only ``nn.LSTM`` and ``nn.Linear`` modules will be quantized dynamically and ``nn.Embedding`` will remain as floating point module after quantization.282283class LSTMModel(nn.Module):284"""Container module with an encoder, a recurrent module, and a decoder."""285286def __init__(self, ntoken, ninp, nhid, nlayers, dropout=0.5):287super(LSTMModel, self).__init__()288self.encoder = nn.Embedding(ntoken, ninp)289self.rnn = nn.LSTM(ninp, nhid, nlayers, dropout=dropout)290self.decoder = nn.Linear(nhid, ntoken)291292self.init_weights()293294self.nhid = nhid295self.nlayers = nlayers296297def init_weights(self):298initrange = 0.1299self.encoder.weight.data.uniform_(-initrange, initrange)300self.decoder.bias.data.zero_()301self.decoder.weight.data.uniform_(-initrange, initrange)302303def forward(self, input, hidden):304emb = self.encoder(input)305output, hidden = self.rnn(emb, hidden)306decoded = self.decoder(output)307return decoded, hidden308309def init_hidden(self, bsz):310weight = next(self.parameters())311return (weight.new_zeros(self.nlayers, bsz, self.nhid),312weight.new_zeros(self.nlayers, bsz, self.nhid))313314##############################################################################315# Then we create the ``float_model`` and quantize it into qmodel.316317ntokens = 10318319float_model = LSTMModel(320ntoken = ntokens,321ninp = 512,322nhid = 256,323nlayers = 5,324)325326float_model.eval()327328qmodel = torch.quantization.quantize_dynamic(329float_model, {nn.LSTM, nn.Linear}, dtype=torch.qint8330)331332##############################################################################333#334# 1. Compare the weights of float and quantized models335# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^336#337# We first call ``compare_weights()`` from PyTorch Numeric Suite to get a dictionary ``wt_compare_dict`` with key corresponding to module names and each entry is a dictionary with two keys 'float' and 'quantized', containing the float and quantized weights.338339wt_compare_dict = ns.compare_weights(float_model.state_dict(), qmodel.state_dict())340341##############################################################################342# Once we get ``wt_compare_dict``, it can be used to compare and compute the quantization error of the weights of float and quantized models as following.343344for key in wt_compare_dict:345if wt_compare_dict[key]['quantized'].is_quantized:346print(key, compute_error(wt_compare_dict[key]['float'], wt_compare_dict[key]['quantized'].dequantize()))347else:348print(key, compute_error(wt_compare_dict[key]['float'], wt_compare_dict[key]['quantized']))349350##############################################################################351#352# The Inf value in ``encoder.weight`` entry above is because encoder module is not quantized and the weights are the same in both floating point and quantized models.353#354# 2. Compare float point and quantized models at corresponding locations355# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^356#357# Then we call ``compare_model_outputs()`` from PyTorch Numeric Suite to get the activations in float model and quantized model at corresponding locations for the given input data. This API returns a dict with module names being keys. Each entry is itself a dict with two keys 'float' and 'quantized' containing the activations. Notice that this sequence model has two inputs, and we can pass both inputs into ``compare_model_outputs()`` and ``compare_model_stub()``.358359360input_ = torch.randint(ntokens, (1, 1), dtype=torch.long)361hidden = float_model.init_hidden(1)362363act_compare_dict = ns.compare_model_outputs(float_model, qmodel, input_, hidden)364print(act_compare_dict.keys())365366##############################################################################367# This dict can be used to compare and compute the quantization error of the activations of float and quantized models as following. The LSTM module in this model has two outputs, in this example we compute the error of the first output.368369370for key in act_compare_dict:371print(key, compute_error(act_compare_dict[key]['float'][0][0], act_compare_dict[key]['quantized'][0][0]))372373##############################################################################374#375# 3. Compare a module in a quantized model with its float point equivalent, with the same input data376# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^377#378# Next we call ``compare_model_stub()`` from PyTorch Numeric Suite to compare LSTM and Linear module with its float point equivalent. This API returns a dict with key corresponding to module names and each entry being a dictionary with two keys 'float' and 'quantized', containing the output tensors of quantized and its matching float shadow module.379#380# We reset the model first.381382383float_model = LSTMModel(384ntoken = ntokens,385ninp = 512,386nhid = 256,387nlayers = 5,388)389float_model.eval()390391qmodel = torch.quantization.quantize_dynamic(392float_model, {nn.LSTM, nn.Linear}, dtype=torch.qint8393)394395##############################################################################396# Next we call ``compare_model_stub()`` from PyTorch Numeric Suite to compare LSTM and Linear module with its float point equivalent. This API returns a dict with key corresponding to module names and each entry being a dictionary with two keys 'float' and 'quantized', containing the output tensors of quantized and its matching float shadow module.397398module_swap_list = [nn.Linear, nn.LSTM]399ob_dict = ns.compare_model_stub(float_model, qmodel, module_swap_list, input_, hidden)400print(ob_dict.keys())401402##############################################################################403# This dict can be then used to compare and compute the module level quantization error.404405for key in ob_dict:406print(key, compute_error(ob_dict[key]['float'][0], ob_dict[key]['quantized'][0]))407408##############################################################################409# SQNR of 40 dB is high and this is a situation where we have very good numerical alignment between the floating point and quantized model.410#411# Conclusion412# ----------413# In this tutorial, we demonstrated how to use PyTorch Numeric Suite to measure and compare the statistics between quantized model and float model in eager mode with unified APIs for both static quantization and dynamic quantization.414#415# Thanks for reading! As always, we welcome any feedback, so please create an issue `here <https://github.com/pytorch/pytorch/issues>`_ if you have any.416#417# References418# ----------419# [1] `DYNAMIC QUANTIZATION ON AN LSTM WORD LANGUAGE MODEL <https://pytorch.org/tutorials/advanced/dynamic_quantization_tutorial.html>`_.420421422