split_ids_op.h 4.6 KB
Newer Older
Q
Qiao Longfei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 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

S
seiriosPlus 已提交
17 18
#include <iterator>
#include <set>
Q
qiaolongfei 已提交
19
#include <unordered_map>
Q
Qiao Longfei 已提交
20 21 22 23 24 25 26 27 28 29
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
class SplitIdsOpKernel : public framework::OpKernel<T> {
 public:
30
  void Compute(const framework::ExecutionContext &ctx) const override {
Q
Qiao Longfei 已提交
31 32
    auto place = ctx.GetPlace();
    if (!platform::is_cpu_place(place)) {
S
seiriosPlus 已提交
33 34
      PADDLE_THROW(platform::errors::Unimplemented(
          "SplitIds do not support GPU kernel"));
Q
Qiao Longfei 已提交
35 36
    }

S
seiriosPlus 已提交
37 38
    const auto ids_vars = ctx.MultiInputVar("Ids");

S
seiriosPlus 已提交
39 40 41
    PADDLE_ENFORCE_GT(platform::errors::InvalidArgument(
        ids_vars.size(), 0, "The number of Ids expected > 0, but got %d",
        ids_vars.size()));
S
seiriosPlus 已提交
42 43
    auto *ids_var = ids_vars[0];

44
    if (ids_var->IsType<framework::LoDTensor>()) {
S
seiriosPlus 已提交
45 46 47 48 49
      int batch_size = 0;
      const auto ids_tensors = ctx.MultiInput<framework::LoDTensor>("Ids");
      for (size_t i = 0; i < ids_tensors.size(); ++i) {
        batch_size += ids_tensors[i]->dims()[0];
      }
M
minqiyang 已提交
50
      VLOG(4) << "Get Total BatchSize is: " << batch_size;
S
seiriosPlus 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63

      std::vector<T> all_ids(batch_size);
      int offset = 0;
      for (size_t i = 0; i < ids_tensors.size(); ++i) {
        const auto *ids = ids_tensors[i];
        std::memcpy(all_ids.data() + offset, ids->data<T>(),
                    ids->numel() * sizeof(T));
        offset += ids->numel();
      }

      std::set<T> st(all_ids.begin(), all_ids.end());
      all_ids.assign(st.begin(), st.end());

64 65 66 67
      auto outs = ctx.MultiOutput<framework::LoDTensor>("Out");
      const size_t shard_num = outs.size();
      std::vector<std::vector<T>> out_ids;
      out_ids.resize(outs.size());
Q
Qiao Longfei 已提交
68

69
      // split id by their shard_num.
T
Tao Luo 已提交
70
      for (size_t i = 0; i < all_ids.size(); ++i) {
S
seiriosPlus 已提交
71
        T id = all_ids[i];
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        size_t shard_id = static_cast<size_t>(id) % shard_num;
        out_ids[shard_id].push_back(id);
      }

      // create tensor for each shard and send to parameter server
      for (size_t i = 0; i < out_ids.size(); ++i) {
        auto *shard_t = outs[i];
        std::vector<T> ids = out_ids[i];
        auto *shard_data = shard_t->mutable_data<T>(
            framework::make_ddim({static_cast<int64_t>(ids.size()), 1}), place);
        for (size_t i = 0; i < ids.size(); ++i) {
          shard_data[i] = ids[i];
        }
      }
    } else if (ids_var->IsType<framework::SelectedRows>()) {
      const auto *ids_selected_rows = ctx.Input<framework::SelectedRows>("Ids");
      auto &ids_dims = ids_selected_rows->value().dims();
S
seiriosPlus 已提交
89
      const T *ids_data = ids_selected_rows->value().data<T>();
90 91 92
      const auto &ids_rows = ids_selected_rows->rows();
      auto outs = ctx.MultiOutput<framework::SelectedRows>("Out");
      const size_t shard_num = outs.size();
93 94 95
      for (auto &out : outs) {
        out->mutable_rows()->clear();
      }
96
      // get rows for outputs
Q
qiaolongfei 已提交
97
      std::unordered_map<int64_t, size_t> id_to_index;
Q
qiaolongfei 已提交
98 99 100 101
      for (size_t i = 0; i < ids_rows.size(); ++i) {
        id_to_index[ids_rows[i]] = i;
        size_t shard_id = static_cast<size_t>(ids_rows[i]) % shard_num;
        outs[shard_id]->mutable_rows()->push_back(ids_rows[i]);
102
      }
Q
Qiao Longfei 已提交
103

104 105 106 107 108 109
      int64_t row_width = ids_dims[1];
      for (auto &out : outs) {
        out->set_height(ids_selected_rows->height());
        framework::DDim ddim = framework::make_ddim(
            {static_cast<int64_t>(out->rows().size()), row_width});
        T *output = out->mutable_value()->mutable_data<T>(ddim, place);
A
Abhinav Arora 已提交
110
        for (int64_t i = 0; i < ddim[0]; ++i) {
Q
qiaolongfei 已提交
111
          memcpy(output + i * row_width,
S
seiriosPlus 已提交
112
                 ids_data + id_to_index[out->rows()[i]] * row_width,
113 114
                 row_width * sizeof(T));
        }
Q
Qiao Longfei 已提交
115
      }
C
chengduo 已提交
116
    } else {
S
seiriosPlus 已提交
117
      PADDLE_THROW(platform::errors::InvalidArgument(
C
chengduo 已提交
118
          "% should be LoDTensor or SelectedRows, but the received type is %s",
S
seiriosPlus 已提交
119
          ctx.InputNames("Ids")[0], framework::ToTypeName(ids_var->Type())));
Q
Qiao Longfei 已提交
120 121 122 123 124 125
    }
  }
};

}  // namespace operators
}  // namespace paddle