sequence_reshape_op.h 5.7 KB
Newer Older
Y
yangyaming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 "paddle/framework/op_registry.h"
#include "paddle/operators/math/math_function.h"

namespace paddle {
namespace operators {

using LoDTensor = framework::LoDTensor;
template <typename DeviceContext, typename T>
class SequenceReshapeKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* in = context.Input<LoDTensor>("X");
    auto* out = context.Output<LoDTensor>("Out");
29
    int out_width = context.Attr<int>("new_dim");
Y
yangyaming 已提交
30 31 32 33 34 35 36 37 38

    const T* p_in_data = in->data<T>();

    auto in_dims = in->dims();
    int64_t in_width = in_dims[1];
    auto& in_lod = in->lod();

    PADDLE_ENFORCE_EQ(in_lod.size(), 1UL,
                      "Only support one level sequence now.");
39 40 41
    PADDLE_ENFORCE_EQ(
        in_dims[0], in_lod[0].back(),
        "Inconsistent size between X.shape[0] and X.lod()[0].back().");
Y
yangyaming 已提交
42 43 44 45 46

    auto in_lod_l0 = in_lod[0];
    int seq_num = in_lod_l0.size() - 1;

    auto& out_lod = *out->mutable_lod();
47 48 49
    out_lod.resize(1);
    out_lod[0].clear();
    out_lod[0].push_back(0);
Y
yangyaming 已提交
50 51
    for (int i = 0; i < seq_num; ++i) {
      size_t seq_len = in_lod_l0[i + 1] - in_lod_l0[i];
52 53 54 55 56 57 58 59 60 61 62 63
      size_t offset = 0;
      offset = (seq_len * in_width) / out_width;
      PADDLE_ENFORCE_EQ(offset * out_width, seq_len * in_width,
                        "Please make sure (sequence_length * dimension) can be "
                        "divided by new_dim with no remainder for each "
                        "sequence. The %dth sequence is invalid.",
                        i + 1);
      PADDLE_ENFORCE_GT(offset, 0,
                        "Illegal operation, length of the %dth sequence become "
                        "to 0 after reshaped.",
                        i + 1);
      out_lod[0].push_back(out_lod[0].back() + offset);
Y
yangyaming 已提交
64 65
    }

66 67 68
    out->mutable_data<T>(context.GetPlace());
    out->Resize({static_cast<int64_t>(out_lod[0].back()), out_width});
    T* p_out_data = out->mutable_data<T>(context.GetPlace());
Y
yangyaming 已提交
69 70 71 72 73
    math::set_constant(context.device_context(), out, 0.0f);

    for (int i = 0; i < seq_num; ++i) {
      size_t in_offset = in_lod_l0[i] * in_width;
      size_t out_offset = out_lod[0][i] * out_width;
74 75 76
      size_t in_count = (in_lod_l0[i + 1] - in_lod_l0[i]) * in_width;
      size_t out_count = (out_lod[0][i + 1] - out_lod[0][i]) * out_width;
      size_t bytes = sizeof(T) * std::min(in_count, out_count);
Y
yangyaming 已提交
77
      if (platform::is_cpu_place(context.GetPlace())) {
78 79 80 81
        memory::Copy(boost::get<platform::CPUPlace>(context.GetPlace()),
                     p_out_data + out_offset,
                     boost::get<platform::CPUPlace>(context.GetPlace()),
                     p_in_data + in_offset, bytes);
Y
yangyaming 已提交
82 83
      } else {
#ifdef PADDLE_WITH_CUDA
84 85
        auto& dev_ctx =
            context.template device_context<platform::CUDADeviceContext>();
Y
yangyaming 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        memory::Copy(boost::get<platform::CUDAPlace>(context.GetPlace()),
                     p_out_data + out_offset,
                     boost::get<platform::CUDAPlace>(context.GetPlace()),
                     p_in_data + in_offset, bytes, dev_ctx.stream());
#endif
      }
    }
  }
};

template <typename DeviceContext, typename T>
class SequenceReshapeGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* x_tensor_ptr = context.Input<LoDTensor>("X");
    auto* out_tensor_ptr = context.Input<LoDTensor>("Out");
    auto* out_grad_tensor_ptr =
        context.Input<LoDTensor>(framework::GradVarName("Out"));
    auto* x_grad_tensor_ptr =
        context.Output<LoDTensor>(framework::GradVarName("X"));

    T* p_x_grad_data = x_grad_tensor_ptr->mutable_data<T>(context.GetPlace());
    const T* p_out_grad_data = out_grad_tensor_ptr->data<T>();

    auto& x_lod = x_tensor_ptr->lod();
    int seq_num = x_lod[0].size() - 1;
    int x_width = x_tensor_ptr->dims()[1];
    auto& out_lod = out_tensor_ptr->lod();
    int out_width = out_tensor_ptr->dims()[1];

116 117
    math::set_constant(context.device_context(), x_grad_tensor_ptr, 0.0f);

Y
yangyaming 已提交
118 119 120
    for (int i = 0; i < seq_num; ++i) {
      size_t src_offset = out_lod[0][i] * out_width;
      size_t dst_offset = x_lod[0][i] * x_width;
121 122 123
      size_t src_count = (out_lod[0][i + 1] - out_lod[0][i]) * out_width;
      size_t dst_count = (x_lod[0][i + 1] - x_lod[0][i]) * x_width;
      size_t bytes = sizeof(T) * std::min(src_count, dst_count);
Y
yangyaming 已提交
124
      if (platform::is_cpu_place(context.GetPlace())) {
125 126 127 128
        memory::Copy(boost::get<platform::CPUPlace>(context.GetPlace()),
                     p_x_grad_data + dst_offset,
                     boost::get<platform::CPUPlace>(context.GetPlace()),
                     p_out_grad_data + src_offset, bytes);
Y
yangyaming 已提交
129 130
      } else {
#ifdef PADDLE_WITH_CUDA
131 132
        auto& dev_ctx =
            context.template device_context<platform::CUDADeviceContext>();
Y
yangyaming 已提交
133 134 135 136 137 138 139 140 141 142 143 144
        memory::Copy(boost::get<platform::CUDAPlace>(context.GetPlace()),
                     p_x_grad_data + dst_offset,
                     boost::get<platform::CUDAPlace>(context.GetPlace()),
                     p_out_grad_data + src_offset, bytes, dev_ctx.stream());
#endif
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle