sequence_pooling.cc 10.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

A
Abhinav Arora 已提交
15
#include <string>
M
minqiyang 已提交
16 17

#include "paddle/fluid/operators/math/blas.h"
Y
Yi Wang 已提交
18
#include "paddle/fluid/operators/math/math_function.h"
M
minqiyang 已提交
19
#include "paddle/fluid/operators/math/sequence_pooling.h"
20 21 22 23 24

namespace paddle {
namespace operators {
namespace math {

D
dzhwinter 已提交
25 26 27 28 29 30 31 32 33
using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;

34
template <typename T>
D
dzhwinter 已提交
35
class MaxSeqPoolFunctor {
36
 public:
Q
QI JUN 已提交
37
  void operator()(const platform::CPUDeviceContext& context,
38 39 40 41 42
                  const framework::LoDTensor& input, framework::Tensor* output,
                  framework::Tensor* index) {
    auto in_dims = input.dims();
    auto out_dims = output->dims();
    auto idx_dims = index->dims();
D
dangqingqing 已提交
43 44 45
    PADDLE_ENFORCE_GT(in_dims.size(), 1);
    PADDLE_ENFORCE_GT(out_dims.size(), 1);
    for (int64_t i = 1; i < in_dims.size(); ++i) {
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
      PADDLE_ENFORCE_EQ(in_dims[i], out_dims[i]);
    }
    PADDLE_ENFORCE_EQ(idx_dims, out_dims);

    auto starts = input.lod()[0];
    const T* in_data = input.data<T>();
    T* out_data = output->data<T>();
    int* max_index = index->data<int>();

    int64_t num_seq = out_dims[0];
    int64_t dim = output->numel() / num_seq;
    for (int64_t i = 0; i < num_seq; ++i) {
      for (int64_t k = 0; k < dim; ++k) {
        out_data[i * dim + k] = in_data[starts[i] * dim + k];
        max_index[i * dim + k] = starts[i];
      }
      for (size_t j = starts[i] + 1; j < starts[i + 1]; ++j) {
        for (int64_t k = 0; k < dim; ++k) {
          if (in_data[j * dim + k] > out_data[i * dim + k]) {
            out_data[i * dim + k] = in_data[j * dim + k];
            max_index[i * dim + k] = j;
          }
        }
      }
    }
  }
};

template <typename T>
D
dzhwinter 已提交
75
class MaxSeqPoolGradFunctor {
76
 public:
Q
QI JUN 已提交
77
  void operator()(const platform::CPUDeviceContext& context,
78 79 80 81 82 83
                  const framework::Tensor& out_grad,
                  const framework::Tensor& index,
                  framework::LoDTensor* in_grad) {
    auto og_dims = out_grad.dims();
    auto ig_dims = in_grad->dims();
    auto idx_dims = index.dims();
D
dangqingqing 已提交
84 85 86
    PADDLE_ENFORCE_GT(og_dims.size(), 1);
    PADDLE_ENFORCE_GT(ig_dims.size(), 1);
    for (int64_t i = 1; i < og_dims.size(); ++i) {
87 88 89 90 91 92 93 94
      PADDLE_ENFORCE_EQ(og_dims[i], ig_dims[i]);
    }
    PADDLE_ENFORCE_EQ(idx_dims, og_dims);

    const T* og_data = out_grad.data<T>();
    const int* max_index = index.data<int>();
    T* ig_data = in_grad->data<T>();

Q
QI JUN 已提交
95
    SetConstant<platform::CPUDeviceContext, T> set_zero;
96 97 98
    set_zero(context, in_grad, static_cast<T>(0.0));
    int64_t num_seq = og_dims[0];
    int64_t dim = out_grad.numel() / num_seq;
D
dangqingqing 已提交
99 100
    for (int64_t i = 0; i < num_seq; ++i) {
      for (int64_t j = 0; j < dim; ++j) {
101 102 103 104 105 106 107
        int step_id = max_index[i * dim + j];
        ig_data[step_id * dim + j] = og_data[i * dim + j];
      }
    }
  }
};

108
template <typename T>
B
bingyanghuang 已提交
109
class LastSeqPoolFunctor {
110 111
 public:
  void operator()(const platform::CPUDeviceContext& context,
B
bingyanghuang 已提交
112 113
                  const framework::LoDTensor& input,
                  framework::Tensor* output) {
B
bingyanghuang 已提交
114 115 116
    // Create pointers to input and output data
    auto* in_data = input.data<T>();
    auto* out_data = output->data<T>();
B
bingyanghuang 已提交
117

B
bingyanghuang 已提交
118 119 120 121
    // Calculate the size of each item in sequence
    int64_t item_size = input.numel() / input.dims()[0];
    auto lod = input.lod()[0];
    int seq_num = static_cast<int>(lod.size()) - 1;
B
bingyanghuang 已提交
122 123 124 125 126 127 128 129
    for (int i = 0; i < seq_num; ++i) {
      // Calculate the length of each sequence
      int64_t seq_len = static_cast<int64_t>(lod[i + 1] - lod[i]);
      // Point to the begin of next sequence
      in_data += seq_len * item_size;
      // Copy the last item of sequence to output
      std::memcpy(out_data, (in_data - item_size), item_size * sizeof(T));
      out_data += item_size;
B
bingyanghuang 已提交
130
    }
B
bingyanghuang 已提交
131 132 133 134 135 136 137
  }
};

template <typename T>
class FirstSeqPoolFunctor {
 public:
  void operator()(const platform::CPUDeviceContext& context,
B
bingyanghuang 已提交
138 139
                  const framework::LoDTensor& input,
                  framework::Tensor* output) {
B
bingyanghuang 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    // Create pointers to input and output data
    auto* in_data = input.data<T>();
    auto* out_data = output->data<T>();

    // Calculate the size of each item in sequence
    int64_t item_size = input.numel() / input.dims()[0];
    auto lod = input.lod()[0];
    int seq_num = static_cast<int>(lod.size()) - 1;
    for (int i = 0; i < seq_num; ++i) {
      // Calculate the length of each sequence
      int64_t seq_len = static_cast<int64_t>(lod[i + 1] - lod[i]);
      // Copy the first item of sequence to output
      std::memcpy(out_data, in_data, item_size * sizeof(T));
      // Point to the next sequence
      in_data += seq_len * item_size;
      out_data += item_size;
B
bingyanghuang 已提交
156
    }
B
bingyanghuang 已提交
157
  }
158 159
};

D
dzhwinter 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172
template <typename T>
class SequencePoolFunctor<platform::CPUDeviceContext, T> {
 public:
  /* max pool has index output */
  void operator()(const platform::CPUDeviceContext& context,
                  const std::string pooltype, const framework::LoDTensor& input,
                  framework::Tensor* output,
                  framework::Tensor* index = nullptr) {
    if (pooltype == "MAX") {
      math::MaxSeqPoolFunctor<T> max_pool;
      max_pool(context, input, output, index);
      return;
    }
B
bingyanghuang 已提交
173 174 175
    if (pooltype == "LAST") {
      math::LastSeqPoolFunctor<T> last_pool;
      last_pool(context, input, output);
176 177
      return;
    }
B
bingyanghuang 已提交
178 179 180 181 182
    if (pooltype == "FIRST") {
      math::FirstSeqPoolFunctor<T> first_pool;
      first_pool(context, input, output);
      return;
    }
D
dzhwinter 已提交
183 184
    auto lod = input.lod()[0];
    auto& place = *context.eigen_device();
M
minqiyang 已提交
185
    auto blas = math::GetBlas<platform::CPUDeviceContext, T>(context);
D
dzhwinter 已提交
186 187 188 189 190 191 192 193 194 195 196
    for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) {
      Tensor in_t =
          input.Slice(static_cast<int>(lod[i]), static_cast<int>(lod[i + 1]));
      Tensor out_t = output->Slice(i, i + 1);
      int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]);
      int64_t w = input.numel() / input.dims()[0];
      auto in_e = EigenMatrix<T>::From(in_t, framework::make_ddim({h, w}));
      auto out_e = EigenVector<T>::Flatten(out_t);
      if (pooltype == "AVERAGE") {
        out_e.device(place) = in_e.mean(Eigen::array<int, 1>({{0}}));
      } else if (pooltype == "SUM") {
M
minqiyang 已提交
197 198 199 200 201 202 203 204
        if (h > 0) {
          const T* in_data = in_t.data<T>();
          T* out_data = out_t.mutable_data<T>(context.GetPlace());
          blas.VCOPY(w, in_data, out_data);
          for (int64_t r = 1; r != h; ++r) {
            blas.AXPY(w, 1., in_data + r * w, out_data);
          }
        }
D
dzhwinter 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
      } else if (pooltype == "SQRT") {
        out_e.device(place) = in_e.sum(Eigen::array<int, 1>({{0}})) /
                              std::sqrt(static_cast<T>(h));
      } else {
        PADDLE_THROW("unsupported pooling pooltype");
      }
    }
  }
};

template <typename T>
class SequencePoolGradFunctor<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& context,
                  const std::string pooltype, const framework::Tensor& out_grad,
                  framework::LoDTensor* in_grad,
                  /* max pool has index */
                  const framework::Tensor* index = nullptr) {
    if (pooltype == "MAX") {
      math::MaxSeqPoolGradFunctor<T> max_pool_grad;
      max_pool_grad(context, out_grad, *index, in_grad);
      return;
    }

    if (pooltype == "LAST" || pooltype == "FIRST") {
      // set X@Grad be zero at first when pooltype is LAST/FIRST
      math::SetConstant<platform::CPUDeviceContext, T> functor;
      functor(context, in_grad, 0);
    }
    auto lod = in_grad->lod()[0];
    auto& place = *context.eigen_device();
M
minqiyang 已提交
236
    auto blas = math::GetBlas<platform::CPUDeviceContext, T>(context);
D
dzhwinter 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250
    for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) {
      auto in_g_t = in_grad->Slice(static_cast<int>(lod[i]),
                                   static_cast<int>(lod[i + 1]));
      auto out_g_t = out_grad.Slice(i, i + 1);
      int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]);
      int64_t w = in_grad->numel() / in_grad->dims()[0];
      auto in_g_e = EigenMatrix<T>::From(in_g_t, {h, w});
      auto out_g_e = EigenMatrix<T>::From(out_g_t, {1, w});
      auto out_g_e_v = EigenVector<T>::Flatten(out_g_t);
      Eigen::DSizes<int, 2> bcast(h, 1);

      if (pooltype == "AVERAGE") {
        in_g_e.device(place) = (out_g_e / static_cast<T>(h)).broadcast(bcast);
      } else if (pooltype == "SUM") {
M
minqiyang 已提交
251 252 253 254 255
        const T* out_g_data = out_g_t.data<T>();
        T* in_g_data = in_g_t.mutable_data<T>(context.GetPlace());
        for (int r = 0; r != h; ++r) {
          blas.VCOPY(w, out_g_data, in_g_data + r * w);
        }
D
dzhwinter 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
      } else if (pooltype == "SQRT") {
        in_g_e.device(place) =
            (out_g_e / std::sqrt(static_cast<T>(h))).broadcast(bcast);
      } else if (pooltype == "LAST") {
        in_g_e.chip(h - 1, 0).device(place) = out_g_e_v;
      } else if (pooltype == "FIRST") {
        in_g_e.chip(0, 0).device(place) = out_g_e_v;
      } else {
        PADDLE_THROW("unsupported pooling pooltype");
      }
    }
  }
};

template class SequencePoolFunctor<platform::CPUDeviceContext, float>;
template class SequencePoolFunctor<platform::CPUDeviceContext, double>;
template class SequencePoolGradFunctor<platform::CPUDeviceContext, float>;
template class SequencePoolGradFunctor<platform::CPUDeviceContext, double>;
274 275 276 277

}  // namespace math
}  // namespace operators
}  // namespace paddle