crop_op.h 7.7 KB
Newer Older
W
whs 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
W
wanghaoshuang 已提交
2

L
Luo Tao 已提交
3 4 5
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
W
wanghaoshuang 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
W
wanghaoshuang 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
W
wanghaoshuang 已提交
14 15

#pragma once
S
Siddharth Goyal 已提交
16 17
#include <utility>
#include <vector>
Y
Yi Wang 已提交
18 19 20
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/strided_memcpy.h"
W
wanghaoshuang 已提交
21 22

namespace paddle {
23
namespace operators {  // Internal
W
wanghaoshuang 已提交
24 25 26 27

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

F
stash  
fengjiayi 已提交
30 31 32 33
static std::vector<int> GetOffsets(const framework::ExecutionContext& ctx) {
  std::vector<int> res;
  int rank = ctx.Input<Tensor>("X")->dims().size();
  if (ctx.HasInput("Offsets")) {
34 35 36 37
    PADDLE_ENFORCE_EQ(ctx.Attr<std::vector<int>>("offsets").empty(), true,
                      platform::errors::InvalidArgument(
                          "Input 'Offsets' and attribute 'offsets' "
                          "should not be used at the same time for CropOp."));
F
stash  
fengjiayi 已提交
38
    const auto* offsets_tensor = ctx.Input<Tensor>("Offsets");
39 40 41 42 43
    PADDLE_ENFORCE_EQ(offsets_tensor->dims().size(), 1,
                      platform::errors::InvalidArgument(
                          "The number of dimensions of input 'Offsets' for "
                          "CropOp must be 1, but the value received is %d.",
                          offsets_tensor->dims().size()));
F
stash  
fengjiayi 已提交
44 45
    PADDLE_ENFORCE_EQ(
        rank, offsets_tensor->dims()[0],
46 47 48 49 50
        platform::errors::InvalidArgument("The number of elements (%d) for "
                                          "input 'Offsets' must be equal to "
                                          "the number of dimensions (%d) "
                                          "of the input tensor.",
                                          offsets_tensor->dims()[0], rank));
F
fengjiayi 已提交
51 52 53 54 55 56 57 58
    const int* offsets_data;
    framework::Tensor cpu_tmp_tensor;
    if (platform::is_cpu_place(offsets_tensor->place())) {
      offsets_data = offsets_tensor->data<int>();
    } else {
      framework::TensorCopySync(*offsets_tensor, platform::CPUPlace(),
                                &cpu_tmp_tensor);
      offsets_data = cpu_tmp_tensor.data<int>();
F
stash  
fengjiayi 已提交
59
    }
F
fengjiayi 已提交
60
    res = std::vector<int>(offsets_data, offsets_data + rank);
F
stash  
fengjiayi 已提交
61 62 63
  } else {
    res = ctx.Attr<std::vector<int>>("offsets");
    PADDLE_ENFORCE_EQ(
G
gongweibao 已提交
64
        rank, static_cast<int>(res.size()),
65 66 67 68 69
        platform::errors::InvalidArgument("The number of elements (%d) for "
                                          "input 'Offsets' must be equal to "
                                          "the number of dimensions (%d) "
                                          "of the input tensor.",
                                          res.size(), rank));
F
stash  
fengjiayi 已提交
70 71 72 73
  }
  return res;
}

W
whs 已提交
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
template <typename DeviceContext, typename T, size_t D>
void CropFunction(const framework::ExecutionContext& context) {
  auto* x = context.Input<Tensor>("X");
  auto* out = context.Output<Tensor>("Out");
  auto out_dims = out->dims();
  if (out_dims[0] == -1) {
    out_dims[0] = x->dims()[0];
  }
  out->mutable_data<T>(out_dims, context.GetPlace());
  auto x_stride = framework::stride(x->dims());
  auto offsets = GetOffsets(context);
  int64_t offset = 0;
  for (size_t i = 0; i < offsets.size(); ++i) {
    offset += (x_stride[i] * offsets[i]);
  }

  auto x_tensor = EigenTensor<T, D>::From(*x);
  auto out_tensor = EigenTensor<T, D>::From(*out);
  Eigen::array<int, D> e_offsets;
  Eigen::array<int, D> e_shape;
  for (size_t i = 0; i < D; ++i) {
    e_offsets[i] = offsets[i];
    e_shape[i] = out->dims()[i];
  }
  auto& place =
      *context.template device_context<DeviceContext>().eigen_device();
  out_tensor.device(place) = x_tensor.slice(e_offsets, e_shape);
}

template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
104
class CropKernel : public framework::OpKernel<T> {
105 106
 public:
  void Compute(const framework::ExecutionContext& context) const override {
W
whs 已提交
107
    int rank = context.Input<Tensor>("X")->dims().size();
108 109 110 111 112 113 114 115 116 117 118 119
    PADDLE_ENFORCE_GE(
        rank, 1,
        platform::errors::InvalidArgument(
            "The number of dimensions of the Input(X) for CropOp must be "
            "greater than or equal to 1, but the value received is %d.",
            rank));
    PADDLE_ENFORCE_LE(
        rank, 6,
        platform::errors::InvalidArgument(
            "The number of dimensions of the Input(X) for CropOp must be "
            "less than or equal to 6, but the value received is %d.",
            rank));
W
whs 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    switch (rank) {
      case 1:
        CropFunction<DeviceContext, T, 1>(context);
        break;
      case 2:
        CropFunction<DeviceContext, T, 2>(context);
        break;
      case 3:
        CropFunction<DeviceContext, T, 3>(context);
        break;
      case 4:
        CropFunction<DeviceContext, T, 4>(context);
        break;
      case 5:
        CropFunction<DeviceContext, T, 5>(context);
        break;
      case 6:
        CropFunction<DeviceContext, T, 6>(context);
        break;
139 140 141
    }
  }
};
W
wanghaoshuang 已提交
142

Q
QI JUN 已提交
143
template <typename DeviceContext, typename T, size_t D>
W
wanghaoshuang 已提交
144
void CropGradFunction(const framework::ExecutionContext& context) {
145
  auto* d_x = context.Output<Tensor>(framework::GradVarName("X"));
W
whs 已提交
146
  auto* x = context.Input<Tensor>("X");
147
  if (d_x != nullptr) {
148
    auto* d_out = context.Input<Tensor>(framework::GradVarName("Out"));
W
whs 已提交
149
    d_x->mutable_data<T>(x->dims(), context.GetPlace());
F
stash  
fengjiayi 已提交
150
    auto offsets = GetOffsets(context);
151
    Eigen::array<std::pair<int, int>, D> paddings;
Q
qiaolongfei 已提交
152
    for (size_t i = 0; i < D; ++i) {
153
      paddings[i].first = offsets[i];
W
wanghaoshuang 已提交
154
      paddings[i].second = d_x->dims()[i] - d_out->dims()[i] - offsets[i];
155 156 157
    }
    auto d_x_tensor = EigenTensor<T, D>::From(*d_x);
    auto d_out_tensor = EigenTensor<T, D>::From(*d_out);
Q
QI JUN 已提交
158 159
    d_x_tensor.device(
        *context.template device_context<DeviceContext>().eigen_device()) =
160
        d_out_tensor.pad(paddings, 0);
W
wanghaoshuang 已提交
161 162 163
  }
}

Q
QI JUN 已提交
164
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
165
class CropGradKernel : public framework::OpKernel<T> {
W
wanghaoshuang 已提交
166 167
 public:
  void Compute(const framework::ExecutionContext& context) const override {
168
    size_t rank =
169
        context.Input<Tensor>(framework::GradVarName("Out"))->dims().size();
170 171 172 173 174 175 176 177 178 179 180 181
    PADDLE_ENFORCE_GE(
        rank, 1, platform::errors::InvalidArgument(
                     "The number of dimensions of the input 'Out@GRAD' for "
                     "CropGrad must be greater than or equal "
                     "to 1, but the value received is %d.",
                     rank));
    PADDLE_ENFORCE_LE(
        rank, 6, platform::errors::InvalidArgument(
                     "The number of dimensions of the input 'Out@GRAD' for "
                     "CropGrad must be less than or equal "
                     "to 6, but the value received is %d.",
                     rank));
182
    switch (rank) {
W
wanghaoshuang 已提交
183
      case 1:
Q
QI JUN 已提交
184
        CropGradFunction<DeviceContext, T, 1>(context);
W
wanghaoshuang 已提交
185 186
        break;
      case 2:
Q
QI JUN 已提交
187
        CropGradFunction<DeviceContext, T, 2>(context);
W
wanghaoshuang 已提交
188 189
        break;
      case 3:
Q
QI JUN 已提交
190
        CropGradFunction<DeviceContext, T, 3>(context);
W
wanghaoshuang 已提交
191 192
        break;
      case 4:
Q
QI JUN 已提交
193
        CropGradFunction<DeviceContext, T, 4>(context);
W
wanghaoshuang 已提交
194 195
        break;
      case 5:
Q
QI JUN 已提交
196
        CropGradFunction<DeviceContext, T, 5>(context);
W
wanghaoshuang 已提交
197 198
        break;
      case 6:
Q
QI JUN 已提交
199
        CropGradFunction<DeviceContext, T, 6>(context);
W
wanghaoshuang 已提交
200 201 202 203 204 205 206
        break;
    }
  }
};

}  // namespace operators
}  // namespace paddle