meshgrid_op.h 7.0 KB
Newer Older
S
suytingwan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// 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 <vector>

#include <boost/preprocessor/arithmetic/mod.hpp>
#include <boost/preprocessor/comparison/greater.hpp>
#include <boost/preprocessor/comparison/greater_equal.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>

#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
28
#include "paddle/fluid/operators/eigen/eigen_function.h"
S
suytingwan 已提交
29 30 31
#include "paddle/fluid/platform/errors.h"

#define MAX_RANK_SUPPORTED 6
32 33 34 35 36 37 38 39
// 1. BOOST_PP_REPEAT macro represents a fast horizontal repetition construct.
//    Usage: BOOST_PP_REPEAT(count, macro, data).
//    This macro expands to the sequence:
//    macro(z, 0, data) macro(z, 1, data) ... macro(z, count - 1, data).
// 2. As for our case, count = MAX_RANK_SUPPORTED(which is 6).
//    So the range of n is 0-5(which is count-1).
//    We want to generate case 1-6 instead of case 0-5.
//    So we need to change n to n + 1.
S
suytingwan 已提交
40 41 42 43 44 45 46 47
#define MESHGRID_TEMPLATE(z, n, data) \
  case n + 1: {                       \
    MeshgridForward<n + 1>(context);  \
    break;                            \
  }
#define REP_MESHGRID_TEMPLATE(n) BOOST_PP_REPEAT(n, MESHGRID_TEMPLATE, ~)
#define COND(n) BOOST_PP_GREATER_EQUAL(n, BOOST_PP_MOD(n, MAX_RANK_SUPPORTED))

48 49 50 51
#define MESHGRID_GRAD_CASE(n)         \
  case n + 1: {                       \
    MeshgridBackward<n + 1>(context); \
    break;                            \
S
suytingwan 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  }
#define MESHGRID_GRAD_TEMPLATE(z, n, data) \
  BOOST_PP_IF(COND(n), MESHGRID_GRAD_CASE(n), )
#define REP_MESHGRID_GRAD_TEMPLATE(n) \
  BOOST_PP_REPEAT(n, MESHGRID_GRAD_TEMPLATE, ~)

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
class MeshgridKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto ins = context.MultiInput<framework::Tensor>("X");
    auto rank = ins.size();
    switch (rank) {
      REP_MESHGRID_TEMPLATE(MAX_RANK_SUPPORTED)
      default:
        PADDLE_THROW(platform::errors::InvalidArgument(
K
Kqnonrime 已提交
71 72
            "Excepted Tensor numbers between 1 and 6, but only received d% .",
            rank));
S
suytingwan 已提交
73 74 75 76 77 78 79 80 81 82
    }
  }

 protected:
  template <int Rank>
  void MeshgridForward(const framework::ExecutionContext& context) const {
    auto ins = context.MultiInput<framework::Tensor>("X");
    auto outs = context.MultiOutput<framework::Tensor>("Out");
    PADDLE_ENFORCE_EQ(
        ins.size() > 1, true,
K
Kqnonrime 已提交
83 84 85
        platform::errors::InvalidArgument(
            "Expected at least 2 input tensors, but only received d%.",
            ins.size()));
S
suytingwan 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

    int64_t size = ins.size();
    std::vector<int64_t> shape(size);

    for (int64_t i = 0; i < size; i++) {
      switch (ins[i]->dims().size()) {
        case 0:
          shape[i] = 1;
          break;
        case 1:
          shape[i] = ins[i]->dims()[0];
          break;
        default:
          PADDLE_THROW(platform::errors::InvalidArgument(
              "Expected scalar or 1D tensor in the tensor list but got tensor "
              "%d: ",
              i));
      }
    }

    for (int64_t i = 0; i < size; i++) {
      std::vector<int64_t> view_shape(size, 1);
      view_shape[i] = shape[i];

      framework::Tensor reshape_ins_tensor;
      TensorCopy(*ins[i], context.GetPlace(), context.device_context(),
                 &reshape_ins_tensor);
      framework::DDim out_dims_reshape = framework::make_ddim(view_shape);
      reshape_ins_tensor.Resize(out_dims_reshape);
      framework::DDim out_dims = framework::make_ddim(shape);

117
      Eigen::DSizes<Eigen::DenseIndex, Rank> bcast_dims;
S
suytingwan 已提交
118 119 120 121 122 123
      for (int64_t j = 0; j < size; j++) {
        bcast_dims[j] = shape[j];
      }
      bcast_dims[i] = 1;

      outs[i]->Resize(out_dims);
124 125
      auto x = framework::EigenTensor<T, Rank>::From(
          static_cast<const framework::Tensor>(reshape_ins_tensor));
S
suytingwan 已提交
126
      outs[i]->mutable_data<T>(context.GetPlace());
W
wuhuanzhou 已提交
127
      auto y = framework::EigenTensor<T, Rank>::From(*outs[i]);
S
suytingwan 已提交
128 129
      auto& place =
          *context.template device_context<DeviceContext>().eigen_device();
130 131
      EigenBroadcast<std::decay_t<decltype(place)>, T, Rank>::Eval(place, y, x,
                                                                   bcast_dims);
S
suytingwan 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    }
  }
};

template <typename DeviceContext, typename T>
class MeshgridGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto out_grad =
        context.MultiInput<framework::Tensor>(framework::GradVarName("Out"));
    int n = out_grad.size();
    switch (n) {
      REP_MESHGRID_GRAD_TEMPLATE(MAX_RANK_SUPPORTED)
      default:
        PADDLE_THROW(platform::errors::InvalidArgument(
K
Kqnonrime 已提交
147 148
            "Excepted Tensor numbers between 1 and 6, but only received d% .",
            n));
S
suytingwan 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    }
  }

 protected:
  template <int Rank>
  void MeshgridBackward(const framework::ExecutionContext& context) const {
    auto out_grad =
        context.MultiInput<framework::Tensor>(framework::GradVarName("Out"));
    auto ins = context.MultiInput<framework::Tensor>("X");
    auto outs =
        context.MultiOutput<framework::Tensor>(framework::GradVarName("X"));

    int n = out_grad.size();
    auto out_dims = out_grad[0]->dims();

    for (int i = 0; i < n; i++) {
      outs[i]->mutable_data<T>(context.GetPlace());
W
wuhuanzhou 已提交
166 167
      auto out_grad_tmp = framework::EigenVector<T>::Flatten(*out_grad[i]);
      auto in_grad = framework::EigenVector<T>::Flatten(*outs[i]);
S
suytingwan 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181

      std::vector<int> reduce_dims_vec;
      std::vector<int> reshape_dims_vec;
      for (int j = 0; j < n; j++) {
        reduce_dims_vec.push_back(reshape_dims_vec.size());
        if (j == i) {
          reshape_dims_vec.push_back(1);
          reshape_dims_vec.push_back(out_dims[j]);
        } else {
          reshape_dims_vec.push_back(out_dims[j]);
          reshape_dims_vec.push_back(1);
        }
      }

182
      Eigen::DSizes<Eigen::DenseIndex, Rank> reduce_dims;
S
suytingwan 已提交
183 184 185 186
      for (int k = 0; k < n; k++) {
        reduce_dims[k] = reduce_dims_vec[k];
      }

187
      Eigen::DSizes<Eigen::DenseIndex, Rank * 2> reshape_dims;
S
suytingwan 已提交
188 189 190 191 192 193
      for (int k = 0; k < n * 2; k++) {
        reshape_dims[k] = reshape_dims_vec[k];
      }

      auto& place =
          *context.template device_context<DeviceContext>().eigen_device();
194 195
      EigenBroadcastGrad<std::decay_t<decltype(place)>, T, Rank>::Eval(
          place, in_grad, out_grad_tmp, reduce_dims, reshape_dims);
S
suytingwan 已提交
196 197 198 199 200 201
    }
  }
};

}  // namespace operators
}  // namespace paddle