functions.cc 15.4 KB
Newer Older
liangjing's avatar
liangjing committed
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Copyright (c) 2022 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.

#include <cstdint>
#include <vector>
#include "glog/logging.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"

namespace py = pybind11;
namespace framework = paddle::framework;
namespace platform = paddle::platform;

PYBIND11_MAKE_OPAQUE(framework::LoDTensorArray);

constexpr int kInputIdsIdx = 0;
constexpr int kSegmentIdsIdx = 1;
constexpr int kInputMaskIdx = 2;
constexpr int kMaskedLmLabelsIdx = 3;
constexpr int kNextSentenceLabelsIdx = 4;
constexpr int kSeqLenIdx = 5;
constexpr int kPrefixSumSeqLenIdx = 6;
constexpr int kNonZerosIndicesIdx = 7;
constexpr int kMaskedLmIdsIdx = 8;
constexpr int kMaskedLmPositionIdx = 9;
constexpr int kNumValidIdx = 10;

constexpr int kNumTensors = 11;

template <typename T>
std::vector<std::vector<framework::LoDTensorArray>>
ProcessAllGatheredBERTInputs(
    const py::array_t<T, py::array::c_style | py::array::forcecast> &array,
    size_t num_samples,
    size_t max_seq_length,
    size_t batch_size,
    size_t trainer_id,
    size_t num_trainers) {
  using TensorT = framework::LoDTensor;

  PADDLE_ENFORCE_EQ(array.ndim(), 1);
  size_t length = array.shape()[0];
  const T *arr = array.data();

  py::gil_scoped_release gil_release_guard;

  const size_t nbatch = (num_samples + batch_size - 1) / batch_size;
  std::unique_ptr<T[]> seq_indices(new T[batch_size * num_trainers]);

  const size_t numel = num_samples * max_seq_length;
  const size_t num_per_device = numel * 4 + num_samples * 2;
  PADDLE_ENFORCE_EQ(num_per_device * num_trainers, length);

  auto resize_and_alloc = [](TensorT *t, const framework::DDim &dim) -> T * {
    t->Resize(dim);
    return t->mutable_data<T>(platform::CPUPlace());
  };

  auto resize_and_alloc_int = [](TensorT *t,
                                 const framework::DDim &dim) -> int * {
    t->Resize(dim);
    return t->mutable_data<int>(platform::CPUPlace());
  };
  auto resize_and_alloc_float32 = [](TensorT *t,
                                     const framework::DDim &dim) -> float * {
    t->Resize(dim);
    return t->mutable_data<float>(platform::CPUPlace());
  };

  VLOG(10) << "num_samples = " << num_samples;
  VLOG(10) << "max_seq_length = " << max_seq_length;
  VLOG(10) << "batch_size = " << batch_size;
  VLOG(10) << "trainer_id = " << trainer_id;
  VLOG(10) << "num_trainers = " << num_trainers;
  VLOG(10) << "nbatch = " << nbatch;
  VLOG(10) << "length= " << length;

  std::vector<std::vector<framework::LoDTensorArray>> gpu_cpu_tensors;
  std::vector<framework::LoDTensorArray> tensors(nbatch);
  std::vector<framework::LoDTensorArray> tensors_2(nbatch);
  for (size_t i = 0; i < nbatch; ++i) {
    const size_t cur_bs =
        std::min((i + 1) * batch_size, num_samples) - i * batch_size;
    VLOG(10) << "Mini batch " << i << " " << cur_bs;
    const size_t seq_length_offset =
        num_samples * max_seq_length * 4 + num_samples + i * batch_size;
    const size_t total_seq_length = cur_bs * num_trainers;

    std::iota(seq_indices.get(),
              seq_indices.get() + total_seq_length,
              static_cast<size_t>(0));

    std::sort(seq_indices.get(),
              seq_indices.get() + total_seq_length,
              [&](size_t idx1, size_t idx2) {
                size_t real_idx1 = (idx1 % num_trainers) * num_per_device +
                                   (idx1 / num_trainers) + seq_length_offset;
                size_t real_idx2 = (idx2 % num_trainers) * num_per_device +
                                   (idx2 / num_trainers) + seq_length_offset;
                return arr[real_idx1] > arr[real_idx2];
              });
    tensors[i].resize(kNumTensors);
    tensors_2[i].resize(1);
    auto *input_ids = resize_and_alloc(
        &tensors[i][kInputIdsIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *segment_ids = resize_and_alloc(
        &tensors[i][kSegmentIdsIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *input_mask = resize_and_alloc(
        &tensors[i][kInputMaskIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *masked_lm_labels = resize_and_alloc(
        &tensors[i][kMaskedLmLabelsIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *next_sentence_labels = resize_and_alloc(
        &tensors[i][kNextSentenceLabelsIdx], {static_cast<int64_t>(cur_bs)});

    auto *seq_len = resize_and_alloc_int(&tensors[i][kSeqLenIdx],
                                         {static_cast<int64_t>(cur_bs)});
    auto *prefix_sum_seq_len = resize_and_alloc_int(
        &tensors[i][kPrefixSumSeqLenIdx], {static_cast<int64_t>(cur_bs + 1)});

    auto *num_valid = resize_and_alloc_float32(&tensors[i][kNumValidIdx],
                                               {static_cast<int64_t>(1)});

    // cpu tensor
    auto *host_prefix_sum_seq_len = resize_and_alloc_int(
        &tensors_2[i][0], {static_cast<int64_t>(cur_bs + 1)});

    prefix_sum_seq_len[0] = 0;
    int sum_seq_len = 0;
    for (size_t j = 0; j < cur_bs; ++j) {
      const size_t idx = seq_indices.get()[j * num_trainers + trainer_id];
      const size_t dev_id = idx % num_trainers;
      const T *data = arr + dev_id * num_per_device;
      const size_t sample_id = idx / num_trainers + i * batch_size;
      std::memcpy(input_ids + j * max_seq_length,
                  data + sample_id * max_seq_length,
                  max_seq_length * sizeof(T));
      std::memcpy(segment_ids + j * max_seq_length,
                  data + numel + sample_id * max_seq_length,
                  max_seq_length * sizeof(T));
      std::memcpy(input_mask + j * max_seq_length,
                  data + 2 * numel + sample_id * max_seq_length,
                  max_seq_length * sizeof(T));
      std::memcpy(masked_lm_labels + j * max_seq_length,
                  data + 3 * numel + sample_id * max_seq_length,
                  max_seq_length * sizeof(T));
      next_sentence_labels[j] = data[4 * numel + sample_id];

      seq_len[j] = data[4 * numel + num_samples + sample_id];
      sum_seq_len += seq_len[j];
      if (j > 0) {
        prefix_sum_seq_len[j] = prefix_sum_seq_len[j - 1] + seq_len[j - 1];
      }
    }
    prefix_sum_seq_len[cur_bs] =
        prefix_sum_seq_len[cur_bs - 1] + seq_len[cur_bs - 1];

    std::memcpy(host_prefix_sum_seq_len,
                prefix_sum_seq_len,
                sizeof(int) * (cur_bs + 1));

    PADDLE_ENFORCE_LE(sum_seq_len, cur_bs * max_seq_length);

    auto *nonzeros_indices = resize_and_alloc_int(
        &tensors[i][kNonZerosIndicesIdx], {static_cast<int64_t>(sum_seq_len)});
    int cur_nonzero_ind = 0;
    int cur_num_valid = 0;
    for (size_t j = 0; j < cur_bs; ++j) {
      for (size_t k = 0; k < max_seq_length; ++k) {
        int ids = j * max_seq_length + k;
        if (input_mask[ids] != 0) {
          nonzeros_indices[cur_nonzero_ind++] = static_cast<int>(ids);
        }
        if (masked_lm_labels[ids] != 0) {
          cur_num_valid += 1;
        }
      }
    }
    PADDLE_ENFORCE_EQ(cur_nonzero_ind, sum_seq_len);

    *num_valid = static_cast<float>(cur_num_valid);
    auto *masked_lm_ids = resize_and_alloc_int(
        &tensors[i][kMaskedLmIdsIdx], {static_cast<int64_t>(cur_num_valid)});
    auto *masked_lm_positions =
        resize_and_alloc_int(&tensors[i][kMaskedLmPositionIdx],
                             {static_cast<int64_t>(cur_num_valid)});

    cur_num_valid = 0;
    for (size_t j = 0; j < cur_bs; ++j) {
      for (size_t k = 0; k < max_seq_length; ++k) {
        int ids = j * max_seq_length + k;
        if (masked_lm_labels[ids] != 0) {
          masked_lm_positions[cur_num_valid] = ids;
          masked_lm_ids[cur_num_valid] = masked_lm_labels[ids];
          cur_num_valid += 1;
        }
      }
    }
  }
  gpu_cpu_tensors.push_back(tensors);
  gpu_cpu_tensors.push_back(tensors_2);
  return gpu_cpu_tensors;
}

template <typename T>
std::vector<std::vector<framework::LoDTensorArray>> ProcessBERTEvalInputs(
    const py::array_t<T, py::array::c_style | py::array::forcecast> &array,
    size_t max_seq_length,
    size_t batch_size,
    bool need_sort) {
  using TensorT = framework::LoDTensor;

  PADDLE_ENFORCE_EQ(array.ndim(), 2);
  size_t num_samples = array.shape()[0];
  size_t one_sample_len = array.shape()[1];
  const T *arr = array.data();

  py::gil_scoped_release gil_release_guard;

  std::unique_ptr<size_t[]> seq_indices;
  if (need_sort) {
    seq_indices.reset(new size_t[num_samples]);
    std::iota(seq_indices.get(),
              seq_indices.get() + num_samples,
              static_cast<size_t>(0));
    std::sort(seq_indices.get(),
              seq_indices.get() + num_samples,
              [arr, one_sample_len](size_t idx1, size_t idx2) {
                idx1 = (idx1 + 1) * one_sample_len - 1;
                idx2 = (idx2 + 1) * one_sample_len - 1;
                return arr[idx1] < arr[idx2];
              });
  }

  const size_t nbatch = (num_samples + batch_size - 1) / batch_size;

  auto resize_and_alloc = [](TensorT *t, const framework::DDim &dim) -> T * {
    t->Resize(dim);
    return t->mutable_data<T>(platform::CPUPlace());
  };
  auto resize_and_alloc_int = [](TensorT *t,
                                 const framework::DDim &dim) -> int * {
    t->Resize(dim);
    return t->mutable_data<int>(platform::CPUPlace());
  };
  auto resize_and_alloc_float32 = [](TensorT *t,
                                     const framework::DDim &dim) -> float * {
    t->Resize(dim);
    return t->mutable_data<float>(platform::CPUPlace());
  };

  VLOG(10) << "one_sample_len = " << one_sample_len;
  VLOG(10) << "num_samples = " << num_samples;
  VLOG(10) << "max_seq_length = " << max_seq_length;
  VLOG(10) << "batch_size = " << batch_size;
  VLOG(10) << "nbatch = " << nbatch;

  std::vector<std::vector<framework::LoDTensorArray>> gpu_cpu_tensors;
  std::vector<framework::LoDTensorArray> tensors(nbatch);
  std::vector<framework::LoDTensorArray> tensors_2(nbatch);
  for (size_t i = 0; i < nbatch; ++i) {
    const size_t cur_bs =
        std::min((i + 1) * batch_size, num_samples) - i * batch_size;
    VLOG(10) << "Mini batch " << i << " " << cur_bs;

    tensors[i].resize(kNumTensors);
    tensors_2[i].resize(1);
    auto *input_ids = resize_and_alloc(
        &tensors[i][kInputIdsIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *segment_ids = resize_and_alloc(
        &tensors[i][kSegmentIdsIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *input_mask = resize_and_alloc(
        &tensors[i][kInputMaskIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *masked_lm_labels = resize_and_alloc(
        &tensors[i][kMaskedLmLabelsIdx],
        {static_cast<int64_t>(cur_bs), static_cast<int64_t>(max_seq_length)});
    auto *next_sentence_labels = resize_and_alloc(
        &tensors[i][kNextSentenceLabelsIdx], {static_cast<int64_t>(cur_bs)});

    auto *seq_len = resize_and_alloc_int(&tensors[i][kSeqLenIdx],
                                         {static_cast<int64_t>(cur_bs)});
    auto *prefix_sum_seq_len = resize_and_alloc_int(
        &tensors[i][kPrefixSumSeqLenIdx], {static_cast<int64_t>(cur_bs + 1)});
    auto *num_valid = resize_and_alloc_float32(&tensors[i][kNumValidIdx],
                                               {static_cast<int64_t>(1)});

    // cpu tensor
    auto *host_prefix_sum_seq_len = resize_and_alloc_int(
        &tensors_2[i][0], {static_cast<int64_t>(cur_bs + 1)});

    prefix_sum_seq_len[0] = 0;
    int sum_seq_len = 0;
    for (size_t j = 0; j < cur_bs; ++j) {
      const T *data = arr;
      size_t sample_id = j + i * batch_size;
      if (need_sort) sample_id = seq_indices.get()[sample_id];
      std::memcpy(input_ids + j * max_seq_length,
                  data + sample_id * one_sample_len,
                  max_seq_length * sizeof(T));
      std::memcpy(segment_ids + j * max_seq_length,
                  data + sample_id * one_sample_len + max_seq_length,
                  max_seq_length * sizeof(T));
      std::memcpy(input_mask + j * max_seq_length,
                  data + sample_id * one_sample_len + 2 * max_seq_length,
                  max_seq_length * sizeof(T));
      std::memcpy(masked_lm_labels + j * max_seq_length,
                  data + sample_id * one_sample_len + 3 * max_seq_length,
                  max_seq_length * sizeof(T));
      next_sentence_labels[j] =
          data[sample_id * one_sample_len + 4 * max_seq_length];

      seq_len[j] = data[sample_id * one_sample_len + 4 * max_seq_length + 1];
      sum_seq_len += seq_len[j];
      if (j > 0) {
        prefix_sum_seq_len[j] = prefix_sum_seq_len[j - 1] + seq_len[j - 1];
      }
    }
    prefix_sum_seq_len[cur_bs] =
        prefix_sum_seq_len[cur_bs - 1] + seq_len[cur_bs - 1];

    std::memcpy(host_prefix_sum_seq_len,
                prefix_sum_seq_len,
                sizeof(int) * (cur_bs + 1));

    PADDLE_ENFORCE_LE(sum_seq_len, cur_bs * max_seq_length);

    auto *nonzeros_indices = resize_and_alloc_int(
        &tensors[i][kNonZerosIndicesIdx], {static_cast<int64_t>(sum_seq_len)});
    int cur_nonzero_ind = 0;
    int cur_num_valid = 0;
    for (size_t j = 0; j < cur_bs; ++j) {
      for (size_t k = 0; k < max_seq_length; ++k) {
        int ids = j * max_seq_length + k;
        if (input_mask[ids] != 0) {
          nonzeros_indices[cur_nonzero_ind++] = static_cast<int>(ids);
        }
        if (masked_lm_labels[ids] != 0) {
          cur_num_valid += 1;
        }
      }
    }
    PADDLE_ENFORCE_EQ(cur_nonzero_ind, sum_seq_len);

    *num_valid = cur_num_valid;
    auto *masked_lm_ids = resize_and_alloc_int(
        &tensors[i][kMaskedLmIdsIdx], {static_cast<int64_t>(cur_num_valid)});
    auto *masked_lm_positions =
        resize_and_alloc_int(&tensors[i][kMaskedLmPositionIdx],
                             {static_cast<int64_t>(cur_num_valid)});

    cur_num_valid = 0;
    for (size_t j = 0; j < cur_bs; ++j) {
      for (size_t k = 0; k < max_seq_length; ++k) {
        int ids = j * max_seq_length + k;
        if (masked_lm_labels[ids] != 0) {
          masked_lm_positions[cur_num_valid] = ids;
          masked_lm_ids[cur_num_valid] = masked_lm_labels[ids];
          cur_num_valid += 1;
        }
      }
    }
  }
  gpu_cpu_tensors.push_back(tensors);
  gpu_cpu_tensors.push_back(tensors_2);
  return gpu_cpu_tensors;
}

PYBIND11_MODULE(MLPERF_EXTENSION_NAME, m) {
  m.def("process_allgathered_inputs", &ProcessAllGatheredBERTInputs<int16_t>);
  m.def("process_allgathered_inputs", &ProcessAllGatheredBERTInputs<int32_t>);
  m.def("process_allgathered_inputs", &ProcessAllGatheredBERTInputs<int64_t>);
  m.def("process_eval_inputs", &ProcessBERTEvalInputs<int16_t>);
  m.def("process_eval_inputs", &ProcessBERTEvalInputs<int32_t>);
  m.def("process_eval_inputs", &ProcessBERTEvalInputs<int64_t>);
}