sequence_conv_op.h 11.1 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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/eigen.h"
#include "paddle/framework/op_registry.h"
C
chengduoZH 已提交
18
#include "paddle/operators/math/math_function.h"
C
chengduoZH 已提交
19
#include "paddle/operators/math/sequence_project.h"
C
chengduoZH 已提交
20 21 22 23 24 25

namespace paddle {
namespace operators {

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

template <typename Place, typename T>
C
chengduoZH 已提交
34
class SequenceConvKernel : public framework::OpKernel<T> {
C
chengduoZH 已提交
35 36 37 38
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* in = context.Input<LoDTensor>("X");
    auto* out = context.Output<LoDTensor>("Out");
C
chengduoZH 已提交
39
    auto filter = *context.Input<LoDTensor>("Filter");
40

C
chengduoZH 已提交
41
    out->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
42 43 44 45

    int context_start = context.Attr<int>("context_start");
    int context_length = context.Attr<int>("context_length");
    int context_stride = context.Attr<int>("context_stride");
C
chengduoZH 已提交
46
    bool padding_trainable = context.Attr<bool>("padding_trainable");
C
chengduoZH 已提交
47 48 49 50 51 52 53 54 55 56 57 58

    // InferShape by in_lod
    PADDLE_ENFORCE_EQ(in->lod().size(), 1UL,
                      "Only support one level sequence now.");

    const LoDTensor* padding_data = nullptr;
    if (padding_trainable) {
      padding_data = context.Input<LoDTensor>("PaddingData");
    }

    int up_pad = std::max(0, -context_start);
    int down_pad = std::max(0, context_start + context_length - 1);
C
chengduoZH 已提交
59
    int sequence_width;
C
chengduoZH 已提交
60
    sequence_width = static_cast<int>(in->dims()[1]);
C
chengduoZH 已提交
61

C
chengduoZH 已提交
62 63 64 65 66 67 68 69 70
    // use col_shape in the im2col calculation
    framework::DDim col_shape = {in->dims()[0],
                                 sequence_width * context_length};
    LoDTensor col;
    col.mutable_data<T>(col_shape, context.GetPlace());
    // Because if padding_trainable is false, padding data should be zeros.
    auto temp = framework::EigenVector<T>::Flatten(col);
    temp.device(context.GetEigenDevice<Place>()) =
        temp.constant(static_cast<T>(0));
71

C
chengduoZH 已提交
72 73
    paddle::operators::math::SequenceProjectFunctor<Place, T>
        seq_project_functor;
74

C
chengduoZH 已提交
75 76 77
    seq_project_functor(context.device_context(), in, padding_data, &col,
                        padding_trainable, context_start, context_length,
                        context_stride, up_pad, down_pad);
78

C
chengduoZH 已提交
79 80 81
    filter.Resize(framework::make_ddim({context_length * sequence_width, 1}));
    math::matmul<Place, T>(context.device_context(), col, false, filter, false,
                           T(1.0), out, T(0.0));
C
chengduoZH 已提交
82 83 84 85
  }
};

template <typename Place, typename T>
C
chengduoZH 已提交
86
class SequenceConvGradKernel : public framework::OpKernel<T> {
C
chengduoZH 已提交
87 88 89 90
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* out_g = context.Input<LoDTensor>(framework::GradVarName("Out"));
    auto* in_g = context.Output<LoDTensor>(framework::GradVarName("X"));
C
chengduoZH 已提交
91 92
    auto* filter_g =
        context.Output<LoDTensor>(framework::GradVarName("Filter"));
C
chengduoZH 已提交
93 94
    auto* padding_data_g =
        context.Output<LoDTensor>(framework::GradVarName("PaddingData"));
95
    auto* in = context.Input<LoDTensor>("X");
C
chengduoZH 已提交
96 97
    auto* filter = context.Input<LoDTensor>("Filter");

C
chengduoZH 已提交
98 99 100 101
    auto place = context.GetEigenDevice<Place>();

    int context_start = context.Attr<int>("context_start");
    int context_length = context.Attr<int>("context_length");
102
    int context_stride = context.Attr<int>("context_stride");
C
chengduoZH 已提交
103
    bool padding_trainable = context.Attr<bool>("padding_trainable");
C
chengduoZH 已提交
104 105

    // InferShape by in_lod
106
    PADDLE_ENFORCE_EQ(in->lod().size(), 1UL,
C
chengduoZH 已提交
107
                      "Only support one level sequence now.");
108
    auto lod_g_level_0 = in->lod()[0];
C
chengduoZH 已提交
109

C
chengduoZH 已提交
110 111
    int up_pad = std::max(0, -context_start);
    int down_pad = std::max(0, context_start + context_length - 1);
112 113
    int sequence_height, sequence_width;
    int input_row_begin, input_row_end;
C
chengduoZH 已提交
114

C
chengduoZH 已提交
115 116
    sequence_width = static_cast<int>(in->dims()[1]);

C
chengduoZH 已提交
117 118 119 120 121 122 123 124 125 126 127
    // use col_shape in the im2col calculation
    framework::DDim col_shape = {in->dims()[0],
                                 sequence_width * context_length};
    LoDTensor col;

    if (in_g || filter_g || (padding_trainable && padding_data_g)) {
      col.mutable_data<T>(col_shape, context.GetPlace());
      // Because if padding_trainable is false, padding data should be zeros.
      auto temp = framework::EigenVector<T>::Flatten(col);
      temp.device(context.GetEigenDevice<Place>()) =
          temp.constant(static_cast<T>(0));
C
chengduoZH 已提交
128

C
chengduoZH 已提交
129 130 131
      math::matmul<Place, T>(context.device_context(), *out_g, false, *filter,
                             true, T(1.0), &col, T(1.0));
    }
C
chengduoZH 已提交
132

C
chengduoZH 已提交
133 134
    if (in_g) {
      in_g->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
135

C
chengduoZH 已提交
136 137
      math::SetConstant<Place, T> functor;
      functor(context.device_context(), in_g, 0);
138

C
chengduoZH 已提交
139 140 141 142
      paddle::operators::math::Col2ImFunctor<
          paddle::operators::math::ColFormat::kOCF, Place, float>
          col2im_ocf;

C
chengduoZH 已提交
143 144 145 146 147 148
      for (int i = 0; i < static_cast<int>(lod_g_level_0.size()) - 1; ++i) {
        input_row_begin =
            (context_start > 0)
                ? static_cast<int>(lod_g_level_0[i]) + context_start
                : static_cast<int>(lod_g_level_0[i]);
        input_row_end = static_cast<int>(lod_g_level_0[i + 1]);
C
chengduoZH 已提交
149

C
chengduoZH 已提交
150 151
        Tensor col_t = col.Slice(static_cast<int>(lod_g_level_0[i]),
                                 static_cast<int>(lod_g_level_0[i + 1]));
C
chengduoZH 已提交
152

C
chengduoZH 已提交
153
        sequence_height = static_cast<int>(col_t.dims()[0]);
C
chengduoZH 已提交
154 155 156 157 158 159 160

        if (input_row_begin < input_row_end) {
          Tensor in_t = in_g->Slice(input_row_begin, input_row_end);

          std::vector<int64_t> output_shape(
              {sequence_height, 1, 1, context_length,
               sequence_width});  // output_height, output_width,
C
chengduoZH 已提交
161 162
                                  // input_channels, filter_height, filter_width
          col_t.Resize(framework::make_ddim(output_shape));
C
chengduoZH 已提交
163 164 165 166 167 168

          std::vector<int64_t> input_shape(
              {1, input_row_end - input_row_begin,
               sequence_width});  // input_channels, input_height, input_width
          in_t.Resize(framework::make_ddim(input_shape));

C
chengduoZH 已提交
169
          col2im_ocf(context.device_context(), in_t, col_t,
C
chengduoZH 已提交
170 171 172
                     /*stride_height*/ context_stride, /*stride_width*/ 0,
                     up_pad, down_pad);
        }
C
chengduoZH 已提交
173
        col_t.Resize(framework::make_ddim(
C
chengduoZH 已提交
174 175 176 177 178 179
            {sequence_height, context_length * sequence_width}));
      }
    }

    if (padding_trainable && padding_data_g) {
      padding_data_g->mutable_data<T>(context.GetPlace());
C
chengduoZH 已提交
180

C
chengduoZH 已提交
181 182 183 184
      math::SetConstant<Place, T> functor;
      functor(context.device_context(), padding_data_g, 0);

      for (int i = 0; i < static_cast<int>(lod_g_level_0.size()) - 1; ++i) {
C
chengduoZH 已提交
185 186
        Tensor col_t = col.Slice(static_cast<int>(lod_g_level_0[i]),
                                 static_cast<int>(lod_g_level_0[i + 1]));
C
chengduoZH 已提交
187

C
chengduoZH 已提交
188
        sequence_height = static_cast<int>(col_t.dims()[0]);
189

C
chengduoZH 已提交
190
        col_t.Resize(framework::make_ddim(
191 192 193 194 195 196 197 198 199 200
            {sequence_height * context_length, sequence_width}));

        if (up_pad > 0) {  // add up pad
          int padding_rows = std::min(
              up_pad,
              static_cast<int>(lod_g_level_0[i + 1] - lod_g_level_0[i]));

          for (int k = 0; k < padding_rows; ++k) {
            int padding_size =
                k + context_length < up_pad ? context_length : up_pad - k;
C
chengduoZH 已提交
201 202
            Tensor out_t_sub = col_t.Slice(k * context_length,
                                           k * context_length + padding_size);
C
chengduoZH 已提交
203
            Tensor w_sub = padding_data_g->Slice(k, k + padding_size);
204 205 206 207
            // in this block, using EigenVector<T>::Flatten is ok too.
            auto out_t_sub_e = EigenMatrix<T>::From(out_t_sub);
            auto w_sub_e = EigenMatrix<T>::From(w_sub);
            w_sub_e.device(place) = w_sub_e + out_t_sub_e;
C
chengduoZH 已提交
208
          }
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        }
        if (down_pad > 0) {  // add down pad
          int down_pad_begin_row =
              std::max(0,
                       (sequence_height - context_start - context_length) + 1) +
              1;
          int padding_begin = std::max(0, context_start - sequence_height);
          int padding_size =
              sequence_height - context_start >= context_length
                  ? 1
                  : context_length - (sequence_height - context_start);
          if (context_start >= sequence_height) padding_size = context_length;
          int padding_idx = padding_begin;
          for (int t = 0; t + down_pad_begin_row <= sequence_height;
               ++t, ++padding_size) {
            if (context_start >= sequence_height) padding_size = context_length;
            if (padding_size > context_length) {
              padding_size = context_length;
              padding_idx++;
C
chengduoZH 已提交
228
            }
229 230
            if (padding_begin > 0 || sequence_height == context_start)
              padding_idx = padding_begin + t;
C
chengduoZH 已提交
231
            Tensor out_t_sub = col_t.Slice(
232 233
                (down_pad_begin_row + t) * context_length - padding_size,
                (down_pad_begin_row + t) * context_length);
C
chengduoZH 已提交
234
            Tensor w_sub = padding_data_g->Slice(
235 236 237 238
                up_pad + padding_idx, up_pad + padding_idx + padding_size);
            auto out_t_sub_e = EigenMatrix<T>::From(out_t_sub);
            auto w_sub_e = EigenMatrix<T>::From(w_sub);
            w_sub_e.device(place) = w_sub_e + out_t_sub_e;
C
chengduoZH 已提交
239 240
          }
        }
C
chengduoZH 已提交
241
        col_t.Resize(framework::make_ddim(
C
chengduoZH 已提交
242
            {sequence_height, context_length * sequence_width}));
243
      }
C
chengduoZH 已提交
244
    }
C
chengduoZH 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

    if (filter_g) {
      filter_g->mutable_data<T>(context.GetPlace());

      math::SetConstant<Place, T> functor;
      functor(context.device_context(), filter_g, 0);

      Tensor filter_grad_ = *filter_g;
      Tensor out_grad_ = *out_g;

      const LoDTensor* padding_data = nullptr;
      if (padding_trainable) {
        padding_data = context.Input<LoDTensor>("PaddingData");
      }

      sequence_width = static_cast<int>(in->dims()[1]);

      paddle::operators::math::SequenceProjectFunctor<Place, T>
          seq_project_functor;

      seq_project_functor(context.device_context(), in, padding_data, &col,
                          padding_trainable, context_start, context_length,
                          context_stride, up_pad, down_pad);

      filter_grad_.Resize(
          framework::make_ddim({context_length * sequence_width, 1}));

      math::matmul<Place, T>(context.device_context(), col, true, out_grad_,
                             false, T(1.0), &filter_grad_, T(1.0));
    }
C
chengduoZH 已提交
275 276 277 278 279
  }
};

}  // namespace operators
}  // namespace paddle