array_to_lod_tensor_op.cc 9.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
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. */
C
chengduo 已提交
14
#include <paddle/fluid/operators/math/concat_and_split.h>
15
#include <numeric>
D
dzhwinter 已提交
16

Y
Yi Wang 已提交
17 18 19 20 21
#include "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/platform/device_context.h"
22 23 24 25 26 27

namespace paddle {
namespace operators {

using LoD = framework::LoD;

J
JiabinYang 已提交
28
struct ArrayToLoDFunctor;
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
template <typename DeviceContext>
struct ArrayToLoDFunctorImpl {
  const ArrayToLoDFunctor *prev_functor_;
  DeviceContext *dev_ctx_;

  template <typename T>
  void apply();
};

struct ArrayToLoDFunctor : public boost::static_visitor<void> {
  std::vector<framework::Tensor> in;
  mutable framework::Tensor *out;

  template <typename Place>
  void operator()(Place place) const {
    auto &pool = platform::DeviceContextPool::Instance();
    if (std::is_same<Place, platform::CPUPlace>::value) {
      Apply(static_cast<platform::CPUDeviceContext *>(pool.Get(place)));
    } else {
#ifdef PADDLE_WITH_CUDA
      Apply(static_cast<platform::CUDADeviceContext *>(pool.Get(place)));
#else
      PADDLE_THROW("Fluid is not compiled with CUDA");
#endif
    }
  }

  template <typename DeviceContext>
  void Apply(DeviceContext *dev_ctx) const {
    ArrayToLoDFunctorImpl<DeviceContext> functor;
    functor.dev_ctx_ = dev_ctx;
    functor.prev_functor_ = this;
Y
Yu Yang 已提交
61
    framework::VisitDataType(out->type(), functor);
62 63 64 65 66 67 68 69 70 71
  }
};

template <typename DeviceContext>
template <typename T>
void ArrayToLoDFunctorImpl<DeviceContext>::apply() {
  math::ConcatFunctor<DeviceContext, T> func;
  func(*dev_ctx_, prev_functor_->in, 0, prev_functor_->out);
}

72 73 74 75 76 77 78
class ArrayToLoDTensorOp : public framework::OperatorBase {
 public:
  ArrayToLoDTensorOp(const std::string &type,
                     const framework::VariableNameMap &inputs,
                     const framework::VariableNameMap &outputs,
                     const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}
79 80 81 82

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
83 84 85 86 87 88 89 90 91 92 93
    auto &x = scope.FindVar(Input("X"))->Get<framework::LoDTensorArray>();
    auto &rank_table =
        scope.FindVar(Input("RankTable"))->Get<framework::LoDRankTable>();
    auto *out =
        scope.FindVar(Output("Out"))->GetMutable<framework::LoDTensor>();

    // Check dims, place and data type of input's elements and infer output's
    // dim
    PADDLE_ENFORCE(!x.empty(), "There's no element in the input array.");
    int rank = x[0].dims().size();
    platform::Place place = x[0].place();
Y
Yu Yang 已提交
94
    auto data_type = x[0].type();
95
    int64_t batch_size = x[0].dims()[0];
96 97 98
    framework::DDim ins_dims = rank > 1
                                   ? framework::slice_ddim(x[0].dims(), 1, rank)
                                   : framework::make_ddim({0});
99
    for (size_t i = 1; i < x.size(); ++i) {
100 101 102
      auto ins_i_dims = rank > 1 ? framework::slice_ddim(x[i].dims(), 1, rank)
                                 : framework::make_ddim({0});
      PADDLE_ENFORCE_EQ(ins_i_dims, ins_dims,
103 104 105
                        "The dimension of the %zu'th element in LoDTensorArray "
                        "differs from previous ones.",
                        i);
106
      PADDLE_ENFORCE(x[i].place() == place,
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
                     "The place class of the %zu'th element in LoDTensorArray "
                     "differs from previous ones.",
                     i);
      PADDLE_ENFORCE(x[i].type() == data_type,
                     "The date type of the %zu'th element in LoDTensorArray "
                     "differs from previous ones.",
                     i);
      batch_size += x[i].dims()[0];
    }
    auto ins_dim_vec = framework::vectorize(ins_dims);
    ins_dim_vec.insert(ins_dim_vec.begin(), batch_size);
    framework::DDim out_dims = framework::make_ddim(ins_dim_vec);
    out->Resize(out_dims);
    out->mutable_data(place, data_type);

    auto &table_items = rank_table.items();
    std::vector<size_t> table_item_idx(table_items.size());
    // table_item_idx = range(table_items_idx.size())
    std::iota(table_item_idx.begin(), table_item_idx.end(), 0);
    std::sort(table_item_idx.begin(), table_item_idx.end(),
              [&](size_t a, size_t b) {
                return table_items[a].index < table_items[b].index;
              });

    // Build LoDTensor `out`
    framework::LoD *out_lod = out->mutable_lod();
    out_lod->clear();
    auto prefix_lod = rank_table.coarse_lod();
    prefix_lod.emplace_back();
    auto &cur_level_lod = prefix_lod.back();
    cur_level_lod.push_back(0);
138
    ArrayToLoDFunctor functor;
139 140
    for (size_t idx : table_item_idx) {
      cur_level_lod.push_back(cur_level_lod.back() + table_items[idx].length);
141
      PADDLE_ENFORCE_LE(table_items[idx].length, x.size());
142 143 144 145 146 147 148 149 150
      for (size_t x_idx = 0; x_idx < table_items[idx].length; ++x_idx) {
        auto lod_and_offset = framework::GetSubLoDAndAbsoluteOffset(
            x[x_idx].lod(), idx, idx + 1, 0);

        auto &lod_length = lod_and_offset.first;
        framework::AppendLoD(out_lod, lod_length);

        size_t start_offset = lod_and_offset.second.first;
        size_t end_offset = lod_and_offset.second.second;
M
minqiyang 已提交
151 152
        VLOG(10) << "idx=" << idx << " x_idx=" << x_idx << " ["
                 << ", " << end_offset << "]";
153 154 155 156 157 158
        // Copy data
        PADDLE_ENFORCE_GE(end_offset, start_offset);
        size_t len = end_offset - start_offset;
        if (len == 0) {
          continue;
        }
159
        functor.in.emplace_back(x[x_idx].Slice(start_offset, end_offset));
160 161
      }
    }
162 163
    functor.out = out;
    platform::VisitPlace(place, functor);
164 165 166 167 168 169
    out_lod->insert(out_lod->begin(), prefix_lod.begin(), prefix_lod.end());
  }
};

class ArrayToLoDTensorOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
170
  void Make() override {
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    AddInput("X",
             "(std::vector<LodTensor>) A vector of tensors that is going to "
             "be casted to a big LoDTensor.");
    AddInput("RankTable",
             "(LoDRankTable) RankTable provides the coarse lod infomation to "
             "build the output LoDTensor. See "
             "'paddle/framework/lod_rank_table.h' for more details.");
    AddOutput("Out", "(LoDTensor) The LoDTensor formed by input tensor array.");
    AddComment(
        R"DOC(This Op build a big LoDTensor from a std::vector<LoDTensor> 
          and a LoDRankTable. It is supposed to be used in getting dynamic RNN's
          outputs back to a normal LoDTensor. The std::vector<LoDTensor> 
          would be the output of RNN Op and the LoDRankTable would be build 
          with RNN's input.)DOC");
  }
};

class ArrayToLoDTensorInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    PADDLE_ENFORCE(context->HasInput("X"),
Z
zhangchunle 已提交
192
                   "ArrayToLoDTensorOp must have input X.");
193
    PADDLE_ENFORCE(context->HasInput("RankTable"),
Z
zhangchunle 已提交
194
                   "ArrayToLoDTensorOp must have input RankTable.");
195 196 197 198
    // For compile-time, the first dim of input X and output Out should be -1.
    // For runtime, the first dim of output Out should be the sum of all
    // elements's first dim in input X. The output's dims will be re-computed in
    // detail kernel implementation.
199
    context->SetOutputDim("Out", context->GetInputDim("X"));
200 201

    // The output LoDTensor's lod_level should be input X's lod_level + 1.
202
    // For compile-time, we call SetLoDLevel to set output's lod_level.
203 204 205 206 207
    // For runtime, output LoDTensor's lod is determined by input X's lod and
    // the level specified by input RandTable.
    // We cannot get X's detail lod and RankTable's level in this function, so
    // leave this work to the detail kernel implementation.
    if (!context->IsRuntime()) {
208
      context->SetLoDLevel("Out", context->GetLoDLevel("X") + 1);
209
    }
210 211 212
  }
};

H
hong 已提交
213 214
template <typename T>
class ArrayToLoDTensorGradMaker : public framework::SingleGradOpMaker<T> {
215
 public:
H
hong 已提交
216
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
217 218

 protected:
H
hong 已提交
219 220
  std::unique_ptr<T> Apply() const override {
    auto *grad_op = new T();
221
    grad_op->SetType("lod_tensor_to_array");
H
hong 已提交
222 223 224 225 226
    grad_op->SetInput("X", this->OutputGrad("Out"));
    grad_op->SetInput("RankTable", this->Input("RankTable"));
    grad_op->SetOutput("Out", this->InputGrad("X"));
    grad_op->SetAttrMap(this->Attrs());
    return std::unique_ptr<T>(grad_op);
227 228 229 230 231 232 233 234 235
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(array_to_lod_tensor, ops::ArrayToLoDTensorOp,
                  ops::ArrayToLoDTensorOpProtoMaker,
236
                  ops::ArrayToLoDTensorInferShape,
H
hong 已提交
237 238
                  ops::ArrayToLoDTensorGradMaker<paddle::framework::OpDesc>,
                  ops::ArrayToLoDTensorGradMaker<paddle::imperative::OpBase>);