NeuralNetwork.h 5.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
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 27 28 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

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 <memory>
#include <map>
#include <functional>

#include "paddle/utils/ClassRegistrar.h"
#include "paddle/parameter/Parameter.h"
#include "ModelConfig.pb.h"
#include "paddle/gserver/gradientmachines/GradientMachine.h"
#include "paddle/gserver/layers/CostLayer.h"
#include "paddle/gserver/layers/DataLayer.h"
#include "paddle/gserver/dataproviders/DataProvider.h"
#include "paddle/gserver/layers/Layer.h"

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 59 60
                     std::vector<ParameterPtr>* sharedParams);

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

69 70 71 72 73 74 75 76 77
  /**
   * 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 已提交
78
  static void connect(LayerPtr agentLayer, LayerPtr realLayer, int height = 0);
79 80
  void connect(std::string agentLayerName,
               NeuralNetwork* srcNN,
Z
zhangjinchao01 已提交
81 82 83 84 85
               std::string realLayerName);

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

  virtual void forward(const std::vector<Argument>& inArgs,
86 87
                       std::vector<Argument>* outArgs,
                       PassType passType);
Z
zhangjinchao01 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

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

  MatrixPtr getLayerOutput(const std::string& layerName);
  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();

  virtual Evaluator* makeEvaluator();

  virtual void eval(Evaluator* evaluator);
  virtual void resetState();
  virtual void setOutputGrad(const std::vector<Argument>& args);

106
  /// set machine state
Z
zhangjinchao01 已提交
107 108
  virtual void setState(const MachineState& machineState);

109
  /// get machine state
Z
zhangjinchao01 已提交
110 111 112 113 114 115 116 117 118 119 120 121
  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) {
122
    for (auto& l : layers_) {
Z
zhangjinchao01 已提交
123 124 125 126 127 128 129
      if (callback(l)) {
        break;
      }
    }
  }

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

protected:
133 134 135 136 137 138 139 140
  /**
   * 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 已提交
141 142
  NeuralNetwork(std::string subModelName = "",
                NeuralNetwork* rootNetwork = nullptr)
143
      : subModelName_(subModelName), rootNetwork_(rootNetwork) {}
Z
zhangjinchao01 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157

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

  std::vector<DataLayerPtr> dataLayers_;
  std::vector<LayerPtr> outputLayers_;

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

  NeuralNetwork* rootNetwork_;

158 159
  /// Whether parameter of this NN is initialized by its own
  /// (i.e., not by callback supplied with the caller)
Z
zhangjinchao01 已提交
160 161 162 163
  bool paramSelfInited_;
};

}  // namespace paddle