Core ML 后端的量化方案与导出约束
介绍 ExecuTorch 的 Core ML 后端支持的量化方式,包括 PT2E 流程下的 8 位静态与仅权重量化,以及 quantize_ 流程下的 4 位仿射和码本量化,并说明不同方案对 iOS 部署版本的要求。
## 量化[#](<https://docs.pytorch.org/executorch/stable/backends/coreml/coreml-quantization.html#quantization>) 要对核心ML后端的PyTorch模型进行定量,请使用 `CoreMLQuantizer`. `Quantizers` 属于后端特性,这意味着 `CoreMLQuantizer` 被配置为对模型进行量化,以杠杆化Core ML后端提供的量化运算符. ## 支持的量化计划[#](<https://docs.pytorch.org/executorch/stable/backends/coreml/coreml-quantization.html#supported-quantization-schemes>) CoreML代表支持以下量化计划: - 8 - 通过PT2E流的位静态和仅重的量子化;动态量子化不为CoreML所支持. - 4 - 仅位重的affine 量子化(每组或每通道)通过量子化_ 流量 - 1 - 8 位重只重的 LUT 量子化(每组通道)通过量子化_流量 ## 8 - 使用 PT2E 流量进行位量化[#](<https://docs.pytorch.org/executorch/stable/backends/coreml/coreml-quantization.html#bit-quantization-using-the-pt2e-flow>) 与核心ML后端进行量化需要导出iOS 17或以后的型号. 执行8 - 以PT2E流进行位数化,遵循这些步骤: 1. 创建一个 [`coremltools.optimize.torch.quantization.LinearQuantizerConfig`](<https://apple.github.io/coremltools/source/coremltools.optimize.torch.quantization.html#coremltools.optimize.torch.quantization.LinearQuantizerConfig>) 并用它来创建一个实例 `CoreMLQuantizer`. 2. 使用( U) `torch.export.export` 以导出将准备量化的图表模块。 3. 调用 `prepare_pt2e` 以准备模型进行量化。 4. 使用具有代表性的样本运行预制模型,以校准定量的拉诺活化范围。 5. 调用 `convert_pt2e` 以数量化模型。 6. 使用标准流导出并降低模型. 产出 `convert_pt2e` 是一个 PyTorch 模型,可以使用正常流量导出并降低。由于它是常规的 PyTorch 模型,它也可以用来使用标准的 PyTorch 技术来评价量化模型的准确性。 ``` import torch import coremltools as ct import torchvision.models as models from torchvision.models.mobilenetv2 import MobileNet_V2_Weights from executorch.backends.apple.coreml.quantizer import CoreMLQuantizer from executorch.backends.apple.coreml.partition import CoreMLPartitioner from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e from executorch.exir import to_edge_transform_and_lower from executorch.backends.apple.coreml.compiler import CoreMLBackend mobilenet_v2 = models.mobilenetv2.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).eval() sample_inputs = (torch.randn(1, 3, 224, 224), ) # Step 1: Define a LinearQuantizerConfig and create an instance of a CoreMLQuantizer # Note that "linear" here does not mean only linear layers are quantized, but that linear (aka affine) quantization # is being performed static_8bit_config = ct.optimize.torch.quantization.LinearQuantizerConfig( global_config=ct.optimize.torch.quantization.ModuleLinearQuantizerConfig( quantization_scheme="symmetric", activation_dtype=torch.quint8, weight_dtype=torch.qint8, weight_per_channel=True, ) ) quantizer = CoreMLQuantizer(static_8bit_config) # Step 2: Export the model for training training_gm = torch.export.export(mobilenet_v2, sample_inputs).module() # Step 3: Prepare the model for quantization prepared_model = prepare_pt2e(training_gm, quantizer) # Step 4: Calibrate the model on representative data # Replace with your own calibration data for calibration_sample in [torch.randn(1, 3, 224, 224)]: prepared_model(calibration_sample) # Step 5: Convert the calibrated model to a quantized model quantized_model = convert_pt2e(prepared_model) # Step 6: Export the quantized model to Core ML et_program = to_edge_transform_and_lower( torch.export.export(quantized_model, sample_inputs), partitioner=[ CoreMLPartitioner( # iOS17 is required for the quantized ops in this example compile_specs=CoreMLBackend.generate_compile_specs( minimum_deployment_target=ct.target.iOS17 ) ) ], ).to_executorch() ``` 以上进行静态量化(活性化和权重化). 您可以在“% 1” 中看到关于可用量化配置的完整描述。 [coremlatools 文档](<https://apple.github.io/coremltools/source/coremltools.optimize.torch.quantization.html#coremltools.optimize.torch.quantization.LinearQuantizerConfig>)。例如,下面的配置将进行仅重的量化: ``` weight_only_8bit_config = ct.optimize.torch.quantization.LinearQuantizerConfig( global_config=ct.optimize.torch.quantization.ModuleLinearQuantizerConfig( quantization_scheme="symmetric", activation_dtype=torch.float32, weight_dtype=torch.qint8, weight_per_channel=True, ) ) quantizer = CoreMLQuantizer(weight_only_8bit_config) ``` 量化激活需要校准代表性数据上的模型。 请注意, PT2E 目前至少需要通过 1 校准样本后才能调用 。 `convert_pt2e`,甚至用于无数据重重的量化。 见 [PyTorch 2 输出后培训量化](<https://docs.pytorch.org/ao/main/pt2e_quantization/pt2e_quant_ptq.html>) 以获取更多信息。 ## LLM 量化并量化_[#](<https://docs.pytorch.org/executorch/stable/backends/coreml/coreml-quantization.html#llm-quantization-with-quantize>) Core ML 后端也支持用 [火炬岛](<https://github.com/pytorch/ao>) 定量化_ API 。 这最常用于 LLMS , 需要更高级的定量化。 由于定量化_ 不为后端所知, 重要的是使用一个与 Core ML 兼容的配置 : - 使用 IntxWeightOnlyConfig(使用 weight_dtype 火炬.int4 或 火炬.int8) 进行嵌入/线性层的量化,使用 PerGroup 或 PerAxis 颗粒性. 使用 4 - bit 或 PerGroup 量化 需要用 minimum_deployment_target → ct.target.iOS18 进行导出. 使用 8 - bit quentization 和 per-轴颗粒性在 ct.target.IOS16+ 上得到支持. [核心ML软件 `CompileSpec`](<https://docs.pytorch.org/executorch/stable/backends/coreml/coreml-partitioner.html#coreml-compilespec>) 关于确定部署目标的更多信息。 - 将嵌入/线性层与CodebookWeightOnlyConfig(使用dtype Film.uint1通过film.uint8,使用不同的块大小)进行定量. 与CodebookWeightOnlyConfig进行定量需要用minimum_deployment_target QQ ct.goal.iOS18进行导出. [核心ML软件 `CompileSpec`](<https://docs.pytorch.org/executorch/stable/backends/coreml/coreml-partitioner.html#coreml-compilespec>) 关于确定部署目标的更多信息。 以下是一个将嵌入到8 - 每轴位和线性层到4 - 使用group_size = 32 的位元化实例 : ``` from torchao.quantization.granularity import PerGroup, PerAxis from torchao.quantization.quant_api import ( IntxWeightOnlyConfig, quantize_, ) # Quantize embeddings with 8-bits, per channel embedding_config = IntxWeightOnlyConfig( weight_dtype=torch.int8, granularity=PerAxis(0), ) quantize_( eager_model, embedding_config, lambda m, fqn: isinstance(m, torch.nn.Embedding), ) # Quantize linear layers with 4-bits, per-group linear_config = IntxWeightOnlyConfig( weight_dtype=torch.int4, granularity=PerGroup(32), ) quantize_( eager_model, linear_config, ) ``` 下面是另一个使用代码簿量化将嵌入层和线性层均量化到 3 - bits 的示例。在 coremlatools 文档中,这被称为 [调色板化](<https://apple.github.io/coremltools/docs-guides/source/opt-palettization-overview.html>): ``` from torchao.quantization.quant_api import ( quantize_, ) from torchao.prototype.quantization.codebook_coreml import CodebookWeightOnlyConfig quant_config = CodebookWeightOnlyConfig( dtype=torch.uint3, # There is one LUT per 16 rows block_size=[16, -1], ) quantize_( eager_model, quant_config, lambda m, fqn: isinstance(m, torch.nn.Embedding) or isinstance(m, torch.nn.Linear), ) ``` 上述两个例子都将与to_edge_transform_and_lower API导出并降低到核心ML.
查看原始来源