context_project.h 12.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
C
chengduoZH 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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 18
#include <algorithm>
#include <vector>
Y
Yi Wang 已提交
19
#include "paddle/fluid/framework/lod_tensor.h"
Y
Yu Yang 已提交
20
#include "paddle/fluid/operators/math/blas.h"
Y
Yi Wang 已提交
21
#include "paddle/fluid/operators/math/im2col.h"
C
chengduoZH 已提交
22 23 24 25 26

namespace paddle {
namespace operators {
namespace math {

C
chengduoZH 已提交
27 28 29
using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;

C
chengduoZH 已提交
30
/*
C
chengduoZH 已提交
31
 * \brief Context projection concatenates features in adjacent time-steps in
C
chengduoZH 已提交
32 33 34
 * a sequence. The i-th row of the output is the concatenation of
 * context_length rows of the input. The context_length rows are the
 * consecutive rows from the i+shift_start row.
C
sss  
chengduoZH 已提交
35
 * ContextProjectGradFunctor is the inverse process of ContextProjectFunctor.
C
chengduoZH 已提交
36
 *
C
chengduoZH 已提交
37
 * \param in            Input data.
C
chengduoZH 已提交
38 39
 * \param Shape         The shape of Input data:
 *                        [mini-batch, input_hidden_size].
C
chengduoZH 已提交
40
 *
C
chengduoZH 已提交
41
 * \param padding_data  Padding data.
C
chengduoZH 已提交
42 43
 * \param Shape         The shape of Padding data:
 *                        [up_pad + down_pad, input_hidden_size].
C
chengduoZH 已提交
44
 *
C
chengduoZH 已提交
45
 * \param col           Col data.
C
chengduoZH 已提交
46 47
 * \param Shape         The shape of Col data:
 *                        [mini-batch, context_length * input_hidden_size].
C
chengduoZH 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 *
 * For a mini-batch of 2 variable lengths sentences, containing 3, and 1
 * time-steps:
 *
 * Assumed input (X) is a [4, M, N] float LoDTensor, and X->lod()[0] = [0, 3,
 * 4].
 * Besides, for the sake of simplicity, we assume M=1 and N=2.
 *
 * X = [[a1, a2;
 *       b1, b2;
 *       c1, c2]
 *      [d1, d2]]
 *
 * This is to say that input (X) has 4 words and the dimension of each word
 * representation is 2.
 *
 * - Case1:
C
chengduoZH 已提交
65 66 67
 *   If context_start is -1 and padding_trainable is false, we use zero to pad
 *   instead of learned weight to pad,
 *   and the context_length is 3, the output (Out) is:
C
chengduoZH 已提交
68
 *
C
chengduoZH 已提交
69 70 71 72
 *   Out =[[0,  0,  a1, a2, b1, b2;
 *          a1, a2, b1, b2, c1, c2;
 *          b1, b2, c1, c2, 0,  0 ]
 *          [0,  0, d1, d2, 0,  0 ]]
C
chengduoZH 已提交
73 74
 *
 * - Case2:
C
chengduoZH 已提交
75 76 77
 *   If context_start is -1 and padding_trainable is true, we use learned weight
 *   to pad,
 *   and the context_length is 3, the output (Out) is:
C
chengduoZH 已提交
78
 *
C
chengduoZH 已提交
79 80 81 82
 *   Out = [[w1, w2, a1, a2, b1, b2;
 *           a1, a2, b1, b2, c1, c2;
 *           b1, b2, c1, c2, w3, w4]
 *          [w1, w2, d1, d2, w3, w4]]
C
chengduoZH 已提交
83 84 85
 *
 */

Q
QI JUN 已提交
86
template <typename DeviceContext, typename T>
C
chengduoZH 已提交
87
class ContextProjectFunctor {
C
chengduoZH 已提交
88
 public:
Q
QI JUN 已提交
89
  void operator()(const DeviceContext& context, const LoDTensor& in,
90
                  const Tensor* padding_data, bool padding_trainable,
91 92 93
                  const int context_start, const int context_length,
                  const int context_stride, const int up_pad,
                  const int down_pad, Tensor* col) {
C
chengduoZH 已提交
94
    auto lod_level_0 = in.lod()[0];
C
chengduoZH 已提交
95

Q
QI JUN 已提交
96
    math::Im2ColFunctor<math::ColFormat::kOCF, DeviceContext, float> im2col_ocf;
C
sss  
chengduoZH 已提交
97

C
chengduoZH 已提交
98 99 100
    std::vector<int> dilation({1, 1});
    std::vector<int> padding({up_pad, 0, down_pad, 0});
    std::vector<int> stride({context_stride, 1});
C
chengduoZH 已提交
101

C
sss  
chengduoZH 已提交
102 103 104 105 106
    int input_row_begin, input_row_end;
    int sequence_height, sequence_width;
    sequence_width = in.dims()[1];

    for (int i = 0; i < static_cast<int>(lod_level_0.size()) - 1; ++i) {
107 108
      if (lod_level_0[i] == lod_level_0[i + 1]) continue;

C
sss  
chengduoZH 已提交
109 110 111 112 113
      input_row_begin = (context_start > 0)
                            ? static_cast<int>(lod_level_0[i]) + context_start
                            : static_cast<int>(lod_level_0[i]);
      input_row_end = static_cast<int>(lod_level_0[i + 1]);

114 115
      Tensor out_t = col->Slice(static_cast<int>(lod_level_0[i]),
                                static_cast<int>(lod_level_0[i + 1]));
C
sss  
chengduoZH 已提交
116 117 118 119

      sequence_height = static_cast<int>(out_t.dims()[0]);

      if (input_row_begin < input_row_end) {
C
chengduoZH 已提交
120
        Tensor in_t = in.Slice(input_row_begin, input_row_end);
C
sss  
chengduoZH 已提交
121 122 123 124 125 126 127 128 129 130 131

        std::vector<int64_t> output_shape(
            {sequence_height, 1, 1, context_length,
             sequence_width});  // output_height, output_width,
        // input_channels, filter_height, filter_width
        out_t.Resize(framework::make_ddim(output_shape));

        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 已提交
132
        im2col_ocf(context, in_t, dilation, stride, padding, &out_t);
C
sss  
chengduoZH 已提交
133 134 135 136
        out_t.Resize({sequence_height, context_length * sequence_width});
      }
    }
    if (padding_trainable) {
137 138 139 140
      PADDLE_ENFORCE_NOT_NULL(
          padding_data,
          platform::errors::InvalidArgument(
              "The input tensor 'padding_data' should not be NULL."));
C
sss  
chengduoZH 已提交
141
      for (int i = 0; i < static_cast<int>(lod_level_0.size()) - 1; ++i) {
142 143
        if (lod_level_0[i] == lod_level_0[i + 1]) continue;

144 145
        Tensor out_t = col->Slice(static_cast<int>(lod_level_0[i]),
                                  static_cast<int>(lod_level_0[i + 1]));
C
sss  
chengduoZH 已提交
146 147 148 149

        sequence_height = static_cast<int>(out_t.dims()[0]);

        // add up trainable data
L
liuwei1031 已提交
150 151
        out_t.Resize({static_cast<int64_t>(sequence_height) * context_length,
                      sequence_width});
C
sss  
chengduoZH 已提交
152 153 154 155 156 157 158 159

        if (up_pad > 0) {  // add up pad
          int padding_rows = std::min(
              up_pad, static_cast<int>(lod_level_0[i + 1] - lod_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 已提交
160 161
            Tensor out_t_sub = out_t.Slice(k * context_length,
                                           k * context_length + padding_size);
162
            Tensor w_sub = padding_data->Slice(k, k + padding_size);
Y
Yi Wang 已提交
163 164
            framework::TensorCopy(w_sub, context.GetPlace(), context,
                                  &out_t_sub);
C
sss  
chengduoZH 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
          }
        }
        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++;
            }
            if (padding_begin > 0 || sequence_height == context_start)
              padding_idx = padding_begin + t;
C
chengduoZH 已提交
188 189

            Tensor out_t_sub = out_t.Slice(
C
sss  
chengduoZH 已提交
190 191
                (down_pad_begin_row + t) * context_length - padding_size,
                (down_pad_begin_row + t) * context_length);
192
            Tensor w_sub = padding_data->Slice(
C
sss  
chengduoZH 已提交
193
                up_pad + padding_idx, up_pad + padding_idx + padding_size);
Y
Yi Wang 已提交
194 195
            framework::TensorCopy(w_sub, context.GetPlace(), context,
                                  &out_t_sub);
C
sss  
chengduoZH 已提交
196 197
          }
        }
L
liuwei1031 已提交
198 199
        out_t.Resize({sequence_height,
                      static_cast<int64_t>(context_length) * sequence_width});
C
sss  
chengduoZH 已提交
200 201 202 203 204
      }
    }
  }
};

Q
QI JUN 已提交
205
template <typename DeviceContext, typename T>
C
sss  
chengduoZH 已提交
206 207
class ContextProjectGradFunctor {
 public:
Q
QI JUN 已提交
208
  void operator()(const DeviceContext& context, const LoDTensor& in,
209 210 211 212
                  bool padding_trainable, const int context_start,
                  const int context_length, const int context_stride,
                  const int up_pad, const int down_pad, bool pad_grad,
                  bool input_grad, Tensor* padding_data, Tensor* col) {
C
sss  
chengduoZH 已提交
213 214
    auto lod_level_0 = in.lod()[0];

Q
QI JUN 已提交
215
    math::Col2ImFunctor<math::ColFormat::kOCF, DeviceContext, float> col2im_ocf;
C
chengduoZH 已提交
216

C
chengduoZH 已提交
217 218 219
    std::vector<int> dilation({1, 1});
    std::vector<int> padding({up_pad, 0, down_pad, 0});
    std::vector<int> stride({context_stride, 1});
C
chengduoZH 已提交
220

C
chengduoZH 已提交
221 222
    int input_row_begin, input_row_end;
    int sequence_height, sequence_width;
C
chengduoZH 已提交
223
    sequence_width = in.dims()[1];
Y
Yu Yang 已提交
224
    auto blas = math::GetBlas<DeviceContext, T>(context);
C
chengduoZH 已提交
225

C
sss  
chengduoZH 已提交
226
    if (input_grad) {
C
chengduoZH 已提交
227
      for (int i = 0; i < static_cast<int>(lod_level_0.size()) - 1; ++i) {
228 229
        if (lod_level_0[i] == lod_level_0[i + 1]) continue;

C
chengduoZH 已提交
230 231 232 233 234
        input_row_begin = (context_start > 0)
                              ? static_cast<int>(lod_level_0[i]) + context_start
                              : static_cast<int>(lod_level_0[i]);
        input_row_end = static_cast<int>(lod_level_0[i + 1]);

235 236
        Tensor out_t = col->Slice(static_cast<int>(lod_level_0[i]),
                                  static_cast<int>(lod_level_0[i + 1]));
C
chengduoZH 已提交
237 238 239 240

        sequence_height = static_cast<int>(out_t.dims()[0]);

        if (input_row_begin < input_row_end) {
C
chengduoZH 已提交
241
          Tensor in_t = in.Slice(input_row_begin, input_row_end);
C
chengduoZH 已提交
242 243 244 245 246 247 248 249 250 251 252 253

          std::vector<int64_t> output_shape(
              {sequence_height, 1, 1, context_length,
               sequence_width});  // output_height, output_width,
          // input_channels, filter_height, filter_width
          out_t.Resize(framework::make_ddim(output_shape));

          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 已提交
254
          col2im_ocf(context, out_t, dilation, stride, padding, &in_t);
C
chengduoZH 已提交
255
          out_t.Resize({sequence_height, context_length * sequence_width});
C
chengduoZH 已提交
256
        }
C
chengduoZH 已提交
257
      }
C
chengduoZH 已提交
258
    }
C
sss  
chengduoZH 已提交
259
    if (pad_grad) {
C
chengduoZH 已提交
260
      if (padding_trainable) {
C
chengduoZH 已提交
261
        for (int i = 0; i < static_cast<int>(lod_level_0.size()) - 1; ++i) {
262 263
          if (lod_level_0[i] == lod_level_0[i + 1]) continue;

264 265
          Tensor out_t = col->Slice(static_cast<int>(lod_level_0[i]),
                                    static_cast<int>(lod_level_0[i + 1]));
C
chengduoZH 已提交
266 267

          sequence_height = static_cast<int>(out_t.dims()[0]);
L
liuwei1031 已提交
268 269
          out_t.Resize({static_cast<int64_t>(sequence_height) * context_length,
                        sequence_width});
C
chengduoZH 已提交
270

C
sss  
chengduoZH 已提交
271
          if (up_pad > 0) {
C
chengduoZH 已提交
272 273 274 275 276 277
            int padding_rows = std::min(
                up_pad, static_cast<int>(lod_level_0[i + 1] - lod_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 已提交
278 279
              Tensor out_t_sub = out_t.Slice(k * context_length,
                                             k * context_length + padding_size);
280
              Tensor w_sub = padding_data->Slice(k, k + padding_size);
Y
Yu Yang 已提交
281 282
              blas.AXPY(w_sub.numel(), static_cast<T>(1), out_t_sub.data<T>(),
                        w_sub.data<T>());
C
chengduoZH 已提交
283
            }
C
chengduoZH 已提交
284
          }
C
sss  
chengduoZH 已提交
285
          if (down_pad > 0) {
C
chengduoZH 已提交
286 287 288 289 290 291 292 293 294
            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);
C
chengduoZH 已提交
295
            if (context_start >= sequence_height) padding_size = context_length;
C
chengduoZH 已提交
296 297 298 299 300 301 302 303 304 305 306
            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++;
              }
              if (padding_begin > 0 || sequence_height == context_start)
                padding_idx = padding_begin + t;
C
chengduoZH 已提交
307 308

              Tensor out_t_sub = out_t.Slice(
C
chengduoZH 已提交
309 310
                  (down_pad_begin_row + t) * context_length - padding_size,
                  (down_pad_begin_row + t) * context_length);
311
              Tensor w_sub = padding_data->Slice(
C
chengduoZH 已提交
312
                  up_pad + padding_idx, up_pad + padding_idx + padding_size);
Y
Yu Yang 已提交
313 314
              blas.AXPY(w_sub.numel(), static_cast<T>(1), out_t_sub.data<T>(),
                        w_sub.data<T>());
C
chengduoZH 已提交
315 316
            }
          }
L
liuwei1031 已提交
317 318
          out_t.Resize({sequence_height,
                        static_cast<int64_t>(context_length) * sequence_width});
C
chengduoZH 已提交
319 320 321 322 323 324 325 326 327
        }
      }
    }
  }
};

}  // namespace math
}  // namespace operators
}  // namespace paddle