crf_decoding_op.cc 7.5 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 {
22 23 24 25 26 27 28 29
    AddInput(
        "Emission",
        "(Tensor<float>/LoDTensor<float>). For a LoDTensor input, its "
        "shape is [N x D] where N is the total sequence length of the "
        "mini-batch and D is the total tag number. While for a tensor "
        "input, its shape is [B X S X D] with B the batch size and S the "
        "sequence length of each sample after padding. This input is the "
        "unscaled emission weight matrix of the linear_chain_crf operator.");
C
Cao Ying 已提交
30 31
    AddInput(
        "Transition",
32
        "(Tensor<float>). A Tensor with shape [(D + 2) x D]. "
C
Cao Ying 已提交
33 34 35 36 37 38 39
        "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",
40 41
        "(Tensor<int64_t>/LoDTensor<int64_t>). The ground truth with shape "
        "[N x 1] (for LoDTensor) or [B x S] (for Tensor). This input is "
42
        "optional. See more details in the operator's comments.")
C
Cao Ying 已提交
43
        .AsDispensable();
Q
Qiao Longfei 已提交
44 45
    AddOutput(
        "ViterbiPath",
46
        "(Tensor<int64_t>/LoDTensor<int64_t>). The decoding results. What to "
Q
Qiao Longfei 已提交
47 48
        "return changes depending on whether the Input(Label) (the ground "
        "truth) is given. See more details in the operator's comment.");
49 50 51 52 53 54 55 56
    AddInput("Length",
             "(Tensor<int64_t>). The actual length of each sample before "
             "padding with shape [B x 1]. It means the Input(Emission), "
             "Input(Label) "
             "and Output(ViterbiPath) are common tensors with padding when "
             "this input "
             "is given.")
        .AsDispensable();
C
Cao Ying 已提交
57 58
    AddComment(R"DOC(
The crf_decoding operator reads the emission feature weights and the transition
Q
Qiao Longfei 已提交
59
feature weights learned by the linear_chain_crf operator. It implements the
C
Cao Ying 已提交
60 61 62 63 64 65 66
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 已提交
67 68
   This happens in training. This operator is used to co-work with the chunk_eval
   operator.
69 70 71 72
   When Input(Label) is given, the crf_decoding operator returns tensor with the 
   sampe shape as Input(Label) 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 已提交
73 74

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

77 78
The crf_decoding operator returns a row vector with shape [N x 1]/[B x S], here 
the shape depends on the inputs are LoDTensors or common tensors, whose values
Y
yi.wu 已提交
79
range from 0 to maximum tag number - 1, Each element indicates an index of a
C
Cao Ying 已提交
80 81 82 83 84 85 86 87 88 89
predicted tag.
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
90 91 92 93
    PADDLE_ENFORCE_EQ(ctx->HasInput("Emission"), true,
                      "Input(Emission) should be not null.");
    PADDLE_ENFORCE_EQ(ctx->HasInput("Transition"), true,
                      "Input(Transition) should be not null.");
C
Cao Ying 已提交
94

95 96
    PADDLE_ENFORCE_EQ(ctx->HasOutput("ViterbiPath"), true,
                      "Output(ViterbiPath) should be not null.");
C
Cao Ying 已提交
97 98

    auto emission_dims = ctx->GetInputDim("Emission");
99 100 101 102 103 104 105 106 107 108 109
    bool has_length = ctx->HasInput("Length");

    if (has_length) {
      PADDLE_ENFORCE_EQ(emission_dims.size(), 3,
                        "The Input(Emission) should be a 3-D tensor.");
    } else {
      PADDLE_ENFORCE_EQ(emission_dims.size(), 2,
                        "The Input(Emission) should be a 2-D tensor.");
    }
    PADDLE_ENFORCE_NE(emission_dims[0], 0,
                      "An empty mini-batch is not allowed.");
C
Cao Ying 已提交
110 111

    auto transition_dims = ctx->GetInputDim("Transition");
112
    PADDLE_ENFORCE_EQ(transition_dims.size(), 2UL,
C
Cao Ying 已提交
113 114 115 116 117
                      "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].");
118 119
    if (ctx->IsRuntime() || (emission_dims[emission_dims.size() - 1] > 0 &&
                             transition_dims[transition_dims.size() - 1] > 0)) {
120
      PADDLE_ENFORCE_EQ(
121 122 123
          emission_dims[emission_dims.size() - 1],
          transition_dims[transition_dims.size() - 1],
          "The last dimension of the Input(Emission) and the Input(Transition) "
124 125
          "should be equal to the tag number.");
    }
C
Cao Ying 已提交
126 127
    if (ctx->HasInput("Label")) {
      auto label_dims = ctx->GetInputDim("Label");
128 129 130 131 132 133 134 135 136 137 138 139 140 141
      if (ctx->HasInput("Length")) {
        PADDLE_ENFORCE_EQ(
            (label_dims.size() == 3UL && label_dims[2] == 1) ||
                label_dims.size() == 2UL,
            true,
            "The Input(Label) should be a 3-D tensor with last dimension "
            "fixed to 1 or a 2-D tensor in padding mode.");
      } else {
        PADDLE_ENFORCE_EQ((label_dims.size() == 2UL && label_dims[1] == 1) ||
                              label_dims.size() == 1UL,
                          true,
                          "The Input(Label) should be a 2-D tensor with last "
                          "dimension fixed to 1 or a 1-D tensor.");
      }
142 143 144
      if (ctx->IsRuntime() || (emission_dims[0] > 0 && label_dims[0] > 0)) {
        PADDLE_ENFORCE_EQ(
            emission_dims[0], label_dims[0],
145
            "The first dimension of Input(Emission) and Input(Label) "
146 147
            "should be the same.");
      }
C
Cao Ying 已提交
148 149 150
    }

    ctx->ShareLoD("Emission", /*->*/ "ViterbiPath");
151 152 153 154 155
    if (has_length) {
      ctx->SetOutputDim("ViterbiPath", {emission_dims[0], emission_dims[1]});
    } else {
      ctx->SetOutputDim("ViterbiPath", {emission_dims[0], 1});
    }
C
Cao Ying 已提交
156 157 158
  }

 protected:
159
  framework::OpKernelType GetExpectedKernelType(
C
Cao Ying 已提交
160
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
161 162
    return framework::OpKernelType(ctx.Input<LoDTensor>("Emission")->type(),
                                   platform::CPUPlace());
Q
Qiao Longfei 已提交
163
  }
C
Cao Ying 已提交
164 165 166 167 168 169 170 171
};
}  // 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 已提交
172 173 174
    crf_decoding,
    ops::CRFDecodingOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::CRFDecodingOpKernel<paddle::platform::CPUDeviceContext, double>);