NeuralNetwork.h 5.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

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

#pragma once

#include <functional>
Y
Yu Yang 已提交
18 19
#include <map>
#include <memory>
Z
zhangjinchao01 已提交
20 21

#include "ModelConfig.pb.h"
X
Xin Pan 已提交
22 23 24 25 26
#include "paddle/legacy/gserver/dataproviders/DataProvider.h"
#include "paddle/legacy/gserver/gradientmachines/GradientMachine.h"
#include "paddle/legacy/gserver/layers/CostLayer.h"
#include "paddle/legacy/gserver/layers/DataLayer.h"
#include "paddle/legacy/gserver/layers/Layer.h"
X
Xin Pan 已提交
27
#include "paddle/legacy/parameter/Parameter.h"
X
Xin Pan 已提交
28
#include "paddle/legacy/utils/ClassRegistrar.h"
Z
zhangjinchao01 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

namespace paddle {
/*
 * @brief  Init function for the parameters.
 * @param paramId: the id of the parameter to init.
 * @param para: the pointer to the parameter to init.
 * @param sharedParams: the pointer to an array of the parameter to be shared.
 *                      If it is null, no parameter sharing is used.
 *                      Only CPU paramters can be shared.
 * It handles CPU, CPU sparse, CPU sparse remote,
 * and GPU parameters differently. If the type
 * of a parameter is NORMAL. Basically nothing need to be done.
 * CPU value: NORMAL.
 * CPU param: NORMAL.
 *
 * CPU sparse value: NORMAL.
 * CPU sparse gradient: MAT_SPARSE_ROW_AUTO_GROW.
 *
 * CPU sparse remote value: MAT_SPARSE_ROW_PREFETCH(_FULL_SIZE).
 * CPU sparse remote gradient: MAT_SPARSE_ROW (!sharedParams)
 *                             MAT_SPARSE_ROW_AUTO_GROW (sharedParams)
 *
 * GPU value: NORMAL
 * GPU param: NORMAL
 */
54 55
void parameterInitNN(int paramId,
                     Parameter* para,
Z
zhangjinchao01 已提交
56 57 58
                     std::vector<ParameterPtr>* sharedParams);

class NeuralNetwork : public GradientMachine {
W
Wu Yi 已提交
59
 public:
Y
Yu Yang 已提交
60 61 62 63 64 65 66
  virtual void init(const ModelConfig& config,
                    ParamInitCallback callback = nullptr,
                    const std::vector<ParameterType>& parameterTypes =
                        std::vector<ParameterType>{PARAMETER_VALUE,
                                                   PARAMETER_GRADIENT,
                                                   PARAMETER_MOMENTUM},
                    bool useGpu = FLAGS_use_gpu);
Z
zhangjinchao01 已提交
67

68 69 70 71 72 73 74 75 76
  /**
   * Connect two submodels and
   * down-submodel's output become up-submodel's input.
   * By default, connection is one by one,
   * If the agent height is smaller than real layer, *height* has to be filled.
   *
   * @param realLayer  The down-submodel's output layer.
   * @param agentLayer The up-submodel's input agent layer.
   */
Z
zhangjinchao01 已提交
77
  static void connect(LayerPtr agentLayer, LayerPtr realLayer, int height = 0);
78 79
  void connect(std::string agentLayerName,
               NeuralNetwork* srcNN,
Z
zhangjinchao01 已提交
80 81 82 83 84
               std::string realLayerName);

  virtual void prefetch(const std::vector<Argument>& inArgs);

  virtual void forward(const std::vector<Argument>& inArgs,
85 86
                       std::vector<Argument>* outArgs,
                       PassType passType);
Z
zhangjinchao01 已提交
87 88 89

  virtual void backward(const UpdateCallback& callback = nullptr);

L
liaogang 已提交
90
  virtual Argument getLayerOutput(const std::string& layerName);
91

Z
zhangjinchao01 已提交
92 93 94 95 96 97 98 99
  const LayerPtr& getLayer(const std::string& layerName) const {
    auto it = layerMap_.find(layerName);
    CHECK(it != layerMap_.end()) << "Unknown layer " << layerName;
    return it->second;
  }

  virtual void onPassEnd();

100
#ifndef PADDLE_MOBILE_INFERENCE
Y
Yu Yang 已提交
101
  virtual Evaluator* makeEvaluator() const;
Z
zhangjinchao01 已提交
102

Y
Yu Yang 已提交
103
  virtual void eval(Evaluator* evaluator) const;
104 105
#endif

Z
zhangjinchao01 已提交
106 107 108
  virtual void resetState();
  virtual void setOutputGrad(const std::vector<Argument>& args);

109
  /// set machine state
Z
zhangjinchao01 已提交
110 111
  virtual void setState(const MachineState& machineState);

112
  /// get machine state
Z
zhangjinchao01 已提交
113 114 115 116 117 118 119 120 121 122 123 124
  virtual void getState(MachineState& machineState);

  static NeuralNetwork* create(const ModelConfig& config);

  ParameterMap* getParameterMap() { return &parameterMap_; }

  /**
   * @brief Access each layer as a for each loop.
   * @param callback invoke with each layer.
   */
  template <typename T>
  void forEachLayer(T callback) {
125
    for (auto& l : layers_) {
Z
zhangjinchao01 已提交
126 127 128 129 130 131 132
      if (callback(l)) {
        break;
      }
    }
  }

  static NeuralNetwork* newNeuralNetwork(const std::string& name = "",
133
                                         NeuralNetwork* rootNetwork = nullptr);
Z
zhangjinchao01 已提交
134

X
xuwei06 已提交
135 136
  const std::string& getName() const { return subModelName_; }

T
tensor-tang 已提交
137
  /// some finish work, like convert the weight format of MKLDNNLayers
Q
Qiao Longfei 已提交
138
  void finish();
T
tensor-tang 已提交
139

140 141 142 143 144 145 146
  /**
   * @brief   Release the middle layer's output memory.
   *
   * @note    This function is used for memory optimization in inference.
   */
  void releaseOutput();

W
Wu Yi 已提交
147
 protected:
148 149 150 151 152 153 154 155
  /**
   * The constructor of NeuralNetwork.
   * The sub networks can get parameters_ and parameterMap_
   * from base NeuralNetwork.
   *
   * @param subModelName The name of sub-model.
   * @param rootNetwork  It used in MultiNetwork.
   */
Z
zhangjinchao01 已提交
156 157
  NeuralNetwork(std::string subModelName = "",
                NeuralNetwork* rootNetwork = nullptr)
158
      : subModelName_(subModelName), rootNetwork_(rootNetwork) {}
Z
zhangjinchao01 已提交
159 160 161 162 163 164 165 166 167

  std::string subModelName_;
  ModelConfig config_;
  std::vector<LayerPtr> layers_;
  ParameterMap parameterMap_;
  LayerMap layerMap_;

  std::vector<DataLayerPtr> dataLayers_;
  std::vector<LayerPtr> outputLayers_;
168
  std::vector<LayerPtr> middleLayers_;
Z
zhangjinchao01 已提交
169 170 171 172 173

  static std::map<std::string, bool> dllInitMap;

  NeuralNetwork* rootNetwork_;

174 175
  /// Whether parameter of this NN is initialized by its own
  /// (i.e., not by callback supplied with the caller)
Z
zhangjinchao01 已提交
176 177 178 179
  bool paramSelfInited_;
};

}  // namespace paddle