sequence_padding.cc 10.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yiqun Liu 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/math/sequence_padding.h"
16

0
0x45f 已提交
17
#include "paddle/phi/backends/cpu/cpu_context.h"
Y
Yiqun Liu 已提交
18

19
namespace phi {
20
class DenseTensor;
21
}  // namespace phi
22

W
wanghuancoder 已提交
23
namespace paddle {
24
namespace framework {}  // namespace framework
W
wanghuancoder 已提交
25 26 27 28 29
namespace platform {
class CPUDeviceContext;
}  // namespace platform
}  // namespace paddle

Y
Yiqun Liu 已提交
30 31 32 33
namespace paddle {
namespace operators {
namespace math {

Y
yangyaming 已提交
34
template <typename T>
F
fengjiayi 已提交
35 36 37 38
void CopyValidData(framework::Tensor* dst_tensor,
                   const framework::Tensor* src_tensor,
                   const framework::Vector<size_t>& seq_offsets,
                   int pad_seq_len, int step_width, bool norm_by_len,
H
Hui Zhang 已提交
39
                   CopyType type, PadLayout layout) {
F
fengjiayi 已提交
40 41 42 43 44 45 46 47 48 49 50
  int seq_num = seq_offsets.size() - 1;
  const T* src_data = src_tensor->data<T>();
  T* dst_data = dst_tensor->data<T>();

  int seq_cpy_gap = step_width;
  int pad_cpy_gap =
      layout == kBatchLengthWidth ? step_width : seq_num * step_width;
  for (int seq_idx = 0; seq_idx < seq_num; ++seq_idx) {
    int valid_seq_len = seq_offsets[seq_idx + 1] - seq_offsets[seq_idx];
    PADDLE_ENFORCE_GE(
        pad_seq_len, valid_seq_len,
51 52 53 54 55
        platform::errors::InvalidArgument(
            "The padded sequence length can not "
            "be less than its original length. Expected %ld >= %ld, but got "
            "%ld < %ld. Please check input value.",
            pad_seq_len, valid_seq_len, pad_seq_len, valid_seq_len));
F
fengjiayi 已提交
56 57 58 59
    int seq_data_offset = seq_offsets[seq_idx] * step_width;
    int pad_data_offset = layout == kBatchLengthWidth
                              ? seq_idx * pad_seq_len * step_width
                              : seq_idx * step_width;
H
Hui Zhang 已提交
60
    float scale = 1.0f / static_cast<float>(valid_seq_len);
F
fengjiayi 已提交
61 62 63 64 65 66 67 68 69 70

    for (int step_idx = 0; step_idx < valid_seq_len; ++step_idx) {
      const T* src =
          src_data + (type == kSeqToPad ? seq_data_offset : pad_data_offset);
      T* dst =
          dst_data + (type == kSeqToPad ? pad_data_offset : seq_data_offset);
      memcpy(dst, src, step_width * sizeof(T));
      if (norm_by_len) {
        for (int i = 0; i < step_width; ++i) {
          *(dst + i) *= scale;
Y
Yiqun Liu 已提交
71 72
        }
      }
F
fengjiayi 已提交
73 74
      seq_data_offset += seq_cpy_gap;
      pad_data_offset += pad_cpy_gap;
Y
Yiqun Liu 已提交
75 76
    }
  }
77 78
}

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
template <typename T>
static void fast_mem_init(void* dest, size_t dest_size, const T* src,
                          size_t num_bytes) {
  if (dest == nullptr || dest_size == 0 || src == nullptr) return;

  memcpy(dest, src, num_bytes);

  dest_size *= num_bytes;
  while (dest_size > num_bytes) {
    size_t remaining = dest_size - num_bytes;
    size_t count = (remaining > num_bytes) ? num_bytes : remaining;
    memcpy((unsigned char*)dest + num_bytes, dest, count);
    num_bytes += count;
  }
}

Y
yangyaming 已提交
95 96
template <typename T>
class PaddingLoDTensorFunctor<platform::CPUDeviceContext, T> {
97 98 99
 public:
  void operator()(const platform::CPUDeviceContext& context,
                  const framework::LoDTensor& seq_tensor,
F
fengjiayi 已提交
100
                  framework::LoDTensor* pad_tensor,
F
fengjiayi 已提交
101
                  const framework::LoDTensor& pad_value, int pad_seq_len = -1,
F
fengjiayi 已提交
102 103
                  int lod_level = 0, bool norm_by_times = false,
                  const PadLayout layout = kBatchLengthWidth) {
104 105 106 107
    auto seq_lod = seq_tensor.lod();
    const auto seq_offsets = framework::ToAbsOffset(seq_lod)[lod_level];
    const auto& seq_tensor_dims = seq_tensor.dims();
    const auto& pad_tensor_dims = pad_tensor->dims();
F
fengjiayi 已提交
108 109 110 111
    if (pad_seq_len == -1) {
      pad_seq_len = MaximumSequenceLength(seq_offsets);
    }
    int step_width = seq_tensor.numel() / seq_tensor_dims[0];
112

F
fengjiayi 已提交
113 114
    CheckDims(seq_tensor_dims, pad_tensor_dims, seq_offsets, pad_seq_len,
              step_width, layout);
115 116 117 118 119 120 121 122

    PADDLE_ENFORCE_EQ(
        pad_value.numel() == 1 || pad_value.numel() == step_width, true,
        platform::errors::InvalidArgument(
            "The numel of 'pad_value' can only be 1 or be equal to the "
            "'step_width', but got %ld != 1 and %ld. Please check the input "
            "value.",
            pad_value.numel(), step_width));
123

F
fengjiayi 已提交
124 125
    // fill padding value
    T* pad_data = pad_tensor->data<T>();
F
fengjiayi 已提交
126 127
    const T* pad_value_data = pad_value.data<T>();
    if (pad_value.numel() == 1) {
128 129
      fast_mem_init<T>(pad_data, pad_tensor->numel(), pad_value_data,
                       sizeof(T));
F
fengjiayi 已提交
130 131 132 133
    } else {
      for (int i = 0; i < pad_tensor->numel(); i += step_width) {
        memcpy(pad_data + i, pad_value_data, step_width * sizeof(T));
      }
F
fengjiayi 已提交
134
    }
135

F
fengjiayi 已提交
136
    CopyValidData<T>(pad_tensor, &seq_tensor, seq_offsets, pad_seq_len,
H
Hui Zhang 已提交
137
                     step_width, norm_by_times, kSeqToPad, layout);
138
  }
Y
Yiqun Liu 已提交
139 140
};

0
0x45f 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
template <typename T>
class PaddingLoDTensorFunctor<phi::CPUContext, T> {
 public:
  void operator()(const phi::CPUContext& context,
                  const framework::LoDTensor& seq_tensor,
                  framework::LoDTensor* pad_tensor,
                  const framework::LoDTensor& pad_value, int pad_seq_len = -1,
                  int lod_level = 0, bool norm_by_times = false,
                  const PadLayout layout = kBatchLengthWidth) {
    auto seq_lod = seq_tensor.lod();
    const auto seq_offsets = framework::ToAbsOffset(seq_lod)[lod_level];
    const auto& seq_tensor_dims = seq_tensor.dims();
    const auto& pad_tensor_dims = pad_tensor->dims();
    if (pad_seq_len == -1) {
      pad_seq_len = MaximumSequenceLength(seq_offsets);
    }
    int step_width = seq_tensor.numel() / seq_tensor_dims[0];

    CheckDims(seq_tensor_dims, pad_tensor_dims, seq_offsets, pad_seq_len,
              step_width, layout);

    PADDLE_ENFORCE_EQ(
        pad_value.numel() == 1 || pad_value.numel() == step_width, true,
        platform::errors::InvalidArgument(
            "The numel of 'pad_value' can only be 1 or be equal to the "
            "'step_width', but got %ld != 1 and %ld. Please check the input "
            "value.",
            pad_value.numel(), step_width));

    // fill padding value
    T* pad_data = pad_tensor->data<T>();
    const T* pad_value_data = pad_value.data<T>();
    if (pad_value.numel() == 1) {
      fast_mem_init<T>(pad_data, pad_tensor->numel(), pad_value_data,
                       sizeof(T));
    } else {
      for (int i = 0; i < pad_tensor->numel(); i += step_width) {
        memcpy(pad_data + i, pad_value_data, step_width * sizeof(T));
      }
    }

    CopyValidData<T>(pad_tensor, &seq_tensor, seq_offsets, pad_seq_len,
                     step_width, norm_by_times, kSeqToPad, layout);
  }
};

Y
yangyaming 已提交
187 188
template <typename T>
class UnpaddingLoDTensorFunctor<platform::CPUDeviceContext, T> {
Y
Yiqun Liu 已提交
189 190
 public:
  void operator()(const platform::CPUDeviceContext& context,
F
fengjiayi 已提交
191 192 193
                  const framework::LoDTensor& pad_tensor,
                  framework::LoDTensor* seq_tensor, int pad_seq_len = -1,
                  int lod_level = 0, bool norm_by_times = false,
F
fengjiayi 已提交
194
                  const PadLayout layout = kBatchLengthWidth) {
F
fengjiayi 已提交
195
    auto seq_offsets = framework::ToAbsOffset(seq_tensor->lod())[lod_level];
196 197
    const auto& seq_tensor_dims = seq_tensor->dims();
    const auto& pad_tensor_dims = pad_tensor.dims();
F
fengjiayi 已提交
198 199 200 201 202 203 204 205 206
    if (pad_seq_len == -1) {
      pad_seq_len = MaximumSequenceLength(seq_offsets);
    }
    int step_width = seq_tensor->numel() / seq_tensor_dims[0];

    CheckDims(seq_tensor_dims, pad_tensor_dims, seq_offsets, pad_seq_len,
              step_width, layout);

    CopyValidData<T>(seq_tensor, &pad_tensor, seq_offsets, pad_seq_len,
H
Hui Zhang 已提交
207
                     step_width, norm_by_times, kPadToSeq, layout);
Y
Yiqun Liu 已提交
208 209 210
  }
};

0
0x45f 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
template <typename T>
class UnpaddingLoDTensorFunctor<phi::CPUContext, T> {
 public:
  void operator()(const phi::CPUContext& context,
                  const framework::LoDTensor& pad_tensor,
                  framework::LoDTensor* seq_tensor, int pad_seq_len = -1,
                  int lod_level = 0, bool norm_by_times = false,
                  const PadLayout layout = kBatchLengthWidth) {
    auto seq_offsets = framework::ToAbsOffset(seq_tensor->lod())[lod_level];
    const auto& seq_tensor_dims = seq_tensor->dims();
    const auto& pad_tensor_dims = pad_tensor.dims();
    if (pad_seq_len == -1) {
      pad_seq_len = MaximumSequenceLength(seq_offsets);
    }
    int step_width = seq_tensor->numel() / seq_tensor_dims[0];

    CheckDims(seq_tensor_dims, pad_tensor_dims, seq_offsets, pad_seq_len,
              step_width, layout);

    CopyValidData<T>(seq_tensor, &pad_tensor, seq_offsets, pad_seq_len,
                     step_width, norm_by_times, kPadToSeq, layout);
  }
};

Y
yangyaming 已提交
235 236 237 238 239 240 241 242 243
template class PaddingLoDTensorFunctor<platform::CPUDeviceContext, int>;
template class PaddingLoDTensorFunctor<platform::CPUDeviceContext, int64_t>;
template class PaddingLoDTensorFunctor<platform::CPUDeviceContext, float>;
template class PaddingLoDTensorFunctor<platform::CPUDeviceContext, double>;

template class UnpaddingLoDTensorFunctor<platform::CPUDeviceContext, int>;
template class UnpaddingLoDTensorFunctor<platform::CPUDeviceContext, int64_t>;
template class UnpaddingLoDTensorFunctor<platform::CPUDeviceContext, float>;
template class UnpaddingLoDTensorFunctor<platform::CPUDeviceContext, double>;
Y
Yiqun Liu 已提交
244

0
0x45f 已提交
245 246 247 248 249 250 251 252 253 254
template class PaddingLoDTensorFunctor<phi::CPUContext, int>;
template class PaddingLoDTensorFunctor<phi::CPUContext, int64_t>;
template class PaddingLoDTensorFunctor<phi::CPUContext, float>;
template class PaddingLoDTensorFunctor<phi::CPUContext, double>;

template class UnpaddingLoDTensorFunctor<phi::CPUContext, int>;
template class UnpaddingLoDTensorFunctor<phi::CPUContext, int64_t>;
template class UnpaddingLoDTensorFunctor<phi::CPUContext, float>;
template class UnpaddingLoDTensorFunctor<phi::CPUContext, double>;

Y
Yiqun Liu 已提交
255 256 257
}  // namespace math
}  // namespace operators
}  // namespace paddle