PyTorch 2 Export Quantization 透過 Inductor 使用 X86 後端¶
創建於: 2024 年 1 月 25 日 | 最後更新於: 2024 年 4 月 19 日 | 最後驗證於: 2024 年 11 月 05 日
作者: Leslie Fang, Weiwen Xia, Jiong Gong, Jerry Zhang
先決條件¶
簡介¶
本教程介紹了利用 PyTorch 2 Export Quantization 流程生成針對 x86 inductor 後端定製的量化模型的步驟,並解釋瞭如何將量化模型降低到 inductor 中。
PyTorch 2 export quantization 流程使用 torch.export 將模型捕獲到圖中,並在 ATen 圖之上執行量化變換。這種方法預計將顯著提高模型覆蓋率、可程式設計性以及簡化使用者體驗 (UX)。TorchInductor 是新的編譯器後端,它將 TorchDynamo 生成的 FX Graphs 編譯成最佳化的 C++/Triton kernels。
這種結合 Inductor 的量化 2 流程支援靜態量化和動態量化。靜態量化最適用於像 ResNet-50 這樣的 CNN 模型。動態量化更適合像 RNN 和 BERT 這樣的 NLP 模型。有關這兩種量化型別的區別,請參閱以下頁面。
量化流程主要包括三個步驟
步驟 1:基於torch export 機制,從 eager 模型捕獲 FX Graph。
步驟 2:基於捕獲的 FX Graph 應用量化流程,包括定義後端特定的 quantizer,生成帶有 observers 的 prepared model,執行 prepared model 的校準或量化感知訓練,並將 prepared model 轉換為 quantized model。
步驟 3:使用 API
torch.compile將量化模型降低到 inductor 中。
這個流程的高層架構可能看起來像這樣
float_model(Python) Example Input
\ /
\ /
—--------------------------------------------------------
| export |
—--------------------------------------------------------
|
FX Graph in ATen
| X86InductorQuantizer
| /
—--------------------------------------------------------
| prepare_pt2e |
| | |
| Calibrate/Train |
| | |
| convert_pt2e |
—--------------------------------------------------------
|
Quantized Model
|
—--------------------------------------------------------
| Lower into Inductor |
—--------------------------------------------------------
|
Inductor
結合 PyTorch 2 Export 中的量化和 TorchInductor,我們獲得了新的 Quantization 前端的靈活性和生產力,以及編譯器後端的出色開箱即用效能。特別是在 Intel 第四代 (SPR) Xeon 處理器上,透過利用advanced-matrix-extensions 特性可以進一步提升模型的效能。
後訓練量化¶
現在,我們將透過一步一步的教程向您展示如何使用 torchvision resnet18 模型進行後訓練量化。
1. 捕獲 FX Graph¶
我們將首先執行必要的匯入,並從 eager 模組捕獲 FX Graph。
import torch
import torchvision.models as models
import copy
from torch.ao.quantization.quantize_pt2e import prepare_pt2e, convert_pt2e
import torch.ao.quantization.quantizer.x86_inductor_quantizer as xiq
from torch.ao.quantization.quantizer.x86_inductor_quantizer import X86InductorQuantizer
from torch._export import capture_pre_autograd_graph
# Create the Eager Model
model_name = "resnet18"
model = models.__dict__[model_name](pretrained=True)
# Set the model to eval mode
model = model.eval()
# Create the data, using the dummy data here as an example
traced_bs = 50
x = torch.randn(traced_bs, 3, 224, 224).contiguous(memory_format=torch.channels_last)
example_inputs = (x,)
# Capture the FX Graph to be quantized
with torch.no_grad():
# if you are using the PyTorch nightlies or building from source with the pytorch master,
# use the API of `capture_pre_autograd_graph`
# Note 1: `capture_pre_autograd_graph` is also a short-term API, it will be updated to use the official `torch.export` API when that is ready.
exported_model = capture_pre_autograd_graph(
model,
example_inputs
)
# Note 2: if you are using the PyTorch 2.1 release binary or building from source with the PyTorch 2.1 release branch,
# please use the API of `torch._dynamo.export` to capture the FX Graph.
# exported_model, guards = torch._dynamo.export(
# model,
# *copy.deepcopy(example_inputs),
# aten_graph=True,
# )
接下來,我們將獲得要量化的 FX Module。
2. 應用量化¶
捕獲到要量化的 FX Module 後,我們將匯入用於 X86 CPU 的 Backend Quantizer,並配置如何對模型進行量化。
quantizer = X86InductorQuantizer()
quantizer.set_global(xiq.get_default_x86_inductor_quantization_config())
注意
X86InductorQuantizer中的預設量化配置對 activations 和 weights 都使用 8 位。
當 Vector Neural Network Instruction 不可用時,oneDNN 後端會靜默選擇假定乘法為 7 位 x 8 位的 kernels。換句話說,在不帶 Vector Neural Network Instruction 的 CPU 上執行時,可能會出現潛在的數值飽和和精度問題。
預設情況下,量化配置用於靜態量化。要應用動態量化,在獲取 config 時新增引數 is_dynamic=True。
quantizer = X86InductorQuantizer()
quantizer.set_global(xiq.get_default_x86_inductor_quantization_config(is_dynamic=True))
匯入後端特定的 Quantizer 後,我們將準備模型進行後訓練量化。prepare_pt2e 將 BatchNorm 運算元摺疊到之前的 Conv2d 運算元中,並在模型中的適當位置插入 observers。
prepared_model = prepare_pt2e(exported_model, quantizer)
現在,在 observers 插入到模型中後,我們將校準 prepared_model。此步驟僅適用於靜態量化。
# We use the dummy data as an example here
prepared_model(*example_inputs)
# Alternatively: user can define the dataset to calibrate
# def calibrate(model, data_loader):
# model.eval()
# with torch.no_grad():
# for image, target in data_loader:
# model(image)
# calibrate(prepared_model, data_loader_test) # run calibration on sample data
最後,我們將校準後的模型轉換為量化模型。convert_pt2e 接受一個校準後的模型並生成一個量化模型。
converted_model = convert_pt2e(prepared_model)
完成這些步驟後,我們就執行完了量化流程,將獲得量化模型。
3. 降低到 Inductor¶
獲得量化模型後,我們將進一步將其降低到 inductor 後端。預設的 Inductor wrapper 生成 Python 程式碼來呼叫生成的 kernels 和外部 kernels。此外,Inductor 支援生成純 C++ 程式碼的 C++ wrapper。這允許無縫整合生成的和外部的 kernels,有效減少 Python 開銷。未來,利用 C++ wrapper,我們可以擴充套件功能以實現純 C++ 部署。有關 C++ Wrapper 的更全面詳細資訊,請參閱專門的Inductor C++ Wrapper 教程。
# Optional: using the C++ wrapper instead of default Python wrapper
import torch._inductor.config as config
config.cpp_wrapper = True
with torch.no_grad():
optimized_model = torch.compile(converted_model)
# Running some benchmark
optimized_model(*example_inputs)
在更高階的場景中,int8-mixed-bf16 量化發揮作用。在這種情況下,如果沒有後續的量化節點,Convolution 或 GEMM 運算元會產生 BFloat16 輸出資料型別而不是 Float32。隨後,BFloat16 張量會無縫傳播通過後續的 pointwise 運算元,有效最小化記憶體使用並可能提升效能。此功能的利用類似於常規的 BFloat16 Autocast,只需將指令碼包裹在 BFloat16 Autocast 上下文中即可。
with torch.autocast(device_type="cpu", dtype=torch.bfloat16, enabled=True), torch.no_grad():
# Turn on Autocast to use int8-mixed-bf16 quantization. After lowering into Inductor CPP Backend,
# For operators such as QConvolution and QLinear:
# * The input data type is consistently defined as int8, attributable to the presence of a pair
of quantization and dequantization nodes inserted at the input.
# * The computation precision remains at int8.
# * The output data type may vary, being either int8 or BFloat16, contingent on the presence
# of a pair of quantization and dequantization nodes at the output.
# For non-quantizable pointwise operators, the data type will be inherited from the previous node,
# potentially resulting in a data type of BFloat16 in this scenario.
# For quantizable pointwise operators such as QMaxpool2D, it continues to operate with the int8
# data type for both input and output.
optimized_model = torch.compile(converted_model)
# Running some benchmark
optimized_model(*example_inputs)
將所有這些程式碼放在一起,我們就得到了玩具示例程式碼。請注意,由於 Inductor 的 freeze 特性尚未預設開啟,請執行示例程式碼時帶上 TORCHINDUCTOR_FREEZING=1。
例如
TORCHINDUCTOR_FREEZING=1 python example_x86inductorquantizer_pytorch_2_1.py
隨著 PyTorch 2.1 的釋出,TorchBench 測試套件中的所有 CNN 模型都已進行測量,並證明與 Inductor FP32 推理路徑相比是有效的。有關詳細的基準測試資料,請參閱此文件。
量化感知訓練¶
PyTorch 2 Export 量化感知訓練 (QAT) 現在在 X86 CPU 上受支援,使用 X86InductorQuantizer,隨後將量化模型降低到 Inductor 中。為了更深入地理解 PT2 Export 量化感知訓練,我們建議參考專門的PyTorch 2 Export 量化感知訓練教程。
PyTorch 2 Export QAT 流程與 PTQ 流程基本相似
import torch
from torch._export import capture_pre_autograd_graph
from torch.ao.quantization.quantize_pt2e import (
prepare_qat_pt2e,
convert_pt2e,
)
import torch.ao.quantization.quantizer.x86_inductor_quantizer as xiq
from torch.ao.quantization.quantizer.x86_inductor_quantizer import X86InductorQuantizer
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(1024, 1000)
def forward(self, x):
return self.linear(x)
example_inputs = (torch.randn(1, 1024),)
m = M()
# Step 1. program capture
# NOTE: this API will be updated to torch.export API in the future, but the captured
# result shoud mostly stay the same
exported_model = capture_pre_autograd_graph(m, example_inputs)
# we get a model with aten ops
# Step 2. quantization-aware training
# Use Backend Quantizer for X86 CPU
# To apply dynamic quantization, add an argument ``is_dynamic=True`` when getting the config.
quantizer = X86InductorQuantizer()
quantizer.set_global(xiq.get_default_x86_inductor_quantization_config(is_qat=True))
prepared_model = prepare_qat_pt2e(exported_model, quantizer)
# train omitted
converted_model = convert_pt2e(prepared_model)
# we have a model with aten ops doing integer computations when possible
# move the quantized model to eval mode, equivalent to `m.eval()`
torch.ao.quantization.move_exported_model_to_eval(converted_model)
# Lower the model into Inductor
with torch.no_grad():
optimized_model = torch.compile(converted_model)
_ = optimized_model(*example_inputs)
請注意,Inductor 的 freeze 特性並未預設啟用。要使用此功能,您需要在執行示例程式碼時設定 TORCHINDUCTOR_FREEZING=1。
例如
TORCHINDUCTOR_FREEZING=1 python example_x86inductorquantizer_qat.py
結論¶
透過本教程,我們介紹瞭如何在 PyTorch 2 Quantization 中結合 Inductor 和 X86 CPU 使用。使用者可以學習如何使用 X86InductorQuantizer 對模型進行量化,並將其降低到適用於 X86 CPU 裝置的 Inductor 中。