reorder_lod_tensor_by_rank_op.cc 9.2 KB
Newer Older
L
Luo Tao 已提交
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Y
Yang Yu 已提交
2

L
Luo Tao 已提交
3 4 5
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
Y
Yang Yu 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yang Yu 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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
Yang Yu 已提交
14

D
dzhwinter 已提交
15
#include "paddle/framework/lod_rank_table.h"
Y
Yang Yu 已提交
16 17
#include "paddle/framework/op_registry.h"
#include "paddle/operators/detail/safe_ref.h"
D
dzhwinter 已提交
18
#include "paddle/platform/device_context.h"
Y
Yang Yu 已提交
19 20 21 22

namespace paddle {
namespace operators {

Y
Yang Yu 已提交
23 24
class ReorderLoDTensorByRankTableOpProtoMaker
    : public framework::OpProtoAndCheckerMaker {
Y
Yang Yu 已提交
25
 public:
Y
Yang Yu 已提交
26 27
  ReorderLoDTensorByRankTableOpProtoMaker(OpProto *proto,
                                          OpAttrChecker *op_checker)
Y
Yang Yu 已提交
28 29 30 31 32
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "(LoDTensor) the input lod tensor need to be reordered.");
    AddInput("RankTable",
             "(LoDRankTable) the rank table that input need follow");
    AddOutput("Out", "(LoDTensor) reordered lod tensor");
Y
Yang Yu 已提交
33
    AddComment(R"DOC(ReorderLoDTensorByRankTable
Y
Yang Yu 已提交
34 35 36 37 38 39

Reorder the input X by the rank of `RankTable`. If `RankTable` is ordered by
index [3, 0, 2, 1]. Input X will reorder its sequence, the third sequence of
X will be the first sequence of Output.

NOTE: The RankTable does not need to be calculated by X.
Y
Yang Yu 已提交
40 41 42 43 44

For example:
The X = [Seq0, Seq1, Seq2, Seq3]. The indices of RankTable are [3, 0, 2, 1].

The Out =  [Seq3, Seq0, Seq2, Seq1] with correct LoD information.
Y
Yang Yu 已提交
45 46 47 48 49 50 51 52 53 54 55 56
)DOC");
  }
};

class ReorderLoDTensorByRankTableBase : public framework::OperatorBase {
 public:
  ReorderLoDTensorByRankTableBase(const std::string &type,
                                  const framework::VariableNameMap &inputs,
                                  const framework::VariableNameMap &outputs,
                                  const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}
  void Run(const framework::Scope &scope,
D
dzhwinter 已提交
57
           const platform::Place &place) const override {
Y
Yang Yu 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    auto &x =
        detail::Ref(scope.FindVar(Input("X")),
                    "Cannot find input lod tensor variable %s", Input("X"))
            .Get<framework::LoDTensor>();
    auto &rank_table = detail::Ref(scope.FindVar(Input("RankTable")),
                                   "Cannot find input rank table variable %s",
                                   Input("RankTable"))
                           .Get<framework::LoDRankTable>();
    auto &out =
        *detail::Ref(scope.FindVar(Output("Out")),
                     "Cannot find output lod tensor variable %s", Output("Out"))
             .GetMutable<framework::LoDTensor>();

    out.Resize(x.dims());
    out.mutable_data(x.place(), x.type());
D
dzhwinter 已提交
73
    this->process(place, x, rank_table, &out);
Y
Yang Yu 已提交
74 75 76
  }

 protected:
D
dzhwinter 已提交
77
  virtual void process(const platform::Place &place,
Y
Yang Yu 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91
                       const framework::LoDTensor &x,
                       const framework::LoDRankTable &rank_table,
                       framework::LoDTensor *out) const = 0;

  struct AbsoluteRankTableItem {
    size_t offset;  // the absolute/accumulated offset.
    size_t length;  // the length
    framework::LoD lod;
  };

  std::vector<AbsoluteRankTableItem> GetAbsoluteOffsetAndLengthByLoDRankTable(
      const framework::LoDTensor &x) const {
    std::vector<AbsoluteRankTableItem> absolute_table;

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    if (x.lod().empty()) {
      // For Tensor without lod, such as the output of sequence_pool_op
      size_t size = x.dims()[0];
      absolute_table.reserve(size);
      for (size_t i = 0; i < size; ++i) {
        absolute_table.emplace_back();
        absolute_table.back().length = 1;
        absolute_table.back().offset = i;
      }
    } else {
      size_t level = 0;
      size_t size = x.lod()[level].size();

      for (size_t i = 0; i < size - 1; ++i) {
        auto lod_offset =
            framework::GetSubLoDAndAbsoluteOffset(x.lod(), i, i + 1, level);
Y
Yang Yu 已提交
108

109
        auto &offset = lod_offset.second;
Y
Yang Yu 已提交
110

111 112 113 114 115
        absolute_table.emplace_back();
        absolute_table.back().length = offset.second - offset.first;
        absolute_table.back().offset = offset.first;
        absolute_table.back().lod = lod_offset.first;
      }
Y
Yang Yu 已提交
116
    }
117

Y
Yang Yu 已提交
118 119 120
    return absolute_table;
  }

D
dzhwinter 已提交
121
  size_t CopyTensorAndLod(const platform::Place &place,
Y
Yang Yu 已提交
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
                          const AbsoluteRankTableItem &item,
                          const framework::LoDTensor &x,
                          framework::LoDTensor *out, size_t out_offset) const {
    auto &out_lod = *out->mutable_lod();
    auto len = item.length;
    auto x_offset = item.offset;

    if (out_lod.empty()) {
      for (size_t i = 0; i < item.lod.size(); ++i) {
        out_lod.push_back(std::vector<size_t>({0}));
      }
    }

    for (size_t i = 0; i < out_lod.size(); ++i) {
      auto &out_v = out_lod[i];
      auto &new_lod_v = item.lod[i];

      for (auto &detail : new_lod_v) {
        out_v.push_back(out_v.back() + detail);
      }
    }

    auto x_sliced = x.Slice(x_offset, x_offset + len);
    auto out_sliced = out->Slice(out_offset, out_offset + len);

Y
Yu Yang 已提交
147 148
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);
Y
Yang Yu 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    framework::CopyFrom(x_sliced, out_sliced.place(), dev_ctx, &out_sliced);
    out_offset += len;
    return out_offset;
  }
};

class ReorderLoDTensorByRankTableOp : public ReorderLoDTensorByRankTableBase {
 public:
  ReorderLoDTensorByRankTableOp(const std::string &type,
                                const framework::VariableNameMap &inputs,
                                const framework::VariableNameMap &outputs,
                                const framework::AttributeMap &attrs)
      : ReorderLoDTensorByRankTableBase(type, inputs, outputs, attrs) {}

 protected:
D
dzhwinter 已提交
164
  void process(const platform::Place &place, const framework::LoDTensor &x,
Y
Yang Yu 已提交
165 166 167 168 169 170
               const framework::LoDRankTable &rank_table,
               framework::LoDTensor *out) const override {
    auto absolute_table = GetAbsoluteOffsetAndLengthByLoDRankTable(x);
    size_t out_offset = 0;
    out->mutable_lod()->clear();
    for (auto &item : rank_table.items()) {
Y
Yang Yu 已提交
171
      PADDLE_ENFORCE_LT(item.index, absolute_table.size());
D
dzhwinter 已提交
172
      out_offset = CopyTensorAndLod(place, absolute_table[item.index], x, out,
Y
Yang Yu 已提交
173
                                    out_offset);
Y
Yang Yu 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    }
  }
};

class IdentityInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    context->SetOutputDim("Out", context->GetInputDim("X"));
  }
};

class ReorderLodTensorByRankGradOpMaker
    : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
Y
Yang Yu 已提交
191 192
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto *grad_op = new framework::OpDesc();
Y
Yang Yu 已提交
193 194 195 196
    grad_op->SetType("reorder_lod_tensor_by_rank_grad");
    grad_op->SetInput("X", OutputGrad("Out"));
    grad_op->SetOutput("Out", InputGrad("X"));
    grad_op->SetInput("RankTable", Input("RankTable"));
Y
Yang Yu 已提交
197
    return std::unique_ptr<framework::OpDesc>(grad_op);
Y
Yang Yu 已提交
198 199 200 201 202 203 204 205 206 207 208 209
  }
};

class ReorderLoDTensorByRankGradOp : public ReorderLoDTensorByRankTableBase {
 public:
  ReorderLoDTensorByRankGradOp(const std::string &type,
                               const framework::VariableNameMap &inputs,
                               const framework::VariableNameMap &outputs,
                               const framework::AttributeMap &attrs)
      : ReorderLoDTensorByRankTableBase(type, inputs, outputs, attrs) {}

 protected:
D
dzhwinter 已提交
210
  void process(const platform::Place &place, const framework::LoDTensor &x,
Y
Yang Yu 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
               const framework::LoDRankTable &rank_table,
               framework::LoDTensor *out) const override {
    auto absolute_table = GetAbsoluteOffsetAndLengthByLoDRankTable(x);

    // offsets = enumerate([item.index for item in rank_table.items()])
    std::vector<std::pair<size_t, size_t>> offsets;
    offsets.reserve(rank_table.items().size());
    for (size_t i = 0; i < rank_table.items().size(); ++i) {
      offsets.push_back({i, rank_table.items()[i].index});
    }

    // offsets.sort(key=lambda x: x[1])
    std::sort(
        offsets.begin(), offsets.end(),
        [](const std::pair<size_t, size_t> &a,
           const std::pair<size_t, size_t> &b) { return a.second < b.second; });

    // Copy TensorAndLod
    size_t out_offset = 0;
    for (auto &offset : offsets) {
D
dzhwinter 已提交
231
      out_offset = this->CopyTensorAndLod(place, absolute_table[offset.first],
Y
Yang Yu 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244
                                          x, out, out_offset);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(reorder_lod_tensor_by_rank,
                  ops::ReorderLoDTensorByRankTableOp,
                  ops::ReorderLodTensorByRankGradOpMaker,
Y
Yang Yu 已提交
245 246
                  ops::ReorderLoDTensorByRankTableOpProtoMaker,
                  ops::IdentityInferShape);
Y
Yang Yu 已提交
247 248
REGISTER_OPERATOR(reorder_lod_tensor_by_rank_grad,
                  ops::ReorderLoDTensorByRankGradOp, ops::IdentityInferShape);