---
title: quantize_model
description: "| 产品 | 是否支持 |"
url: https://www.hiascend.com/document/detail/zh/canncommercial/latest/devaids/amct/atlasamct_16_0087.html
sourcePath: /source/zh/canncommercial/900/devaids/amct/atlasamct_16_0087.html
indexId: 21cd0c33b653df7626bd047a242a41e2d7d400cdf33d6032e45699b5124d960b65
---
# quantize_model

#### 产品支持情况

| 产品 | 是否支持 |
| --- | --- |
| Atlas 350 加速卡 | √ |
| Atlas A3 训练系列产品 / Atlas A3 推理系列产品 | √ |
| Atlas A2 训练系列产品 / Atlas A2 推理系列产品 | √ |
| Atlas 200I/500 A2 推理产品 | √ |
| Atlas 推理系列产品 | √ |
| Atlas 训练系列产品 | √ |


#### 功能说明

训练后量化接口，将输入的待量化的图结构按照给定的量化配置文件进行量化处理，在传入的图结构中插入权重量化、数据量化相关的算子，生成量化因子记录文件record_file，返回修改后的torch.nn.Module校准模型。


#### 函数原型

```
calibration_model = quantize_model(config_file, modfied_onnx_file, record_file, model, input_data, input_names=None, output_names=None, dynamic_axes=None)
```


#### 参数说明

| 参数名 | 输入/输出 | 说明 |
| --- | --- | --- |
| config\_file | 输入 | 含义：用户生成的量化配置文件，用于指定模型network中量化层的配置情况。 数据类型：string |
| modfied\_onnx\_file | 输入 | 含义：文件名，用于存储融合后模型的onnx格式。 数据类型：string |
| record\_file | 输入 | 含义：量化因子记录文件路径及名称。 数据类型：string |
| model | 输入 | 含义：待量化的模型，已加载权重。 数据类型：torch.nn.Module |
| input\_data | 输入 | 含义：模型的输入数据。一个torch.tensor会被等价为tuple（torch.tensor）。 数据类型：tuple |
| input\_names | 输入 | 含义：模型的输入的名称，用于modfied\_onnx\_file中显示。 默认值：None 数据类型：list(string) |
| output\_names | 输入 | 含义：模型的输出的名称，用于modfied\_onnx\_file中显示。 默认值：None 数据类型：list(string) |
| dynamic\_axes | 输入 | 含义：对模型输入输出动态轴的指定，例如对于输入inputs（NCHW），N、H、W为不确定大小，输出outputs（NL），N为不确定大小，则dynamic\_axes={"inputs": [0,2,3], "outputs": [0]}。 默认值：None 数据类型：dict<string, dict<python:int, string>> or dict<string, list(int)> |


#### 返回值说明

返回修改后的torch.nn.Module校准模型。


#### 调用示例

```
import amct_pytorch as amct
# 建立待量化的网络图结构
model = build_model()
model.load_state_dict(torch.load(state_dict_path))
input_data = tuple([torch.randn(input_shape)])

scale_offset_record_file = os.path.join(TMP, 'scale_offset_record.txt')
modfied_model = os.path.join(TMP, 'modfied_model.onnx')
# 插入量化API
calibration_model = amct.quantize_model(config_json_file,
                                        modfied_model,
                                        scale_offset_record_file,
                                        model,
                                        input_data,
                                        input_names=['input'],
                                        output_names=['output'],
                                        dynamic_axes={'input':{0: 'batch_size'},
                                                      'output':{0: 'batch_size'}})
```
