如何写新的C++ OP
如何寫新的C++ OP
概念簡介
簡單介紹需要用到基類,詳細介紹請參考設(shè)計文檔。
? framework::OperatorBase: Operator(簡寫,Op)基類。
? framework::OpKernel: Op計算函數(shù)的基類,稱作Kernel。
? framework::OperatorWithKernel:繼承自O(shè)peratorBase,Op有計算函數(shù),稱作有Kernel。
? framework::OpProtoAndCheckerMaker:描述該Op的輸入、輸出、屬性、注釋,主要用于Python API接口生成。
根據(jù)是否包含Kernel,可以將Op分為兩種:包含Kernel的Op和不包含kernel的Op:
? 包含Kernel的Op繼承自O(shè)peratorWithKernel,這類Op的功能實現(xiàn)與輸入的數(shù)據(jù)類型、數(shù)據(jù)布局、數(shù)據(jù)所在的設(shè)備以及Op實現(xiàn)所調(diào)用第三方庫等有關(guān)。比如ConvOp,如果使用CPU計算,一般通過調(diào)用mkl庫中的矩陣乘操作實現(xiàn),如果使用GPU計算,一般通過調(diào)用cublas庫中的矩陣乘操作實現(xiàn),或者直接調(diào)用cudnn庫中的卷積操作。
? 不包含Kernel的Op繼承自O(shè)peratorBase,因為這類Op的功能實現(xiàn)與設(shè)備以及輸入的數(shù)據(jù)不相關(guān)。比如WhileOp、IfElseOp等。
本文主要介紹帶Kernel的Op如何寫,簡單總結(jié)Op需要包含的內(nèi)容如下:
實現(xiàn)新的op都添加至目錄paddle/fluid/operators下,文件命名以*_op.h(如有)、_op.cc 、_op.cu(如有)結(jié)尾。系統(tǒng)會根據(jù)文件名自動構(gòu)建op和其對應(yīng)的Python擴展。
下面以矩陣乘操作,即MulOp為例來介紹如何寫帶Kernel的Operator。
實現(xiàn)C++類
定義ProtoMaker類
矩陣乘法的公式:Out=X?YOut=X?Y, 可見該計算由兩個輸入,一個輸出組成。
首先定義ProtoMaker來描述該Op的輸入、輸出,并添加注釋:
class MulOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput(“X”, “(Tensor), The first input tensor of mul op.”);
AddInput(“Y”, “(Tensor), The second input tensor of mul op.”);
AddOutput(“Out”, “(Tensor), The output tensor of mul op.”);
AddAttr(“use_mkldnn”,
“(bool, default false) Only used in mkldnn kernel”)
.SetDefault(false);
AddAttr(
“x_num_col_dims”,
R"DOC((int, default 1), The mul_op can take tensors with more than two
dimensions as its inputs. If the input XXX is a tensor with more
than two dimensions, XXX will be flattened into a two-dimensional
matrix first. The flattening rule is: the first num_col_dims
will be flattened to form the first dimension of the final matrix
(the height of the matrix), and the rest rank(X) - num_col_dims
dimensions are flattened to form the second dimension of the final
matrix (the width of the matrix). As a result, height of the
flattened matrix is equal to the product of XXX‘s first
x_num_col_dims dimensions’ sizes, and width of the flattened
matrix is equal to the product of XXX‘s last rank(x) - num_col_dims
dimensions’ size. For example, suppose XXX is a 6-dimensional
tensor with the shape [2, 3, 4, 5, 6], and x_num_col_dims = 3.
Thus, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] =
[24, 30].
)DOC")
.SetDefault(1)
.EqualGreaterThan(1);
AddAttr(
“y_num_col_dims”,
R"DOC((int, default 1), The mul_op can take tensors with more than two,
dimensions as its inputs. If the input YYY is a tensor with more
than two dimensions, YYY will be flattened into a two-dimensional
matrix first. The attribute y_num_col_dims determines how YYY is
flattened. See comments of x_num_col_dims for more details.
)DOC")
.SetDefault(1)
.EqualGreaterThan(1);
AddAttr(
“scale_x”,
“scale_x to be used for int8 mul input data x. scale_x has the”
“same purpose as scale_in in OPs that support quantization.”
“Only to be used with MKL-DNN INT8”)
.SetDefault(1.0f);
AddAttr<std::vector>(
“scale_y”,
“scale_y to be used for int8 mul input data y. scale_y has the”
“same purpose as scale_weights in OPs that support quantization.”
“Only to be used with MKL-DNN INT8”)
.SetDefault({1.0f});
AddAttr(“scale_out”,
“scale_out to be used for int8 output data.”
“Only used with MKL-DNN INT8”)
.SetDefault(1.0f);
AddAttr(
“force_fp32_output”,
“(bool, default false) Force quantize kernel output FP32, only "
“used in quantized MKL-DNN.”)
.SetDefault(false);
AddComment(R"DOC(
Mul Operator.
This operator is used to perform matrix multiplication for input XXX and YYY.
The equation is:
Out=X?YOut = X * YOut=X?Y
Both the input XXX and YYY can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD information with input XXX.
)DOC”);
}
};
MulOpMaker繼承自framework::OpProtoAndCheckerMaker。
開發(fā)者通過覆蓋framework::OpProtoAndCheckerMaker中的Make函數(shù)來定義Op所對應(yīng)的Proto,通過AddInput添加輸入?yún)?shù),通過AddOutput添加輸出參數(shù),通過AddAttr添加屬性參數(shù),通過AddComment添加Op的注釋。這些函數(shù)會將對應(yīng)內(nèi)容添加到OpProto中。
上面的代碼在MulOp中添加兩個輸入X和Y,添加了一個輸出Out,以及use_mkldnn等屬性,并解釋了各自含義,命名請遵守命名規(guī)范。
定義GradOpMaker類
通常情況下,大部分Op只有一個對應(yīng)的反向Op,每個Op的會有一個對應(yīng)的GradOpMaker。為方便代碼編寫,paddle為只有一個反向的Op提供了一個模板類SingleGradOpMaker。MulOp的GradOpMaker需要繼承這個模板類,并在Apply()方法中設(shè)置反向Op的輸入、輸出和屬性。此外,paddle還提供了一個默認(rèn)的GradOpMaker, DefaultGradOpMaker,該模板類會使用前向Op的全部輸入(Input)輸出(Output)以及輸出變量所對應(yīng)的梯度(Output@Grad)作為反向Op的輸入,將前向Op的輸入變量所對應(yīng)的的梯度(Input@Grad)作為輸出。
注意: 不要將反向Op不會用到的變量放到反向Op的輸入列表中,這樣會導(dǎo)致這些不會被反向Op用到的變量的空間不能夠及時回收,進而有可能導(dǎo)致用到該Op的模型可以設(shè)置的batch_size較低。 比如relu操作的前向操作為:out.device(d) = x.cwiseMax(static_cast(0));反向操作為:dx.device(d) = dout * (out > static_cast(0)).template cast();。顯然,反向操作中只是用到了out、dout、dx,沒有用到x。因此,通常不建議使用默認(rèn)的DefaultGradOpMaker。
下面示例定義了MulOp的GradOpMaker。
template
class MulOpGradMaker : public framework::SingleGradOpMaker {
public:
using framework::SingleGradOpMaker::SingleGradOpMaker;
protected:
void Apply(GradOpPtr retv) const override {
retv->SetType(“mul_grad”);
retv->SetInput(“X”, this->Input(“X”));
retv->SetInput(“Y”, this->Input(“Y”));
retv->SetInput(framework::GradVarName(“Out”), this->OutputGrad(“Out”));
retv->SetOutput(framework::GradVarName(“X”), this->InputGrad(“X”));
retv->SetOutput(framework::GradVarName(“Y”), this->InputGrad(“Y”));
retv->SetAttrMap(this->Attrs());
}
};
注意:
? 有些Op的前向邏輯和反向邏輯是一樣的,比如ScaleOp.這種情況下,前向Op和反向Op的Kernel可以為同一個。
? 有些前向Op所對應(yīng)的反向Op可能有多個,比如SumOp,這種情況下,GradMaker需要繼承framework::GradOpDescMakerBase。
? 有些Op的反向?qū)?yīng)另一個Op的前向,比如SplitOp,這種情況下,SplitGradMaker中定義的SplitOp反向Op的Type就是concat,
? 為高效地同時支持命令式編程模式(動態(tài)圖)和聲明式編程模式(靜態(tài)圖),SingleGradOpMaker是一個模板類,在注冊O(shè)perator時需要同時注冊MulOpGradMaker(聲明式編程模式使用)和MulOpGradMaker(命令式編程模式使用)。
定義Operator類
下面實現(xiàn)了MulOp的定義:
class MulOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE_EQ(
ctx->HasInput(“X”), true,
platform::errors::NotFound(“Input(X) of MulOp should not be null.”));
PADDLE_ENFORCE_EQ(
ctx->HasInput(“Y”), true,
platform::errors::NotFound(“Input(Y) of MulOp should not be null.”));
PADDLE_ENFORCE_EQ(
ctx->HasOutput(“Out”), true,
platform::errors::NotFound(“Output(Out) of MulOp should not be null.”));
auto x_dims = ctx->GetInputDim("X");
auto y_dims = ctx->GetInputDim("Y");int x_num_col_dims = ctx->Attrs().Get<int>("x_num_col_dims");
int y_num_col_dims = ctx->Attrs().Get<int>("y_num_col_dims");VLOG(3) << "mul operator x.shape=" << x_dims << " y.shape=" << y_dims<< " x_num_col_dims=" << x_num_col_dims<< " y_num_col_dims=" << y_num_col_dims;PADDLE_ENFORCE_NE(framework::product(y_dims), 0,platform::errors::PreconditionNotMet("The Input variable Y(%s) has not ""been initialized. You may need to confirm ""if you put exe.run(startup_program) ""after optimizer.minimize function.",ctx->Inputs("Y").front()));
PADDLE_ENFORCE_GT(x_dims.size(), x_num_col_dims,platform::errors::InvalidArgument("The input tensor X's dimensions of MulOp ""should be larger than x_num_col_dims. But received X's ""dimensions = %d, X's shape = [%s], x_num_col_dims = %d.",x_dims.size(), x_dims, x_num_col_dims));
PADDLE_ENFORCE_GT(y_dims.size(), y_num_col_dims,platform::errors::InvalidArgument("The input tensor Y's dimensions of MulOp ""should be larger than y_num_col_dims. But received Y's ""dimensions = %d, Y's shape = [%s], y_num_col_dims = %d.",y_dims.size(), y_dims, y_num_col_dims));auto x_mat_dims = framework::flatten_to_2d(x_dims, x_num_col_dims);
auto y_mat_dims = framework::flatten_to_2d(y_dims, y_num_col_dims);PADDLE_ENFORCE_EQ(x_mat_dims[1], y_mat_dims[0],platform::errors::InvalidArgument("After flatten the input tensor X and Y to 2-D dimensions ""matrix X1 and Y1, the matrix X1's width must be equal with matrix ""Y1's height. But received X's shape = [%s], X1's shape = [%s], ""X1's ""width = %s; Y's shape = [%s], Y1's shape = [%s], Y1's height = ""%s.",x_dims, x_mat_dims, x_mat_dims[1], y_dims, y_mat_dims,y_mat_dims[0]));
std::vector<int64_t> output_dims;
output_dims.reserve(static_cast<size_t>(x_num_col_dims + y_dims.size() - y_num_col_dims));for (int i = 0; i < x_num_col_dims; ++i) {output_dims.push_back(x_dims[i]);
}for (int i = y_num_col_dims; i < y_dims.size(); ++i) {output_dims.push_back(y_dims[i]);
}ctx->SetOutputDim("Out", framework::make_ddim(output_dims));
ctx->ShareLoD("X", /*->*/ "Out");
}
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const {
framework::LibraryType library = framework::LibraryType::kPlain;
framework::DataLayout layout = framework::DataLayout::kAnyLayout;
int customized_type_value =
framework::OpKernelType::kDefaultCustomizedTypeValue;
auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, “X”);
#ifdef PADDLE_WITH_MKLDNN
if (library == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library = framework::LibraryType::kMKLDNN;
layout = framework::DataLayout::kMKLDNN;
if (input_data_type == framework::DataTypeTrait<int8_t>::DataType() ||input_data_type == framework::DataTypeTrait<uint8_t>::DataType()) {customized_type_value = kMULMKLDNNINT8;}
}
#endif
return framework::OpKernelType(input_data_type, ctx.GetPlace(), layout,library, customized_type_value);
}
};
MulOp繼承自O(shè)peratorWithKernel。public成員:
using framework::OperatorWithKernel::OperatorWithKernel;
這句表示使用基類OperatorWithKernel的構(gòu)造函數(shù),也可寫成:
MulOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
此外,Operator類通常需要重寫InferShape接口,并在有必要時重寫GetExpectedKernelType接口。InferShape為const函數(shù),不能修改Op的成員變量,參數(shù)為framework::InferShapeContext* ctx,通過該參數(shù)可獲取到輸入輸出以及屬性。它的功能是:
? 做檢查, 盡早報錯:檢查輸入數(shù)據(jù)維度、類型等是否合法。
? 設(shè)置輸出Tensor的形狀以及LoD信息。
GetExpectedKernelType接口OperatorWithKernel類中用于獲取指定設(shè)備(例如CPU,GPU)上指定數(shù)據(jù)類型(例如double,float)的OpKernel的方法。該方法的重寫可見請參考寫C++ OP相關(guān)注意事項。
通常OpProtoMaker和Op類的定義寫在.cc文件中,和下面將要介紹的注冊函數(shù)一起放在.cc中
InferShape區(qū)分 compile time 和 run time
在我們的聲明式編程模式網(wǎng)絡(luò)中,InferShape操作在編譯時(compile time)和運行時(run time)都會被調(diào)用,在compile time時,由于真實的維度未知,框架內(nèi)部用-1來表示,在run time時,用實際的維度表示,因此維度的值在compile time和 run time時可能不一致,如果存在維度的判斷和運算操作,InferShape就需要區(qū)分compile time 和 run time。
以下兩種情況需要區(qū)分compile time和 run time。
1.檢查
如以下代碼:
auto x_dim = ctx->GetInputDim(“X”);
int i = xxx;
PADDLE_ENFORCE_GT( x_dim[i] , 10)
在compile time的時候,x_dim[i]可能等于-1,導(dǎo)致這個PADDLE_ENFORCE_GT報錯退出。
如果用了以下paddle中定義的宏進行判斷:
PADDLE_ENFORCE_EQ ( x_dim[i] , 10)
PADDLE_ENFORCE_NE ( x_dim[i] , 10)
PADDLE_ENFORCE_GT ( x_dim[i] , 10)
PADDLE_ENFORCE_GE ( x_dim[i] , 10)
PADDLE_ENFORCE_LT ( x_dim[i] , 10)
PADDLE_ENFORCE_LE ( x_dim[i] , 10)
都需要區(qū)分compile time和run time
2. 運算
如以下代碼:
auto x_dim = ctx->GetInputDim(“X”);
int i = xxx;
y_dim[0] = x_dim[i] + 10
在compile time的時候,x_dim[i]可能等于-1,得到的 y_dim[0] 等于 9,是不符合邏輯的
如果用到了類似以下的運算操作
y_dim[i] = x_dim[i] + 10
y_dim[i] = x_dim[i] - 10
y_dim[i] = x_dim[i] * 10
y_dim[i] = x_dim[i] / 10
y_dim[i] = x_dim[i] + z_dim[i]
都需要區(qū)分compile time和run time
處理的標(biāo)準(zhǔn):
? 檢查: compile time的時候不判斷維度等于-1的情況,但在runtime的時候檢查
? 運算: -1和其他數(shù)做任何運算都要等于-1
參考代碼
-
判斷的實現(xiàn)方法可以參考cross_entropy_op,cross_entropy_op 要求X和labels的兩個輸入,除了最后一維以外,其他的維度完全一致
bool contain_unknown_dim = framework::contain_unknown_dim(x_dims) ||
framework::contain_unknown_dim(label_dims);
bool check = ctx->IsRuntime() || !contain_unknown_dim;
if (check) {
PADDLE_ENFORCE_EQ(framework::slice_ddim(x_dims, 0, rank - 1),
framework::slice_ddim(label_dims, 0, rank - 1),
"Input(X) and Input(Label) shall have the same shape "
“except the last dimension.”);
} -
運算的實現(xiàn)可以參考concat_op,concat在InferShape判斷時,調(diào)用ComputeAndCheckShape,除了進行concat軸之外,其他的維度完全一致;在生成output的維度時,把concat軸的維度求和,其他的維度和輸入保持一致。
const size_t n = inputs_dims.size();
auto out_dims = inputs_dims[0];
size_t in_zero_dims_size = out_dims.size();
for (size_t i = 1; i < n; i++) {
for (size_t j = 0; j < in_zero_dims_size; j++) {
if (j == axis) {
if (is_runtime) {
out_dims[axis] += inputs_dims[i][j];
} else {
if (inputs_dims[i][j] == -1) {
out_dims[axis] = -1;
} else {
out_dims[axis] += inputs_dims[i][j];
}
}
} else {
bool check_shape =
is_runtime || (out_dims[j] > 0 && inputs_dims[i][j] > 0);
if (check_shape) {
// check all shape in run time
PADDLE_ENFORCE_EQ(
inputs_dims[0][j], inputs_dims[i][j],
"ShapeError: Dimension %d in inputs’ shapes must be equal. "
"But recevied input[0]'s shape = "
“[%s], input[%d]'s shape = [%s].”,
j, inputs_dims[0], i, inputs_dims[i]);
}
}
}
}
定義OpKernel類
MulKernel繼承自framework::OpKernel,帶有下面兩個模板參數(shù):
? typename DeviceContext: 表示設(shè)備類型。不同設(shè)備(CPU、CUDA)共享同一個Kernel時,需加該模板參數(shù);不共享則不加,一個不共享的例子是SGDOpKernel。
? typename T : 表示數(shù)據(jù)類型,如float, double, int16等。
需要為MulKernel類重寫Compute接口。
? Compute接受一個輸入?yún)?shù):const framework::ExecutionContext& context。
? 與InferShapeContext相比,ExecutionContext增加了設(shè)備類型,同樣可獲取到輸入輸出和屬性參數(shù)。
? Compute函數(shù)里實現(xiàn)OpKernel的具體計算邏輯。
Op的輸入和輸出可分別通過ExecutionContext::Input()和ExecutionContext::Output()獲得。
注意: 若op的輸入/輸出的變量類型是LoDTensor(paddle默認(rèn)所有的Tensor默認(rèn)都是LoDTensor類型),請寫成ExecutionContext::Input()和ExecutionContext::Output(),不要寫ExecutionContext::Input()和ExecutionContext::Output()。因為若實際的變量類型為SelectedRows,Input()和Output()方法會將SelectedRows類型特化為Tensor,導(dǎo)致潛在的錯誤。
下面是 MulKernel Compute的實現(xiàn):
template <typename DeviceContext, typename T>
class MulKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& context) const override {
const Tensor* x = context.Input(“X”);
const Tensor* y = context.Input(“Y”);
Tensor* z = context.Output(“Out”);
const Tensor x_matrix =
x->dims().size() > 2
? framework::ReshapeToMatrix(
*x, context.template Attr(“x_num_col_dims”))
: *x;
const Tensor y_matrix =
y->dims().size() > 2
? framework::ReshapeToMatrix(
*y, context.template Attr(“y_num_col_dims”))
: *y;z->mutable_data(context.GetPlace());
auto z_dim = z->dims();
if (z_dim.size() != 2) {
z->Resize({x_matrix.dims()[0], y_matrix.dims()[1]});
}auto blas = math::GetBlas<DeviceContext, T>(context);
blas.MatMul(x_matrix, y_matrix, z);
if (z_dim.size() != 2) {
z->Resize(z_dim);
}
}
};
需要注意:不同設(shè)備(CPU、CUDA)共享一個Op定義,是否則共享同一個OpKernel,取決于Compute調(diào)用的函數(shù)是否支持不同設(shè)備。
MulOp的CPU、CUDA實現(xiàn)共享同一個Kernel。OpKernel不共享的例子可以參考:SGDOpKernel。
為了使OpKernel的計算過程書寫更加簡單,并且CPU、CUDA的代碼可以復(fù)用,我們通常借助 Eigen unsupported Tensor模塊來實現(xiàn)Compute接口。關(guān)于在PaddlePaddle中如何使用Eigen庫,請參考使用文檔。
到此,前向Op實現(xiàn)完成。接下來,需要在.cc文件中注冊該op和kernel。 反向Op類的定義,反向OpKernel的定義與前向Op類似,這里不再贅述。
注冊O(shè)perator
? 在.cc文件中注冊前向、反向Op類,注冊CPU Kernel。
? namespace ops = paddle::operators;
? REGISTER_OPERATOR(mul, ops::MulOp, ops::MulOpMaker, ops::MulOpInferVarType,
? ops::MulOpGradMakerpaddle::framework::OpDesc,
? ops::MulOpGradMakerpaddle::imperative::OpBase);
?
? REGISTER_OPERATOR(mul_grad, ops::MulGradOp);
?
? REGISTER_OP_CPU_KERNEL(mul,
? ops::MulKernel<paddle::platform::CPUDeviceContext, float>,
? ops::MulKernel<paddle::platform::CPUDeviceContext, double>);
? REGISTER_OP_CPU_KERNEL(mul_grad,
? ops::MulGradKernel<paddle::platform::CPUDeviceContext, float>,
? ops::MulGradKernel<paddle::platform::CPUDeviceContext, double>);
在上面的代碼中,使用REGISTER_OPERATOR注冊了ops::MulOp類,類型名為mul,該類的ProtoMaker為ops::MulOpMaker,其GradOpMaker分別是ops::MulOpGradMakerpaddle::framework::OpDesc(聲明式編程模式使用)和ops::MulOpGradMakerpaddle::imperative::OpBase(命令式編程模式使用),并使用REGISTER_OPERATOR注冊ops::MulGradOp,類型名為mul_grad。然后,使用REGISTER_OP_CPU_KERNEL注冊了ops::MulKernel類,并特化模板參數(shù)為設(shè)備為paddle::platform::CPUPlace、數(shù)據(jù)類型為float類型和double類型;同理,注冊ops::MulGradKernel類。
? 在 .cu文件中注冊CUDA Kernel。
o 請注意,如果CUDA Kernel的實現(xiàn)基于Eigen unsupported模塊,那么在 .cu的開始請加上宏定義 #define EIGEN_USE_GPU,代碼示例如下:
? // if use Eigen unsupported module before include head files
? #define EIGEN_USE_GPU
?
? namespace ops = paddle::operators;
? REGISTER_OP_CUDA_KERNEL(mul,
? ops::MulKernel<paddle::platform::CUDADeviceContext, float>,
? ops::MulKernel<paddle::platform::CUDADeviceContext, double>);
? REGISTER_OP_CUDA_KERNEL(mul_grad,
? ops::MulGradKernel<paddle::platform::CUDADeviceContext, float>,
? ops::MulGradKernel<paddle::platform::CUDADeviceContext, double>);
注意:
在運行Op時,框架系統(tǒng)會根據(jù)輸入數(shù)據(jù)所在的設(shè)備、輸入數(shù)據(jù)的類型等信息自動的選擇合適的OpKernel,比如輸入的數(shù)據(jù)是在GPU上,并且為float類型,框架系統(tǒng)會選擇由REGISTER_OP_CUDA_KERNEL注冊的ops::MulKernel<paddle::platform::CUDADeviceContext, float>。如果用戶希望指定運行時可被調(diào)用的OpKernel,用戶需要覆蓋framework::OperatorWithKernel中的GetExpectedKernelType函數(shù),比如MulOp會根據(jù)屬性use_mkldnn為false還是為true決定是否調(diào)用mkldnn庫來完成計算。
編譯
詳細的編譯環(huán)境準(zhǔn)備和執(zhí)行流程可參考從源碼編譯,下面簡單介紹幾個主要步驟。 在Paddle代碼目錄下創(chuàng)建并切換到build目錄:
mkdir build && cd build
執(zhí)行cmake命令,具體選項可參考從源碼編譯中的介紹,下面的命令為編譯Python3.5,GPU版本,帶測試,Release版本的Paddle。
cmake … -DPY_VERSION=3.5 -DWITH_GPU=ON -DWITH_TESTING=ON -DCMAKE_BUILD_TYPE=Release
在build目錄下,運行下面命令可以進行編譯整個paddle:
make -j$(nproc)
注意: 新增op后請重新執(zhí)行cmake命令,然后再執(zhí)行make命令編譯paddle。
綁定Python
系統(tǒng)會對新增的op自動綁定Python,并鏈接到生成的lib庫中。
使用mul操作在Python端構(gòu)建Layer
在Python端,mul操作用于構(gòu)建FC層,即:
Out=Act(X?W+b)Out=Act(X?W+b)
具體實現(xiàn)方式可參考FC層的實現(xiàn)代碼。
實現(xiàn)單元測試
單測包括對比前向Op不同設(shè)備(CPU、CUDA)的實現(xiàn)、對比反向OP不同設(shè)備(CPU、CUDA)的實現(xiàn)、反向Op的梯度測試。下面介紹介紹MulOp的單元測試。
注意:
單測中的測試用例需要盡可能的覆蓋Op中的所有分支。
前向Operator單測
Op單元測試?yán)^承自O(shè)pTest。各項具體的單元測試在TestMulOp里完成。測試Operator,需要: -
在setUp函數(shù)定義輸入、輸出,以及相關(guān)的屬性參數(shù)。
注意:輸入輸出請以ndarray的類型配置輸入/輸出,如果需要配置一個帶LOD的輸入/輸出,請以tuple的形式傳入,tuple中應(yīng)該有兩個類型為ndarray的元素,第一個是實際的數(shù)據(jù),第二個是LOD -
生成隨機的輸入數(shù)據(jù)。
-
在Python腳本中實現(xiàn)與前向operator相同的計算邏輯,得到輸出值,與operator前向計算的輸出進行對比。
-
反向計算已經(jīng)自動集成進測試框架,直接調(diào)用相應(yīng)接口即可。
-
import unittest
-
import numpy as np
-
from op_test import OpTest
-
class TestMulOp(OpTest):
-
def setUp(self): -
self.op_type = "mul" -
self.inputs = { -
'X': np.random.random((32, 84)).astype("float32"), -
'Y': np.random.random((84, 100)).astype("float32") -
} -
self.outputs = {'Out': np.dot(self.inputs['X'], self.inputs['Y'])} -
def test_check_output(self): -
self.check_output() -
def test_check_grad_normal(self): -
self.check_grad(['X', 'Y'], 'Out', max_relative_error=0.5) -
def test_check_grad_ingore_x(self): -
self.check_grad( -
['Y'], 'Out', max_relative_error=0.5, no_grad_set=set("X")) -
def test_check_grad_ingore_y(self): -
self.check_grad( -
['X'], 'Out', max_relative_error=0.5, no_grad_set=set('Y'))
上面的代碼首先導(dǎo)入依賴的包,下面是對setUp函數(shù)中操作的重要變量的詳細解釋:
o self.op_type = “mul” : 定義類型,與operator注冊時注冊的類型一致。
o self.inputs : 定義輸入,類型為numpy.array,并初始化。
o self.outputs : 定義輸出,并在Python腳本中完成與operator同樣的計算邏輯,返回Python端的計算結(jié)果。
反向operator單測
而反向測試中:
? test_check_grad_normal中調(diào)用check_grad使用數(shù)值法檢測梯度正確性和穩(wěn)定性。
o 第一個參數(shù)[“X”, “Y”] : 指定對輸入變量X、Y做梯度檢測。
o 第二個參數(shù)"Out" : 指定前向網(wǎng)絡(luò)最終的輸出目標(biāo)變量Out。
o 第三個參數(shù)max_relative_error:指定檢測梯度時能容忍的最大錯誤值。
? test_check_grad_ingore_x和test_check_grad_ingore_y分支用來測試只需要計算一個輸入梯度的情況。
編譯和執(zhí)行
python/paddle/fluid/tests/unittests/ 目錄下新增的 test_.py 單元測試會被自動加入工程進行編譯。
請注意,運行單元測試測時需要編譯整個工程,并且編譯時需要打開WITH_TESTING。
參考上述編譯過程,編譯成功后,在build目錄下執(zhí)行下面的命令來運行單元測試:
make test ARGS="-R test_mul_op -V"
或者執(zhí)行:
ctest -R test_mul_op
注意事項
? 注冊O(shè)p時的類型名,需要和該Op的名字一樣。即不允許在A_op.cc里面,注冊REGISTER_OPERATOR(B, …)等,這將會導(dǎo)致單元測試出錯。
? 如果Op沒有實現(xiàn)CUDA Kernel,請不要創(chuàng)建空的_op.cu,這將會導(dǎo)致單元測試出錯。
? 如果多個Op依賴一些共用的函數(shù),可以創(chuàng)建非*_op.*格式的文件來存放,如gather.h文件。
PADDLE_ENFORCE使用注意
實現(xiàn)Op時檢查數(shù)據(jù)的合法性需要使用PADDLE_ENFORCE以及PADDLE_ENFORCE_EQ等宏定義,基本格式如下:
PADDLE_ENFORCE(表達式, 錯誤提示信息)
PADDLE_ENFORCE_EQ(比較對象A, 比較對象B, 錯誤提示信息)
如果表達式為真,或者比較對象A=B,則檢查通過,否則會終止程序運行,向用戶反饋相應(yīng)的錯誤提示信息。 為了確保提示友好易懂,開發(fā)者需要注意其使用方法。
總體原則
任何使用了PADDLE_ENFORCE與PADDLE_ENFORCE_XX檢查的地方,必須有詳略得當(dāng)?shù)膫渥⒔忉?#xff01;錯誤提示信息不能為空!
提示信息書寫標(biāo)準(zhǔn)
- [required] 哪里錯了?為什么錯了?
o 例如:ValueError: Mismatched label shape - [optional] 期望的輸入是什么樣的?實際的輸入是怎樣的?
o 例如:Expected labels dimension=1. Received 4. - [optional] 能否給出修改意見?
o 例如:Suggested Fix:If your classifier expects one-hot encoding label,check your n_classes argument to the estimatorand/or the shape of your label.Otherwise, check the shape of your label.
如果并非必要或者簡潔的描述即可表達清楚以上要點,根據(jù)情況書寫亦可。
FAQ 典型問題 - 無報錯信息或報錯信息過于簡單,不能給用戶提供有效的提示!
問題示例1 :未寫提示信息
PADDLE_ENFORCE(ctx->HasInput(“X”), “”);
問題示例2 :提示信息過于簡單
PADDLE_ENFORCE(i != nullptr, “i must be set”); // i是什么? - 在報錯信息中使用開發(fā)人員定義的變量縮寫,不易理解!
問題示例:
PADDLE_ENFORCE(forward_pd != nullptr,
“Fail to find eltwise_fwd_pd in device context”); //eltwise_fwd_pd用戶可能看不懂 - OP內(nèi)部調(diào)用非法接口:Op內(nèi)部如果出現(xiàn)Output = ShareDataWith(Input) 問題示例:
- auto *out = ctx.Outputframework::LoDTensor(“Out”);
- auto *in = ctx.Inputframework::LoDTensor(“X”);
- out->ShareDataWith(*in);
Op內(nèi)部如果出現(xiàn)Output = ShareDataWith(Input),相當(dāng)于operator圖的中有一條隱藏邊,連接了Input和Output,這條邊無法在圖分析中表達,引發(fā)基于圖優(yōu)化的錯誤。 - OP實現(xiàn)的性能實踐 調(diào)用了eigen的broadcast, chop等操作,性能會比手寫cuda kernel差幾倍以上。此時cpu的實現(xiàn)可以復(fù)用eigen,gpu實現(xiàn)可以實現(xiàn)cuda kernel.
OP InferShape檢查提示信息特別說明
? 檢查輸入輸出變量,統(tǒng)一遵循以下格式 Input(變量名) of OP名 operator should not be null.
正確示例:
PADDLE_ENFORCE(ctx->HasInput(“Input”),
“Input(Input) of LSTMP operator should not be null.”);
? 反向Op的輸入輸出檢查,要寫明反向Op的名字
正確示例:
PADDLE_ENFORCE(ctx->HasInput(“X”),
“Input(X) of LoDResetGrad opreator should not be null.”);
總結(jié)
以上是生活随笔為你收集整理的如何写新的C++ OP的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 模型压缩
- 下一篇: C++ OP相关注意事项