/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "paddle/framework/tensor.h" #include "unsupported/Eigen/CXX11/Tensor" namespace paddle { namespace framework { // EigenDim converts paddle::platform::DDim into Eigen::DSizes. template struct EigenDim { using Type = Eigen::DSizes; static Type From(const DDim& dims) { PADDLE_ENFORCE(arity(dims) == D, "D must match arity(DDim)"); Type ret; for (int d = 0; d < arity(dims); d++) { ret[d] = dims[d]; } return ret; } }; // Interpret paddle::platform::Tensor as EigenTensor and EigenConstTensor. template struct EigenTensor { using Type = Eigen::TensorMap, Eigen::Aligned>; using ConstType = Eigen::TensorMap, Eigen::Aligned>; static Type From(Tensor& tensor, DDim dims) { return Type(tensor.data(), EigenDim::From(dims)); } static Type From(Tensor& tensor) { return From(tensor, tensor.dims_); } static ConstType From(const Tensor& tensor, DDim dims) { return ConstType(tensor.data(), EigenDim::From(dims)); } static ConstType From(const Tensor& tensor) { return From(tensor, tensor.dims_); } }; // Interpret paddle::platform::Tensor as EigenVecotr and EigenConstVector. template struct EigenVector { using Type = Eigen::TensorMap, Eigen::Aligned>; using ConstType = Eigen::TensorMap, Eigen::Aligned>; // From is to transfer a one dimension Tensor into a one dimension EigenVector static Type From(Tensor& tensor) { return EigenTensor::From(tensor); } // Flatten is to reshape a Tensor into a one dimension EigenVector static Type Flatten(Tensor& tensor) { return EigenTensor::From( tensor, make_ddim({static_cast(product(tensor.dims_))})); } static ConstType From(const Tensor& tensor) { return EigenTensor::From(tensor); } static ConstType Flatten(const Tensor& tensor) { return EigenTensor::From( tensor, make_ddim({static_cast(product(tensor.dims_))})); } }; // Interpret paddle::platform::Tensor as EigenMatrix and EigenConstMatrix. template struct EigenMatrix { using Type = Eigen::TensorMap, Eigen::Aligned>; using ConstType = Eigen::TensorMap, Eigen::Aligned>; static Type From(Tensor& tensor) { return EigenTensor::From(tensor); } static ConstType From(const Tensor& tensor) { return EigenTensor::From(tensor); } }; } // namespace framework } // namespace paddle