sequence_pooling.cc 18.0 KB
Newer Older
1
/* Copyright (c) 2023 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. */

15
#include "paddle/phi/kernels/funcs/sequence_pooling.h"
16

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

19
#include "paddle/phi/kernels/funcs/blas/blas.h"
20
#include "paddle/phi/kernels/funcs/eigen/common.h"
21
#include "paddle/phi/kernels/funcs/jit/kernels.h"
22
#include "paddle/phi/kernels/funcs/math_function.h"
23

24 25
namespace phi {
namespace funcs {
26

27 28
template <typename T,
          int MajorType = Eigen::RowMajor,
D
dzhwinter 已提交
29
          typename IndexType = Eigen::DenseIndex>
30
using EigenVector = phi::EigenVector<T, MajorType, IndexType>;
31 32
template <typename T,
          int MajorType = Eigen::RowMajor,
D
dzhwinter 已提交
33
          typename IndexType = Eigen::DenseIndex>
34
using EigenMatrix = phi::EigenMatrix<T, MajorType, IndexType>;
D
dzhwinter 已提交
35

J
Jacek Czaja 已提交
36
template <typename T, bool is_test>
D
dzhwinter 已提交
37
class MaxSeqPoolFunctor {
38
 public:
L
Leo Chen 已提交
39
  void operator()(const phi::CPUContext& context,
40
                  const phi::DenseTensor& input,
41
                  T pad_value,
42
                  phi::DenseTensor* output,
43
                  phi::DenseTensor* index) {
44 45 46
    auto in_dims = input.dims();
    auto out_dims = output->dims();
    auto idx_dims = index->dims();
47 48
    PADDLE_ENFORCE_GT(in_dims.size(),
                      1,
49
                      errors::InvalidArgument(
50 51 52
                          "The rank of input shall be greater than 1, but got "
                          "the rank is %ld. Please check the input value",
                          in_dims.size()));
53 54
    PADDLE_ENFORCE_GT(out_dims.size(),
                      1,
55
                      errors::InvalidArgument(
56 57 58
                          "The rank of output shall be greater than 1, but got "
                          "the rank is %ld. Please check the input value",
                          out_dims.size()));
D
dangqingqing 已提交
59
    for (int64_t i = 1; i < in_dims.size(); ++i) {
60
      PADDLE_ENFORCE_EQ(
61 62
          in_dims[i],
          out_dims[i],
63
          errors::InvalidArgument(
64 65
              "The dimension of input and output shall be same. Expected %ld "
              "== %ld, but got %ld != %ld. Please check the input value.",
66 67 68 69
              in_dims[i],
              out_dims[i],
              in_dims[i],
              out_dims[i]));
70
    }
71
    PADDLE_ENFORCE_EQ(
72 73
        idx_dims,
        out_dims,
74
        errors::InvalidArgument(
75 76
            "The dimension of index and output shall be same. Expected %ld == "
            "%ld, but got %ld != %ld. Please check the input value.",
77 78 79 80
            idx_dims,
            out_dims,
            idx_dims,
            out_dims));
81

82 83
    auto lod_level = input.lod().size();
    auto starts = input.lod()[lod_level - 1];
84 85 86 87 88 89 90
    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) {
91 92 93 94 95 96 97
      if (starts[i] == starts[i + 1]) {
        for (int64_t k = 0; k < dim; ++k) {
          out_data[i * dim + k] = pad_value;
          max_index[i * dim + k] = -1;
        }
        continue;
      }
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
      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;
          }
        }
      }
    }
  }
};
J
Jacek Czaja 已提交
113 114 115 116 117
// Instantisation of Max Sequence Pooling for test phase eg. no need to fill
// index buffer
template <typename T>
class MaxSeqPoolFunctor<T, true> {
 public:
L
Leo Chen 已提交
118
  void operator()(const phi::CPUContext& context,
119
                  const phi::DenseTensor& input,
120
                  T pad_value,
121
                  phi::DenseTensor* output,
122
                  phi::DenseTensor* index) {
J
Jacek Czaja 已提交
123 124
    auto in_dims = input.dims();
    auto out_dims = output->dims();
125 126
    PADDLE_ENFORCE_GT(in_dims.size(),
                      1,
127
                      errors::InvalidArgument(
128 129 130
                          "The rank of input shall be greater than 1, but got "
                          "%ld <= 1. Please check the input value.",
                          in_dims.size()));
131 132
    PADDLE_ENFORCE_GT(out_dims.size(),
                      1,
133
                      errors::InvalidArgument(
134 135 136
                          "The rank of output shall be greater than 1, but got "
                          "%ld <= 1. Please check the input value.",
                          out_dims.size()));
J
Jacek Czaja 已提交
137
    for (int64_t i = 1; i < in_dims.size(); ++i) {
138
      PADDLE_ENFORCE_EQ(
139 140
          in_dims[i],
          out_dims[i],
141
          errors::InvalidArgument(
142 143
              "The dimension of input and output shall be same. Expected %ld "
              "== %ld, but got %ld != %ld. Please check the input value.",
144 145 146 147
              in_dims[i],
              out_dims[i],
              in_dims[i],
              out_dims[i]));
J
Jacek Czaja 已提交
148 149
    }

150 151
    auto lod_level = input.lod().size();
    auto starts = input.lod()[lod_level - 1];
J
Jacek Czaja 已提交
152 153
    const T* in_data = input.data<T>();
    T* out_data = output->data<T>();
154

J
Jacek Czaja 已提交
155 156 157
    int64_t num_seq = out_dims[0];
    int64_t dim = output->numel() / num_seq;
    for (int64_t i = 0; i < num_seq; ++i) {
158 159 160 161 162 163
      if (starts[i] == starts[i + 1]) {
        for (int64_t k = 0; k < dim; ++k) {
          out_data[i * dim + k] = pad_value;
        }
        continue;
      }
164 165
      std::memcpy(
          &out_data[i * dim], &in_data[starts[i] * dim], dim * sizeof(T));
J
Jacek Czaja 已提交
166 167 168 169 170 171 172 173 174 175
      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];
          }
        }
      }
    }
  }
};
176
template <typename T>
D
dzhwinter 已提交
177
class MaxSeqPoolGradFunctor {
178
 public:
L
Leo Chen 已提交
179
  void operator()(const phi::CPUContext& context,
180
                  const phi::DenseTensor& out_grad,
181
                  const phi::DenseTensor& index,
182
                  phi::DenseTensor* in_grad) {
183 184 185
    auto og_dims = out_grad.dims();
    auto ig_dims = in_grad->dims();
    auto idx_dims = index.dims();
186 187
    PADDLE_ENFORCE_GT(og_dims.size(),
                      1,
188
                      errors::InvalidArgument(
189 190 191
                          "The rank of output@Grad shall be greater than 1, "
                          "but got %ld <= 1. Please check the input value.",
                          og_dims.size()));
192 193
    PADDLE_ENFORCE_GT(ig_dims.size(),
                      1,
194
                      errors::InvalidArgument(
195 196 197
                          "The rank of input@Grad shall be greater than 1, but "
                          "got %ld <= 1. Please check the input value.",
                          ig_dims.size()));
D
dangqingqing 已提交
198
    for (int64_t i = 1; i < og_dims.size(); ++i) {
199 200
      PADDLE_ENFORCE_EQ(og_dims[i],
                        ig_dims[i],
201
                        errors::InvalidArgument(
202 203 204
                            "The dimension of input@Grad and output@Grad shall "
                            "be same. Expected %ld == %ld, but got %ld != %ld. "
                            "Please check the input value.",
205 206 207 208
                            og_dims[i],
                            ig_dims[i],
                            og_dims[i],
                            ig_dims[i]));
209
    }
210
    PADDLE_ENFORCE_EQ(
211 212
        idx_dims,
        og_dims,
213
        errors::InvalidArgument(
214 215
            "The dimension of index and output@Grad shall be same. Expected "
            "%ld == %ld, but got %ld != %ld. Please check the input value.",
216 217 218 219
            idx_dims,
            og_dims,
            idx_dims,
            og_dims));
220 221 222 223 224

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

L
Leo Chen 已提交
225
    phi::funcs::SetConstant<phi::CPUContext, T> set_zero;
226 227 228
    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 已提交
229 230
    for (int64_t i = 0; i < num_seq; ++i) {
      for (int64_t j = 0; j < dim; ++j) {
231
        int step_id = max_index[i * dim + j];
232
        if (step_id == -1) continue;
233 234 235 236 237 238
        ig_data[step_id * dim + j] = og_data[i * dim + j];
      }
    }
  }
};

239
template <typename T>
B
bingyanghuang 已提交
240
class LastSeqPoolFunctor {
241
 public:
L
Leo Chen 已提交
242
  void operator()(const phi::CPUContext& context,
243
                  const phi::DenseTensor& input,
244
                  T pad_value,
245
                  phi::DenseTensor* output) {
B
bingyanghuang 已提交
246 247 248
    // Create pointers to input and output data
    auto* in_data = input.data<T>();
    auto* out_data = output->data<T>();
B
bingyanghuang 已提交
249

B
bingyanghuang 已提交
250 251
    // Calculate the size of each item in sequence
    int64_t item_size = input.numel() / input.dims()[0];
252 253
    auto lod_level = input.lod().size();
    auto lod = input.lod()[lod_level - 1];
B
bingyanghuang 已提交
254
    int seq_num = static_cast<int>(lod.size()) - 1;
B
bingyanghuang 已提交
255 256 257
    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]);
258 259 260 261 262 263 264 265 266 267
      if (seq_len == 0) {
        for (int j = 0; j < item_size; ++j) {
          out_data[j] = pad_value;
        }
      } else {
        // 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));
      }
B
bingyanghuang 已提交
268
      out_data += item_size;
B
bingyanghuang 已提交
269
    }
B
bingyanghuang 已提交
270 271 272 273 274 275
  }
};

template <typename T>
class FirstSeqPoolFunctor {
 public:
L
Leo Chen 已提交
276
  void operator()(const phi::CPUContext& context,
277
                  const phi::DenseTensor& input,
278
                  T pad_value,
279
                  phi::DenseTensor* output) {
B
bingyanghuang 已提交
280 281 282 283 284 285
    // 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];
286 287
    auto lod_level = input.lod().size();
    auto lod = input.lod()[lod_level - 1];
B
bingyanghuang 已提交
288 289 290 291
    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]);
292 293 294 295 296 297 298 299 300 301
      if (seq_len == 0) {
        for (int j = 0; j < item_size; ++j) {
          out_data[j] = pad_value;
        }
      } else {
        // 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;
      }
B
bingyanghuang 已提交
302
      out_data += item_size;
B
bingyanghuang 已提交
303
    }
B
bingyanghuang 已提交
304
  }
305 306
};

M
minqiyang 已提交
307 308 309
template <typename T>
class SumSeqPoolGradFunctor {
 public:
L
Leo Chen 已提交
310
  void operator()(const phi::CPUContext& context,
311 312
                  const phi::DenseTensor& out_grad,
                  phi::DenseTensor* in_grad) {
313 314
    auto lod_level = in_grad->lod().size();
    auto lod = in_grad->lod()[lod_level - 1];
M
minqiyang 已提交
315 316
    int64_t out_w = out_grad.numel() / out_grad.dims()[0];
    int64_t in_w = in_grad->numel() / in_grad->dims()[0];
317 318
    PADDLE_ENFORCE_EQ(in_w,
                      out_w,
319
                      errors::InvalidArgument(
320 321 322
                          "The feature size of input@Grad and output@Grad "
                          "shall be same. Expected %ld == %ld, but got %ld != "
                          "%ld. Please check the input value.",
323 324 325 326
                          in_w,
                          out_w,
                          in_w,
                          out_w));
M
minqiyang 已提交
327
    const T* out_g_data = out_grad.data<T>();
328
    T* in_g_data = context.template Alloc<T>(in_grad);
L
Leo Chen 已提交
329
    auto blas = phi::funcs::GetBlas<phi::CPUContext, T>(context);
M
minqiyang 已提交
330 331
    for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) {
      int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]);
332
      if (h == 0) continue;
M
minqiyang 已提交
333 334 335 336 337 338 339 340 341 342
      int64_t in_offset = lod[i] * in_w;
      const T* out_pos = out_g_data + i * out_w;
      T* in_pos = in_g_data + in_offset;
      for (int r = 0; r != h; ++r) {
        blas.VCOPY(in_w, out_pos, in_pos + r * in_w);
      }
    }
  }
};

D
dzhwinter 已提交
343
template <typename T>
L
Leo Chen 已提交
344
class SequencePoolFunctor<phi::CPUContext, T> {
D
dzhwinter 已提交
345 346
 public:
  /* max pool has index output */
L
Leo Chen 已提交
347
  void operator()(const phi::CPUContext& context,
348 349
                  const std::string pooltype,
                  T pad_value,
350 351
                  const phi::DenseTensor& input,
                  phi::DenseTensor* output,
352
                  bool is_test,
353
                  phi::DenseTensor* index = nullptr) {
D
dzhwinter 已提交
354
    if (pooltype == "MAX") {
J
Jacek Czaja 已提交
355
      if (is_test) {
356
        phi::funcs::MaxSeqPoolFunctor<T, true> max_pool;
357
        max_pool(context, input, pad_value, output, index);
J
Jacek Czaja 已提交
358
      } else {
359
        phi::funcs::MaxSeqPoolFunctor<T, false> max_pool;
360
        max_pool(context, input, pad_value, output, index);
J
Jacek Czaja 已提交
361
      }
D
dzhwinter 已提交
362 363
      return;
    }
B
bingyanghuang 已提交
364
    if (pooltype == "LAST") {
365
      phi::funcs::LastSeqPoolFunctor<T> last_pool;
366
      last_pool(context, input, pad_value, output);
367 368
      return;
    }
B
bingyanghuang 已提交
369
    if (pooltype == "FIRST") {
370
      phi::funcs::FirstSeqPoolFunctor<T> first_pool;
371
      first_pool(context, input, pad_value, output);
B
bingyanghuang 已提交
372 373
      return;
    }
374 375
    auto lod_level = input.lod().size();
    auto lod = input.lod()[lod_level - 1];
T
tensor-tang 已提交
376 377
    if (pooltype == "SUM") {
      auto place = context.GetPlace();
378
      PADDLE_ENFORCE_EQ(
379
          place == phi::CPUPlace(),
380
          true,
381
          errors::InvalidArgument(
382
              "Sequence_pool should run on CPU Device when pooltype is SUM"));
T
tensor-tang 已提交
383
      const T* src = input.data<T>();
384
      T* dst = context.template Alloc<T>(output);
385
      phi::jit::seq_pool_attr_t attr(
T
tensor-tang 已提交
386
          static_cast<int>(input.numel() / input.dims()[0]),
387 388
          phi::jit::SeqPoolType::kSum);
      auto seqpool = phi::jit::KernelFuncs<phi::jit::SeqPoolTuple<T>,
389
                                           phi::CPUPlace>::Cache()
390
                         .At(attr);
T
tensor-tang 已提交
391 392
      for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) {
        attr.h = static_cast<int>(lod[i + 1] - lod[i]);
393 394 395 396 397 398 399
        if (attr.h == 0) {
          for (int j = 0; j < attr.w; ++j) {
            dst[j] = pad_value;
          }
        } else {
          seqpool(src, dst, &attr);
        }
T
tensor-tang 已提交
400 401 402 403 404
        dst += attr.w;
        src += attr.h * attr.w;
      }
      return;
    }
D
dzhwinter 已提交
405 406
    auto& place = *context.eigen_device();
    for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) {
407
      phi::DenseTensor out_t = output->Slice(i, i + 1);
408 409 410 411 412 413 414
      int64_t w = input.numel() / input.dims()[0];
      if (lod[i] == lod[i + 1]) {
        for (int j = 0; j < w; ++j) {
          out_t.data<T>()[j] = pad_value;
        }
        continue;
      }
415
      phi::DenseTensor in_t =
D
dzhwinter 已提交
416 417
          input.Slice(static_cast<int>(lod[i]), static_cast<int>(lod[i + 1]));
      int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]);
418
      auto in_e = EigenMatrix<T>::From(in_t, phi::make_ddim({h, w}));
D
dzhwinter 已提交
419 420 421 422 423 424 425
      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 == "SQRT") {
        out_e.device(place) = in_e.sum(Eigen::array<int, 1>({{0}})) /
                              std::sqrt(static_cast<T>(h));
      } else {
426
        PADDLE_THROW(errors::InvalidArgument(
427 428 429
            "unsupported pooling pooltype: %s. Only support \"AVERAGE\" and "
            "\"SQRT\"",
            pooltype));
D
dzhwinter 已提交
430 431 432 433 434 435
      }
    }
  }
};

template <typename T>
L
Leo Chen 已提交
436
class SequencePoolGradFunctor<phi::CPUContext, T> {
D
dzhwinter 已提交
437
 public:
L
Leo Chen 已提交
438
  void operator()(const phi::CPUContext& context,
439
                  const std::string pooltype,
440 441
                  const phi::DenseTensor& out_grad,
                  phi::DenseTensor* in_grad,
D
dzhwinter 已提交
442
                  /* max pool has index */
443
                  const phi::DenseTensor* index = nullptr) {
D
dzhwinter 已提交
444
    if (pooltype == "MAX") {
445
      phi::funcs::MaxSeqPoolGradFunctor<T> max_pool_grad;
D
dzhwinter 已提交
446 447 448 449 450 451
      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
L
Leo Chen 已提交
452
      phi::funcs::SetConstant<phi::CPUContext, T> functor;
D
dzhwinter 已提交
453 454
      functor(context, in_grad, 0);
    }
M
minqiyang 已提交
455 456

    if (pooltype == "SUM") {
457
      phi::funcs::SumSeqPoolGradFunctor<T> sum_pool_grad;
M
minqiyang 已提交
458
      sum_pool_grad(context, out_grad, in_grad);
M
minqiyang 已提交
459 460 461
      return;
    }

462 463
    auto lod_level = in_grad->lod().size();
    auto lod = in_grad->lod()[lod_level - 1];
D
dzhwinter 已提交
464 465
    auto& place = *context.eigen_device();
    for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) {
466
      if (lod[i] == lod[i + 1]) continue;
D
dzhwinter 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
      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 == "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 {
487
        PADDLE_THROW(errors::InvalidArgument(
488 489 490
            "unsupported pooling pooltype: %s. Only support \"AVERAGE\", "
            "\"SQRT\", \"LAST\" and \"FIRST\"",
            pooltype));
D
dzhwinter 已提交
491 492 493 494 495
      }
    }
  }
};

L
Leo Chen 已提交
496 497 498 499
template class SequencePoolFunctor<phi::CPUContext, float>;
template class SequencePoolFunctor<phi::CPUContext, double>;
template class SequencePoolGradFunctor<phi::CPUContext, float>;
template class SequencePoolGradFunctor<phi::CPUContext, double>;
500

501 502
}  // namespace funcs
}  // namespace phi