Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【PaddlePaddle Hackathon 2】11新增 API index_fill #42454

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions paddle/fluid/operators/index_fill_op.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/* Copyright (c) 2022 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 <memory>
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/unary.h"

namespace paddle {
namespace operators {

class IndexFillOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;

framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
}
};

class IndexFillOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"(Tensor, default input Tensor<float>), "
iclementine marked this conversation as resolved.
Show resolved Hide resolved
"the input feature data of IndexFillOp, dtype should be"
"bool, int32, int64, float16, float32, float64.");
AddInput("IndexTensor",
"(Tensor, optional) If provided, index fill will use this."
"It has the highest priority of IndexTensor and attr(index).")
.AsDispensable();
AddInput("AxisTensor",
"(Tensor) If provided, use this as "
"axis, this has a higher priority than "
"attr(axis), the shape of this tensor MUST BE 1.")
.AsDispensable();
AddAttr<std::vector<int>>(
"index",
"(list<int>) Starting indices of corresponding axis in `axes`");
AddAttr<int>("axis", "(int), the dimension in which we index.");
AddAttr<float>("fill_value", "(float) The value to be filled.");
AddOutput("Out",
"(Tensor, default Tensor<float>),"
iclementine marked this conversation as resolved.
Show resolved Hide resolved
" the output of IndexFillOp, whose dtype is the same as X.");
AddComment(R"DOC(
IndexFill operator
Fills the elements of the input tensor with value
by selecting the indices in the order given in index.

This operator also supports inplace modification.
)DOC");
}
};

template <typename T>
class IndexFillGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

void Apply(GradOpPtr<T> op) const override {
op->SetType("index_fill_grad");
if (this->HasInput("AxisTensor")) {
op->SetInput("AxisTensor", this->Input("AxisTensor"));
}
if (this->HasInput("IndexTensor")) {
op->SetInput("IndexTensor", this->Input("IndexTensor"));
}
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetAttrMap(this->Attrs());
}
};

class IndexFillGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;

protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out")),
ctx.GetPlace());
}
};

DECLARE_INPLACE_OP_INFERER(IndexFillInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(IndexFillGradInplaceInferer,
{framework::GradVarName("Out"),
framework::GradVarName("X")});

} // namespace operators
} // namespace paddle

namespace ops = paddle::operators;
DECLARE_INFER_SHAPE_FUNCTOR(index_fill, IndexFillInferShapeFunctor,
PD_INFER_META(phi::IndexFillInferMeta));

REGISTER_OPERATOR(index_fill, ops::IndexFillOp, ops::IndexFillOpMaker,
ops::IndexFillGradMaker<paddle::framework::OpDesc>,
ops::IndexFillGradMaker<paddle::imperative::OpBase>,
ops::IndexFillInplaceInferer, IndexFillInferShapeFunctor);

DECLARE_INFER_SHAPE_FUNCTOR(index_fill_grad, IndexFillGradInferShapeFunctor,
PD_INFER_META(phi::IndexFillGradInferMeta));

REGISTER_OPERATOR(index_fill_grad, ops::IndexFillGradOp,
ops::IndexFillGradInplaceInferer,
IndexFillGradInferShapeFunctor);
133 changes: 133 additions & 0 deletions paddle/fluid/operators/index_fill_tensor_op.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/* Copyright (c) 2022 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 <memory>
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/binary.h"

namespace paddle {
namespace operators {

class IndexFillTensorOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;

framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
}
};

class IndexFillTensorOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"(Tensor), "
"the input feature data of IndexFillTensorOp, dtype should be"
"bool, int32, int64, float16, float32, float64.");
AddInput("FillValue",
"(Tensor>), "
"the input tensor of IndexFillTensorOp, dtype should be"
"the same as input tensor X");
AddInput("IndexTensor",
"(Tensor, optional) If provided, index fill will use this."
"It has the highest priority of IndexTensor and attr(index).")
.AsDispensable();
AddInput("AxisTensor",
"(Tensor) If provided, use this as "
"axis, this has a higher priority than "
"attr(axis), the shape of this tensor MUST BE 1.")
.AsDispensable();
AddAttr<std::vector<int>>(
"index",
"(list<int>) Starting indices of corresponding axis in `axes`");
AddAttr<int>("axis", "(int), the dimension in which we index.");
AddOutput(
"Out",
"(Tensor, default Tensor<float>),"
" the output of IndexFillTensorOp, whose dtype is the same as X.");
AddComment(R"DOC(
IndexFillTensor operator
Fills the elements of the input tensor with value
by selecting the indices in the order given in index.

This operator also supports inplace modification.
)DOC");
}
};

template <typename T>
class IndexFillTensorGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

void Apply(GradOpPtr<T> op) const override {
op->SetType("index_fill_tensor_grad");
if (this->HasInput("AxisTensor")) {
op->SetInput("AxisTensor", this->Input("AxisTensor"));
}
if (this->HasInput("IndexTensor")) {
op->SetInput("IndexTensor", this->Input("IndexTensor"));
}
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetOutput(framework::GradVarName("FillValue"),
this->InputGrad("FillValue"));
op->SetAttrMap(this->Attrs());
}
};

class IndexFillTensorGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;

protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out")),
ctx.GetPlace());
}
};

DECLARE_INPLACE_OP_INFERER(IndexFillTensorInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(IndexFillTensorGradInplaceInferer,
{framework::GradVarName("Out"),
framework::GradVarName("X")});

} // namespace operators
} // namespace paddle

namespace ops = paddle::operators;
DECLARE_INFER_SHAPE_FUNCTOR(index_fill_tensor, IndexFillTensorInferShapeFunctor,
PD_INFER_META(phi::IndexFillTensorInferMeta));

REGISTER_OPERATOR(index_fill_tensor, ops::IndexFillTensorOp,
ops::IndexFillTensorOpMaker,
ops::IndexFillTensorGradMaker<paddle::framework::OpDesc>,
ops::IndexFillTensorGradMaker<paddle::imperative::OpBase>,
ops::IndexFillTensorInplaceInferer,
IndexFillTensorInferShapeFunctor);

DECLARE_INFER_SHAPE_FUNCTOR(index_fill_tensor_grad,
IndexFillTensorGradInferShapeFunctor,
PD_INFER_META(phi::IndexFillTensorGradInferMeta));

REGISTER_OPERATOR(index_fill_tensor_grad, ops::IndexFillTensorGradOp,
ops::IndexFillTensorGradInplaceInferer,
IndexFillTensorGradInferShapeFunctor);
55 changes: 55 additions & 0 deletions paddle/phi/infermeta/binary.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,61 @@ void HuberLossInferMeta(const MetaTensor& input,
out->share_lod(input);
}

void IndexFillTensorInferMeta(const MetaTensor& x,
const MetaTensor& fill_tensor,
const IntArray& index_arr,
const Scalar& axis_scalar,
MetaTensor* output) {
auto input_dim = x.dims();
auto index = index_arr.GetData();
auto axis = axis_scalar.to<int>();

PADDLE_ENFORCE_EQ(
fill_tensor.dtype() == x.dtype(),
true,
phi::errors::InvalidArgument(
"The dtype of fill_tensor should be same as input tensor."));

PADDLE_ENFORCE_EQ(
axis < input_dim.size() && axis >= (0 - input_dim.size()),
true,
phi::errors::OutOfRange(
"Axis is out of range, It's expected "
"to be in range of [-%d, %d). But received Attr(dim) = %d.",
input_dim.size(),
input_dim.size() - 1,
axis));

PADDLE_ENFORCE_EQ(
index.size() > 0,
true,
phi::errors::InvalidArgument("The index array should not be empty."));

output->set_dims(x.dims());
output->set_dtype(x.dtype());
output->set_layout(x.layout());
output->share_lod(x);
}

void IndexFillTensorGradInferMeta(const MetaTensor& out_grad,
const IntArray& index_arr,
const Scalar& axis_scalar,
MetaTensor* x_grad,
MetaTensor* fill_tensor_grad) {
auto do_dims = out_grad.dims();
if (x_grad) {
x_grad->set_dims(do_dims);
x_grad->set_dtype(out_grad.dtype());
x_grad->set_layout(out_grad.layout());
x_grad->share_lod(out_grad);
}

if (fill_tensor_grad) {
fill_tensor_grad->set_dims(phi::make_ddim({1}));
fill_tensor_grad->set_dtype(out_grad.dtype());
}
}

void IndexSampleInferMeta(const MetaTensor& x,
const MetaTensor& y,
MetaTensor* out,
Expand Down
13 changes: 13 additions & 0 deletions paddle/phi/infermeta/binary.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ limitations under the License. */

#pragma once

#include "paddle/phi/common/int_array.h"
#include "paddle/phi/common/scalar.h"
#include "paddle/phi/core/meta_tensor.h"

Expand Down Expand Up @@ -184,6 +185,18 @@ void HuberLossInferMeta(const MetaTensor& input_meta,
MetaTensor* residual,
MetaConfig config = MetaConfig());

void IndexFillTensorInferMeta(const MetaTensor& x,
const MetaTensor& fill_tensor,
const IntArray& index_arr,
const Scalar& axis_scalar,
MetaTensor* output);

void IndexFillTensorGradInferMeta(const MetaTensor& out_grad,
const IntArray& index_arr,
const Scalar& axis_scalar,
MetaTensor* x_grad,
MetaTensor* fill_tensor_grad);

void IndexSampleInferMeta(const MetaTensor& x,
const MetaTensor& y,
MetaTensor* out,
Expand Down
42 changes: 42 additions & 0 deletions paddle/phi/infermeta/unary.cc
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,48 @@ void IncrementInferMeta(const MetaTensor& x, float value, MetaTensor* out) {
out->set_dtype(x.dtype());
}

void IndexFillInferMeta(const MetaTensor& x,
const IntArray& index_arr,
const Scalar& axis_scalar,
float fill_value,
MetaTensor* output) {
auto input_dim = x.dims();
auto index = index_arr.GetData();
auto axis = axis_scalar.to<int>();

PADDLE_ENFORCE_EQ(
axis < input_dim.size() && axis >= (0 - input_dim.size()),
true,
phi::errors::OutOfRange(
"Axis is out of range, It's expected "
"to be in range of [-%d, %d). But received Attr(dim) = %d.",
input_dim.size(),
input_dim.size() - 1,
axis));

PADDLE_ENFORCE_EQ(
index.size() > 0,
true,
phi::errors::InvalidArgument("The index array should not be empty."));

output->set_dims(x.dims());
output->set_dtype(x.dtype());
output->set_layout(x.layout());
output->share_lod(x);
}

void IndexFillGradInferMeta(const MetaTensor& out_grad,
const IntArray& index_arr,
const Scalar& axis_scalar,
float fill_value,
MetaTensor* x_grad) {
auto do_dims = out_grad.dims();
x_grad->set_dims(do_dims);
x_grad->set_dtype(out_grad.dtype());
x_grad->set_layout(out_grad.layout());
x_grad->share_lod(out_grad);
}

static phi::DDim ValidateShape(const std::vector<int64_t> shape,
const phi::DDim& in_dims) {
const int64_t in_size = phi::product(in_dims);
Expand Down
Loading