Ravi Patel
Ravi Patel

Reputation: 37

C++ Accessing Eigen::Tensor Class function from Tensorflow::Tensor object

This is probably a stupid question but I'm having difficulty accessing a Eigen::Tensor class function from within a custom op function (void Compute) in tensorflow.

Eigen::Tensor has a member function called "extract_patches" that i'd like to access from inside the op. When I "typeid()" the tensor object, it returns tensorflow::Tensor. How do access the underlying Eigen::Tensor?

Note the code for "extract_patches" is directly from the Eigen documentation.

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/framework/numeric_op.h"
#include "tensorflow/core/util/tensor_format.h"
#include <vector>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"

using namespace tensorflow;

class SauronOp : public OpKernel {
 public:
  explicit SauronOp(OpKernelConstruction* context) : OpKernel(context) {// Some checks}

  void Compute(OpKernelContext* context) override {

    //declare temporary storage 
    TensorShape a_shape_temp({act_in_batch, act_in_rows, act_in_cols });
    Tensor a_temp;
    OP_REQUIRES_OK(context, context->allocate_temp( DataTypeToEnum<float>::value,
                                        a_shape_temp,  &a_temp));
    //auto a_matrix = a_temp.shaped<float,3>({{act_in_batch, act_in_rows, act_in_cols });
    auto a_tensor = a_temp.tensor<float,3>();

    //unrelated stuff

    Eigen::Tensor<float, 4> patch;
    Eigen::array<ptrdiff_t, 3> patch_dims;
    patch_dims[0] = filter_height;
    patch_dims[1] = filter_width;
    patch_dims[2] = act_in_cols;

// THIS LINE GENERATES THIS PROBLEM (sorry for yelling)
    patch = a_tensor.extract_patches(patch_dims);

// output for debug
    std::cout<<"type "<< typeid(a_tensor).name()<<std::endl;
    std::cout<<"type "<< typeid(a_temp).name()<<std::endl;
  }

Output

type N5Eigen9TensorMapINS_6TensorIfLi3ELi1ElEELi16EEE
type N10tensorflow6TensorE

Upvotes: 0

Views: 1219

Answers (1)

mrry
mrry

Reputation: 126184

I suspect the problem is that extract_patches() returns an Eigen::TensorPatchOp<...> (representing the unevaluated expression) and not an Eigen::Tensor<...> (representing the evaluated value). To make this work you need to (i) call .eval() on the result of .extract_patches(), and (ii) declare patch as being row-major to obtain an object of the desired type.

The following code compiles for me in a Compute() method:

Tensor a_temp;
// Initialize `a_temp`...

const auto& a_tensor = a_temp.shaped<float, 3>(
    {act_in_batch, act_in_rows, act_in_cols});

Eigen::array<ptrdiff_t, 3> patch_dims;
patch_dims[0] = filter_height;
patch_dims[1] = filter_width;
patch_dims[2] = act_in_cols;

const auto& patch_expr = a_tensor.extract_patches(patch_dims);

Eigen::Tensor<float, 4, Eigen::RowMajor> patch = patch_expr.eval();

Upvotes: 0

Related Questions