diag_embed_op.cc 5.0 KB
Newer Older
L
Li Fuchen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Copyright (c) 2020 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/fluid/operators/diag_embed_op.h"

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE_EQ(
26 27
        ctx->HasInput("Input"),
        true,
L
Li Fuchen 已提交
28 29 30
        platform::errors::NotFound("Input of DiagEmbedOp is not found."));

    PADDLE_ENFORCE_EQ(
31 32
        ctx->HasOutput("Out"),
        true,
L
Li Fuchen 已提交
33 34 35 36 37 38 39 40
        platform::errors::NotFound("Output of DiagEmbedOp is not found."));

    int offset = ctx->Attrs().Get<int>("offset");
    int dim1 = ctx->Attrs().Get<int>("dim1");
    int dim2 = ctx->Attrs().Get<int>("dim2");

    auto x_dims = ctx->GetInputDim("Input");

41
    PADDLE_ENFORCE_GE(
42 43
        dim1,
        -(x_dims.size() + 1),
44 45 46
        platform::errors::OutOfRange(
            "Dim1 is out of range (expected to be in range of [%ld, "
            "%ld], but got %ld).",
47 48 49
            -(x_dims.size() + 1),
            x_dims.size(),
            dim1));
L
Li Fuchen 已提交
50
    PADDLE_ENFORCE_LE(
51 52
        dim1,
        x_dims.size(),
L
Li Fuchen 已提交
53 54 55
        platform::errors::OutOfRange(
            "Dim1 is out of range (expected to be in range of [%ld, "
            "%ld], but got %ld).",
56 57 58
            -(x_dims.size() + 1),
            x_dims.size(),
            dim1));
59 60

    PADDLE_ENFORCE_GE(
61 62
        dim2,
        -(x_dims.size() + 1),
63 64 65
        platform::errors::OutOfRange(
            "Dim2 is out of range (expected to be in range of [%ld, "
            "%ld], but got %ld).",
66 67 68
            -(x_dims.size() + 1),
            x_dims.size(),
            dim2));
L
Li Fuchen 已提交
69
    PADDLE_ENFORCE_LE(
70 71
        dim2,
        x_dims.size(),
L
Li Fuchen 已提交
72 73 74
        platform::errors::OutOfRange(
            "Dim2 is out of range (expected to be in range of [%ld, "
            "%ld], but got %ld).",
75 76 77
            -(x_dims.size() + 1),
            x_dims.size(),
            dim2));
78 79 80 81 82

    int dim1_ = dim1 < 0 ? x_dims.size() + dim1 + 1 : dim1;
    int dim2_ = dim2 < 0 ? x_dims.size() + dim2 + 1 : dim2;
    int offset_ = std::abs(offset);

83 84
    PADDLE_ENFORCE_NE(dim1_,
                      dim2_,
L
Li Fuchen 已提交
85 86 87
                      platform::errors::InvalidArgument(
                          "diagonal dimensions should not be identical "
                          "%ld vs %ld.",
88 89
                          dim1,
                          dim2));
L
Li Fuchen 已提交
90 91 92 93 94 95

    int new_dim_len = offset_ + x_dims[x_dims.size() - 1];
    auto sizes = vectorize(x_dims);
    sizes.pop_back();
    sizes.insert(sizes.begin() + std::min(dim1_, dim2_), new_dim_len);
    sizes.insert(sizes.begin() + std::max(dim1_, dim2_), new_dim_len);
96
    ctx->SetOutputDim("Out", phi::make_ddim(sizes));
L
Li Fuchen 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  }
};

class DiagEmbedOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("Input", "The input tensor. Must be at least 1-dimensional.");
    AddOutput("Out", "A matrix whose certain 2D planes is diagonal matrix.");

    AddAttr<int>(
        "offset",
        R"DOC((int, default 0), which diagonal to consider. Default: 0 (main diagonal).
        )DOC")
        .SetDefault(0);
    AddAttr<int>(
        "dim1",
        R"DOC((int, default -2), first dimension with respect to which to take diagonal. Default: -2.
        )DOC")
        .SetDefault(-2);
    AddAttr<int>(
        "dim2",
        R"DOC((int, default -1), second dimension with respect to which to take diagonal. Default: -1.
        )DOC")
        .SetDefault(-1);

    AddComment(R"DOC(Creates a tensor whose diagonals of certain 2D planes 
              (specified by dim1 and dim2) are filled by input. 
              To facilitate creating batched diagonal matrices, 
              the 2D planes formed by the last two dimensions of the returned tensor
              are chosen by default. 
              )DOC");
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace platform = paddle::platform;
REGISTER_OPERATOR(
136 137 138
    diag_embed,
    ops::DiagEmbedOp,
    ops::DiagEmbedOpMaker,
L
Li Fuchen 已提交
139 140 141
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OP_CPU_KERNEL(
142 143
    diag_embed,
    ops::DiagEmbedKernel<paddle::platform::CPUDeviceContext, int>,
L
Li Fuchen 已提交
144 145 146
    ops::DiagEmbedKernel<paddle::platform::CPUDeviceContext, float>,
    ops::DiagEmbedKernel<paddle::platform::CPUDeviceContext, double>,
    ops::DiagEmbedKernel<paddle::platform::CPUDeviceContext, int64_t>);