title: tensorflow custom op gradient
body: <p>We want to create a custom layer in tensorflow. Therefore, we decided to simply start with a toy example: a copy-Layer. After some try and error, we got to the point where it seems like the gradient would pass the right values through. However, in the second iteration the features get NAN's.
  It may be a simple mistake, but currently I can't see it.</p>
  
  <p>In general, I have two questions:</p>
  
  <ol>
  <li>Can someone spot the problem here and how to solve it?</li>
  <li>What is a good method to debug a tensorflow session?</li>
  </ol>
  
  <hr>
  
  <p><strong>copy_op.cc</strong></p>
  
  <pre class="lang-cc prettyprint-override"><code>#include "tensorflow/core/framework/op.h"
  #include "tensorflow/core/framework/op_kernel.h"
  #include &lt;stdio.h&gt;
  
  namespace tensorflow {
  
  
  
  typedef Eigen::ThreadPoolDevice CPUDevice;
  typedef Eigen::GpuDevice GPUDevice;
  
  template&lt;typename Device, typename T&gt;
  class MyCopyOp: public OpKernel {
  public:
      explicit MyCopyOp(OpKernelConstruction* context) :
              OpKernel(context) {
      }
  
      void Compute(OpKernelContext* context) override {
          const Tensor&amp; input = context-&gt;input(0);
          auto in_flat = input.flat&lt;T&gt;();
  
          printf("Debug MyCopyOp Features: %s \n",input.DebugString().c_str());
  
          Tensor* output = nullptr;
          OP_REQUIRES_OK(context,
                  context-&gt;allocate_output(0, input.shape(), &amp;output));
  
          auto out_flat = output-&gt;flat&lt;T&gt;();
          out_flat.setZero();
  
          for (int d = 0; d &lt; input.dims(); ++d) {
              for (int i = 0; i &lt; input.dim_size(d); ++i) {
                  out_flat(d * input.dim_size(d) + i) = in_flat(
                          d * input.dim_size(d) + i);
              }
          }
  
          printf("Debug MyCopyOp Output: %s \n",output-&gt;DebugString().c_str());
      }
  
  };
  
  
  template&lt;typename Device, typename T&gt;
  class MyCopyGradOp: public OpKernel {
  public:
      explicit MyCopyGradOp(OpKernelConstruction* context) :
              OpKernel(context) {
  
      }
  
      void Compute(OpKernelContext* context) override {
          printf("called MyCopyGradOp.Compute() \n");
          const Tensor&amp; gradients = context-&gt;input(0);
          const Tensor&amp; features = context-&gt;input(1);
          printf("Debug MyCopyOpGrad Gradients: %s \n",gradients.DebugString().c_str());
          printf("Debug MyCopyOpGrad Features: %s \n",features.DebugString().c_str());
  
          TensorShape output_shape = features.shape();
  
          Tensor* output = nullptr;
          OP_REQUIRES_OK(context,
                  context-&gt;allocate_output(0, output_shape, &amp;output));
          output-&gt;flat&lt;T&gt;().setZero();
  
          const T* btm_ptr = gradients.flat&lt;T&gt;().data();
          T* top_ptr = output-&gt;flat&lt;T&gt;().data();
  
          for (int i = 0; i &lt; gradients.NumElements(); ++i) {
              top_ptr[i] = btm_ptr[i];
          }
  
          printf("Debug MyCopyOpGrad Output: %s \n",output-&gt;DebugString().c_str());
          printf("---------------------------------- \n");
      }
  
  };
  
  
  REGISTER_OP("MyCopy")
  .Input("features: T")
  .Output("output: T")
  .Attr("T: realnumbertype")
  .Doc(R"doc(
  Copies all input values to the output
  )doc");
  
  REGISTER_OP("MyCopyGrad")
  .Input("gradients: T")
  .Input("features: T")
  .Output("backprops: T")
  .Attr("T: realnumbertype")
  .Doc(R"doc(
  TODO!!
  )doc");
  
  
  #define REGISTER_MYCOPY_KERNELS(type)                                           \
    REGISTER_KERNEL_BUILDER(                                                      \
        Name("MyCopy").Device(DEVICE_CPU).TypeConstraint&lt;type&gt;("T"),              \
        MyCopyOp&lt;Eigen::ThreadPoolDevice, type&gt;);                                 \
    REGISTER_KERNEL_BUILDER(                                                      \
        Name("MyCopyGrad").Device(DEVICE_CPU).TypeConstraint&lt;type&gt;("T"),          \
        MyCopyGradOp&lt;Eigen::ThreadPoolDevice, type&gt;);                             //  \
    // REGISTER_KERNEL_BUILDER(                                                      \
    //     Name("MyCopy").Device(DEVICE_GPU).TypeConstraint&lt;type&gt;("T"),              \
    //     MyCopyOp&lt;Eigen::GpuDevice, type&gt;);                                        \
    // REGISTER_KERNEL_BUILDER(                                                      \
    //     Name("MyCopyGrad").Device(DEVICE_GPU).TypeConstraint&lt;type&gt;("T"),          \
    //     MyCopyGradOp&lt;Eigen::GpuDevice, type&gt;);                                
  
  
  REGISTER_MYCOPY_KERNELS(float); 
  REGISTER_MYCOPY_KERNELS(int);
  REGISTER_MYCOPY_KERNELS(double);
  
  
  }
  </code></pre>
  
  <p>We used the simple MNIST example as the basis:</p>
  
  <p><strong>layer_test.py</strong></p>
  
  <pre class="lang-py prettyprint-override"><code>from tensorflow.examples.tutorials.mnist import input_data
  mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
  
  import tensorflow as tf
  from tensorflow.python.framework import ops
  copy_op_module = tf.load_op_library('copy_op.so')
  
  @ops.RegisterGradient("MyCopy")
  def _CopyOpGrad(op, grad):
    return copy_op_module.my_copy_grad(grad,op.inputs[0])
  
  sess = tf.InteractiveSession()
  
  x = tf.placeholder(tf.float32, shape=[None, 784])
  y_ = tf.placeholder(tf.float32, shape=[None, 10])
  
  W = tf.Variable(tf.zeros([784,10]))
  b = tf.Variable(tf.zeros([10]))
  
  sess.run(tf.initialize_all_variables())
  
  y1 = tf.nn.softmax(tf.matmul(x,W) + b)
  y = copy_op_module.my_copy(y1)            //Here: MyCopy Layer is inserted
  
  cross_entropy = -tf.reduce_sum(y_*tf.log(y))
  
  train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
  
  for i in range(2):
    batch = mnist.train.next_batch(50)
    train_step.run(feed_dict={x: batch[0], y_: batch[1]})
  
  correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
  </code></pre>
  
  <p><strong>compile</strong></p>
  
  <pre><code>TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())')
  TF_LIB=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_lib())')
  g++ -std=c++11 -shared copy_op.cc -o copy_op.so -I $TF_INC -L $TF_LIB -fPIC -Wl,-rpath $TF_LIB
  </code></pre>
  
  <p><strong>output:</strong></p>
  
  <pre><code>Debug MyCopyOp Features: Tensor&lt;type: float shape: [50,10] values: 0.1 0.1 0.1...&gt; 
  Debug MyCopyOp Output: Tensor&lt;type: float shape: [50,10] values: 0.1 0.1 0.1...&gt; 
  called MyCopyGradOp.Compute() 
  Debug MyCopyOpGrad Gradients: Tensor&lt;type: float shape: [50,10] values: -0 -0 -0...&gt; 
  Debug MyCopyOpGrad Features: Tensor&lt;type: float shape: [50,10] values: 0.1 0.1 0.1...&gt; 
  Debug MyCopyOpGrad Output: Tensor&lt;type: float shape: [50,10] values: -0 -0 -0...&gt; 
  ---------------------------------- 
  Debug MyCopyOp Features: Tensor&lt;type: float shape: [50,10] values: nan nan nan...&gt; 
  Debug MyCopyOp Output: Tensor&lt;type: float shape: [50,10] values: nan nan nan...&gt; 
  called MyCopyGradOp.Compute() 
  Debug MyCopyOpGrad Gradients: Tensor&lt;type: float shape: [50,10] values: nan nan nan...&gt; 
  Debug MyCopyOpGrad Features: Tensor&lt;type: float shape: [50,10] values: nan nan nan...&gt; 
  Debug MyCopyOpGrad Output: Tensor&lt;type: float shape: [50,10] values: nan nan nan...&gt; 
  ---------------------------------- 
  Debug MyCopyOp Features: Tensor&lt;type: float shape: [10000,10] values: nan nan nan...&gt; 
  Debug MyCopyOp Output: Tensor&lt;type: float shape: [10000,10] values: nan nan nan...&gt; 
  0.098
  </code></pre>
  
  <p>Thanks a lot in advance!</p>