* refactor toc * refactor toc * Change to pydata-sphinx-theme and update packages requirement list for ReadtheDocs * Remove customized css for old theme * Add index page to each top bar section and limit dropdown maximum to be 4 * Use js to change 'More' to 'Libraries' * Add custom.css to conf.py for further css changes * Add BigDL logo and search bar * refactor toc * refactor toc and add overview * refactor toc and add overview * refactor toc and add overview * refactor get started * add paper and video section * add videos * add grid columns in landing page * add document roadmap to index * reapply search bar and github icon commit * reorg orca and chronos sections * Test: weaken ads by js * update: change left attrbute * update: add comments * update: change opacity to 0.7 * Remove useless theme template override for old theme * Add sidebar releases component in the home page * Remove sidebar search and restore top nav search button * Add BigDL handouts * Add back to homepage button to pages except from the home page * Update releases contents & styles in left sidebar * Add version badge to the top bar * Test: weaken ads by js * update: add comments * remove landing page contents * rfix chronos install * refactor install * refactor chronos section titles * refactor nano index * change chronos landing * revise chronos landing page * add document navigator to nano landing page * revise install landing page * Improve css of versions in sidebar * Make handouts image pointing to a page in new tab * add win guide to install * add dliib installation * revise title bar * rename index files * add index page for user guide * add dllib and orca API * update user guide landing page * refactor side bar * Remove extra style configuration of card components & make different card usage consistent * Remove extra styles for Nano how-to guides * Remove extra styles for Chronos how-to guides * Remove dark mode for now * Update index page description * Add decision tree for choosing BigDL libraries in index page * add dllib models api, revise core layers formats * Change primary & info color in light mode * Restyle card components * Restructure Chronos landing page * Update card style * Update BigDL library selection decision tree * Fix failed Chronos tutorials filter * refactor PPML documents * refactor and add friesian documents * add friesian arch diagram * update landing pages and fill key features guide index page * Restyle link card component * Style video frames in PPML sections * Adjust Nano landing page * put api docs to the last in index for convinience * Make badge horizontal padding smaller & small changes * Change the second letter of all header titles to be small capitalizd * Small changes on Chronos index page * Revise decision tree to make it smaller * Update: try to change the position of ads. * Bugfix: deleted nonexist file config * Update: update ad JS/CSS/config * Update: change ad. * Update: delete my template and change files. * Update: change chronos installation table color. * Update: change table font color to --pst-color-primary-text * Remove old contents in landing page sidebar * Restyle badge for usage in card footer again * Add quicklinks template on landing page sidebar * add quick links * Add scala logo * move tf, pytorch out of the link * change orca key features cards * fix typo * fix a mistake in wording * Restyle badge for card footer * Update decision tree * Remove useless html templates * add more api docs and update tutorials in dllib * update chronos install using new style * merge changes in nano doc from master * fix quickstart links in sidebar quicklinks * Make tables responsive * Fix overflow in api doc * Fix list indents problems in [User guide] section * Further fixes to nested bullets contents in [User Guide] section * Fix strange title in Nano 5-min doc * Fix list indent problems in [DLlib] section * Fix misnumbered list problems and other small fixes for [Chronos] section * Fix list indent problems and other small fixes for [Friesian] section * Fix list indent problem and other small fixes for [PPML] section * Fix list indent problem for developer guide * Fix list indent problem for [Cluster Serving] section * fix dllib links * Fix wrong relative link in section landing page Co-authored-by: Yuwen Hu <yuwen.hu@intel.com> Co-authored-by: Juntao Luo <1072087358@qq.com>
		
			
				
	
	
	
	
		
			5.8 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	TensorFlow Inference
BigDL-Nano provides several APIs which can help users easily apply optimizations on inference pipelines to improve latency and throughput. Currently, performance accelerations are achieved by integrating extra runtimes as inference backend engines or using quantization methods on full-precision trained models to reduce computation during inference. Keras Model (bigdl.nano.tf.keras.Model) and Sequential (bigdl.nano.tf.keras.Sequential) provides the APIs for all optimizations that you need for inference.
For quantization, BigDL-Nano provides only post-training quantization in Model.quantize() for users to infer with models of 8-bit precision. Quantization-Aware Training is not available for now. Model conversion to 16-bit like BF16, and FP16 will be coming soon.
Before you go ahead with these APIs, you have to make sure BigDL-Nano is correctly installed for TensorFlow. If not, please follow this to set up your environment.
Quantization
Quantization is widely used to compress models to a lower precision, which not only reduces the model size but also accelerates inference. BigDL-Nano provides Model.quantize() API for users to quickly obtain a quantized model with accuracy control by specifying a few arguments. Sequential has similar usage, so we will only show how to use an instance of Model to enable quantization pipeline here.
To use INC as your quantization engine, you can choose accelerator as None or 'onnxruntime'. Otherwise, accelerator='openvino' means using OpenVINO POT to do quantization.
By default, Model.quantize() doesn't search the tuning space and returns the fully-quantized model without considering the accuracy drop. If you need to search quantization tuning space for a model with accuracy control, you'll have to specify a few arguments to define the tuning space. More instructions in Quantization with Accuracy Control
Quantization using Intel Neural Compressor
By default, Intel Neural Compressor is not installed with BigDL-Nano. So if you determine to use it as your quantization backend, you'll need to install it first:
# We have tested on neural-compressor>=1.8.1,<=1.11.0
pip install 'neural-compressor>=1.8.1,<=1.11.0'
Quantization without extra accelerator
Without extra accelerators, Model.quantize() returns a Keras module with desired precision and accuracy. Taking MobileNetV2 as an example, you can add quantization as below:
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
import numpy as np
from bigdl.nano.tf.keras import Model
# step 1: create your model
model = MobileNetV2(weights=None, input_shape=[40, 40, 3], classes=10)
model = Model(inputs=model.inputs, outputs=model.outputs)
# step 2: prepare your data and dataloader
train_examples = np.random.random((100, 40, 40, 3))
train_labels = np.random.randint(0, 10, size=(100,))
train_dataset = tf.data.Dataset.from_tensor_slices((train_examples, train_labels))
# (Optional) step 3: Something else, like training ...
model.fit(train_dataset)
# step 4: execute quantization
q_model = model.quantize(calib_dataset=train_dataset)
# run simple prediction
y_hat = q_model(train_examples)
# evaluate, predict also support acceleration
q_model.evaluate(train_dataset)
q_model.predict(train_dataset)
This is a most basic usage to quantize a model with defaults, INT8 precision, and without search tuning space to control accuracy drop.
To use quantization, you must use functional API to create a keras model. This is a known limitation of INC.
Quantization with Accuracy Control
A set of arguments that helps to tune the results for both INC and POT quantization:
- 
calib_dataset: Atf.data.Datasetobject for calibration. Required for static quantization. It's also used as a validation dataloader. - 
metric: Atensorflow.keras.metrics.Metricobject for evaluation. - 
accuracy_criterion: A dictionary to specify the acceptable accuracy drop, e.g.{'relative': 0.01, 'higher_is_better': True}relative/absolute: Drop type, the accuracy drop should be relative or absolute to baselinehigher_is_better: Indicate if a larger value of metric means better accuracy
 - 
max_trials: Maximum trails on the search, if the algorithm can't find a satisfying model, it will exit and raise the error. - 
batch: Specify the batch size of the dataloader. This will only take effect on evaluation. If it's not set, then we usebatch=1for evaluation. 
Accuracy Control with INC There are a few arguments required only by INC.
tuning_strategy(optional): it specifies the algorithm to search the tuning space. In most cases, you don't need to change it.timeout: Timeout of your tuning. Defaults0means endless time for tuning.inputs: A list of input names. Default: None, automatically get names from the graph.outputs: A list of output names. Default: None, automatically get names from the graph. Here is an example to use INC with accuracy control as below. It will search for a model within 1% accuracy drop with 10 trials.
from torchmetrics.classification import Accuracy
q_model = model.quantize(precision='int8',
                         accelerator=None,
                         calib_dataset= train_dataset,
                         metric=Accuracy(),
                         accuracy_criterion={'relative': 0.01, 'higher_is_better': True},
                         approach='static',
                         tuning_strategy='bayesian',
                         timeout=0,
                         max_trials=10,
                         )
# run simple prediction
y_hat = q_model(train_examples)
# evaluate, predict also support acceleration
q_model.evaluate(train_dataset)
q_model.predict(train_dataset)