OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[Docs] Update NNCF QAT docs (#28818)
Andrey Churkin69ace0365f38
diff --git a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training.rst b/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training.rstindex f543b5d4591..24143675a74 100644--- a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training.rst+++ b/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training.rst@@ -45,8 +45,7 @@ quantization errors part of the overall training loss and tries to minimize theiTo learn more, see:-* guide on quantization for :doc:`PyTorch <./compressing-models-during-training/quantization-aware-training-pytorch>`.-* guide on quantization for :doc:`Tensorflow <./compressing-models-during-training/quantization-aware-training-tensorflow>`.+* guide on quantization for :doc:`PyTorch and TensorFlow <./compressing-models-during-training/quantization-aware-training>`.* Jupyter notebook on `Quantization Aware Training with NNCF and PyTorch <https://github.com/openvinotoolkit/openvino_notebooks/tree/latest/notebooks/pytorch-quantization-aware-training>`__.* Jupyter notebook on `Quantization Aware Training with NNCF and TensorFlow <https://github.com/openvinotoolkit/openvino_notebooks/tree/latest/notebooks/tensorflow-quantization-aware-training>`__.diff --git a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training-pytorch.rst b/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training-pytorch.rstdeleted file mode 100644index 21eaa5b81ac..00000000000--- a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training-pytorch.rst+++ /dev/null@@ -1,72 +0,0 @@-Quantization-aware Training (QAT) with PyTorch-===============================================--Below are the steps required to integrate QAT from NNCF into a training script written with-PyTorch:---1. Apply Post Training Quantization to the Model-##################################################--Quantize the model using the :doc:`Post-Training Quantization <../quantizing-models-post-training/basic-quantization-flow>` method.--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py- :language: python- :fragment: [quantize]---2. Fine-tune the Model-########################--This step assumes applying fine-tuning to the model the same way it is done for the baseline model. For QAT, it is required to train the model for a few epochs with a small learning rate, for example, 1e-5.-Quantized models perform all computations in floating-point precision during fine-tuning by modeling quantization errors in both forward and backward passes.--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py- :language: python- :fragment: [tune_model]---.. note::- The precision of weights transitions to INT8 only after converting the model to OpenVINO Intermediate Representation.- You can expect a reduction in model footprint only for that format.---These steps outline the basics of applying the QAT method from the NNCF. However, in some cases, it is required to save/load model-checkpoints during training. Since NNCF wraps the original model with its own object, it provides an API for these needs.--3. (Optional) Save Checkpoint-####################################--To save a model checkpoint, use the following API:--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py- :language: python- :fragment: [save_checkpoint]---4. (Optional) Restore from Checkpoint-################################################--To restore the model from checkpoint, use the following API:--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py- :language: python- :fragment: [load_checkpoint]---Deploying the Quantized Model-###############################--The model can be converted into the OpenVINO Intermediate Representation (IR) if needed, compiled, and run with OpenVINO without any additional steps.--.. doxygensnippet:: docs/optimization_guide/nncf/ptq/code/ptq_torch.py- :language: python- :fragment: [inference]--For more details, see the corresponding :doc:`documentation <../../running-inference>`.--Examples-####################--* `Quantization-aware Training of Resnet18 PyTorch Model <https://github.com/openvinotoolkit/nncf/tree/develop/examples/quantization_aware_training/torch/resnet18>`__-* `Quantization-aware Training of STFPM PyTorch Model <https://github.com/openvinotoolkit/nncf/tree/develop/examples/quantization_aware_training/torch/anomalib>`__diff --git a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training-tensorflow.rst b/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training-tensorflow.rstdeleted file mode 100644index 57abad31a42..00000000000--- a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training-tensorflow.rst+++ /dev/null@@ -1,113 +0,0 @@-Quantization-aware Training (QAT) with TensorFlow-===================================================--Below are the steps required to integrate QAT from NNCF into a training script written with TensorFlow:--.. note::- Currently, NNCF for TensorFlow supports optimization of the models created using Keras- `Sequential API <https://www.tensorflow.org/guide/keras/sequential_model>`__ or- `Functional API <https://www.tensorflow.org/guide/keras/functional>`__.--1. Import NNCF API-########################--Add NNCF-related imports in the beginning of the training script:--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py- :language: python- :fragment: [imports]--2. Create NNCF Configuration-####################################--Define NNCF configuration which consists of model-related parameters (the ``"input_info"`` section) and parameters-of optimization methods (the ``"compression"`` section). For faster convergence, it is also recommended to register a dataset object-specific to the DL framework. The data object will be used at the model creation step to initialize quantization parameters.--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py- :language: python- :fragment: [nncf_congig]---3. Apply Optimization Methods-####################################--Wrap the original model object with the ``create_compressed_model()`` API using the configuration-defined in the previous step. This method returns a so-called compression controller and a wrapped model that can be used the-same way as the original model. Optimization methods are applied at this step, so that the model-undergoes a set of corresponding transformations and contains additional operations required for optimization. In case of QAT, the compression controller object is used for model export and, optionally, in distributed training as demonstrated below.--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py- :language: python- :fragment: [wrap_model]---4. Fine-tune the Model-####################################--This step assumes applying fine-tuning to the model the same way it is done for the baseline model. For QAT, it is required to train the model for a few epochs with a small learning rate, for example, 10e-5. In principle,-you can skip this step, meaning that the post-training optimization will be applied to the model.--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py- :language: python- :fragment: [tune_model]---5. Multi-GPU Distributed Training-####################################--In the case of distributed multi-GPU training (not DataParallel), call ``compression_ctrl.distributed()`` before fine-tuning. This informs optimization methods to make adjustments to function in the distributed mode.--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py- :language: python- :fragment: [distributed]---.. note::- The precision of weights transitions to INT8 only after converting the model to OpenVINO Intermediate Representation.- You can expect a reduction in model footprint only for that format.---These steps outline the basics of applying the QAT method from the NNCF. However, in some cases, it is required to save/load model-checkpoints during training. Since NNCF wraps the original model with its own object, it provides an API for these needs.--6. (Optional) Save Checkpoint-####################################--To save a model checkpoint, use the following API:--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py- :language: python- :fragment: [save_checkpoint]---7. (Optional) Restore from Checkpoint-################################################--To restore the model from checkpoint, use the following API:--.. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py- :language: python- :fragment: [load_checkpoint]---For more details on saving/loading checkpoints in the NNCF, see the corresponding-`NNCF documentation <https://github.com/openvinotoolkit/nncf/blob/develop/docs/usage/training_time_compression/other_algorithms/Usage.md#saving-and-loading-compressed-models>`__.--Deploying quantized model-#########################--The model can be converted into the OpenVINO Intermediate Representation (IR) if needed, compiled and run with OpenVINO.-No extra steps or options are required.--.. doxygensnippet:: docs/optimization_guide/nncf/ptq/code/ptq_tensorflow.py- :language: python- :fragment: [inference]--For more details, see the corresponding :doc:`documentation <../../running-inference>`.--Examples-####################--* `Quantizing TensorFlow model with NNCF <https://github.com/openvinotoolkit/openvino_notebooks/tree/latest/notebooks/tensorflow-quantization-aware-training>`__-diff --git a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training.rst b/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training.rstindex f5ec455a7e2..a0610d7fdd5 100644--- a/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training.rst+++ b/docs/articles_en/openvino-workflow/model-optimization-guide/compressing-models-during-training/quantization-aware-training.rst@@ -1,12 +1,6 @@Quantization-aware Training (QAT)=================================-.. toctree::- :maxdepth: 1- :hidden:-- Quantization-aware Training with PyTorch <quantization-aware-training-pytorch>- Quantization-aware Training with TensorFlow <quantization-aware-training-tensorflow>Introduction####################@@ -16,6 +10,136 @@ degradation caused by quantization. In fact, this is the most accurate quantizatapply QAT from the Neural Network Compression Framework (NNCF) to get 8-bit quantized models. This assumes that you areknowledgeable in Python programming and familiar with the training code for the model in the source DL framework.-:doc:`Quantization-aware Training with PyTorch <quantization-aware-training-pytorch>`+Steps required to apply QAT to the model:++.. note::+ Currently, NNCF for TensorFlow supports the optimization of models created using the Keras+ `Sequential API <https://www.tensorflow.org/guide/keras/sequential_model>`__ or+ `Functional API <https://www.tensorflow.org/guide/keras/functional>`__.++1. Apply Post Training Quantization to the Model+#################################################++Quantize the model using the :doc:`Post-Training Quantization <../quantizing-models-post-training/basic-quantization-flow>` method.++.. tab-set::++ .. tab-item:: PyTorch+ :sync: pytorch++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py+ :language: python+ :fragment: [quantize]++ .. tab-item:: TensorFlow 2+ :sync: tensorflow-2++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py+ :language: python+ :fragment: [quantize]++2. Fine-tune the Model+#######################++This step assumes applying fine-tuning to the model the same way it is done for the+baseline model. For QAT, it is required to train the model for a few epochs with a small+learning rate, for example, 1e-5. Quantized models perform all computations in the+floating-point precision during fine-tuning by modeling quantization errors in both+forward and backward passes.++.. tab-set::++ .. tab-item:: PyTorch+ :sync: pytorch++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py+ :language: python+ :fragment: [tune_model]++ .. tab-item:: TensorFlow 2+ :sync: tensorflow-2++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py+ :language: python+ :fragment: [tune_model]++.. note::+ The precision of weight transitions to INT8 only after converting the model to OpenVINO+ Intermediate Representation. You can expect a reduction in the model footprint only for+ that format.++These steps outline the basics of applying the QAT method from the NNCF. However, in some cases, it is required to save/load model+checkpoints during training. Since NNCF wraps the original model with its own object, it provides an API for these needs.++3. (Optional) Save Checkpoint+##############################++To save a model checkpoint, use the following API:++.. tab-set::++ .. tab-item:: PyTorch+ :sync: pytorch++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py+ :language: python+ :fragment: [save_checkpoint]++ .. tab-item:: TensorFlow 2+ :sync: tensorflow-2++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py+ :language: python+ :fragment: [save_checkpoint]++4. (Optional) Restore from Checkpoint+######################################++To restore the model from checkpoint, use the following API:++.. tab-set::++ .. tab-item:: PyTorch+ :sync: pytorch++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_torch.py+ :language: python+ :fragment: [load_checkpoint]++ .. tab-item:: TensorFlow 2+ :sync: tensorflow-2++ .. doxygensnippet:: docs/optimization_guide/nncf/code/qat_tf.py+ :language: python+ :fragment: [load_checkpoint]++Deploying the Quantized Model+##############################++You can convert the model to OpenVINO IR, if needed, compile it and run with OpenVINO without+any additional steps.++.. tab-set::++ .. tab-item:: PyTorch+ :sync: pytorch++ .. doxygensnippet:: docs/optimization_guide/nncf/ptq/code/ptq_torch.py+ :language: python+ :fragment: [inference]++ .. tab-item:: TensorFlow 2+ :sync: tensorflow-2++ .. doxygensnippet:: docs/optimization_guide/nncf/ptq/code/ptq_tensorflow.py+ :language: python+ :fragment: [inference]++For more details, see the corresponding :doc:`documentation <../../running-inference>`.++Examples+#########-:doc:`Quantization-aware Training with TensorFlow <quantization-aware-training-tensorflow>`\ No newline at end of file+* `Quantization-aware Training of Resnet18 PyTorch Model <https://github.com/openvinotoolkit/nncf/tree/develop/examples/quantization_aware_training/torch/resnet18>`__+* `Quantization-aware Training of STFPM PyTorch Model <https://github.com/openvinotoolkit/nncf/tree/develop/examples/quantization_aware_training/torch/anomalib>`__+* `Quantization-aware Training of MobileNet v2 TensorFlow Model <https://github.com/openvinotoolkit/nncf/tree/develop/examples/quantization_aware_training/tensorflow/mobilenet_v2>`__diff --git a/docs/optimization_guide/nncf/code/qat_tf.py b/docs/optimization_guide/nncf/code/qat_tf.pyindex 06ceb8e190d..c65cff04dc3 100644--- a/docs/optimization_guide/nncf/code/qat_tf.py+++ b/docs/optimization_guide/nncf/code/qat_tf.py@@ -1,69 +1,45 @@# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-#! [imports]-import tensorflow as tf--from nncf import NNCFConfig-from nncf.tensorflow import create_compressed_model, register_default_init_args-#! [imports]--#! [nncf_congig]-nncf_config_dict = {- "input_info": {"sample_size": [1, 3, 224, 224]}, # input shape required for model tracing- "compression": {- "algorithm": "quantization", # 8-bit quantization with default settings- },-}-nncf_config = NNCFConfig.from_dict(nncf_config_dict)-nncf_config = register_default_init_args(nncf_config, train_dataset, batch_size=1) # train_dataset is an instance of tf.data.Dataset-#! [nncf_congig]--#! [wrap_model]+#! [quantize]model = KerasModel() # instance of the tensorflow.keras.Model-compression_ctrl, model = create_compressed_model(model, nncf_config)-#! [wrap_model]--#! [distributed]-compression_ctrl.distributed() # call it before the training-#! [distributed]+quantized_model = nncf.quantize(model, ...)+#! [quantize]#! [tune_model]... # fine-tuning preparations, e.g. dataset, loss, optimization setup, etc.-# create compression callbacks to control optimization parameters and dump compression statistics-compression_callbacks = create_compression_callbacks(compression_ctrl, log_dir="./compression_log")# tune quantized model for 5 epochs the same way as the baseline-model.fit(train_dataset, epochs=5, callbacks=compression_callbacks)+quantized_model.fit(train_dataset, epochs=5)#! [tune_model]-#! [export]-compression_ctrl.export_model("compressed_model.pb") #export to Frozen Graph-#! [export]-#! [save_checkpoint]-from nncf.tensorflow.utils.state import TFCompressionState+from nncf.tensorflow import ConfigState+from nncf.tensorflow import get_configfrom nncf.tensorflow.callbacks.checkpoint_callback import CheckpointManagerCallback-checkpoint = tf.train.Checkpoint(model=model,- compression_state=TFCompressionState(compression_ctrl),+nncf_config = get_config(quantized_model)+checkpoint = tf.train.Checkpoint(model=quantized_model,+ nncf_config_state=ConfigState(nncf_config),... # the rest of the user-defined objects to save)callbacks = []callbacks.append(CheckpointManagerCallback(checkpoint, path_to_checkpoint))...-model.fit(..., callbacks=callbacks)+quantized_model.fit(..., callbacks=callbacks)#! [save_checkpoint]#! [load_checkpoint]-from nncf.tensorflow.utils.state import TFCompressionStateLoader+from nncf.tensorflow import ConfigState+from nncf.tensorflow import load_from_config-checkpoint = tf.train.Checkpoint(compression_state=TFCompressionStateLoader())+checkpoint = tf.train.Checkpoint(nncf_config_state=ConfigState())checkpoint.restore(path_to_checkpoint)-compression_state = checkpoint.compression_state.state-compression_ctrl, model = create_compressed_model(model, nncf_config, compression_state)-checkpoint = tf.train.Checkpoint(model=model,- ...)+quantized_model = load_from_config(model, checkpoint.nncf_config_state.config)++checkpoint = tf.train.Checkpoint(model=quantized_model+ ... # the rest of the user-defined objects to load+ )checkpoint.restore(path_to_checkpoint)#! [load_checkpoint]diff --git a/docs/optimization_guide/nncf/code/qat_torch.py b/docs/optimization_guide/nncf/code/qat_torch.pyindex 2d8e8516ead..92ab0b241ed 100644--- a/docs/optimization_guide/nncf/code/qat_torch.py+++ b/docs/optimization_guide/nncf/code/qat_torch.py@@ -3,7 +3,7 @@#! [quantize]model = TorchModel() # instance of torch.nn.Module-model = nncf.quantize(model, ...)+quantized_model = nncf.quantize(model, ...)#! [quantize]#! [tune_model]