QAT Model Adaptation to CANN Format
An already-quantized original TensorFlow model is referred to as a QAT model. Prior to generating an offline model adapted to the AI processor with ATC, you need to use the function provided in this section to convert the QAT model into the CANN format, and then use ATC to convert the CANN quantization model into an offline model adapted to the AI processor.
Restrictions:
- The original QAT model must have FakeQuant layers, including FakeQuantWithMinMaxVars and FakeQuantWithMinMaxVarsPerChannel (weights only).
- Only the Conv2D, MatMul, DepthwiseConv2dNative, Conv2DBackpropInput, and AvgPool layers can match fake_quant nodes, which means only these layers are adaptable. Workflow shows the layer restrictions.
Adaptation Principles
The following figure shows the adaptation principles. The user implements the operations in blue, while those in gray are implemented by using the convert_qat_model API in AMCT. Specifically, import the package to the TensorFlow QAT network inference code and call the API where appropriate for adaptation. QAT models do not support Automatic Quantization. For the adaptation example, see Sample List. You can also obtain the command line example to quickly experience the feature.
Example
This example details how to use AMCT to convert a TensorFlow QAT model to a CANN format.
- Take the following steps to get started. Update the sample code based on your situation.
- Tweak the arguments passed to AMCT API calls as required.
- Import the AMCT package and set the log level.
1 2
import amct_tensorflow as amct amct.set_logging_level(print_level='info', save_level='info')
- (Optional) Run inference on the original model for quantization in the TensorFlow environment based on the test dataset to validate the inference script and environment setup. (Update the sample code based on your situation.)
This step is recommended as it guarantees a properly functioning original model for inference with acceptable accuracy. You can use a subset from the test dataset to improve the efficiency.
1user_do_inference(ori_qat_model, test_data)
- Call the convert_qat_model API in AMCT to perform model adaptation.This API parses the .pb model into a graph, preprocesses and modifies the graph, inserts operators such as AscendQuant and AscendDequant into the modified graph, and then saves the quantized model.
1 2 3 4 5 6
quant_model_path = './results/user_model' record_file = './results/record.txt' amct.convert_qat_model(pb_model=ori_qat_model, outputs=ori_qat_model_outputs, save_path=quant_model_path, record_file=record_file)
- (Optional) Run inference on the quantized model user_model_quantized.pb in the TensorFlow environment based on the test dataset to test the accuracy. (Update the sample code based on your situation.)
Compare the accuracy of the fake-quantized model with that of the original model (see 2).
1 2
quant_model = './results/user_model_quantized.pb' user_do_inference(quant_model, test_data)