sequence_pad_op.h 2.4 KB
Newer Older
Y
yangyaming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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
16 17

#include <vector>
Y
yangyaming 已提交
18 19 20
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/operators/math/math_function.h"
21
#include "paddle/fluid/operators/math/sequence_padding.h"
Y
yangyaming 已提交
22 23 24 25 26 27 28 29 30 31 32

namespace paddle {
namespace operators {

using LoDTensor = framework::LoDTensor;
using LoD = framework::LoD;

template <typename DeviceContext, typename T>
class SequencePadOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
33 34 35
    const auto* x = ctx.Input<LoDTensor>("X");
    auto* out = ctx.Output<LoDTensor>("Out");
    out->mutable_data<T>(ctx.GetPlace());
Y
yangyaming 已提交
36

37 38 39 40
    const auto* pad_value = ctx.Input<LoDTensor>("PadValue");
    const T* pad_value_data = pad_value->data<T>();
    std::vector<T> pad_value_vec(pad_value_data,
                                 pad_value_data + pad_value->numel());
41

42
    int padded_length = ctx.Attr<int>("padded_length");
Y
yangyaming 已提交
43

44
    math::PaddingLoDTensorFunctor<DeviceContext, T>()(
45 46
        ctx.template device_context<DeviceContext>(), *x, out, pad_value_vec,
        padded_length, 0, false, math::kBatchLengthWidth);
Y
yangyaming 已提交
47 48 49 50 51 52 53
  }
};

template <typename DeviceContext, typename T>
class SequencePadGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
54 55 56 57
    auto* d_x = ctx.Output<LoDTensor>(framework::GradVarName("X"));
    if (d_x) {
      const auto* d_out = ctx.Input<LoDTensor>(framework::GradVarName("Out"));
      d_x->mutable_data<T>(ctx.GetPlace());
Y
yangyaming 已提交
58

59
      int padded_length = ctx.Attr<int>("padded_length");
60

61 62 63 64
      math::UnpaddingLoDTensorFunctor<DeviceContext, T>()(
          ctx.template device_context<DeviceContext>(), *d_out, d_x,
          padded_length, 0, false, math::kBatchLengthWidth);
    }
Y
yangyaming 已提交
65 66 67 68 69
  }
};

}  // namespace operators
}  // namespace paddle