crf_decoding_op.cc 5.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
C
Cao Ying 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/crf_decoding_op.h"
C
Cao Ying 已提交
16 17 18 19 20

namespace paddle {
namespace operators {
class CRFDecodingOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
21
  void Make() override {
C
Cao Ying 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
    AddInput("Emission",
             "(LoDTensor, default: LoDTensor<float>). A LoDTensor with shape "
             "[N x D] where N is the size of the mini-batch and D is the total "
             "tag number. This input is the unscaled emission weight matrix of "
             "the linear_chain_crf operator.");
    AddInput(
        "Transition",
        "(Tensor, default: Tensor<float>). A Tensor with shape [(D + 2) x D]. "
        "This input is the transition weights learned by the linear_chain_crf "
        "operator, denoted as w. The 1st row of w are transition weights for "
        "the start mask. The 2nd row of w are transition weights for the end "
        "mask. Transition weights between other tags begin from the 3rd row of "
        "w. See more details in comments of the linear_chain_crf operator.");
    AddInput(
        "Label",
Q
Qiao Longfei 已提交
37
        "(LoDTensor,  LoDTensor<int64_t>). The ground truth with shape "
C
Cao Ying 已提交
38 39 40
        "[N x 1]. This input is optional. See more details in the operator's "
        "comments.")
        .AsDispensable();
Q
Qiao Longfei 已提交
41 42 43 44 45
    AddOutput(
        "ViterbiPath",
        "(LoDTensor, LoDTensor<int64_t>). The decoding results. What to "
        "return changes depending on whether the Input(Label) (the ground "
        "truth) is given. See more details in the operator's comment.");
C
Cao Ying 已提交
46 47
    AddComment(R"DOC(
The crf_decoding operator reads the emission feature weights and the transition
Q
Qiao Longfei 已提交
48
feature weights learned by the linear_chain_crf operator. It implements the
C
Cao Ying 已提交
49 50 51 52 53 54 55
Viterbi algorithm which is a dynamic programming algorithm for finding the most
likely sequence of hidden states, called the Viterbi path, that results in a
sequence of observed tags.

The output of this operator changes according to whether Input(Label) is given:

1. Input(Label) is given:
Y
yi.wu 已提交
56 57 58 59 60 61
   This happens in training. This operator is used to co-work with the chunk_eval
   operator.
   When Input(Label) is given, the crf_decoding operator returns a row vector
   with shape [N x 1] whose values are fixed to be 0, indicating an incorrect
   prediction, or 1 indicating a tag is correctly predicted. Such an output is the
   input to chunk_eval operator.
C
Cao Ying 已提交
62 63

2. Input(Label) is not given:
Y
yi.wu 已提交
64
   This is the standard decoding process.
C
Cao Ying 已提交
65

Q
Qiao Longfei 已提交
66
The crf_decoding operator returns a row vector with shape [N x 1] whose values
Y
yi.wu 已提交
67
range from 0 to maximum tag number - 1, Each element indicates an index of a
C
Cao Ying 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
predicted tag.
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Emission"),
                   "Input(Emission) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput("Transition"),
                   "Input(Transition) should be not null.");

    PADDLE_ENFORCE(ctx->HasOutput("ViterbiPath"),
                   "Output(ViterbiPath) should be not null.");

    auto emission_dims = ctx->GetInputDim("Emission");
T
tensor-tang 已提交
87
    PADDLE_ENFORCE_EQ(emission_dims.size(), 2,
C
Cao Ying 已提交
88 89 90 91
                      "The Input(Emission) should be a 2-D tensor.");
    PADDLE_ENFORCE(emission_dims[0], "An empty mini-batch is not allowed.");

    auto transition_dims = ctx->GetInputDim("Transition");
T
tensor-tang 已提交
92
    PADDLE_ENFORCE_EQ(transition_dims.size(), 2,
C
Cao Ying 已提交
93 94 95 96 97
                      "The Input(Transition) should be a 2-D tensor.");
    PADDLE_ENFORCE_EQ(
        transition_dims[0] - 2, transition_dims[1],
        "An invalid dimension for the Input(Transition), which should "
        "be a 2-D tensor with shape [(D + 2) x D].");
98 99 100 101 102 103
    if (ctx->IsRuntime() || (emission_dims[1] > 0 && transition_dims[1] > 0)) {
      PADDLE_ENFORCE_EQ(
          emission_dims[1], transition_dims[1],
          "The 2nd dimension of the Input(Emission) and the Input(Transition) "
          "should be equal to the tag number.");
    }
C
Cao Ying 已提交
104 105 106 107 108
    if (ctx->HasInput("Label")) {
      auto label_dims = ctx->GetInputDim("Label");
      PADDLE_ENFORCE(label_dims.size() == 2UL && label_dims[1] == 1UL,
                     "The Input(Label) should be a 2-D tensor with the 2nd "
                     "dimensions fixed to 1.");
109 110 111 112 113 114
      if (ctx->IsRuntime() || (emission_dims[0] > 0 && label_dims[0] > 0)) {
        PADDLE_ENFORCE_EQ(
            emission_dims[0], label_dims[0],
            "The height of Input(Emission) and the height of Input(Label) "
            "should be the same.");
      }
C
Cao Ying 已提交
115 116 117 118 119 120 121
    }

    ctx->ShareLoD("Emission", /*->*/ "ViterbiPath");
    ctx->SetOutputDim("ViterbiPath", {emission_dims[0], 1});
  }

 protected:
122
  framework::OpKernelType GetExpectedKernelType(
C
Cao Ying 已提交
123
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
124 125
    return framework::OpKernelType(ctx.Input<LoDTensor>("Emission")->type(),
                                   platform::CPUPlace());
Q
Qiao Longfei 已提交
126
  }
C
Cao Ying 已提交
127 128 129 130 131 132 133 134
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_WITHOUT_GRADIENT(crf_decoding, ops::CRFDecodingOp,
                             ops::CRFDecodingOpMaker);
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
135 136 137
    crf_decoding,
    ops::CRFDecodingOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::CRFDecodingOpKernel<paddle::platform::CPUDeviceContext, double>);