AverageOptimizer.h 4.7 KB
Newer Older
Z
zhangjinchao01 已提交
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 27
/* Copyright (c) 2016 Baidu, Inc. 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. */

#pragma once

#include "FirstOrderOptimizer.h"

namespace paddle {

// After Optimization, parameter values are further averaged within
// time range.
class AverageOptimizer : public ParameterOptimizer {
public:
  // if *useParameterApply* set, use PARAMETER_APPLY to store averaged parameter
  // else use PARAMETER_VALUE, and value backup in PARAMETER_GRADIENT
  AverageOptimizer(const OptimizationConfig& optConfig,
28 29
                   ParameterOptimizer* optimizer,
                   bool useParameterApply);
Z
zhangjinchao01 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

  static ParameterOptimizer* create(const OptimizationConfig& optConfig,
                                    ParameterOptimizer* optimizer,
                                    bool isParameterSparse = false,
                                    bool useParameterApply = false);

  virtual void init(size_t numRows, const ParameterConfig* config) {
    optimizer_->init(numRows, config);
  }

  virtual void startPass() { optimizer_->startPass(); }
  virtual void finishPass() {
    optimizer_->finishPass();
    updateAverageWindowLimit();
  }

  virtual void startBatch(int64_t numSamplesProcessed);
  virtual void finishBatch();
48 49
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
                      size_t sparseId) const {
    optimizer_->update(vecs, paraConfig, sparseId);
    vecs[PARAMETER_SUM1]->add(*vecs[PARAMETER_VALUE], 1.0f);
  }

  virtual TraverseCallback needSpecialTraversal(
      const ParameterConfig& config) const;

  virtual TraverseCallback startCatchUpWith() const {
    return optimizer_->startCatchUpWith();
  }
  virtual void finishCatchUpWith() { return optimizer_->finishCatchUpWith(); }

  virtual TraverseCallback apply();
  virtual TraverseCallback restore();

  virtual void setNoDecay() { optimizer_->setNoDecay(); }

protected:
  std::unique_ptr<ParameterOptimizer> optimizer_;
  bool useApply_;

  // should only be called from finishPass()
  void updateAverageWindowLimit() {
    if (!optConfig_.has_max_average_window()) {
      // use the number of batches in the last pass as maxAverageWindow_
      CHECK_GT(numUpdates_, prevNumUpdates_);
      maxAverageWindow_ = numUpdates_ - prevNumUpdates_;
      prevNumUpdates_ = numUpdates_;
    }
    minAverageWindow_ = std::min(minAverageWindow_, numUpdates_);
  }

  bool isAverageWindowTooLong() const {
    return numAccumulates_ >= minAverageWindow_ &&
           numAccumulates_ >=
               std::min<int64_t>(maxAverageWindow_,
                                 numUpdates_ * optConfig_.average_window());
  }

  static const int64_t kMaxNumAccumulates = 16384;
  int64_t numUpdates_;
  int64_t prevNumUpdates_;
  int64_t numAccumulates_;
  int64_t oldNumAccumulates_;
  int64_t minAverageWindow_;
  int64_t maxAverageWindow_;
};

// Average Optimizer with Sparse support.
class AverageSparseOptimizer : public AverageOptimizer {
public:
  AverageSparseOptimizer(const OptimizationConfig& optConfig,
103 104
                         ParameterOptimizer* optimizer,
                         bool useParameterApply)
Z
zhangjinchao01 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118
      : AverageOptimizer(optConfig, optimizer, useParameterApply) {}

  virtual void init(size_t numRows, const ParameterConfig* config) {
    AverageOptimizer::init(numRows, config);

    t0Vec_.resize(numRows);

    timer_ = 0;
    t0Vec_.assign(t0Vec_.size(), 0);
  }
  virtual void finishBatch() {
    AverageOptimizer::finishBatch();
    timer_++;
  }
119 120
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
121
                      size_t sparseId) const;
122 123
  void catchUpWith(const VectorPtr vecs[],
                   const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
                   size_t sparseId) const;
  virtual TraverseCallback startCatchUpWith() const;
  virtual void finishCatchUpWith() {
    optimizer_->finishCatchUpWith();

    timer_ = 0;
    t0Vec_.assign(t0Vec_.size(), 0);
  }

protected:
  /**
   *  counting batches, clear after catch up with
   *  t(timer_) is current time,
   *  t0(t0Vec_) are last occur time of i rows.
   *  if one block is update by multi threads,
   *  caller should hash sparse ids to avoid write conflict in t0Vec_.
   */
  int timer_;
  mutable std::vector<int32_t> t0Vec_;
};

}  // namespace paddle