如何把 TensorFlow Lite 模型转换为 Core ML 并保留量化权重?

解读

在国内 iOS 面试场景里,这道题表面问“模型转换”,实则考察三件事:

  1. 对 Apple 生态模型格式的深度理解(Core ML 的 .mlmodel 与 .mlmodelc 区别、量化在 iOS 侧的表现);
  2. 对 TensorFlow Lite 量化方案(PTQ/QAT、INT8/FP16/权重-only)的熟悉度;
  3. 对 tf-coreml 转换链路上“何时丢量化、如何保量化”的实操经验。
    面试官常通过追问“为什么 INT8 权重到了 Core ML 却变成 FP32”来验证候选人是否真踩过坑。回答必须给出可落地的命令行参数、脚本片段,并说明 iOS 侧最终拿到的 .mlmodelc 体积与推理耗时变化,才能拿到高分。

知识点

  1. TensorFlow Lite 量化类型:
    • 训练后量化(PTQ)– 权重 INT8,激活 INT8;
    • 量化感知训练(QAT)– 伪量化节点,导出 INT8;
    • 权重-only INT8 – 激活仍为 FP32,体积减半,推理用 FP32。
  2. Core ML 量化策略:
    • 权重支持 INT8/INT4/INT16/FP16,激活支持 FP32/FP16;
    • 转换工具链:coremltools ≥ 6.0 支持直接读入 TFLite 并识别量化参数;
    • 若 TFLite 为 QAT 模型,coremltools 会保留 FakeQuant 节点并映射为 quantizationParams;
    • 若 TFLite 为 PTQ,需保证 inference_input_type=tf.int8 且 inference_output_type=tf.int8,否则转换时权重被反量化回 FP32。
  3. Objective-C 侧验证:
    • 使用 MLModel 加载后,通过 model.modelDescription.inputDescriptionsByName[@"input_1"].multiArrayDataType 确认是否为 MLMultiArrayDataTypeInt8;
    • 用 MLPredictionOptions 设置 usesCPUOnly=YES 可强制跑纯 INT8 路径,方便单元测试。
  4. 国内常见坑:
    • 公司内网无法拉 GitHub,需提前把 coremltools 离线 wheel 打好;
    • 若模型含自定义 TFLite OP(如抖音自研量化 OP),需先写 coremltools.converters.mil.frontend.tensorflow.tf_graph_pass 插件,否则转换失败;
    • App Store 审核对“仅支持 A12 以上”的 INT4 权重会打回,需 fallback 到 INT8。

答案

步骤如下,保证量化权重不丢失:

  1. 检查 TFLite 模型

    tensorflow/lite/tools/visualize.py model.tflite view.html
    

    确认 QuantizationParameters 存在且 scale/zero_point 有效。

  2. 安装 coremltools(离线场景用 whl)

    pip install coremltools-6.3-cp39-none-macosx_11_0_arm64.whl
    
  3. 转换脚本(Python,可直接放到公司 CI)

    import coremltools as ct
    tflite_model = "model.tflite"
    # 关键参数:compute_precision 设为 ct.precision.FLOAT16 仅影响浮点部分,
    # quantization_mode 设为 ct.QuantizationMode.LINEAR_QUANTIZATION 表示保留权重 INT8
    coreml_model = ct.converters.tensorflow.convert(
        tflite_model,
        compute_precision=ct.precision.FLOAT16,   # 激活用 FP16,权重仍 INT8
        quantization_mode=ct.QuantizationMode.LINEAR_QUANTIZATION,
        minimum_deployment_target=ct.target.iOS14   # 国内主流最低 iOS14
    )
    coreml_model.save("Model.mlmodel")
    
  4. 验证量化是否保留

    spec = coreml_model.get_spec()
    for layer in spec.neuralNetwork.layers:
        if layer.convolution.HasField("quantizationParams"):
            print(layer.name, "weightBits:", layer.convolution.quantizationParams.numberOfBits)
    

    若输出 weightBits: 8 即成功。

  5. Xcode 侧验证
    把 Model.mlmodel 拖入工程,Xcode 自动生成 Model.mlmodelc。
    Objective-C 调用:

    Model *model = [[Model alloc] init];
    ModelInput *input = [[ModelInput alloc] initWithInput_1:multiArrayInt8];
    ModelOutput *output = [model predictionFromInput_1:input error:&error];
    NSLog(@"output dataType: %ld", output.output_1.dataType); // 期望 1001=Int8
    

    若 dataType 为 1001 则量化链路完整。

  6. 体积与性能对比
    原 FP32 .mlmodel 23 MB → INT8 权重后 6.1 MB;
    iPhone 13 上同一帧耗时 8.3 ms → 5.1 ms,满足国内短视频 SDK 实时要求。

拓展思考

  1. 若 TFLite 使用权重-仅 INT8、激活 FP32,如何进一步让 Core ML 也跑 INT8 激活?
    答:需在转换前把 TFLite 重新校准,生成激活 INT8,再执行上述脚本;否则 Core ML 会插入 Dequantize→FP32 Conv→Quantize,反而变慢。
  2. 遇到 Core ML 3 的 INT4 新特性,能否再压体积?
    答:可以,把 quantization_mode=ct.QuantizationMode.LINEAR_QUANTIZATION, nbits=4,但需 A12+ 且 iOS 14+;国内低端机(iPhone 6s 仍在架)需 fallback,建议同一模型出两份 .mlmodelc,运行时根据 sysctlbyname("hw.optional.arm.FEAT_LPC) 动态选择。
  3. Objective-C 如何运行时判断模型是否量化?
    答:通过 MLModelConfiguration 的 computeUnits 与 model.modelDescription 各层 parameterType 遍历,可写 Category 封装成 - (BOOL)isQuantizedModel,方便 A/B 实验上报。