shuffle_batch_op.h 5.3 KB
Newer Older
Z
zhoushiyu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright (c) 2019 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.

#pragma once

#include <atomic>
#include <cstring>
#include <ctime>
#include <random>
#include <string>
Y
yaoxuefeng 已提交
22
#include <utility>
Z
zhoushiyu 已提交
23
#include <vector>
24

Z
zhoushiyu 已提交
25 26 27 28 29 30
#include "glog/logging.h"
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/platform/timer.h"
H
Huang Jiyi 已提交
31
#include "paddle/phi/core/mixed_vector.h"
Z
zhoushiyu 已提交
32 33 34

namespace paddle {
namespace operators {
35

Z
zhoushiyu 已提交
36
template <typename T>
H
Huang Jiyi 已提交
37
using Vector = phi::Vector<T>;
Z
zhoushiyu 已提交
38

39
template <typename T, typename DeviceContext>
Z
zhoushiyu 已提交
40 41 42
class ShuffleBatchKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
43 44 45 46 47
    auto *x = context.Input<phi::DenseTensor>("X");
    auto *seed = context.Input<phi::DenseTensor>("Seed");
    auto *out = context.Output<phi::DenseTensor>("Out");
    auto *shuffleidx = context.Output<phi::DenseTensor>("ShuffleIdx");
    auto *seed_out = context.Output<phi::DenseTensor>("SeedOut");
Z
zhoushiyu 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

    auto x_embed_size = x->dims()[x->dims().size() - 1];
    auto elem_size = 1;
    for (auto i = 0; i < x->dims().size() - 1; i++) elem_size *= x->dims()[i];

    std::vector<int64_t> idx_vec;  // record shuffled order
    idx_vec.reserve(elem_size);
    for (auto i = 0; i < elem_size; i++) {
      idx_vec.push_back(i);
    }
    int64_t seed_int = 0;
    if (seed->IsInitialized()) {
      seed_int = *seed->data<int64_t>();
    } else {
      seed_int = context.Attr<int>("startup_seed");
    }
    std::default_random_engine engine;
    engine.seed(seed_int);
Y
yaoxuefeng 已提交
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

    auto custom_random_shuffle = [&idx_vec]() {
      std::random_device rnd;
      int64_t seed_tmp = rnd();
      std::default_random_engine rng(seed_tmp);
      const int n = idx_vec.size();
      std::vector<int> v(n);
      std::iota(v.begin(), v.end(), 0);
      std::vector<bool> visit(n, false);
      while (!v.empty()) {
        std::shuffle(v.begin(), v.end(), rng);
        int tmp = v.back();
        v.pop_back();
        if (v.empty()) {
          std::uniform_int_distribution<int> distr(0, n - 2);
          idx_vec[tmp] = tmp;
          std::swap(idx_vec[tmp], idx_vec[(distr(rng) + tmp + 1) % n]);
          return;
        }
        visit[tmp] = true;
        std::shuffle(v.begin(), v.end(), rng);
        int curr = v.back();
        v.pop_back();
        v.push_back(tmp);
        idx_vec[tmp] = curr;
        while (!visit[curr]) {
          visit[curr] = true;
          std::shuffle(v.begin(), v.end(), rng);
          idx_vec[curr] = v.back();
          v.pop_back();
          curr = idx_vec[curr];
        }
      }
    };
    custom_random_shuffle();
    // change shuffle to custom_random_shuffle
    // std::shuffle(idx_vec.begin(), idx_vec.end(), engine);
Z
zhoushiyu 已提交
103 104

    // ShuffleIdx record shuffle order
105
    shuffleidx->Resize(phi::make_ddim({(int64_t)idx_vec.size()}));
Z
zhoushiyu 已提交
106 107 108 109 110 111 112 113 114
    auto *shuffleidx_data =
        shuffleidx->mutable_data<int64_t>(context.GetPlace());
    for (size_t i = 0; i < idx_vec.size(); i++) {
      shuffleidx_data[i] = idx_vec[i];
    }
    // copy data according to idx_vec
    auto *x_data = x->data<T>();
    auto *out_data = out->mutable_data<T>(context.GetPlace());
    for (auto i = 0; i < elem_size; i++) {
115 116
      memcpy(out_data + idx_vec[i] * x_embed_size,
             x_data + i * x_embed_size,
Z
zhoushiyu 已提交
117 118 119
             x_embed_size * sizeof(T));
    }
    // set new seed
120
    *seed_out->mutable_data<int64_t>(phi::make_ddim({1}), context.GetPlace()) =
121
        engine();
Z
zhoushiyu 已提交
122 123 124
  }
};

125
template <typename T, typename DeviceContext>
Z
zhoushiyu 已提交
126 127 128
class ShuffleBatchGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
129 130 131 132 133
    auto *out_grad =
        context.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto *shuffleidx = context.Input<phi::DenseTensor>("ShuffleIdx");
    auto *x_grad =
        context.Output<phi::DenseTensor>(framework::GradVarName("X"));
Z
zhoushiyu 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

    auto embed_size = out_grad->dims()[out_grad->dims().size() - 1];
    auto elem_size = 1;
    for (auto i = 0; i < out_grad->dims().size() - 1; i++)
      elem_size *= out_grad->dims()[i];

    std::vector<int> idx_vec_grad(elem_size);
    auto *shuffleidx_data = shuffleidx->data<int64_t>();
    for (size_t i = 0; i < idx_vec_grad.size(); i++) {
      idx_vec_grad[shuffleidx_data[i]] = i;
    }

    // copy data according to idx_vec_grad
    auto *out_grad_data = out_grad->data<T>();
    auto *x_grad_data = x_grad->mutable_data<T>(context.GetPlace());
    for (auto i = 0; i < elem_size; i++) {
      memcpy(x_grad_data + idx_vec_grad[i] * embed_size,
151 152
             out_grad_data + i * embed_size,
             embed_size * sizeof(T));
Z
zhoushiyu 已提交
153 154 155 156 157
    }
  }
};
}  // namespace operators
}  // namespace paddle