tile_op.h 11.6 KB
Newer Older
L
lilong12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright (c) 2016 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 <algorithm>
#include <vector>

#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
23
#include "paddle/fluid/operators/eigen/eigen_function.h"
L
lilong12 已提交
24 25 26 27 28 29 30 31 32 33 34

#define MAX_RANK_SUPPORTED 6

namespace paddle {
namespace operators {
inline std::vector<int> get_repeat_times(
    const framework::ExecutionContext& ctx) {
  if (ctx.HasInput("RepeatTimes")) {
    auto* repeat_tensor = ctx.Input<framework::LoDTensor>("RepeatTimes");
    auto* repeat_data = repeat_tensor->data<int>();
    framework::Tensor cpu_repeat_tensor;
35
    if (platform::is_gpu_place(repeat_tensor->place()) ||
36
        platform::is_xpu_place(repeat_tensor->place()) ||
37
        platform::is_npu_place(repeat_tensor->place())) {
38 39
      paddle::framework::TensorCopySync(*repeat_tensor, platform::CPUPlace(),
                                        &cpu_repeat_tensor);
L
lilong12 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53
      repeat_data = cpu_repeat_tensor.data<int>();
    }
    auto vec_repeat_times =
        std::vector<int>(repeat_data, repeat_data + repeat_tensor->numel());
    return vec_repeat_times;
  }

  auto list_repeat_times_tensor =
      ctx.MultiInput<framework::Tensor>("repeat_times_tensor");
  if (list_repeat_times_tensor.size() > 0) {
    // get tensor from
    std::vector<int> vec_repeat_times;
    for (size_t i = 0; i < list_repeat_times_tensor.size(); ++i) {
      auto tensor = list_repeat_times_tensor[i];
54
      if (platform::is_gpu_place(tensor->place()) ||
55
          platform::is_xpu_place(tensor->place()) ||
56
          platform::is_npu_place(tensor->place())) {
L
lilong12 已提交
57
        framework::Tensor temp;
58
        paddle::framework::TensorCopySync(*tensor, platform::CPUPlace(), &temp);
L
lilong12 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        vec_repeat_times.push_back(*temp.data<int32_t>());
      } else {
        vec_repeat_times.push_back(*tensor->data<int32_t>());
      }
    }
    return vec_repeat_times;
  } else {
    return ctx.Attr<std::vector<int>>("repeat_times");
  }
}

using Tensor = framework::Tensor;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;
template <typename T, size_t D, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>;
using framework::To32BitIndex;

template <typename DeviceContext, typename T>
class TileKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto rank = context.Input<Tensor>("X")->dims().size();
    PADDLE_ENFORCE_GE(
        rank, 1, platform::errors::InvalidArgument(
                     "The rank of the input 'x' for tile op must be a positive "
                     "integer, but the value received is %d.",
                     rank));
    PADDLE_ENFORCE_LE(
        rank, MAX_RANK_SUPPORTED,
        platform::errors::InvalidArgument(
            "The rank of the input 'x' for tile op "
            "must be less than or equal to %d, but the value received is %d.",
            MAX_RANK_SUPPORTED, rank));
    auto repeat_times = get_repeat_times(context);
    int repeat_times_size = repeat_times.size();
    PADDLE_ENFORCE_GE(
        repeat_times_size, 1,
        platform::errors::InvalidArgument(
            "The number of elements of the input 'repeat_times' for tile "
            "op must be positive, but the value received is %d.",
            repeat_times_size));
    PADDLE_ENFORCE_LE(
        repeat_times_size, MAX_RANK_SUPPORTED,
        platform::errors::InvalidArgument(
            "The number of elements of the input 'repeat_times' for tile op "
            "must be less than or equal to %d, but the value received is %d.",
            MAX_RANK_SUPPORTED, repeat_times_size));
    rank = std::max(rank, repeat_times_size);
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    switch (rank) {
      case 1:
        Tile<1>(context);
        break;
      case 2:
        Tile<2>(context);
        break;
      case 3:
        Tile<3>(context);
        break;
      case 4:
        Tile<4>(context);
        break;
      case 5:
        Tile<5>(context);
        break;
      case 6:
        Tile<6>(context);
        break;
    }
L
lilong12 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  }

 protected:
  template <int Rank>
  void Tile(const framework::ExecutionContext& context) const {
    auto* in0 = context.Input<Tensor>("X");

    auto in_dims = in0->dims();
    auto repeat_times = get_repeat_times(context);
    for (size_t i = 0; i < repeat_times.size(); ++i) {
      PADDLE_ENFORCE_GT(
          repeat_times[i], 0,
          platform::errors::InvalidArgument(
              "All elements of the input 'repeat_times' for tile op must "
              "be positive integers, but the value received is %d.",
              repeat_times[i]));
    }
147
    auto vec_in_dims = phi::vectorize<int>(in_dims);
L
lilong12 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161
    if (repeat_times.size() < vec_in_dims.size()) {
      int diff = vec_in_dims.size() - repeat_times.size();
      repeat_times.insert(repeat_times.begin(), diff, 1);
    } else {
      int diff = repeat_times.size() - vec_in_dims.size();
      vec_in_dims.insert(vec_in_dims.begin(), diff, 1);
    }
    PADDLE_ENFORCE_EQ(
        repeat_times.size(), vec_in_dims.size(),
        platform::errors::InvalidArgument(
            "The rank (%d) of the input 'x' and the rank (%d) of the input "
            "'repeat_times' for tile op must match after promotion.",
            vec_in_dims.size(), repeat_times.size()));
    auto* out0 = context.Output<Tensor>("Out");
162
    Eigen::DSizes<Eigen::DenseIndex, Rank> bcast_dims;
L
lilong12 已提交
163 164 165 166
    for (size_t i = 0; i < repeat_times.size(); ++i) {
      bcast_dims[i] = repeat_times[i];
    }

167
    framework::DDim new_in_dims = phi::make_ddim(vec_in_dims);
L
lilong12 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181
    framework::DDim out_dims(new_in_dims);
    for (size_t i = 0; i < repeat_times.size(); ++i) {
      out_dims[i] *= repeat_times[i];
    }

    out0->Resize(out_dims);
    auto x = EigenTensor<T, Rank>::From(*in0, new_in_dims);
    out0->mutable_data<T>(context.GetPlace());
    auto y = EigenTensor<T, Rank>::From(*out0, out_dims);
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
    // use 32-bit index to speed up
    bool use_32bit_index = y.size() < Eigen::NumTraits<int>::highest();
    if (use_32bit_index) {
182 183
      EigenBroadcast<std::decay_t<decltype(place)>, T, Rank>::Eval(
          place, To32BitIndex(y), To32BitIndex(x), bcast_dims);
L
lilong12 已提交
184
    } else {
185 186
      EigenBroadcast<std::decay_t<decltype(place)>, T, Rank>::Eval(place, y, x,
                                                                   bcast_dims);
L
lilong12 已提交
187 188 189 190 191 192 193 194
    }
  }
};

template <typename DeviceContext, typename T>
class TileGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
L
Leo Chen 已提交
195
    auto* x = context.Input<Tensor>("X");
L
lilong12 已提交
196
    auto repeat_times = get_repeat_times(context);
L
Leo Chen 已提交
197
    auto x_dims = x->dims();
198
    auto vec_in_dims = phi::vectorize<int>(x_dims);
L
lilong12 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    if (repeat_times.size() < vec_in_dims.size()) {
      int diff = vec_in_dims.size() - repeat_times.size();
      repeat_times.insert(repeat_times.begin(), diff, 1);
    } else {
      int diff = repeat_times.size() - vec_in_dims.size();
      vec_in_dims.insert(vec_in_dims.begin(), diff, 1);
    }
    // 1. reshape_dims_vec is the broadcast parameter.
    // 2. reduce_dims_vec is the dimension parameter to compute gradients. For
    //    each dimension expanded, the gradients should be summed to original
    //    size.
    std::vector<int> reshape_dims_vec;
    std::vector<int> reduce_dims_vec;
    for (size_t i = 0; i < repeat_times.size(); ++i) {
      reduce_dims_vec.push_back(reshape_dims_vec.size());
      reshape_dims_vec.push_back(repeat_times[i]);
      reshape_dims_vec.push_back(vec_in_dims[i]);
    }

    int dims = reduce_dims_vec.size();

    bool just_copy = true;
    for (size_t i = 0; i < repeat_times.size(); i++) {
      if (repeat_times[i] != 1) {
        just_copy = false;
        break;
      }
    }
    // no need reduce, just copy
    if (just_copy) {
L
Leo Chen 已提交
229 230 231 232 233 234 235
      auto* dout = context.Input<Tensor>(framework::GradVarName("Out"));
      auto* dx = context.Output<Tensor>(framework::GradVarName("X"));
      dx->mutable_data<T>(context.GetPlace());
      framework::TensorCopy(*dout, context.GetPlace(), context.device_context(),
                            dx);
      // TensorCopy may change the dims of dx
      dx->Resize(x_dims);
L
lilong12 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248
    } else {
      PADDLE_ENFORCE_GE(dims, 1,
                        platform::errors::InvalidArgument(
                            "Th rank of the input 'Out@GRAD' for tile_grad op "
                            " must be greater than or equal to 1, but "
                            "the value received is %d.",
                            dims));
      PADDLE_ENFORCE_LE(dims, MAX_RANK_SUPPORTED,
                        platform::errors::InvalidArgument(
                            "The rank of the input 'Out@GRAD' for tile_grad op "
                            "must be less than or equal "
                            "to %d, but the value received is %d.",
                            MAX_RANK_SUPPORTED, dims));
249
      switch (dims) {
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        case 1:
          TileBackward<1>(context, reshape_dims_vec, reduce_dims_vec);
          break;
        case 2:
          TileBackward<2>(context, reshape_dims_vec, reduce_dims_vec);
          break;
        case 3:
          TileBackward<3>(context, reshape_dims_vec, reduce_dims_vec);
          break;
        case 4:
          TileBackward<4>(context, reshape_dims_vec, reduce_dims_vec);
          break;
        case 5:
          TileBackward<5>(context, reshape_dims_vec, reduce_dims_vec);
          break;
        case 6:
          TileBackward<6>(context, reshape_dims_vec, reduce_dims_vec);
          break;
268 269 270 271 272 273
        default:
          PADDLE_THROW(platform::errors::InvalidArgument(
              "Only support tensor with rank being between 1 and 6. But "
              "received tensor's rank = %d.",
              dims));
      }
L
lilong12 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287
    }
  }

 protected:
  template <int Dims>
  void TileBackward(const framework::ExecutionContext& context,
                    const std::vector<int>& reshape_dims_vec,
                    const std::vector<int>& reduce_dims_vec) const {
    size_t reshape_size = reshape_dims_vec.size();
    size_t reduce_size = reduce_dims_vec.size();
    auto* in0 = context.Input<Tensor>(framework::GradVarName("Out"));
    auto* out0 = context.Output<Tensor>(framework::GradVarName("X"));
    out0->mutable_data<T>(context.GetPlace());
    auto x_grad = EigenVector<T>::Flatten(*out0);
288
    Eigen::DSizes<Eigen::DenseIndex, Dims * 2> reshape_dims;
L
lilong12 已提交
289 290 291
    for (size_t i = 0; i < reshape_size; ++i) {
      reshape_dims[i] = reshape_dims_vec[i];
    }
292
    Eigen::DSizes<Eigen::DenseIndex, Dims> reduce_dims;
L
lilong12 已提交
293 294 295
    for (size_t i = 0; i < reduce_size; ++i) {
      reduce_dims[i] = reduce_dims_vec[i];
    }
L
Leo Chen 已提交
296

L
lilong12 已提交
297
    auto out_grad = EigenVector<T>::Flatten(*in0);
298 299 300 301
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
    EigenBroadcastGrad<std::decay_t<decltype(place)>, T, Dims>::Eval(
        place, x_grad, out_grad, reduce_dims, reshape_dims);
L
lilong12 已提交
302 303 304 305 306
  }
};

}  // namespace operators
}  // namespace paddle