fc_op.cc 5.9 KB
Newer Older
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 26
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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/framework/op_registry.h"
#include "paddle/operators/net_op.h"

namespace paddle {
namespace operators {

class FCOp : public NetOp {
 public:
  FCOp(const std::string &type, const framework::VariableNameMap &inputs,
       const framework::VariableNameMap &outputs,
       const framework::AttributeMap &attrs)
      : NetOp(type, inputs, outputs, attrs) {
L
Liu Yiqun 已提交
27 28
    auto x = Inputs("X");
    auto w = Inputs("W");
29
    auto mul_out = Outputs("MulOut");
L
Liu Yiqun 已提交
30 31 32 33
    PADDLE_ENFORCE_EQ(
        x.size(), w.size(),
        "The size of inputs X(%d) should be the same as that of weights W(%d).",
        x.size(), w.size());
34 35 36 37
    PADDLE_ENFORCE_EQ(mul_out.size(), x.size(),
                      "The size of intermediate mul_out(%d) should be the same "
                      "as that of inputs X(%d).",
                      mul_out.size(), x.size());
L
Liu Yiqun 已提交
38

39 40
    size_t n = x.size();
    PADDLE_ENFORCE_GE(n, static_cast<size_t>(1),
L
Liu Yiqun 已提交
41 42
                      "The size of inputs X(%d) should be no less than 1.", n);

43 44 45 46 47 48 49 50 51 52 53
    auto x_num_col_dims = Attr<std::vector<int>>("xNumColDims");
    auto w_num_col_dims = Attr<std::vector<int>>("wNumColDims");
    PADDLE_ENFORCE_EQ(x_num_col_dims.size(), n,
                      "The size of attribute xNumColDims(%d) should be the "
                      "same as that of inputs X(%d).",
                      x_num_col_dims.size(), n);
    PADDLE_ENFORCE_EQ(w_num_col_dims.size(), n,
                      "The size of attribute wNumColDims(%d) should be the "
                      "same as that of inputs X(%d).",
                      w_num_col_dims.size(), n)

54
    // mul_out[i] = X[i] * W[i]
55 56 57 58 59 60 61
    for (size_t i = 0; i < n; i++) {
      framework::AttributeMap mul_attr;
      mul_attr["x_num_col_dims"] = static_cast<int>(x_num_col_dims[i]);
      mul_attr["y_num_col_dims"] = static_cast<int>(w_num_col_dims[i]);
      AppendOp(
          framework::OpRegistry::CreateOp("mul", {{"X", {x[i]}}, {"Y", {w[i]}}},
                                          {{"Out", {mul_out[i]}}}, mul_attr));
62
    }
L
Liu Yiqun 已提交
63

64 65 66
    // sum_out = X[0] * W[0] + ... + X[n-1] * W[n-1]
    if (n > 1) {
      AppendOp(framework::OpRegistry::CreateOp(
67
          "sum", {{"X", {mul_out}}}, {{"Out", {Output("SumOut")}}}, {}));
68
    } else {
L
Liu Yiqun 已提交
69
      AppendOp(framework::OpRegistry::CreateOp(
70
          "identity", {{"X", {mul_out[0]}}}, {{"Y", {Output("SumOut")}}}, {}));
L
Liu Yiqun 已提交
71
    }
72

73
    // add_out = sum_out + b
74 75
    auto b = Input("B");
    std::string add_out = "SumOut";
76
    if (b != framework::kEmptyVarName) {
77
      add_out = "AddOut";
78
      AppendOp(framework::OpRegistry::CreateOp(
79
          "rowwise_add", {{"X", {Output("SumOut")}}, {"b", {Input("B")}}},
80
          {{"Out", {Output(add_out)}}}, {}));
81
    } else {
82 83
      if (Output("AddOut") != framework::kEmptyVarName) {
        this->Rename(Output("AddOut"), framework::kEmptyVarName);
84
      }
85 86
    }

L
Liu Yiqun 已提交
87 88 89
    auto activation = Attr<std::string>("activation");
    AppendOp(framework::OpRegistry::CreateOp(
        activation, {{"X", {Output(add_out)}}}, {{"Y", {Output("Y")}}}, {}));
90 91 92 93 94 95 96 97
    CompleteAddOp(false);
  }
};

class FCOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  FCOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
98 99 100 101
    AddInput("X", "The inputs of FC operator, a ordered vector of 2-D matrix.")
        .AsDuplicable();
    AddInput("W", "The weights of FC operator, a ordered vector of 2-D matrix.")
        .AsDuplicable();
102
    AddInput("B", "The 1-D bias vector of FC operator");
103

L
Liu Yiqun 已提交
104
    AddOutput("Y", "The activated output matrix of FC operator");
105
    AddOutput("MulOut",
106 107 108 109
              "The intermediate outputs of FC operator, "
              "saving the product of X[i] * W[i]")
        .AsIntermediate()
        .AsDuplicable();
110
    AddOutput("SumOut",
111 112
              "The intermediate output of FC operator, "
              "saving the sum of products, sum(X[i] * W[i])")
113
        .AsIntermediate();
114
    AddOutput("AddOut",
115
              "The non-actived output of FC operator, saving X * W + b")
116 117 118 119
        .AsIntermediate();
    AddAttr<std::string>("activation", "The activation type of FC operator.")
        .SetDefault("identity")
        .InEnum({"identity", "sigmoid", "softmax"});
120 121
    AddAttr<std::vector<int>>("xNumColDims", "");
    AddAttr<std::vector<int>>("wNumColDims", "");
122 123 124 125 126 127 128 129 130 131

    AddComment(R"DOC(
Fully Connected Operator, known as Fully Connected Layer or Inner Product Layer
in Convolutional Neural Networks. Neurons in a fully connected layer have
full connections to all activations in the previous layer.
It computes an inner product of a set of
learned weights with a matrix multiplication followed by a bias offset
(optionally).

Equation:
L
Liu Yiqun 已提交
132
  Y = Act(sum_n{X_i * W_i} + b)
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

where X_i is a 2D matrix of size (M x K), usually M is the minibatch size and
K is the number of features. W_i is also a 2D matrix of size (K x N),
where N means the number of neurons in the fully connected layer.
b is a 1D vector of size N. Thus, the output Y is a 2D matrix of size (M x N).
Activation type can be set to `identity` (default), `sigmoid` or `softmax`.

  The config api is `paddle.v2.layer.fc`.
)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

USE_OP(mul);
USE_OP(rowwise_add);
USE_NO_KERNEL_OP(identity);
USE_OP(sigmoid);
USE_OP(softmax);

namespace ops = paddle::operators;
155
REGISTER_OP_WITHOUT_GRADIENT(fc, ops::FCOp, ops::FCOpMaker);