写出 MLIR 的 Q-Operator 对 MatMul 的 scale 约束

解读

在国内大模型推理加速面试中,面试官问“MLIR 的 Q-Operator 对 MatMul 的 scale 约束”并不是想听你背公式,而是考察三件事:

  1. 你是否真的用 mlir::quant::QuantizedType 做过量化 dialect 的 lowering;
  2. 你是否理解 scale 是跨 op 的“语义契约”,一旦写错就会让后端对接 TOSA/LLVM 时直接崩溃;
  3. 你是否能把 对称量化 per-channel / per-tensor 的 scale 传播规则讲清楚,并给出可落地的 MLIR 校验代码片段。
    因此,回答必须给出 mlir 源码级约束表达式,并说明在 qmatmul → tosa.matmul 降级路径 上 scale 如何被强制执行。

知识点

  1. Q-Operator 在 MLIR 中的定义:
    位于 mlir/Dialect/Quant/QuantOps.td,由 quant.qcast、quant.dcast、quant.matmul 三个 op 构成,其中 quant.matmul 是 QuantizedOpInterface 的实现体。
  2. scale 的两种载体:
    • per-tensor:uniform<si8:f32, scale=0.123>,整个 tensor 一个 scale;
    • per-channel:uniform<si8:f32:0, {scale=[0.1,0.2,…]}>,第 0 维每通道一个 scale。
  3. Q-Operator 对 MatMul 的语义约束(官方文档 QuantizedMatmulOp 的 verifier):
    • lhs scale · rhs scale = output scale 必须成立;
    • zero-point 必须全 0(对称量化),否则 emitOpError;
    • per-channel 场景:
      – 若 lhs 为 per-channel,则 channel 维必须对应 MatMul 的 reduction 维(K 维),且 rhs 必须是 per-tensor;
      – 若 rhs 为 per-channel,则 channel 维必须对应 MatMul 的 输出维(N 维),且 lhs 必须是 per-tensor;
      – 禁止 lhs、rhs 同时 per-channel。
  4. scale 类型在 MLIR 中的 C++ 校验代码(面试常让你手写):
    auto lhsScale = getElementTypeOrSelf(lhsType).cast<UniformQuantizedType>().getScale();
    auto rhsScale = getElementTypeOrSelf(rhsType).cast<UniformQuantizedType>().getScale();
    auto outScale = getElementTypeOrSelf(outType).cast<UniformQuantizedType>().getScale();
    if (std::abs(lhsScale * rhsScale - outScale) > 1e-6)
      return emitOpError() << "scale constraint violated: "
                           << lhsScale << " * " << rhsScale << " != " << outScale;
    

答案

在 MLIR 的量化 dialect 中,quant.matmul 对 scale 的约束可归纳为一条等式 + 三条通道规则:

  1. 等式约束:
    lhs_scale × rhs_scale = output_scale(允许 1e-6 浮点误差)。
  2. zero-point 约束:
    lhs、rhs、output 的 zero_point 必须全 0(对称量化)。
  3. per-channel 排他约束:
    • 只允许 lhs 或 rhs 其中一张是 per-channel,且 channel 维必须落在 MatMul 的 K 维(lhs)或 N 维(rhs);
    • 禁止双 per-channel;
    • per-channel 张量的 scale 数组长度必须等于对应维度的 size。
  4. 类型验证:
    所有张量元素类型必须是 quant.uniformsi8:f32 或 quant.uniform<si8:f32:channel_axis, [{scale}]>,否则 verifier 直接失败。

满足以上四条,MLIR 的 -quant-to-tosa 降级管道才会把 quant.matmul 成功映射为 tosa.matmul,并在 TOSA 层面继续保证 scale 作为 1D fp32 buffer 被正确传入后续对接的 ACL / XNNPACK / 自研 INT8 内核。

拓展思考

  1. 动态 shape 场景:
    当 K 维在运行期才确定时,per-channel scale 数组长度无法静态验证,此时需要在 shape 推断阶段插入 quant.matmul_shape 辅助 op,把 scale 数组长度与 K 维符号表达式绑定,否则 -reconcile-uniform-quantized-types pass 会报错退出。
  2. int4 / int16 扩展:
    目前社区 patch 把 scale 约束硬编码成 si8,若未来支持 int4,需要把等式改为 lhs_scale × rhs_scale / output_scale = 1.0f,并引入 shift 参数做 2 的幂对齐,才能兼容 TOSA 的 tosa.matmul_scale8_4 扩展 op。
  3. 面试反杀技巧:
    如果面试官追问“为什么不是 lhs_scale × rhs_scale / output_scale = 1”,你可以回答:
    “在 TOSA spec v0.70 之前确实用除法形式,但 MLIR 量化 dialect 为了 避免 fp32 除法精度尾差,统一改成乘法等式,并在 quant.uniform 类型里强制 scale 为 正有限数,这样 bit-exact 校验只需一次乘法,减少后端硬件 scale 单元面积。” 这句话一出,基本锁定 offer。