如何冻结/锁定一个TensorFlow变量的权重(例如,一个层的一个CNN内核)

JHa*_*nko 8 pruning tensorflow

我有一个表现良好的TensorFlow CNN模型,我们希望在硬件中实现这个模型; 即一个FPGA.这是一个相对较小的网络,但如果它更小,它将是理想的.有了这个目标,我已经检查了内核,发现有一些权重非常强,还有一些根本没有做太多(内核值都接近于零).这特别发生在第2层,对应于名为"W_conv2"的tf.Variable().W_conv2具有形状[3,3,32,32].我想冻结/锁定W_conv2 [:,:,29,13]的值并将它们设置为零,以便可以训练网络的其余部分进行补偿.将该内核的值设置为零有效地从硬件实现中移除/修剪内核,从而实现上述目标.

我发现了类似的问题,建议通常围绕两种方法之一;

建议#1:

    tf.Variable(some_initial_value, trainable = False)
Run Code Online (Sandbox Code Playgroud)

实现此建议会冻结整个变量.我想冻结一个切片,特别是W_conv2 [:,:,29,13].

建议#2:

    Optimizer = tf.train.RMSPropOptimizer(0.001).minimize(loss, var_list)
Run Code Online (Sandbox Code Playgroud)

同样,实现此建议不允许使用切片.例如,如果我尝试我所声明目标的反转(仅优化单个变量的单个内核),如下所示:

    Optimizer = tf.train.RMSPropOptimizer(0.001).minimize(loss, var_list = W_conv2[:,:,0,0]))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

    NotImplementedError: ('Trying to optimize unsupported type ', <tf.Tensor 'strided_slice_2228:0' shape=(3, 3) dtype=float32>)
Run Code Online (Sandbox Code Playgroud)

以我在这里尝试的方式切换tf.Variables()是不可能的.我尝试过的唯一可以接近做我想要的就是使用.assign(),但这是非常低效,笨重,和穴居人一样,因为我已经按照以下方式实现了它(在训练模型之后):

    for _ in range(10000):
        # get a new batch of data
        # reset the values of W_conv2[:,:,29,13]=0 each time through
        for m in range(3):
            for n in range(3):
                assign_op = W_conv2[m,n,29,13].assign(0)
                sess.run(assign_op)
        # re-train the rest of the network
        _, loss_val = sess.run([optimizer, loss], feed_dict = {
                                   dict_stuff_here
                               })
        print(loss_val)
Run Code Online (Sandbox Code Playgroud)

该模型在Keras开始,然后转移到TensorFlow,因为Keras似乎没有达到预期结果的机制.我开始认为TensorFlow不允许修剪,但发现这很难相信; 它只需要正确的实施.

zoh*_*kom 2

一种可能的方法是用零初始化这些特定权重,并修改最小化过程,以便不对它们应用梯度。可以通过将调用替换为minimize()以下内容来完成:

W_conv2_weights = np.ones((3, 3, 32, 32))
W_conv2_weights[:, :, 29, 13] = 0
W_conv2_weights_const = tf.constant(W_conv2_weights)

optimizer = tf.train.RMSPropOptimizer(0.001)

W_conv2_orig_grads = tf.gradients(loss, W_conv2)
W_conv2_grads = tf.multiply(W_conv2_weights_const, W_conv2_orig_grads)
W_conv2_train_op = optimizer.apply_gradients(zip(W_conv2_grads, W_conv2))

rest_grads = tf.gradients(loss, rest_of_vars)
rest_train_op = optimizer.apply_gradients(zip(rest_grads, rest_of_vars))

tf.group([rest_train_op, W_conv2_train_op])
Run Code Online (Sandbox Code Playgroud)

IE,

  1. Preparing a constant Tensor for canceling the appropriate gradients
  2. Compute gradients only for W_conv2, then multiply element-wise with the constant W_conv2_weights to zero the appropriate gradients and only then apply gradients.
  3. Compute and apply gradients "normally" to the rest of the variables.
  4. Group the 2 train ops to a single training op.