【问题标题】:How to backprop for custom quantization in tensorflow 2.0?如何在 tensorflow 2.0 中支持自定义量化?
【发布时间】:2020-03-26 09:16:21
【问题描述】:

当我在 tf2.0 急切模式下量化张量时,我想用恒等式(直接通过估计器)进行反向传播。我能够执行前向传递,但在尝试为我的模型应用渐变以进行反向传播时遇到 ValueError: No gradients provided for any variable.. 错误。

我尝试使用自定义渐变。作为一个最小示例,请考虑以下代码:

import tensorflow as tf
@tf.custom_gradient
def quantize(x):
    x = tf.cast(x, dtype=tf.uint8)
    def grad(dy):
        return dy
    return x, grad

@tf.custom_gradient
def dequantize(x):
  x = tf.cast(x, dtype=tf.float32)
  def grad(dy):
       return dy
  return x, grad

x = tf.ones([10,10])
with tf.GradientTape() as g:
  g.watch(x)
  y = dequantize(quantize(x))*2
dy_dx = g.gradient(y, x) 

print(dy_dx) # outputs None

渐变为无,这意味着当我在模型中使用此类函数时,我将无法进行反向传播。我应该如何解决这个问题?考虑到我需要 tf.quantize() 以外的东西,有没有更好的方法来实现量化?

另外,我使用GradientTape g的方式是根据官方教程,但我不明白为什么他们会在with范围之外使用g(最后 代码中的行)。任何澄清表示赞赏。

【问题讨论】:

标签: python tensorflow machine-learning tensorflow2.0 quantization


【解决方案1】:

问题是您通过转换为整数来量化。改用 floor 函数

@tf.custom_gradient
def quantize(x):
    x = tf.math.floor(x)
    def grad(dy):
        return dy
    return x, grad

x = tf.ones((10,10))
with tf.GradientTape() as g:
  g.watch(x)
  y = quantize(1.1*x+.1)*2

dy_dx = g.gradient(y, x, output_gradients = tf.ones((10,10)))

print(dy_dx)

【讨论】:

    猜你喜欢
    • 2020-10-18
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    相关资源
    最近更新 更多