|
| 1 | +/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. |
| 2 | +
|
| 3 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + you may not use this file except in compliance with the License. |
| 5 | + You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | + Unless required by applicable law or agreed to in writing, software |
| 10 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + See the License for the specific language governing permissions and |
| 13 | + limitations under the License. */ |
| 14 | + |
| 15 | +#include "paddle/framework/op_registry.h" |
| 16 | +#include "paddle/framework/operator.h" |
| 17 | + |
| 18 | +namespace paddle { |
| 19 | +namespace operators { |
| 20 | + |
| 21 | +constexpr char kInput[] = "X"; |
| 22 | +constexpr char kOutput[] = "Out"; |
| 23 | + |
| 24 | +class IsEmptyOp : public framework::OperatorBase { |
| 25 | + public: |
| 26 | + IsEmptyOp(const std::string &type, const framework::VariableNameMap &inputs, |
| 27 | + const framework::VariableNameMap &outputs, |
| 28 | + const framework::AttributeMap &attrs) |
| 29 | + : OperatorBase(type, inputs, outputs, attrs) {} |
| 30 | + |
| 31 | + void Run(const framework::Scope &scope, |
| 32 | + const platform::DeviceContext &dev_ctx) const override { |
| 33 | + // get input |
| 34 | + auto *var = scope.FindVar(Input(kInput)); |
| 35 | + PADDLE_ENFORCE_NOT_NULL(var); |
| 36 | + auto &tensor = var->Get<framework::LoDTensor>(); |
| 37 | + // get output |
| 38 | + auto *out = scope.FindVar(Output(kOutput)); |
| 39 | + PADDLE_ENFORCE_NOT_NULL(out); |
| 40 | + auto *out_tensor = out->GetMutable<framework::LoDTensor>(); |
| 41 | + |
| 42 | + out_tensor->Resize({1}); |
| 43 | + out_tensor->mutable_data<bool>(platform::CPUPlace())[0] = |
| 44 | + framework::product(tensor.dims()) == 0; |
| 45 | + } |
| 46 | +}; |
| 47 | + |
| 48 | +class IsEmptyOpProtoMaker : public framework::OpProtoAndCheckerMaker { |
| 49 | + public: |
| 50 | + IsEmptyOpProtoMaker(framework::OpProto *proto, |
| 51 | + framework::OpAttrChecker *op_checker) |
| 52 | + : OpProtoAndCheckerMaker(proto, op_checker) { |
| 53 | + AddInput(kInput, "(Tensor) Tensor which is to be checked."); |
| 54 | + AddOutput(kOutput, "(Tensor) a boolean Tensor that indicate empty or not."); |
| 55 | + AddComment(R"DOC( |
| 56 | +IsEmpty Operator which checks whether a tensor is empty. |
| 57 | +
|
| 58 | +It will just return product(tensor.ddims()) > 0; |
| 59 | + )DOC"); |
| 60 | + } |
| 61 | +}; |
| 62 | + |
| 63 | +} // namespace operators |
| 64 | +} // namespace paddle |
| 65 | + |
| 66 | +REGISTER_OP_WITHOUT_GRADIENT(is_empty, paddle::operators::IsEmptyOp, |
| 67 | + paddle::operators::IsEmptyOpProtoMaker); |
0 commit comments