fc_op.cc 7.1 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
    auto x_num_col_dims = Attr<std::vector<int>>("xNumColDims");
44 45 46 47 48 49 50 51 52 53 54 55 56

    // Set all values or set no values (use the default value)
    if (!x_num_col_dims.empty()) {
      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);
    } else {
      x_num_col_dims.resize(n);
      for (size_t i = 0; i < n; i++) {
        x_num_col_dims[i] = 1;
      }
    }
57

58
    // mul_out[i] = X[i] * W[i]
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]);
62
      mul_attr["y_num_col_dims"] = static_cast<int>(1);
63 64 65
      AppendOp(
          framework::OpRegistry::CreateOp("mul", {{"X", {x[i]}}, {"Y", {w[i]}}},
                                          {{"Out", {mul_out[i]}}}, mul_attr));
66
    }
L
Liu Yiqun 已提交
67

68
    // sum_out = X[0] * W[0] + ... + X[n-1] * W[n-1]
69
    auto sum_out = mul_out[0];
70
    if (n > 1) {
71 72 73
      sum_out = Output("SumOut");
      AppendOp(framework::OpRegistry::CreateOp("sum", {{"X", {mul_out}}},
                                               {{"Out", {sum_out}}}, {}));
74
    } else {
75 76 77
      if (Output("SumOut") != framework::kEmptyVarName) {
        this->Rename(Output("SumOut"), framework::kEmptyVarName);
      }
L
Liu Yiqun 已提交
78
    }
79

80
    // add_out = sum_out + b
81
    auto b = Input("B");
82
    auto add_out = sum_out;
83
    if (b != framework::kEmptyVarName) {
84
      add_out = Output("AddOut");
85
      AppendOp(framework::OpRegistry::CreateOp(
86 87
          "rowwise_add", {{"X", {sum_out}}, {"b", {Input("B")}}},
          {{"Out", {add_out}}}, {}));
88
    } else {
89 90
      if (Output("AddOut") != framework::kEmptyVarName) {
        this->Rename(Output("AddOut"), framework::kEmptyVarName);
91
      }
92 93
    }

L
Liu Yiqun 已提交
94
    auto activation = Attr<std::string>("activation");
95 96
    AppendOp(framework::OpRegistry::CreateOp(activation, {{"X", {add_out}}},
                                             {{"Y", {Output("Out")}}}, {}));
97 98 99 100 101 102 103 104
    CompleteAddOp(false);
  }
};

class FCOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  FCOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
105 106 107 108 109
    AddInput("X",
             "(A vector of Tensors) each input Tensor can be of arbitrary "
             "dimension, and will be reshaped to a 2-D matrix of size "
             "(minibatch, number_of_input_features) according to attribute "
             "xNumColDims.")
110
        .AsDuplicable();
111 112 113 114
    AddInput("W",
             "(A vector of Tensors) the weights of FC operator, a "
             "vector of 2-D matrix of size "
             "(number_of_input_features, number_of_neurons).")
115
        .AsDuplicable();
116 117 118
    AddInput("B",
             "(Tensor) the bias of FC operator, a 1-D vector of size "
             "number_of_neurons.");
119

120
    AddOutput("Out",
121 122
              "(Tensor) the activated output matrix of FC operator, a 2-D "
              "matrix of size (minibatch, number_of_neurons).");
123
    AddOutput("MulOut",
124 125
              "(A vector of Tensors) the intermediate outputs of FC operator, "
              "each Tensor saving the product of X_i * W_i.")
126 127
        .AsIntermediate()
        .AsDuplicable();
128 129 130 131
    AddOutput(
        "SumOut",
        "(Tensor) the intermediate output of FC operator, "
        "saving the sum of the products of X and W, that is sum{X_i * W_i}.")
132
        .AsIntermediate();
133
    AddOutput("AddOut",
134 135
              "(Tensor) the non-actived output of FC operator, "
              "saving sum{X_i * W_i} + B.")
136
        .AsIntermediate();
137 138 139
    AddAttr<std::string>(
        "activation",
        "(string, default identity) the activation type of FC operator.")
140 141
        .SetDefault("identity")
        .InEnum({"identity", "sigmoid", "softmax"});
142 143 144 145 146 147 148 149 150 151
    AddAttr<std::vector<int>>(
        "xNumColDims",
        "(std::vector<int>) The inputs Tensors of FC operator can be of "
        "more than 2 dimensions. In that case, each input Tensor `X_i` will be "
        "reshaped to a 2-D matrix. The matrix's first dimension "
        "(the length of column) will be the product of `X_i`'s last "
        "`xNumColDims_i` dimensions, that is "
        "`X_i.dims[0] x ... x X_i.dims[xNumColDims_i - 1]`. "
        "The matrix's second dimension (the length of row) will be the product "
        "of `X_i`'s first `rank - xNumColDims_i` dimensions, that is "
152 153
        "`X_i.dims[xNumColDims_i] x ... x X_i.dims[rank - 1]`)")
        .SetDefault(std::vector<int>{});
154 155 156 157 158 159 160 161 162 163

    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:
164
  Out = Act(sum_n{X_i * W_i} + B)
165

166 167 168 169
where X_i is Tensor that will be reshaped to a 2-D matrix of size (M x K),
usually M is the minibatch size and K is the number of input features.
W_i is a 2-D matrix of size (K x N), where N means the number of neurons
in the fully connected layer. B is a 1-D vector of size N.
170
Thus, the output Out is a 2-D matrix of size (M x N).
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
Activation type can be set to `identity` (default), `sigmoid` or `softmax`.
)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;
186
REGISTER_OP_WITHOUT_GRADIENT(fc, ops::FCOp, ops::FCOpMaker);