我正在尝试使用 TensorFlow 的@tf.custom_gradient
功能将自定义渐变分配给具有多个输入的函数。我可以为一个输入组合一个工作设置,但不能为两个或更多输入。
我的代码基于TensorFlow 的 custom_gradient 文档,它适用于一个输入,如下例所示:
import tensorflow as tf
import os
# Suppress Tensorflow startup info
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
# Custom gradient decorator on a function,
# as described in documentation
@tf.custom_gradient
def my_identity(x):
# The custom gradient
def grad(dy):
return dy
# Return the result AND the gradient
return tf.identity(x), grad
# Make a variable, run it through the custom op
x = tf.get_variable('x', initializer=1.)
y = my_identity(x)
# Calculate loss, make an optimizer, train the variable
loss = tf.abs(y)
opt = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train = opt.minimize(loss)
# Start a TensorFlow session, initialize variables, train
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(train)
此示例静默运行,然后关闭。没有问题,没有错误。变量按预期进行优化。但是,在我的应用程序中,我需要使用多个输入进行这样的计算,所以这种形式的东西:
@tf.custom_gradient
def my_identity(x, z):
def grad(dy):
return dy
return tf.identity(x*z), grad
运行它来代替示例(并将另一个变量输入添加到 的调用my_identify
)会导致以下错误输出。据我所知,错误的最后一部分来自操作的动态生成——信息格式与操作建立所需的 C++ 格式相匹配(尽管这就是我所知道的全部)。
Traceback (most recent call last):
File "testing.py", line 27, in <module>
train = opt.minimize(loss)
File "/usr/lib/python3/dist-packages/tensorflow/python/training/optimizer.py", line 400, in minimize
grad_loss=grad_loss)
File "/usr/lib/python3/dist-packages/tensorflow/python/training/optimizer.py", line 519, in compute_gradients
colocate_gradients_with_ops=colocate_gradients_with_ops)
File "/usr/lib/python3/dist-packages/tensorflow/python/ops/gradients_impl.py", line 630, in gradients
gate_gradients, aggregation_method, stop_gradients)
File "/usr/lib/python3/dist-packages/tensorflow/python/ops/gradients_impl.py", line 821, in _GradientsHelper
_VerifyGeneratedGradients(in_grads, op)
File "/usr/lib/python3/dist-packages/tensorflow/python/ops/gradients_impl.py", line 323, in _VerifyGeneratedGradients
"inputs %d" % (len(grads), op.node_def, len(op.inputs)))
ValueError: Num gradients 2 generated for op name: "IdentityN"
op: "IdentityN"
input: "Identity"
input: "x/read"
input: "y/read"
attr {
key: "T"
value {
list {
type: DT_FLOAT
type: DT_FLOAT
type: DT_FLOAT
}
}
}
attr {
key: "_gradient_op_type"
value {
s: "CustomGradient-9"
}
}
do not match num inputs 3
基于其他自定义渐变选项,我推测问题是缺少为第二个输入参数提供的渐变。因此,我将功能更改为:
@tf.custom_gradient
def my_identity(x, z):
def grad(dy):
return dy
return tf.identity(x*z), grad, grad
这会导致以下更熟悉的错误:
Traceback (most recent call last):
File "testing.py", line 22, in <module>
y = my_identity(x, z)
File "/usr/lib/python3/dist-packages/tensorflow/python/ops/custom_gradient.py", line 111, in decorated
return _graph_mode_decorator(f, *args, **kwargs)
File "/usr/lib/python3/dist-packages/tensorflow/python/ops/custom_gradient.py", line 132, in _graph_mode_decorator
result, grad_fn = f(*args)
ValueError: too many values to unpack (expected 2)
装饰器仅将@custom_gradient
最后返回的元素标识为渐变。因此,我尝试将两个渐变放入一个元组中,(grad, grad)
这样该函数只会有“两个”输出。TensorFlow 也拒绝了这一点,这一次是因为它不能像调用张量那样调用元组——事后看来,这是完全合理的。
我已经对这个例子大惊小怪了一些,但无济于事。无论我尝试什么,我都无法获得自定义渐变来处理多个输入。我希望在自定义操作和渐变方面比我有更多知识的人对此有更好的了解——在此先感谢您的帮助!