affine_grid_op.h 7.7 KB
Newer Older
W
whs 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 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>
17

W
whs 已提交
18 19
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
20 21
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/math_function.h"
W
whs 已提交
22 23 24 25 26

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
27 28 29
template <typename T,
          size_t D,
          int MajorType = Eigen::RowMajor,
W
whs 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42
          typename IndexType = Eigen::DenseIndex>
using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>;

using Array1 = Eigen::DSizes<int64_t, 1>;
using Array2 = Eigen::DSizes<int64_t, 2>;
using Array3 = Eigen::DSizes<int64_t, 3>;
using Array4 = Eigen::DSizes<int64_t, 4>;

/**
 *Return a tensor with evenly spaced numbers over a specified interval.
 */
template <typename DeviceContext, typename T>
struct Linspace {
43 44 45 46
  void operator()(T start,
                  T end,
                  int count,
                  bool align_corners,
47
                  framework::Tensor* numbers,
48
                  const framework::ExecutionContext& ctx);
W
whs 已提交
49 50
};

51
template <typename DeviceContext, typename T>
52 53 54 55 56
inline void GetIdxMap(int n,
                      int h,
                      int w,
                      bool align_corners,
                      Tensor* grid,
57 58 59 60 61 62 63
                      const framework::ExecutionContext& ctx) {
  auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
  grid->mutable_data<T>({n, h, w, 3}, ctx.GetPlace());
  auto grid_t = EigenTensor<T, 4>::From(*grid);
  // Get indexes of height with shape [height, width, 1]
  Tensor h_idx;
  Linspace<DeviceContext, T> linspace;
64
  linspace((T)-1, (T)1, h, align_corners, &h_idx, ctx);
65 66 67
  auto h_idx_t = EigenTensor<T, 1>::From(h_idx);
  // Get indexes of width with shape [height, width, 1]
  Tensor w_idx;
68
  linspace((T)-1, (T)1, w, align_corners, &w_idx, ctx);
69 70 71 72
  auto w_idx_t = EigenTensor<T, 1>::From(w_idx);
  // Get constant ones tensor with shape [height, width, 1]
  Tensor ones;
  ones.mutable_data<T>({h, w, 1}, ctx.GetPlace());
73

74
  phi::funcs::SetConstant<DeviceContext, T>()(
75 76
      ctx.template device_context<DeviceContext>(), &ones, static_cast<T>(1));
  auto ones_t = EigenTensor<T, 3>::From(ones);
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
  // Get grid tensor with shape [n, h, w, 3] by concatenating h_idx, w_idx and
  // ones
  Tensor w_idx_map;
  w_idx_map.mutable_data<T>({h, w, 1}, ctx.GetPlace());
  auto w_idx_map_t = EigenTensor<T, 3>::From(w_idx_map);
  Tensor h_idx_map;
  h_idx_map.mutable_data<T>({h, w, 1}, ctx.GetPlace());
  auto h_idx_map_t = EigenTensor<T, 3>::From(h_idx_map);
  Tensor w_h_idx_map;
  w_h_idx_map.mutable_data<T>({h, w, 2}, ctx.GetPlace());
  auto w_h_idx_map_t = EigenTensor<T, 3>::From(w_h_idx_map);
  Tensor w_h_one_idx_map;
  w_h_one_idx_map.mutable_data<T>({h, w, 3}, ctx.GetPlace());
  auto w_h_one_idx_map_t = EigenTensor<T, 3>::From(w_h_one_idx_map);
  w_idx_map_t.device(place) = w_idx_t.reshape(Array2(1, w))
                                  .broadcast(Array2(h, 1))
                                  .reshape(Array3(h, w, 1));
  h_idx_map_t.device(place) = h_idx_t.reshape(Array2(1, h))
                                  .broadcast(Array2(w, 1))
                                  .shuffle(Array2(1, 0))
                                  .reshape(Array3(h, w, 1));

  w_h_idx_map_t.device(place) = w_idx_map_t.concatenate(h_idx_map_t, 2);
  w_h_one_idx_map_t.device(place) = w_h_idx_map_t.concatenate(ones_t, 2);
  grid_t.device(place) = w_h_one_idx_map_t.reshape(Array4(1, h, w, 3))
                             .broadcast(Array4(n, 1, 1, 1));
}

W
whs 已提交
105 106 107 108 109 110 111
template <typename DeviceContext, typename T>
class AffineGridOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* theta = ctx.Input<Tensor>("Theta");
    int n = theta->dims()[0];
    auto size_attr = ctx.Attr<std::vector<int>>("output_shape");
112
    auto align_corners = ctx.Attr<bool>("align_corners");
W
whs 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    int h = 0;
    int w = 0;
    if (size_attr.size() == 0) {
      auto* output_shape = ctx.Input<Tensor>("OutputShape");
      Tensor h_sizes;
      framework::TensorCopy(*output_shape, platform::CPUPlace(), &h_sizes);
      const int* h_size_data = h_sizes.data<int>();
      h = h_size_data[2];
      w = h_size_data[3];
    } else {
      h = size_attr[2];
      w = size_attr[3];
    }
    auto* output = ctx.Output<Tensor>("Output");
    output->mutable_data<T>({n, h, w, 2}, ctx.GetPlace());
128
    phi::funcs::SetConstant<DeviceContext, T>()(
129 130
        ctx.template device_context<DeviceContext>(),
        output,
W
whs 已提交
131 132
        static_cast<T>(0));
    Tensor grid;
133
    GetIdxMap<DeviceContext, T>(n, h, w, align_corners, &grid, ctx);
W
whs 已提交
134 135
    // output = grid * theta.T
    // TODO(wanghaoshuang): Refine batched matrix multiply
136
    auto blas = phi::funcs::GetBlas<DeviceContext, T>(ctx);
W
whs 已提交
137
    for (int i = 0; i < n; ++i) {
S
SunGaofeng 已提交
138 139
      Tensor sliced_grid = grid.Slice(i, i + 1).Resize(
          {static_cast<int64_t>(h) * static_cast<int64_t>(w), 3});
W
whs 已提交
140
      Tensor sliced_theta = theta->Slice(i, i + 1).Resize({2, 3});
S
SunGaofeng 已提交
141 142
      Tensor sliced_out = output->Slice(i, i + 1).Resize(
          {static_cast<int64_t>(h) * static_cast<int64_t>(w), 2});
143 144
      blas.MatMul(
          sliced_grid, false, sliced_theta, true, T(1), &sliced_out, T(0));
W
whs 已提交
145 146 147 148 149 150 151 152 153 154 155 156
    }
  }
};

template <typename DeviceContext, typename T>
class AffineGridGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto output_grad = ctx.Input<Tensor>(framework::GradVarName("Output"));
    auto theta_grad = ctx.Output<Tensor>(framework::GradVarName("Theta"));
    int n = output_grad->dims()[0];
    auto size_attr = ctx.Attr<std::vector<int>>("output_shape");
157
    auto align_corners = ctx.Attr<bool>("align_corners");
W
whs 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171
    int h = 0;
    int w = 0;
    if (size_attr.size() == 0) {
      auto* output_shape = ctx.Input<Tensor>("OutputShape");
      Tensor h_sizes;
      framework::TensorCopy(*output_shape, platform::CPUPlace(), &h_sizes);
      const int* h_size_data = h_sizes.data<int>();
      h = h_size_data[2];
      w = h_size_data[3];
    } else {
      h = size_attr[2];
      w = size_attr[3];
    }
    theta_grad->mutable_data<T>({n, 2, 3}, ctx.GetPlace());
172
    phi::funcs::SetConstant<DeviceContext, T>()(
173 174
        ctx.template device_context<DeviceContext>(),
        theta_grad,
W
whs 已提交
175 176
        static_cast<T>(0));
    Tensor grid;
177
    GetIdxMap<DeviceContext, T>(n, h, w, align_corners, &grid, ctx);
W
whs 已提交
178 179
    // output = grid * theta.T
    // TODO(wanghaoshuang): Refine batched matrix multiply
180
    auto blas = phi::funcs::GetBlas<DeviceContext, T>(ctx);
W
whs 已提交
181
    for (int i = 0; i < n; ++i) {
S
SunGaofeng 已提交
182 183 184 185
      Tensor sliced_grid = grid.Slice(i, i + 1).Resize(
          {static_cast<int64_t>(h) * static_cast<int64_t>(w), 3});
      Tensor sliced_out_grad = output_grad->Slice(i, i + 1).Resize(
          {static_cast<int64_t>(h) * static_cast<int64_t>(w), 2});
W
whs 已提交
186
      Tensor sliced_theta_grad = theta_grad->Slice(i, i + 1).Resize({2, 3});
187 188 189 190 191 192 193
      blas.MatMul(sliced_out_grad,
                  true,
                  sliced_grid,
                  false,
                  T(1),
                  &sliced_theta_grad,
                  T(0));
W
whs 已提交
194 195 196 197 198 199
    }
  }
};

}  // namespace operators
}  // namespace paddle