Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into ctc_evaluator_py
commit
25dec82f24
@ -0,0 +1,121 @@
|
||||
## Add Kernels for a New Device
|
||||
|
||||
### Background
|
||||
|
||||
PaddlePaddle Fluid have hundreds of operators. Each operator could have one or more kernels. A kernel is an implementation of the operator for a certain device, which could be a hardware device, e.g., the CUDA GPU, or a library that utilizes a device, e.g., Intel MKL that makes full use of the Xeon CPU.
|
||||
|
||||
[This document](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/howto/dev/new_op_en.md) explains how to add an operator, and its kernels. The kernels of an operator are indexed by a C++ type [`OpKernelType`](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/operator_kernel_type.md). An operator chooses the right kernel at runtime. This choosing mechanism is described [here](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/switch_kernel.md).
|
||||
|
||||
### Write Kernels for A New Device
|
||||
|
||||
#### Add A New Device
|
||||
|
||||
For some historical reaons, we misuse the word *library* for *device*. For example, we call the deivce type by *library type*. An example is the header file [`library_type.h`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/library_type.h#L24). We will correct this ASAP.
|
||||
|
||||
To register a new device, we need to add an enum value to `LibraryType`:
|
||||
|
||||
```
|
||||
enum class LibraryType {
|
||||
kPlain = 0,
|
||||
kMKLDNN = 1,
|
||||
kCUDNN = 2,
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
#### Add A New [Place](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/platform/place.h#L53)
|
||||
|
||||
If you have a new kind of Device, firstly you need to add a new kind of [`Place`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/platform/place.h#L53). For example `CUDAPlace`:
|
||||
|
||||
```cpp
|
||||
struct CUDAPlace {
|
||||
CUDAPlace() : CUDAPlace(0) {}
|
||||
explicit CUDAPlace(int d) : device(d) {}
|
||||
|
||||
inline int GetDeviceId() const { return device; }
|
||||
// needed for variant equality comparison
|
||||
inline bool operator==(const CUDAPlace &o) const {
|
||||
return device == o.device;
|
||||
}
|
||||
inline bool operator!=(const CUDAPlace &o) const { return !(*this == o); }
|
||||
|
||||
int device;
|
||||
};
|
||||
|
||||
typedef boost::variant<CUDAPlace, CPUPlace> Place;
|
||||
```
|
||||
|
||||
#### Add [device context]((https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/platform/device_context.h#L37))
|
||||
After a new kind of Device is added, you should add a corresponding [DeviceContext](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/platform/device_context.h#L37) for it.
|
||||
|
||||
```cpp
|
||||
class DeviceContext {
|
||||
public:
|
||||
virtual ~DeviceContext() {}
|
||||
virtual Place GetPlace() const = 0;
|
||||
|
||||
virtual void Wait() const {}
|
||||
};
|
||||
```
|
||||
|
||||
#### Implement new [OpKernel](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/operator.h#L351) for your Device.
|
||||
|
||||
A detailed documentation can be found in [`new_op_and_kernel`](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/howto/dev/new_op_en.md)
|
||||
|
||||
```cpp
|
||||
class OpKernelBase {
|
||||
public:
|
||||
/**
|
||||
* ExecutionContext is the only parameter of Kernel Run function.
|
||||
* Run will get input/output variables, state such as momentum and
|
||||
* device resource such as CUDA stream, cublas handle, etc. from
|
||||
* ExecutionContext. User should construct it before run the Operator.
|
||||
*/
|
||||
|
||||
virtual void Compute(const ExecutionContext& context) const = 0;
|
||||
|
||||
virtual ~OpKernelBase() = default;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class OpKernel : public OpKernelBase {
|
||||
public:
|
||||
using ELEMENT_TYPE = T;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
#### Register the OpKernel to framework
|
||||
|
||||
After writing the components described above, we should register the kernel to the framework.
|
||||
|
||||
We use `REGISTER_OP_KERNEL` to do the registration.
|
||||
|
||||
```cpp
|
||||
REGISTER_OP_KERNEL(
|
||||
op_type,
|
||||
library_type,
|
||||
place_type,
|
||||
kernel0, kernel1, ...)
|
||||
```
|
||||
|
||||
kernel0, kernel1 are kernels that have the same `op_type`, `library_type`, `place_type` but different `data_types`.
|
||||
|
||||
take [`conv2d`]((https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/conv_cudnn_op.cu.cc#L318)) as an example:
|
||||
|
||||
```cpp
|
||||
REGISTER_OP_KERNEL(conv2d, CPU, paddle::platform::CPUPlace,
|
||||
paddle::operators::GemmConvKernel<paddle::platform::CPUDeviceContext, float>,
|
||||
paddle::operators::GemmConvKernel<paddle::platform::CPUDeviceContext, double>);
|
||||
|
||||
REGISTER_OP_KERNEL(conv2d, CUDNN, ::paddle::platform::CUDAPlace,
|
||||
paddle::operators::CUDNNConvOpKernel<float>,
|
||||
paddle::operators::CUDNNConvOpKernel<double>);
|
||||
```
|
||||
|
||||
In the code above:
|
||||
|
||||
- `conv2d` is the type/name of the operator
|
||||
- `CUDNN/CPU` is `library`
|
||||
- `paddle::platform::CUDAPlace/CPUPlace` is `place`
|
||||
- template parameter `float/double` on `CUDNNConvOpKernel<T>` is `data_type`.
|
@ -0,0 +1,44 @@
|
||||
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
|
||||
|
||||
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/data_layout_transform.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "paddle/platform/device_context.h"
|
||||
|
||||
TEST(DataTransform, DataLayoutFunction) {
|
||||
using namespace paddle::framework;
|
||||
using namespace paddle::platform;
|
||||
|
||||
auto place = CPUPlace();
|
||||
Tensor in = Tensor();
|
||||
Tensor out = Tensor();
|
||||
in.mutable_data<double>(make_ddim({2, 3, 1, 2}), place);
|
||||
in.set_layout(DataLayout::kNHWC);
|
||||
|
||||
auto kernel_nhwc = OpKernelType(proto::DataType::FP32, place,
|
||||
DataLayout::kNHWC, LibraryType::kPlain);
|
||||
auto kernel_ncwh = OpKernelType(proto::DataType::FP32, place,
|
||||
DataLayout::kNCHW, LibraryType::kPlain);
|
||||
|
||||
TransDataLayout(kernel_nhwc, kernel_ncwh, in, &out);
|
||||
|
||||
EXPECT_TRUE(out.layout() == DataLayout::kNCHW);
|
||||
EXPECT_TRUE(out.dims() == make_ddim({2, 2, 3, 1}));
|
||||
|
||||
TransDataLayout(kernel_ncwh, kernel_nhwc, in, &out);
|
||||
|
||||
EXPECT_TRUE(in.layout() == DataLayout::kNHWC);
|
||||
EXPECT_TRUE(in.dims() == make_ddim({2, 3, 1, 2}));
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
|
||||
|
||||
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/operators/ctc_align_op.h"
|
||||
|
||||
namespace paddle {
|
||||
namespace operators {
|
||||
|
||||
class CTCAlignOp : public framework::OperatorWithKernel {
|
||||
public:
|
||||
using framework::OperatorWithKernel::OperatorWithKernel;
|
||||
|
||||
void InferShape(framework::InferShapeContext* ctx) const override {
|
||||
PADDLE_ENFORCE(ctx->HasInput("Input"),
|
||||
"Input of CTCAlignOp should not be null.");
|
||||
PADDLE_ENFORCE(ctx->HasOutput("Output"),
|
||||
"Output of CTCAlignOp should not be null.");
|
||||
|
||||
auto input_dims = ctx->GetInputDim("Input");
|
||||
|
||||
// TODO(wanghaoshuang): it is tricky to set the wrong dimension here.
|
||||
ctx->SetOutputDim("Output", input_dims);
|
||||
}
|
||||
|
||||
protected:
|
||||
framework::OpKernelType GetExpectedKernelType(
|
||||
const framework::ExecutionContext& ctx) const override {
|
||||
return framework::OpKernelType(
|
||||
framework::ToDataType(ctx.Input<Tensor>("Input")->type()),
|
||||
ctx.device_context());
|
||||
}
|
||||
};
|
||||
|
||||
class CTCAlignOpMaker : public framework::OpProtoAndCheckerMaker {
|
||||
public:
|
||||
CTCAlignOpMaker(OpProto* proto, OpAttrChecker* op_checker)
|
||||
: OpProtoAndCheckerMaker(proto, op_checker) {
|
||||
AddInput("Input",
|
||||
"(LodTensor, default: LoDTensor<int>), Its shape is "
|
||||
"[Lp, 1], where Lp is the sum of all input sequences' length.");
|
||||
AddOutput("Output", "(Tensor, default: Tensor<int>), The align result.");
|
||||
AddAttr<int>("blank",
|
||||
"(int, default: 0), the blank label setted in Connectionist "
|
||||
"Temporal Classification (CTC) op.")
|
||||
.SetDefault(0);
|
||||
AddAttr<bool>("merge_repeated",
|
||||
"(bool, default: true), whether to "
|
||||
"merge repeated elements between two blanks. ")
|
||||
.SetDefault(true);
|
||||
AddComment(R"DOC(
|
||||
CTCAlign op is used to merge repeated elements between two blanks
|
||||
and then delete all blanks in sequence.
|
||||
|
||||
Given:
|
||||
Input.data = [0, 1, 2, 2, 0, 4, 0, 4, 5, 0, 6,
|
||||
6, 0, 0, 7, 7, 7, 0]
|
||||
Input.dims = {18, 1}
|
||||
Input.LoD = [[0, 11, 18]]
|
||||
|
||||
And:
|
||||
blank = 0
|
||||
merge_repeated = True
|
||||
|
||||
Then:
|
||||
Output.data = [1, 2, 4, 4, 5, 6,
|
||||
6, 7]
|
||||
Output.dims = {8, 1}
|
||||
Output.LoD = [[0, 6, 8]]
|
||||
|
||||
)DOC");
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace operators
|
||||
} // namespace paddle
|
||||
|
||||
namespace ops = paddle::operators;
|
||||
REGISTER_OPERATOR(ctc_align, ops::CTCAlignOp, ops::CTCAlignOpMaker,
|
||||
paddle::framework::EmptyGradOpMaker);
|
||||
REGISTER_OP_CPU_KERNEL(
|
||||
ctc_align, ops::CTCAlignKernel<paddle::platform::CPUDeviceContext, int>,
|
||||
ops::CTCAlignKernel<paddle::platform::CPUDeviceContext, int64_t>);
|
@ -0,0 +1,91 @@
|
||||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
|
||||
|
||||
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 <stdio.h>
|
||||
#include <thrust/device_vector.h>
|
||||
#include <thrust/host_vector.h>
|
||||
#include "paddle/operators/ctc_align_op.h"
|
||||
|
||||
namespace paddle {
|
||||
namespace operators {
|
||||
|
||||
template <typename T>
|
||||
__global__ void MergeAndDelCudaKernel(const int64_t num_token, const T* tokens,
|
||||
const size_t num_seq, size_t* lod0,
|
||||
const int blank, const int merge_repeated,
|
||||
size_t* out_lod0, T* output) {
|
||||
int ouput_idx = 0;
|
||||
out_lod0[0] = 0;
|
||||
|
||||
for (int i = 0; i < num_seq; ++i) {
|
||||
T pre_token = -1;
|
||||
for (int j = lod0[i]; j < lod0[i + 1]; ++j) {
|
||||
if (tokens[j] != blank && !(merge_repeated && tokens[j] == pre_token)) {
|
||||
output[ouput_idx] = tokens[j];
|
||||
++ouput_idx;
|
||||
}
|
||||
pre_token = tokens[j];
|
||||
}
|
||||
out_lod0[i + 1] = ouput_idx;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class CTCAlignOpCUDAKernel : public framework::OpKernel<T> {
|
||||
public:
|
||||
void Compute(const framework::ExecutionContext& ctx) const override {
|
||||
PADDLE_ENFORCE(platform::is_gpu_place(ctx.GetPlace()),
|
||||
"It must use CUDAPlace.");
|
||||
const size_t level = 0;
|
||||
auto* input = ctx.Input<LoDTensor>("Input");
|
||||
auto* output = ctx.Output<LoDTensor>("Output");
|
||||
auto input_lod = framework::ToAbsOffset(input->lod());
|
||||
|
||||
const T* tokens = input->data<T>();
|
||||
const int64_t num_tokens = input->dims()[0];
|
||||
const size_t num_seq = input_lod[level].size() - 1;
|
||||
|
||||
const int blank = ctx.Attr<int>("blank");
|
||||
const int merge_repeated =
|
||||
static_cast<int>(ctx.Attr<bool>("merge_repeated"));
|
||||
|
||||
// prepare a lod to record lod information while merging elements
|
||||
thrust::device_vector<size_t> dev_out_lod0(input_lod[level].size());
|
||||
size_t* dev_out_lod0_ptr = thrust::raw_pointer_cast(dev_out_lod0.data());
|
||||
|
||||
// merge elements and delete blank
|
||||
T* output_data = output->mutable_data<T>({num_tokens, 1}, ctx.GetPlace());
|
||||
|
||||
auto stream = ctx.cuda_device_context().stream();
|
||||
MergeAndDelCudaKernel<T><<<1, 1, 0, stream>>>(
|
||||
num_tokens, tokens, num_seq, input_lod[level].data(), blank,
|
||||
merge_repeated, dev_out_lod0_ptr, output_data);
|
||||
|
||||
// set output lod
|
||||
thrust::host_vector<size_t> host_out_lod0(dev_out_lod0.begin(),
|
||||
dev_out_lod0.end());
|
||||
framework::LoD out_lod;
|
||||
out_lod.push_back(host_out_lod0);
|
||||
output->set_lod(out_lod);
|
||||
|
||||
// resize output dims
|
||||
output->Resize({static_cast<int64_t>(host_out_lod0.back()), 1});
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace operators
|
||||
} // namespace paddle
|
||||
|
||||
REGISTER_OP_CUDA_KERNEL(ctc_align, paddle::operators::CTCAlignOpCUDAKernel<int>,
|
||||
paddle::operators::CTCAlignOpCUDAKernel<int64_t>);
|
@ -0,0 +1,75 @@
|
||||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
|
||||
|
||||
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 <string.h>
|
||||
#include "paddle/framework/op_registry.h"
|
||||
namespace paddle {
|
||||
namespace operators {
|
||||
|
||||
using Tensor = framework::Tensor;
|
||||
using LoDTensor = framework::LoDTensor;
|
||||
|
||||
template <typename DeviceContext, typename T>
|
||||
class CTCAlignKernel : public framework::OpKernel<T> {
|
||||
public:
|
||||
void Compute(const framework::ExecutionContext& ctx) const override {
|
||||
auto* input = ctx.Input<LoDTensor>("Input");
|
||||
auto* output = ctx.Output<LoDTensor>("Output");
|
||||
const size_t level = 0;
|
||||
auto input_lod = framework::ToAbsOffset(input->lod());
|
||||
|
||||
// check input dims and lod
|
||||
auto input_dims = input->dims();
|
||||
PADDLE_ENFORCE_EQ(input_dims[0],
|
||||
static_cast<int64_t>(input_lod[level].back()),
|
||||
"The first dimension of Input(Input) should be equal to "
|
||||
"the sum of all sequences' lengths.");
|
||||
|
||||
const size_t num_sequences = input_lod[level].size() - 1;
|
||||
size_t blank = static_cast<size_t>(ctx.Attr<int>("blank"));
|
||||
bool merge_repeated = ctx.Attr<bool>("merge_repeated");
|
||||
|
||||
// merge repeated tokens and delete blank
|
||||
T* output_data = output->mutable_data<T>(ctx.GetPlace());
|
||||
size_t output_idx = 0;
|
||||
std::vector<size_t> output_lod0(1, 0);
|
||||
const T* input_data = input->data<T>();
|
||||
for (size_t seq_idx = 0; seq_idx < num_sequences; ++seq_idx) {
|
||||
T prev_token = -1;
|
||||
for (size_t i = input_lod[level][seq_idx];
|
||||
i < input_lod[level][seq_idx + 1]; ++i) {
|
||||
if (input_data[i] != blank &&
|
||||
!(merge_repeated && input_data[i] == prev_token)) {
|
||||
output_data[output_idx] = input_data[i];
|
||||
++output_idx;
|
||||
}
|
||||
prev_token = input_data[i];
|
||||
}
|
||||
output_lod0.push_back(output_idx);
|
||||
}
|
||||
|
||||
// set output lod
|
||||
framework::LoD output_lod;
|
||||
output_lod.push_back(output_lod0);
|
||||
output->set_lod(output_lod);
|
||||
|
||||
// resize output dims
|
||||
output->Resize({static_cast<int64_t>(output_lod0.back()), 1});
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace operators
|
||||
} // namespace paddle
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue