crf_decoding_op.cc 9.2 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
    AddInput(
        "Emission",
Y
Yibing Liu 已提交
24 25 26 27 28 29 30
        "(Tensor/LoDTensor). 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. The data type is float32 "
        "or float64.");
C
Cao Ying 已提交
31 32
    AddInput(
        "Transition",
Y
Yibing Liu 已提交
33
        "(Tensor). A Tensor with shape [(D + 2) x D]. "
C
Cao Ying 已提交
34 35 36 37
        "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 "
Y
Yibing Liu 已提交
38 39
        "w. See more details in comments of the linear_chain_crf operator. "
        "The data type is the same as Input(Emission).");
C
Cao Ying 已提交
40 41
    AddInput(
        "Label",
Y
Yibing Liu 已提交
42
        "(Tensor/LoDTensor). The ground truth with shape "
43
        "[N x 1] (for LoDTensor) or [B x S] (for Tensor). This input is "
Y
Yibing Liu 已提交
44 45
        "optional. See more details in the operator's comments. The data type "
        "is int64.")
C
Cao Ying 已提交
46
        .AsDispensable();
Q
Qiao Longfei 已提交
47 48
    AddOutput(
        "ViterbiPath",
Y
Yibing Liu 已提交
49
        "(Tensor/LoDTensor). The decoding results. What to "
Q
Qiao Longfei 已提交
50
        "return changes depending on whether the Input(Label) (the ground "
Y
Yibing Liu 已提交
51 52
        "truth) is given. See more details in the operator's comment. "
        "The data type is int64.");
53
    AddInput("Length",
Y
Yibing Liu 已提交
54
             "(Tensor). The actual length of each sample before "
55
             "padding with shape [B x 1]. It means the Input(Emission), "
Y
Yibing Liu 已提交
56 57
             "Input(Label) and Output(ViterbiPath) are common tensors with "
             "padding when this input is given. The data type is int64.")
58
        .AsDispensable();
C
Cao Ying 已提交
59 60
    AddComment(R"DOC(
The crf_decoding operator reads the emission feature weights and the transition
Y
Yibing Liu 已提交
61 62 63 64
feature weights learned by the linear_chain_crf operator and performs decoding. 
It implements the 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.
C
Cao Ying 已提交
65 66 67 68

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

1. Input(Label) is given:
Y
yi.wu 已提交
69 70
   This happens in training. This operator is used to co-work with the chunk_eval
   operator.
71 72 73 74
   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 已提交
75 76

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

79 80
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 已提交
81
range from 0 to maximum tag number - 1, Each element indicates an index of a
C
Cao Ying 已提交
82 83 84 85 86 87 88 89 90 91
predicted tag.
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
92 93 94 95 96 97
    OP_INOUT_CHECK(ctx->HasInput("Emission"), "Input", "Emission",
                   "CRFDecoding");
    OP_INOUT_CHECK(ctx->HasInput("Transition"), "Input", "Transition",
                   "CRFDecoding");
    OP_INOUT_CHECK(ctx->HasOutput("ViterbiPath"), "Output", "ViterbiPath",
                   "CRFDecoding");
C
Cao Ying 已提交
98 99

    auto emission_dims = ctx->GetInputDim("Emission");
100 101 102 103
    bool has_length = ctx->HasInput("Length");

    if (has_length) {
      PADDLE_ENFORCE_EQ(emission_dims.size(), 3,
104 105 106 107
                        platform::errors::InvalidArgument(
                            "The Input(Emission) should be a 3-D tensor. But "
                            "received: input rank %u, input shape [%s]. ",
                            emission_dims.size(), emission_dims));
108 109
    } else {
      PADDLE_ENFORCE_EQ(emission_dims.size(), 2,
110 111 112 113
                        platform::errors::InvalidArgument(
                            "The Input(Emission) should be a 2-D tensor. But "
                            "received: input rank %u, input shape [%s].",
                            emission_dims.size(), emission_dims));
114
    }
C
Cao Ying 已提交
115 116

    auto transition_dims = ctx->GetInputDim("Transition");
117
    PADDLE_ENFORCE_EQ(transition_dims.size(), 2UL,
118 119 120 121
                      platform::errors::InvalidArgument(
                          "The Input(Transition) should be a 2-D tensor. But "
                          "received: input rank %u, input shape [%s].",
                          transition_dims.size(), transition_dims));
C
Cao Ying 已提交
122 123
    PADDLE_ENFORCE_EQ(
        transition_dims[0] - 2, transition_dims[1],
124 125 126 127 128 129
        platform::errors::InvalidArgument(
            "An invalid dimension for the Input(Transition), which should "
            "be a 2-D tensor with shape [(D + 2) x D]. But received: input "
            "rank %u, "
            "input shape [%s].",
            transition_dims.size(), transition_dims));
130 131
    if (ctx->IsRuntime() || (emission_dims[emission_dims.size() - 1] > 0 &&
                             transition_dims[transition_dims.size() - 1] > 0)) {
132 133 134 135 136 137 138 139 140 141 142
      PADDLE_ENFORCE_EQ(emission_dims[emission_dims.size() - 1],
                        transition_dims[transition_dims.size() - 1],
                        platform::errors::InvalidArgument(
                            "The last dimension of the Input(Emission) and the "
                            "Input(Transition) "
                            "should be equal to the tag number. But received "
                            "Input(Emission): rank "
                            "%u, shape [%s]; received Input(Transition): rank "
                            "%u, shape [%s].",
                            emission_dims.size(), emission_dims,
                            transition_dims.size(), transition_dims));
143
    }
C
Cao Ying 已提交
144 145
    if (ctx->HasInput("Label")) {
      auto label_dims = ctx->GetInputDim("Label");
146 147 148 149 150
      if (ctx->HasInput("Length")) {
        PADDLE_ENFORCE_EQ(
            (label_dims.size() == 3UL && label_dims[2] == 1) ||
                label_dims.size() == 2UL,
            true,
151 152 153 154 155 156
            platform::errors::InvalidArgument(
                "The Input(Label) should be a 3-D tensor with last dimension "
                "fixed to 1 or a 2-D tensor in padding mode. But received: "
                "input "
                "rank %u, input shape [%s].",
                label_dims.size(), label_dims));
157
      } else {
158 159 160 161 162 163 164 165
        PADDLE_ENFORCE_EQ(
            (label_dims.size() == 2UL && label_dims[1] == 1) ||
                label_dims.size() == 1UL,
            true, platform::errors::InvalidArgument(
                      "The Input(Label) should be a 2-D tensor with last "
                      "dimension fixed to 1 or a 1-D tensor. But received: "
                      "input rank %u, input shape [%s].",
                      label_dims.size(), label_dims));
166
      }
167 168 169
      if (ctx->IsRuntime() || (emission_dims[0] > 0 && label_dims[0] > 0)) {
        PADDLE_ENFORCE_EQ(
            emission_dims[0], label_dims[0],
170 171 172 173 174 175
            platform::errors::InvalidArgument(
                "The first dimension of Input(Emission) and Input(Label) "
                "should be the same. But received Input(Emission): rank %u, "
                "shape [%s]; received Input(Label): rank %u, shape [%s].",
                emission_dims.size(), emission_dims, label_dims.size(),
                label_dims));
176
      }
C
Cao Ying 已提交
177 178 179
    }

    ctx->ShareLoD("Emission", /*->*/ "ViterbiPath");
180 181 182 183 184
    if (has_length) {
      ctx->SetOutputDim("ViterbiPath", {emission_dims[0], emission_dims[1]});
    } else {
      ctx->SetOutputDim("ViterbiPath", {emission_dims[0], 1});
    }
C
Cao Ying 已提交
185 186 187
  }

 protected:
188
  framework::OpKernelType GetExpectedKernelType(
C
Cao Ying 已提交
189
      const framework::ExecutionContext& ctx) const override {
190 191 192
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Emission"),
        platform::CPUPlace());
Q
Qiao Longfei 已提交
193
  }
C
Cao Ying 已提交
194 195 196 197 198 199 200 201
};
}  // 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 已提交
202 203 204
    crf_decoding,
    ops::CRFDecodingOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::CRFDecodingOpKernel<paddle::platform::CPUDeviceContext, double>);