Feature/rnn to array to lod tensor (#5411)
* Add LoDRankTable LoD Rank Table stores the `level` of `lod` which is ordered by sequence length in descending order. It is useful when implement dynamic RNN and is shared by dynamic RNN memory, dynamic RNN slice input and dynamic RNN slice output operators. * Add skeleton for array_to_lod_tensor and lod_tensor_to_array * Add VarType::LoDTensorArray * Add PyBind of LoDTensorArray * Add InferVarType * Add first unittest * Add ut * Add unittest * Add unittest * Add unittests * update * init * add infershape for lod_tensor_to_array_op * compelete array_to_lod_tensor_op * copy data * clean code * clean code * Fix unittest data * fix bugs * fix compile error * Refine TensorToArrayOp * refactor array_to_lod_tensor * Unittest * fix bugs * Fix unittest * Fix unittest * debug * Debug * Fix unittest * clean code * refactor * use ostream * update test * fix gpu build error * make gpu test passmobile_baidu
parent
d9e5eba0b1
commit
f72729d407
@ -0,0 +1,152 @@
|
||||
/* Copyright (c) 2016 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 <numeric>
|
||||
#include "paddle/framework/lod_rank_table.h"
|
||||
#include "paddle/framework/lod_tensor_array.h"
|
||||
#include "paddle/framework/op_registry.h"
|
||||
#include "paddle/memory/memcpy.h"
|
||||
|
||||
namespace paddle {
|
||||
namespace operators {
|
||||
|
||||
using LoD = framework::LoD;
|
||||
|
||||
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) {}
|
||||
void Run(const framework::Scope &scope,
|
||||
const platform::DeviceContext &dev_ctx) const override {
|
||||
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();
|
||||
std::type_index data_type = x[0].type();
|
||||
framework::DDim ins_dims = framework::slice_ddim(x[0].dims(), 1, rank);
|
||||
int64_t batch_size = x[0].dims()[0];
|
||||
for (size_t i = 1; i < x.size(); ++i) {
|
||||
PADDLE_ENFORCE_EQ(framework::slice_ddim(x[i].dims(), 1, rank), ins_dims,
|
||||
"The dimension of the %zu'th element in LoDTensorArray "
|
||||
"differs from previous ones.",
|
||||
i);
|
||||
PADDLE_ENFORCE(platform::places_are_same_class(x[i].place(), place),
|
||||
"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();
|
||||
size_t out_offset = 0;
|
||||
auto prefix_lod = rank_table.coarse_lod();
|
||||
prefix_lod.emplace_back();
|
||||
auto &cur_level_lod = prefix_lod.back();
|
||||
cur_level_lod.push_back(0);
|
||||
for (size_t idx : table_item_idx) {
|
||||
cur_level_lod.push_back(cur_level_lod.back() + table_items[idx].length);
|
||||
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;
|
||||
VLOG(10) << "idx=" << idx << " x_idx=" << x_idx << " ["
|
||||
<< ", " << end_offset << "]";
|
||||
// Copy data
|
||||
PADDLE_ENFORCE_GE(end_offset, start_offset);
|
||||
size_t len = end_offset - start_offset;
|
||||
if (len == 0) {
|
||||
continue;
|
||||
}
|
||||
out->Slice(out_offset, out_offset + len)
|
||||
.CopyFrom(x[x_idx].Slice(start_offset, end_offset), place, dev_ctx);
|
||||
out_offset += len;
|
||||
}
|
||||
}
|
||||
out_lod->insert(out_lod->begin(), prefix_lod.begin(), prefix_lod.end());
|
||||
}
|
||||
};
|
||||
|
||||
class ArrayToLoDTensorOpProtoMaker : public framework::OpProtoAndCheckerMaker {
|
||||
public:
|
||||
ArrayToLoDTensorOpProtoMaker(framework::OpProto *proto,
|
||||
framework::OpAttrChecker *op_checker)
|
||||
: OpProtoAndCheckerMaker(proto, op_checker) {
|
||||
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"),
|
||||
"ArrayToLoDTensorOp must has input X.");
|
||||
PADDLE_ENFORCE(context->HasInput("RankTable"),
|
||||
"ArrayToLoDTensorOp must has input RankTable.");
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace operators
|
||||
} // namespace paddle
|
||||
|
||||
namespace ops = paddle::operators;
|
||||
REGISTER_OPERATOR(array_to_lod_tensor, ops::ArrayToLoDTensorOp,
|
||||
ops::ArrayToLoDTensorOpProtoMaker,
|
||||
ops::ArrayToLoDTensorInferShape);
|
@ -0,0 +1,143 @@
|
||||
/* Copyright (c) 2016 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 "paddle/framework/lod_rank_table.h"
|
||||
#include "paddle/framework/lod_tensor_array.h"
|
||||
#include "paddle/framework/op_registry.h"
|
||||
|
||||
namespace paddle {
|
||||
namespace operators {
|
||||
|
||||
struct CopyRange {
|
||||
size_t begin;
|
||||
size_t end;
|
||||
};
|
||||
|
||||
class LoDTensorToArrayOp : public framework::OperatorBase {
|
||||
public:
|
||||
LoDTensorToArrayOp(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,
|
||||
const platform::DeviceContext &dev_ctx) const override {
|
||||
auto &x = scope.FindVar(Input("X"))->Get<framework::LoDTensor>();
|
||||
auto &rank_table =
|
||||
scope.FindVar(Input("RankTable"))->Get<framework::LoDRankTable>();
|
||||
auto &out =
|
||||
*scope.FindVar(Output("Out"))->GetMutable<framework::LoDTensorArray>();
|
||||
|
||||
auto &items = rank_table.items();
|
||||
auto max_seq_len = items[0].length;
|
||||
auto rank_level = rank_table.level();
|
||||
out.resize(max_seq_len);
|
||||
std::vector<std::vector<CopyRange>> copy_ranges(max_seq_len);
|
||||
|
||||
// set out[i] lod
|
||||
for (size_t t = 0; t < max_seq_len; t++) {
|
||||
auto &lod = *out[t].mutable_lod();
|
||||
lod.clear();
|
||||
for (auto &item : items) {
|
||||
if (t >= item.length) {
|
||||
break;
|
||||
}
|
||||
size_t start_idx = x.lod()[rank_level][item.index] + t;
|
||||
auto lod_and_offset = framework::GetSubLoDAndAbsoluteOffset(
|
||||
x.lod(), start_idx, start_idx + 1, rank_level + 1);
|
||||
|
||||
auto &lod_length = lod_and_offset.first;
|
||||
framework::AppendLoD(&lod, lod_length);
|
||||
|
||||
size_t start_offset = lod_and_offset.second.first;
|
||||
size_t end_offset = lod_and_offset.second.second;
|
||||
copy_ranges[t].emplace_back(CopyRange{start_offset, end_offset});
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < max_seq_len; ++i) {
|
||||
auto &ranges = copy_ranges[i];
|
||||
size_t height = std::accumulate(
|
||||
ranges.begin(), ranges.end(), 0UL,
|
||||
[](size_t a, const CopyRange &b) { return a + b.end - b.begin; });
|
||||
auto x_dim = x.dims();
|
||||
x_dim[0] = static_cast<int64_t>(height);
|
||||
out[i].Resize(x_dim);
|
||||
out[i].mutable_data(x.place(), x.type());
|
||||
size_t offset = 0;
|
||||
for (auto &each_range : ranges) {
|
||||
size_t len = each_range.end - each_range.begin;
|
||||
if (len == 0) {
|
||||
continue;
|
||||
}
|
||||
// out[i][offset: offset+len] = x[each_range.begin: each_range.end]
|
||||
out[i]
|
||||
.Slice(static_cast<int>(offset), static_cast<int>(offset + len))
|
||||
.CopyFrom(x.Slice(static_cast<int>(each_range.begin),
|
||||
static_cast<int>(each_range.end)),
|
||||
x.place(), dev_ctx);
|
||||
offset += len;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class LoDTensorToArrayOpProtoMaker : public framework::OpProtoAndCheckerMaker {
|
||||
public:
|
||||
LoDTensorToArrayOpProtoMaker(framework::OpProto *proto,
|
||||
framework::OpAttrChecker *op_checker)
|
||||
: OpProtoAndCheckerMaker(proto, op_checker) {
|
||||
AddInput("X", "");
|
||||
AddInput("RankTable", "");
|
||||
AddOutput("Out", "");
|
||||
AddComment("");
|
||||
}
|
||||
};
|
||||
|
||||
class LoDTensorToArrayInferShape : public framework::InferShapeBase {
|
||||
public:
|
||||
void operator()(framework::InferShapeContext *context) const override {
|
||||
PADDLE_ENFORCE(context->HasInput("X"),
|
||||
"Input(X) of LoDTensorToArrayOp should not be null.");
|
||||
PADDLE_ENFORCE(
|
||||
context->HasInput("RankTable"),
|
||||
"Input(RankTable) of LoDTensorToArrayOp should not be null.");
|
||||
|
||||
PADDLE_ENFORCE(context->HasOutput("Out"),
|
||||
"Output(Out) of LoDTensorToArrayOp should not be null.");
|
||||
|
||||
auto x_dim = context->GetInputDim("X");
|
||||
// The first dim of each LoDTensor in Output can only be set at run-time.;
|
||||
// We still have to Resize each LoDTensor in Output.
|
||||
context->SetOutputDim("Out", x_dim);
|
||||
}
|
||||
};
|
||||
|
||||
class LoDTensorToArrayInferVarType : public framework::VarTypeInference {
|
||||
public:
|
||||
void operator()(const framework::OpDescBind &op_desc,
|
||||
framework::BlockDescBind *block) const override {
|
||||
for (auto &out_var : op_desc.Output("Out")) {
|
||||
block->Var(out_var)->SetType(framework::VarDesc::LOD_TENSOR_ARRAY);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace operators
|
||||
} // namespace paddle
|
||||
|
||||
namespace ops = paddle::operators;
|
||||
REGISTER_OPERATOR(lod_tensor_to_array, ops::LoDTensorToArrayOp,
|
||||
ops::LoDTensorToArrayOpProtoMaker,
|
||||
ops::LoDTensorToArrayInferShape,
|
||||
ops::LoDTensorToArrayInferVarType);
|
@ -0,0 +1,127 @@
|
||||
import unittest
|
||||
import paddle.v2.framework.core as core
|
||||
import numpy
|
||||
import paddle.v2.framework.layers as layers
|
||||
from paddle.v2.framework.framework import Program
|
||||
from paddle.v2.framework.executor import Executor
|
||||
|
||||
|
||||
class TestCPULoDTensorArrayOps(unittest.TestCase):
|
||||
def place(self):
|
||||
return core.CPUPlace()
|
||||
|
||||
def test_lod_tensor_to_array_level_0(self):
|
||||
tensor = core.LoDTensor()
|
||||
tensor.set(
|
||||
numpy.arange(10).reshape(10, 1).astype('int32'), self.place())
|
||||
tensor.set_lod([[0, 3, 9, 10]])
|
||||
expect = map(lambda x: numpy.array(x).astype('int32'),
|
||||
[[3, 0, 9], [4, 1], [5, 2], [6], [7], [8]])
|
||||
self.main(tensor=tensor, expect_array=expect, expect_lod=[] * 6)
|
||||
|
||||
def test_lod_tensor_to_array_level_0_empty_seq(self):
|
||||
tensor = core.LoDTensor()
|
||||
tensor.set(
|
||||
numpy.arange(10).reshape(10, 1).astype('int32'), self.place())
|
||||
tensor.set_lod([[0, 3, 9, 9, 10]])
|
||||
expect = map(lambda x: numpy.array(x).astype('int32'),
|
||||
[[3, 0, 9], [4, 1], [5, 2], [6], [7], [8]])
|
||||
self.main(tensor=tensor, expect_array=expect, expect_lod=[] * 6)
|
||||
|
||||
def test_lod_tensor_to_array_level_1(self):
|
||||
tensor = core.LoDTensor()
|
||||
tensor.set(
|
||||
numpy.arange(20).reshape(20, 1).astype('int32'), self.place())
|
||||
tensor.set_lod([[0, 2, 5], [0, 3, 9, 11, 17, 20]])
|
||||
|
||||
expect = [
|
||||
numpy.array(
|
||||
[9, 10, 0, 1, 2], dtype='int32'), numpy.array(
|
||||
[11, 12, 13, 14, 15, 16, 3, 4, 5, 6, 7, 8], dtype='int32'),
|
||||
numpy.array(
|
||||
[17, 18, 19], dtype='int32')
|
||||
]
|
||||
|
||||
lod = [[[0, 2, 5]], [[0, 6, 12]], [[0, 3]]]
|
||||
self.main(tensor=tensor, expect_array=expect, expect_lod=lod)
|
||||
|
||||
def test_lod_tensor_to_array_level_1_empty_seq(self):
|
||||
tensor = core.LoDTensor()
|
||||
tensor.set(
|
||||
numpy.arange(31).reshape(31, 1).astype('int32'), self.place())
|
||||
|
||||
tensor.set_lod([[0, 3, 5, 9, 11],
|
||||
[0, 3, 7, 11, 11, 12, 17, 19, 21, 23, 30, 31]])
|
||||
|
||||
expect = [
|
||||
numpy.array(
|
||||
item, dtype='int32')
|
||||
for item in [[
|
||||
12, 13, 14, 15, 16, 0, 1, 2, 23, 24, 25, 26, 27, 28, 29
|
||||
], [17, 18, 3, 4, 5, 6, 11, 30], [19, 20, 7, 8, 9, 10], [21, 22]]
|
||||
]
|
||||
|
||||
lod = [[[0, 5, 8, 8, 15]], [[0, 2, 6, 7, 8]], [[0, 2, 6]], [[0, 2]]]
|
||||
self.main(tensor=tensor, expect_array=expect, expect_lod=lod)
|
||||
|
||||
def test_lod_tensor_to_array_level_2(self):
|
||||
tensor = core.LoDTensor()
|
||||
tensor.set(
|
||||
numpy.arange(50).reshape(50, 1).astype('int32'), self.place())
|
||||
tensor.set_lod([[0, 2, 5, 6], [0, 2, 5, 6, 10, 12, 13],
|
||||
[0, 3, 7, 11, 17, 21, 22, 23, 27, 31, 39, 45, 46, 50]])
|
||||
|
||||
expect = [
|
||||
numpy.array(
|
||||
item, dtype='int32')
|
||||
for item in [[21, 0, 1, 2, 3, 4, 5, 6, 46, 47, 48, 49], range(
|
||||
22, 39) + range(7, 21), range(39, 46)]
|
||||
]
|
||||
lod = [[[0, 1, 3, 4], [0, 1, 4, 8, 12]],
|
||||
[[0, 4, 7], [0, 1, 5, 9, 17, 21, 27, 31]], [[0, 2], [0, 6, 7]]]
|
||||
self.main(tensor=tensor, expect_array=expect, expect_lod=lod)
|
||||
|
||||
def test_lod_tensor_to_array_level_2_skip_level(self):
|
||||
tensor = core.LoDTensor()
|
||||
tensor.set(
|
||||
numpy.arange(50).reshape(50, 1).astype('int32'), self.place())
|
||||
tensor.set_lod([[0, 2, 5, 6], [0, 2, 5, 6, 10, 12, 13],
|
||||
[0, 3, 7, 11, 17, 21, 22, 23, 27, 31, 39, 45, 46, 50]])
|
||||
self.main(tensor=tensor, expect_array=None, expect_lod=None, level=1)
|
||||
|
||||
def main(self, tensor, expect_array, expect_lod, level=0):
|
||||
place = self.place()
|
||||
program = Program()
|
||||
x = layers.data(name='x', shape=[10], main_program=program)
|
||||
x.persistable = True
|
||||
table = layers.lod_rank_table(x, level=level, main_program=program)
|
||||
array = layers.lod_tensor_to_array(x, table, main_program=program)
|
||||
array.persistable = True
|
||||
|
||||
result = layers.array_to_lod_tensor(array, table, main_program=program)
|
||||
result.persistable = True
|
||||
exe = Executor(place)
|
||||
scope = core.Scope()
|
||||
exe.run(program, feed={'x': tensor}, scope=scope)
|
||||
var = scope.find_var(array.name)
|
||||
array = var.get_lod_tensor_array()
|
||||
if expect_array is not None and expect_lod is not None:
|
||||
self.check_array_same(array, expect_array, expect_lod)
|
||||
self.check_tensor_same(scope.find_var(result.name).get_tensor(), tensor)
|
||||
|
||||
def check_array_same(self, array, expect_tensor, expect_lod):
|
||||
self.assertEqual(len(expect_tensor), len(array))
|
||||
for i, exp in enumerate(zip(expect_tensor, expect_lod)):
|
||||
exp_tensor, exp_lod = exp
|
||||
exp_tensor = numpy.expand_dims(exp_tensor, axis=1)
|
||||
self.assertTrue(numpy.allclose(exp_tensor, numpy.array(array[i])))
|
||||
self.assertEqual(exp_lod, array[i].lod())
|
||||
|
||||
def check_tensor_same(self, actual, expect):
|
||||
self.assertTrue(
|
||||
numpy.allclose(numpy.array(actual), numpy.array(expect)))
|
||||
self.assertEqual(actual.lod(), expect.lod())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
Loading…
Reference in new issue