Trainer.h 5.1 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

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 "paddle/utils/Util.h"

#include <stdio.h>

#include "hl_gpu.h"
X
Xin Pan 已提交
22 23
#include "paddle/legacy/gserver/dataproviders/DataProvider.h"
#include "paddle/legacy/gserver/gradientmachines/GradientMachine.h"
Z
zhangjinchao01 已提交
24

Y
Yu Yang 已提交
25 26 27
#include <stdlib.h>
#include <fstream>
#include "ParamUtil.h"
Z
zhangjinchao01 已提交
28 29
#include "ParameterUpdater.h"
#include "Tester.h"
Y
Yu Yang 已提交
30 31
#include "TrainerConfigHelper.h"
#include "TrainerInternal.h"
Z
zhangjinchao01 已提交
32

33
DECLARE_int32(num_passes);
Z
zhangjinchao01 已提交
34 35 36 37 38 39 40 41 42 43

namespace paddle {

/**
 * Trainer Class
 *
 * Trainer combines GradientMachine, ParameterUpdater, DataProvider together to
 * train/test a NeuralNetwork.
 */
class Trainer {
W
Wu Yi 已提交
44
 public:
Z
zhangjinchao01 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
  /**
   * Ctor.
   * @return
   */
  Trainer() : acceptedPassId_(0) {}

  virtual ~Trainer() {}

  /**
   * initialize a new trainer using config
   *
   * @param config TrainerConfig.
   * @param testing true if only for testing
   * @param gradientMachine GradientMachine that will be trained.
   *                        nullptr if create from config.
   * @param dataProvider Train Data Provider. null if create from config.
   * @param testDataProvider Test Data Provider. null if create from config.
   */
  virtual void init(
64
      const std::shared_ptr<TrainerConfigHelper>& config,
Z
zhangjinchao01 已提交
65
      bool testing = false,
66 67 68
      const std::shared_ptr<GradientMachine>& gradientMachine = nullptr,
      const std::shared_ptr<DataProvider>& dataProvider = nullptr,
      const std::shared_ptr<DataProvider>& testDataProvider = nullptr);
Z
zhangjinchao01 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

  /**
   * Train until num_passes reached.
   * One pass means neural network train through all training data.
   *
   * @param numPasses the number of traning pass.
   * @note Durning neural network training, the num passes may set a very large
   * value, and kill training process when result is good enough.
   */
  void train(size_t numPasses = (size_t)FLAGS_num_passes);

  /**
   * compare the gradient from bp with finite difference
   * @return  the maximal difference
   */
  real checkGradient();

E
emailweixu 已提交
86 87 88 89 90
  void startTrain();
  void finishTrain();
  void startTrainPass();
  void finishTrainPass();
  void trainOneDataBatch(DataBatch& dataBatch);
91
  void time();
Z
zhangjinchao01 已提交
92 93 94 95 96 97 98 99

  /**
   * given a dataBatch and the current parameter value
   * calculate its gradient and return the cost.
   *
   * TODO(yuyang18): I think this method is deprecated and buggy. Should it be
   * removed?
   */
100 101
  real calcGradient(const DataBatch& dataBatch,
                    const Vector& value,
Z
zhangjinchao01 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
                    Vector& gradient);

  /**
   * Get Trainer Config.
   */
  const TrainerConfig& getConfig() const { return config_->getConfig(); }

  /**
   * Get Train Data Provider
   */
  const DataProviderPtr& getDataProvider() { return dataProvider_; }

  /**
   * Get Gradient Machine.
   */
  const GradientMachinePtr& getGradientMachine() {
    return trainerInternal_.getGradientMachine();
  }

  /**
   * Get batch size in optimization config.
   * @note This method didn't return the actual batch size. Just batch size
   * set in the optimization config. The actual batch size in one trainer may
   * less than batch size in config due to there are not enough data.
   */
  int getBatchSize();

  /**
   * Do test job
   */
  void test();

  /**
   * Get parameter util ptr
   *
   * TODO(yuyang18): Make it return a smart pointer.
   */
  ParameterUtil* getParameterUtilPtr();

W
Wu Yi 已提交
141
 protected:
Z
zhangjinchao01 已提交
142
  /**
E
emailweixu 已提交
143
   * Train one pass of data.
Z
zhangjinchao01 已提交
144 145 146
   *
   * SGD Method.
   */
E
emailweixu 已提交
147
  void trainOnePass();
Z
zhangjinchao01 已提交
148 149 150 151 152 153 154 155 156 157 158 159

  /**
   * Train one pass in one batch.
   *
   */
  void trainOnePassBatch(int passId);

  /**
   * set parameter gradient to zero
   */
  void clearGradient();

E
emailweixu 已提交
160 161
  void createTester();

W
Wu Yi 已提交
162
 private:
Z
zhangjinchao01 已提交
163 164
  std::unique_ptr<TesterConfig> createTesterConfig();

W
Wu Yi 已提交
165
 protected:
Z
zhangjinchao01 已提交
166 167 168 169 170 171 172 173
  std::shared_ptr<TrainerConfigHelper> config_;
  std::shared_ptr<TrainerStats> stats_;

  DataProviderPtr dataProvider_;
  DataProviderPtr testDataProvider_;
  MachineState trainState_;
  MachineState testState_;

E
emailweixu 已提交
174 175 176 177 178 179 180 181 182 183 184
  struct TrainPassContext {
    int64_t batchId;
    real avgTestCost;
    int64_t numAvgTests;
    int passId;
    int passInnerId;
  };
  std::vector<paddle::Argument> forwardOutput_;

  TrainPassContext trainPassContext_;

Z
zhangjinchao01 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  std::unique_ptr<Evaluator> evaluator_;
  std::unique_ptr<Evaluator> currentEvaluator_;
  std::unique_ptr<Evaluator> averageEvaluator_;
  // training mode
  // used to decide which GradientMachine and ParameterUpdater to create
  GradientMachine::CreateMode mode_;
  int testing_;
  int acceptedPassId_;

  // trainer tester
  std::unique_ptr<Tester> tester_;

  // parameter util
  std::unique_ptr<ParameterUtil> paramUtil_;

  // trainer Internal
  TrainerInternal trainerInternal_;
};

}  // namespace paddle