sequence_reverse_op.h 6.1 KB
Newer Older
S
sneaxiy 已提交
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

17
#include <memory>
18

S
sneaxiy 已提交
19 20
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/for_range.h"
21
#include "paddle/phi/kernels/funcs/algorithm.h"
S
sneaxiy 已提交
22 23 24 25 26 27 28 29 30

namespace paddle {
namespace operators {

class SequenceReverseOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
31
    PADDLE_ENFORCE_EQ(
32 33
        ctx->HasInput("X"),
        true,
34 35
        platform::errors::NotFound("Input(X) of SequenceReverse must exist"));
    PADDLE_ENFORCE_EQ(
36 37
        ctx->HasOutput("Y"),
        true,
38
        platform::errors::NotFound("Output(Y) of SequenceReverse must exist"));
S
sneaxiy 已提交
39 40

    auto x_dim = ctx->GetInputDim("X");
41
    PADDLE_ENFORCE_GE(
42 43
        x_dim.size(),
        2,
44 45 46 47 48
        platform::errors::InvalidArgument(
            "The rank of SequenceReverseOp Input(X) must be greater "
            "than or equal to 2. But the Input(X) tensor's rank we received is "
            "%d",
            x_dim.size()));
S
sneaxiy 已提交
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 75 76 77 78 79 80 81 82 83 84 85 86

    ctx->SetOutputDim("Y", x_dim);
    ctx->ShareLoD("X", "Y");
  }
};

class SequenceReverseOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "The input LoDTensor of sequence_reverse op.");
    AddOutput("Y", "The output LoDTensor of sequence_reverse op.");
    AddComment(R"DOC(
SequenceReverse Operator.

Reverse each sequence in input X along dim 0.

Assuming X is a LoDTensor with dims [5, 4] and lod [[0, 2, 5]], where:

X.data() = [
  [1, 2, 3, 4],
  [5, 6, 7, 8], # the 0-th sequence with length 2
  [9, 10, 11, 12],
  [13, 14, 15, 16],
  [17, 18, 19, 20] # the 1-st sequence with length 3
]

The output Y would be a LoDTensor sharing the same dims and lod with input X,
and:

Y.data() = [
  [5, 6, 7, 8],
  [1, 2, 3, 4], # the reversed 0-th sequence with length 2
  [17, 18, 19, 20],
  [13, 14, 15, 16],
  [9, 10, 11, 12] # the reversed 1-st sequence with length 3
]

This Operator is useful to build a reverse dynamic RNN network.
S
sneaxiy 已提交
87 88

This Operator only supports one-level lod currently.
S
sneaxiy 已提交
89 90 91 92 93 94
    )DOC");
  }
};

template <typename T>
struct SequenceReverseFunctor {
95 96
  SequenceReverseFunctor(
      const T *x, T *y, const size_t *lod, size_t lod_count, size_t row_numel)
S
sneaxiy 已提交
97 98 99 100
      : x_(x), y_(y), lod_(lod), lod_count_(lod_count), row_numel_(row_numel) {}

  HOSTDEVICE void operator()(size_t idx_x) const {
    auto row_idx_x = idx_x / row_numel_;
101
    auto lod_idx = phi::funcs::UpperBound(lod_, lod_count_, row_idx_x);
S
sneaxiy 已提交
102 103 104 105 106 107 108 109 110 111 112 113
    auto row_idx_y = lod_[lod_idx - 1] + (lod_[lod_idx] - 1 - row_idx_x);
    auto idx_y = row_idx_y * row_numel_ + idx_x % row_numel_;
    y_[idx_y] = x_[idx_x];
  }

  const T *x_;
  T *y_;
  const size_t *lod_;
  size_t lod_count_;
  size_t row_numel_;
};

H
huangjiyi 已提交
114
template <typename T, typename DeviceContext>
S
sneaxiy 已提交
115
class SequenceReverseOpKernel : public framework::OpKernel<T> {
116
  using LoDTensor = phi::DenseTensor;
S
sneaxiy 已提交
117 118 119 120 121 122

 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    auto &x = *ctx.Input<LoDTensor>("X");
    auto *y = ctx.Output<LoDTensor>("Y");

123 124
    PADDLE_ENFORCE_EQ(x.lod().empty(),
                      false,
125 126 127 128
                      platform::errors::NotFound(
                          "Input(X) Tensor of SequenceReverseOp does not "
                          "contain LoD information."));

129 130
    PADDLE_ENFORCE_EQ(x.lod().size(),
                      1,
131 132 133 134
                      platform::errors::InvalidArgument(
                          "SequenceReverseOp only support one "
                          "level lod. But the Input(X) lod size is %d",
                          x.lod().size()));
S
sneaxiy 已提交
135 136 137 138

    const size_t *lod;
    size_t lod_count = x.lod()[0].size();

139
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
sneaxiy 已提交
140
    if (platform::is_gpu_place(ctx.GetPlace())) {
141
      auto xlod = x.lod()[0];
H
Huang Jiyi 已提交
142
      phi::MixVector<size_t> mixv_xlod(&xlod);
143
      lod = mixv_xlod.CUDAData(ctx.GetPlace());
S
sneaxiy 已提交
144 145 146
    } else {
#endif
      lod = x.lod()[0].data();
147
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
sneaxiy 已提交
148 149 150 151 152 153 154 155
    }
#endif

    size_t limit = static_cast<size_t>(x.numel());
    size_t row_numel = static_cast<size_t>(limit / x.dims()[0]);
    auto *x_data = x.data<T>();
    auto *y_data = y->mutable_data<T>(ctx.GetPlace());

156
    PADDLE_ENFORCE_NE(
157 158
        x_data,
        y_data,
159 160
        platform::errors::InvalidArgument(
            "SequenceReverse Op does not support in-place operation"));
S
sneaxiy 已提交
161

162 163 164 165 166 167
    if (platform::is_cpu_place(ctx.GetPlace())) {
      for (size_t idx = 0; idx < lod_count - 1; idx++) {
        auto start_pos = lod[idx];
        auto end_pos = lod[idx + 1];
        for (auto pos = start_pos; pos < end_pos; pos++) {
          auto cur_pos = end_pos - pos - 1 + start_pos;
168 169
          std::memcpy(y_data + pos * row_numel,
                      x_data + cur_pos * row_numel,
170 171 172 173 174 175
                      row_numel * sizeof(T));
        }
      }
    } else {
      auto &dev_ctx = ctx.template device_context<DeviceContext>();

176 177
      SequenceReverseFunctor<T> functor(
          x_data, y_data, lod, lod_count, row_numel);
178 179 180
      platform::ForRange<DeviceContext> for_range(dev_ctx, limit);
      for_range(functor);
    }
S
sneaxiy 已提交
181 182 183
  }
};

H
hong 已提交
184 185
template <typename T>
class SequenceReverseGradOpMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
186
 public:
H
hong 已提交
187
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
188 189

 protected:
190
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
191
    op->SetType("sequence_reverse");
H
hong 已提交
192 193 194
    op->SetInput("X", this->OutputGrad("Y"));
    op->SetOutput("Y", this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
195 196 197 198 199
  }
};

}  // namespace operators
}  // namespace paddle