【问题标题】:Question about inconsistency between tensorflow lite quantization code, paper and documentation关于tensorflow lite量化代码、论文和文档不一致的问题
【发布时间】:2020-10-18 12:05:37
【问题描述】:

在google发表的this论文(Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference)中,量化方案描述如下:

在哪里,

M = S1 * S2 / S3

S1、S2和S3分别是输入和输出的尺度。

S1(和零点 Z1)和 S2(和零点 Z2 ) 可以很容易地确定,无论是“离线”还是“在线”。但是 S3(和零点 Z3)呢?这些参数取决于“实际”输出比例(即,没有量化的float 值)。但输出规模在计算之前是未知的。

根据张量流documentation

在推理时,权重从 8 位精度转换为浮点,并使用浮点内核进行计算。此转换只进行一次并缓存以减少延迟。

但下面的code 表示不同:

  tensor_utils::BatchQuantizeFloats(
      input_ptr, batch_size, input_size, quant_data, scaling_factors_ptr,
      input_offset_ptr, params->asymmetric_quantize_inputs);
  for (int b = 0; b < batch_size; ++b) {
    // Incorporate scaling of the filter.
    scaling_factors_ptr[b] *= filter->params.scale;
  }

  // Compute output += weight * quantized_input
  int32_t* scratch = GetTensorData<int32_t>(accum_scratch);
  tensor_utils::MatrixBatchVectorMultiplyAccumulate(
      filter_data, num_units, input_size, quant_data, scaling_factors_ptr,
      batch_size, GetTensorData<float>(output), /*per_channel_scale=*/nullptr,
      input_offset_ptr, scratch, row_sums_ptr, &data->compute_row_sums,
      CpuBackendContext::GetFromContext(context));

在这里我们可以看到:

  scaling_factors_ptr[b] *= filter->params.scale;

我认为这意味着:

  1. S1 * S2 已计算。
  2. 权重仍然是整数。只是最终结果是浮点数。
  3. 似乎不必计算 S3 和 Z3。但如果是这样,最终的浮点结果如何接近未量化的结果?

论文、文档和代码之间的这种不一致让我很困惑。我说不出我想念什么。谁能帮帮我?

【问题讨论】:

    标签: tensorflow tensorflow-lite quantization


    【解决方案1】:

    让我回答我自己的问题。突然间我看到了我错过的东西 骑自行车。上面问题中的代码来自函数 tflite::ops::builtin::fully_connected::EvalHybrid()。这里 名字说明了一切!矩阵乘法的输出值为 在论文的第 2.2 节中表示为 r3。就方程而言 (2) 在第 2.2 节中,我们有:

    如果我们想得到矩阵乘法的float结果,我们可以使用2.2节中的等式(4),然后将结果转换回float,或者我们可以使用等式(3)将左边替换为r3,如:

    如果我们把所有的零点都选为0,那么上面的公式就变成了:

    这正是EvalHybrid() 所做的(暂时忽略偏见)。原来这篇论文给出了量化算法的概要,而实现使用了不同的变体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2011-03-04
      相关资源
      最近更新 更多