目录

Exporting a Quantized Model

Introduction

After a Transformer model is quantized (one-stop quantization of LLMs or plugin-based quantization PTQ/QAT), or after the quantization base model is fine-tuned using LoRA, you can follow the process described in this section to extract the quantization parameter file and export the ONNX model (quantized IR). The quantization parameter file and ONNX model are used for offline model compilation by OMC/OMG.

Supported quantization weight sources:

Quantization Weight Source Quantization Policy File Quantization Weight Description
One-stop quantization for LLMs dopt_config.json trained_quant_weight.pth (dynamic quantization) or trained.pth (static quantization) Quantization output
Plugin-based quantization (PTQ/QAT) Quantization configuration file Quantization weight PTH file saved after calibration or quantization aware training See Plugin-based Quantization
LoRA fine-tuning on a quantized base model dopt_config_lora.json lora_calibrated.pth LoRA adaptation output. See LoRA Fine-Tuning on a Quantized Base Model.

Export procedure:

  1. Export quantization parameters: Extract the quantization parameter file based on the quantization policy file and quantization weights.

  2. Export the ONNX model: Export the ONNX model that contains quantization errors.

For LLMs, convert the exported ONNX model into a CANN offline model. For details, see Converting an ONNX Model into a CANN Model.

For details about how to export quantization parameters and ONNX models for AIGC VIT models, see the following description. For details about how to convert a model into a CANN model, see Converting an ONNX Model into a CANN Model.

Exporting Quantization Parameters

After using the optimize_model API to implant the quantized structure and load the quantization weights, call the generate_quant_params API to extract the quantization parameter file. The quantization parameter file is used for subsequent offline model conversion using OMC. In addition, the fake quantization weight file fakequant_weight.pth is generated. The location and naming of the generated files are described as follows:

Quantization parameter extraction can also be performed immediately after calibration is complete. The procedures are separated to prevent repeated calibration due to errors.

import sys
import torch
sys.path.append('lightweighting tool chain directory')
from dopt_lm.do_opt import (
    generate_quant_params,
    optimize_model,
    set_quant_state,
    set_calibrate_state,
)

output_dir = './quant_params_output'  ### Output directory for storing the quantization parameters
model = "your model define" ### Floating-point nn.module instance object
### Select the quantization policy file and quantization weights based on the preceding table. The following uses the quantization base model as an example.
quant_config = 'dopt_config.json' ### For LoRA, use 'dopt_config_lora.json'.
quant_weight = 'trained_quant_weight.pth' ### For LoRA, use lora_calibrated.pth.
model = optimize_model(model, quant_config)
### Load the quantization weights saved after quantization calibration.
model.load_state_dict(torch.load(quant_weight, map_location='cpu'), strict=False)
### Disable quantization parameter update and export quantization parameters.
set_quant_state(model, weight_state=True, input_state=True)
set_calibrate_state(model, False)
platform = "9030" ### Select "9030", "9050", or "9020" based on the actual platform. For 4-bit or lower, this parameter is mandatory. Otherwise, it is not required. (If this parameter is not passed, the tool does not report an error, but the output does not match the target platform.)
generate_quant_params(model, output_dir, platform=platform)
### The quantization parameter file is './quant_params_output_v2' (same name as output_dir with the suffix "_v2"), generated in the parent directory at the same level as output_dir.
### The fakequant_weight.pth file (used only to replace floating-point weights in general ONNX export mode) is also generated in the same-level directory.
### quant_info.txt; The output_dir directory itself does not generate or store any files.

Exporting the ONNX Model

The optimize_model_for_onnx_export API is used to inject the quantization structure for ONNX export. This API internally removes all quant_op-related keys from the quantization weights (the lora_A quantization parameter of LoRA is not included in the ONNX graph) and replaces the Linear layer with a structure dedicated to ONNX export. In the external LoRA scenario, the LoRA branch is reconstructed using pure floating-point nn.Linear layers, using only the rank in the LoRA blocks.

import os
import shutil
import sys
import torch
import onnx
sys.path.append('lightweighting tool chain directory')
from dopt_lm.do_opt import optimize_model_for_onnx_export, process_onnx

transformer_model = "your model define"
### Select the quantization policy file and quantization weights based on the export object:
### Quantization base model: dopt_config.json + trained_quant_weight.pth (dynamic quantization) or trained.pth (static quantization)
### External LoRA: dopt_config_lora.json + lora_calibrated.pth
quant_config = 'dopt_config.json'
quant_weight = 'trained_quant_weight.pth'
ckpt = torch.load(quant_weight, map_location='cpu')
platform = "9030" ### Select "9030", "9050", or "9020" based on the actual SoC model. For 4-bit or lower, this parameter is mandatory. (If this parameter is not transferred, the tool does not report an error, but the export output does not match the target platform.) In non-4-bit scenarios, this parameter does not need to be transferred.
transformer_model = optimize_model_for_onnx_export(
    transformer_model,
    quant_config, ckpt,
    platform=platform
)
transformer_model.eval()
### Randomly generate the input used for exporting the ONNX model based on the model input.
dummy_input = ()
transformer_model(*dummy_input) ### Check the model forward inference.
### Set the names of the ONNX input and output nodes.
input_names = ["in0_name", "in1_name", "..."]
output_names = ["out0_name", "out1_name", "..."]
### Specify the final output directory (only for storing the final delivery files). Create a temporary directory to store the exported intermediate files.
output_dir = './onnx_output'
tmp_dir = './onnx_export_tmp'
os.makedirs(output_dir, exist_ok=True)
os.makedirs(tmp_dir, exist_ok=True)
tmp_onnx_path = os.path.join(tmp_dir, 'xxx.onnx')
final_onnx_path = os.path.join(output_dir, 'xxx.onnx')
with torch.no_grad():
    torch.onnx.export(
        transformer_model,
        dummy_input,
        tmp_onnx_path,
        input_names=input_names,
        output_names=output_names,
        opset_version=17,
        do_constant_folding=True
    )
### When the total size of the weight files of a large model exceeds 2 GB, torch.onnx.export cannot inline the weight files into a single ONNX file. Instead, it will generate
### a large number of weight files (such as onnx__MatMul_xxx) in the export directory. Therefore, export the files to a temporary directory (all scattered files are stored in the temporary directory).
### Then, load the model and save all weight files to a single weight file in the specified directory.
### The transit weight file is named by adding the .pb suffix to the ONNX file name (xxx.onnx.pb).
### It is naturally distinguished from the final weight file (xxx.pb) generated by process_onnx and will not have the same name:
relay_weights_name = os.path.basename(final_onnx_path) + '.pb'
m = onnx.load(tmp_onnx_path) ### Load the weight file from the temporary directory along with the separate files.
onnx.save(m, final_onnx_path,
          save_as_external_data=True,
          all_tensors_to_one_file=True,
          location=relay_weights_name)
shutil.rmtree (tmp_dir) ### Delete the temporary directory (including all separate files).
process_onnx(final_onnx_path) ### Post-processing incorporates the weights in the transit file into the final weight file xxx.pb, and the reference in the ONNX graph is also changed to xxx.pb.
os.remove(os.path.join(output_dir, relay_weights_name)) ### Delete only the transit file xxx.onnx.pb. Retain the final weight file xxx.pb (which is being referenced by ONNX).

The final output directory of the preceding process contains only two deliverables: xxx.onnx (graph structure) and xxx.pb (weight file). The xxx.onnx.pb file is only an exported transit file (used to carry weights for process_onnx to read and package). After process_onnx is complete, its content has been incorporated into xxx.pb, and the reference within the ONNX graph also points to xxx.pb. After the transit file is deleted from the temporary directory, it is still the only source of weights for process_onnx and must be deleted after process_onnx is complete. (In practice, deleting the transit file does not affect ONNX loading and inference.)

The xxx.onnx and xxx.pb files must be stored in the same directory. In the ONNX graph, the weight in the PB file is referenced using location+offset. If either of them is missing or separated from the directory, an error (ValidationError) will be reported by onnx.load. The delivery and subsequent OMC conversion must be performed in the same directory.

If the ONNX model is directly exported to the final directory and not stored in a unified manner (as separate files), the process_onnx process will also collect the separate files into the PB file. After the collection is complete, the separate files are no longer referenced and can be deleted. However, the process directory is disordered, so this method is not recommended.

For the common export mode that does not use optimize_model_for_onnx_export, you can load fakequant_weight.pth to replace the weights of the floating-point model, and then use torch.onnx.export to export the floating-point model. If necessary, simplify the ONNX model and ensure that the names of the conv and linear operators are consistent with those defined in torch.