简体   繁体   中英

Why does the following segfault?

The following seg faults for me for some reason after compiling with:

g++ 1.cpp -I/path_to_eigen/eigen -std=c++0x

It is supposed to do a dot product between two tensors of rank 1 of the same length (and hence give a tensor of rank 1 and dimension 1).

#include <Eigen/Core>
#include <unsupported/Eigen/CXX11/Tensor>
#include <iostream>
#include <array>

using namespace Eigen;
using namespace std;


int main()
{
        Eigen::Tensor<double, 1> tensor(5);
        Eigen::Tensor<double, 1> tensor2(5);

        std::array<Eigen::IndexPair<int>, 1> product_dims = { IndexPair<int>(0, 0) };

        Eigen::Tensor<double, 1> tensor3(1);

        tensor3 = tensor.contract(tensor2, product_dims);
}

NOTE: if I change

        tensor3 = tensor.contract(tensor2, product_dims);

to

        auto v = tensor.contract(tensor2, product_dims);

then it compiles, and executes without segfaulting, but I am not sure what type v is! I need it to be a tensor of rank 1 and dimension 1, as specified here in the documentation:

https://github.com/RLovelett/eigen/blob/master/unsupported/Eigen/CXX11/src/Tensor/README.md

Similarly, the inner product of 2 1d tensors (through contractions) returns a 1d tensor.

EDIT: The following gives an assertion error:

#include <Eigen/Core>
#include <unsupported/Eigen/CXX11/Tensor>
#include <iostream>
#include <array>

using namespace Eigen;
using namespace std;


int main()
{
        Eigen::Tensor<double, 1> tensor(5);
        Eigen::Tensor<double, 1> tensor2(5);

        tensor.setConstant(1);
        tensor2.setConstant(2);
        tensor(1) = 1;
        tensor2(1) = 2;

        std::array<Eigen::IndexPair<int>, 1> product_dims = { IndexPair<int>(0, 0) };

        Eigen::Tensor<double, 1> tensor3(1);

        tensor3.setConstant(0);

        auto v = tensor.contract(tensor2, product_dims);

        cerr<<v<<endl;

        tensor3 = tensor3 + v;

        cerr<<tensor3<<endl;
}

where I now use tensor3 = tensor3 + v instead of directly assigning v tensor3.

The error is:

Assertion failed: (dimensions_match(m_leftImpl.dimensions(), m_rightImpl.dimensions())), function TensorEvaluator, file /Users/eigen/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h, line 355.

The documentation is outdated. The rank of the result of a contraction is given by the following equation: RankL + RankR - 2*CDims, where RankL is the rank of the first input tensor, RankR the rank of the second input tensor, and CDims the number of contracted dimensions.

In your example, the rank of the result is 0. You should write Eigen::Tensor<double, 0> tensor3 = tensor.contract(tensor2, product_dims);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM