【问题标题】:Use tensor's value to modify another tensor at run-time使用张量的值在运行时修改另一个张量
【发布时间】:2023-03-21 17:09:01
【问题描述】:

在 TensorFlow 中,我想将“假”量化函数之一应用于我的一个张量。具体来说我有兴趣使用this函数:

fake_quant_with_min_max_args(
    inputs,
    min=-6,
    max=6,
    num_bits=8,
    narrow_range=False,
    name=None
    )

开箱即用,效果很好。理想情况下,我想根据输入张量调整 minmax 参数。具体来说,我想使用99.7% rule 来定义该范围。换句话说,我想使用的值范围是,如果将输入张量表示为一维向量,则其 99.7% 的元素将位于 [mean-3*std, mean + 3*std ] 范围。

为此,我执行以下操作:

def smartFakeQuantization(tensor):
    # Convert the input tensor to a 1-d tensor
    t_1d_data = tf.reshape(tensor,[tf.size(tensor), 1])
    # get the moments of that tensor. Now mean and var have shape (1,)
    mean, var = tf.nn.moments(t_1d_data, axes=[0])
    # get a tensor containing the std
    std = tf.sqrt(var)

    < some code to get the values of those tensors at run-time>

    clip_range = np.round([mean_val - 3*std_val, mean_val + 3*stdstd_val], decimals=3)
    return tf.fake_quant_with_min_max_args(tensor, min=clip_range[0], max=clip_range[1])

我知道我可以通过执行以下操作来评估图中的任何张量:myTensor.eval()mySession.run(myTensor) 但如果我在我的函数上方添加这些类型的线,它会在执行图表时崩溃。我会收到表单错误:

张量 <...> 已被标记为不可获取。

我所遵循的步骤可能不是 TensorFlow 的“图形”性质的正确步骤。任何想法如何做到这一点?总而言之,我想在运行时使用张量的值来修改另一个张量。我想说这个问题比tf.cond() 可以解决的问题更复杂。

【问题讨论】:

  • 我想我已经缩小了一点问题的范围。似乎我收到此错误是因为图形尚未初始化......因此执行 .eval() 会崩溃。

标签: python tensorflow quantization


【解决方案1】:

我认为没有一种简单的方法可以做你想做的事。 fake_quant_with_min_max_argsminmax 参数被转换为操作属性并在底层内核的construction 中使用。它们不能在运行时更改。有一些(似乎不是公共 API 的一部分)ops(参见 LastValueQuantizeMovingAvgQuantize)会根据他们看到的数据调整其间隔,但它们并没有完全按照您的意愿行事。

您可以编写自己的自定义操作,或者如果您认为这通常很有价值,请在 github 上提交功能请求。

【讨论】:

    【解决方案2】:

    您可以使用 tf.fake_quant_with_min_max_vars,它接受张量作为最小/最大参数:

    return tf.fake_quant_with_min_max_vars(tensor, min=mean-3*std, max=mean+3*std)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2019-07-23
      • 2020-08-01
      • 2019-12-12
      相关资源
      最近更新 更多