Skip to main content
 首页 » 编程设计

python之Tensorflow 每 channel 量化

2024年12月31日29xxx_UU

使用当前的 Tensorflow quantization ops ,我将如何在推理过程中模拟每 channel 量化?这paper将每层量化定义为

We can specify a single quantizer (defined by the scale and zero-point) for an entire tensor referred to as per-layer quantization

和每 channel 量化为

Per-channel quantization has a different scale and offset for each convolutional kernel.

假设我们有这个子图

import tensorflow as tf 
 
x = np.random.uniform(size=500*80*64*1) 
      .astype('float32') 
      .reshape(500, 80, 64, 1) 
W1 = tf.get_variable('W1', 9, 5, 1, 96], 
                    initializer=tf.truncated_normal_initializer(stddev=0.1)) 
h1 = tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='VALID') 

在目前的 API 下,我可能会做这样的事情来模拟推理时的每层量化

import tensorflow as tf 
 
x = np.random.uniform(size=500*80*64*1) 
      .astype('float32') 
      .reshape(500, 80, 64, 1) 
min_x = tf.reduce_min(x) 
max_x = tf.reduce_max(x) 
 
W1 = tf.get_variable('W1', 9, 5, 1, 96], 
                    initializer=tf.truncated_normal_initializer(stddev=0.1)) 
min_W1 = tf.reduce_min(W1) 
max_W1 = tf.reduce_max(W1) 
 
qX = tf.quantize(A, min_X, max_X, tf.quint8, mode='MIN_FIRST') 
qW = tf.quantize(W, min_W, max_W, tf.quint8, mode='MIN_FIRST') 
 
# This is how one would simulate per layer quantization for convolution. 
qAW = tf.nn.quantized_conv2d(qX[0], qW[0], qX[1], qX[2], qW[1], qW[2],  
strides = [1, 1, 1, 1], padding='VALID') 

我的问题是如何模拟每个 channel 的量化?据我了解 tf.quantization.quantize实际上是在做per-layer quantization 而不是per-channel quantization。此外,tf.nn.quantized_conv2d 实际上是在对量化层内核卷积执行量化层输入。

根据我对per-channel 量化的理解,会有k、output_min 和output_max。在我的示例中,k 是 96(内核数量,类似于 API)。

tensorflow 中是否存在任何可以处理每 channel 量化的现有操作,或者是否有办法使其与现有操作一起使用?

请您参考如下方法:

目前无法在 tflite 上模拟每个 channel 的量化推理。 如我所见,如今的 tensorflow 开发人员正在实现 experimental symmetric per channel quantization .但是没有办法测试它