OptimizerWithRegularizer.cpp 6.5 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

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 "OptimizerWithRegularizer.h"

namespace paddle {

ParameterOptimizer::TraverseCallback
OptimizerWithRegularizerEveryNumBatches::needSpecialTraversal(
    const ParameterConfig& config) const {
  TraverseCallbackVec callbacks;

  if (isRegularizationBatch(config)) {
    callbacks.emplace_back(
26 27
        [this](const VectorPtr vecs[],
               const ParameterConfig& config,
Z
zhangjinchao01 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41
               size_t sparseId) { this->doTraversal(vecs, config); });
  }

  if (auto callback = optimizer_->needSpecialTraversal(config)) {
    callbacks.emplace_back(callback);
  }

  return composeCallbacks(callbacks);
}

void OptimizerWithRegularizerEveryNumBatches::doTraversal(
    const VectorPtr vecs[], const ParameterConfig& config) const {
  int32_t base =
      std::max(baseTimer_, (timer_ + 1 - config.num_batches_regularization()));
42 43
  regularizer_->update(
      vecs, config, optimizer_->getLearningRate(), base, timer_ + 1);
Z
zhangjinchao01 已提交
44 45 46 47 48 49 50 51 52 53 54 55
}

ParameterOptimizer::TraverseCallback
OptimizerWithRegularizerEveryNumBatches::startCatchUpWith() const {
  TraverseCallbackVec callbacks;

  if (auto callback = optimizer_->startCatchUpWith()) {
    callbacks.emplace_back(callback);
  }

  if (baseTimer_ < timer_) {
    callbacks.emplace_back(
56 57
        [this](const VectorPtr vecs[],
               const ParameterConfig& config,
Z
zhangjinchao01 已提交
58 59 60 61 62 63 64
               size_t sparseId) { this->catchUpWith(vecs, config, sparseId); });
  }

  return composeCallbacks(callbacks);
}

void OptimizerWithRegularizerEveryNumBatches::catchUpWith(
65 66
    const VectorPtr vecs[],
    const ParameterConfig& config,
Z
zhangjinchao01 已提交
67 68
    size_t sparseId) const {
  int32_t base = timer_ - timer_ % config.num_batches_regularization();
69 70 71 72 73
  regularizer_->update(vecs,
                       config,
                       optimizer_->getLearningRate(),
                       std::max(base, baseTimer_),
                       timer_);
Z
zhangjinchao01 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
}

void OptimizerWithRegularizerSparse::init(size_t numRows,
                                          const ParameterConfig* config) {
  OptimizerWithRegularizer::init(numRows, config);
  t0Vec_.resize(numRows);

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

void OptimizerWithRegularizerSparse::update(const VectorPtr vecs[],
                                            const ParameterConfig& config,
                                            size_t sparseId) const {
  optimizer_->update(vecs, config, sparseId);
  // para W(t0) -> W(t+1)
  CHECK_LT(sparseId, t0Vec_.size());
91 92 93 94 95
  regularizer_->update(vecs,
                       config,
                       optimizer_->getLearningRate(),
                       t0Vec_[sparseId],
                       timer_ + 1);
Z
zhangjinchao01 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108
  t0Vec_[sparseId] = timer_ + 1;
}

ParameterOptimizer::TraverseCallback
OptimizerWithRegularizerSparse::startCatchUpWith() const {
  TraverseCallbackVec callbacks;

  if (auto callback = optimizer_->startCatchUpWith()) {
    callbacks.emplace_back(callback);
  }

  if (timer_ > 0) {
    callbacks.emplace_back(
109 110
        [this](const VectorPtr vecs[],
               const ParameterConfig& config,
Z
zhangjinchao01 已提交
111 112 113 114 115 116 117 118 119 120 121
               size_t sparseId) { this->catchUpWith(vecs, config, sparseId); });
  }

  return composeCallbacks(callbacks);
}

void OptimizerWithRegularizerSparse::catchUpWith(const VectorPtr vecs[],
                                                 const ParameterConfig& config,
                                                 size_t sparseId) const {
  // para W(t0) -> W(t+1)
  CHECK_LT(sparseId, t0Vec_.size());
122 123
  regularizer_->update(
      vecs, config, optimizer_->getLearningRate(), t0Vec_[sparseId], timer_);
Z
zhangjinchao01 已提交
124 125 126 127
}

// factory method to create instance of OptimizerWithRegularizer
ParameterOptimizer* OptimizerWithRegularizer::create(
128 129 130 131
    const OptimizationConfig& optConfig,
    const ParameterConfig& paraConfig,
    bool isParameterSparse,
    bool inPserver) {
Z
zhangjinchao01 已提交
132 133 134
  ParameterOptimizer* optimizer =
      ParameterOptimizer::create(optConfig, inPserver);
  if (paraConfig.gradient_clipping_threshold() > 0.0f &&
135
      !dynamic_cast<AddOptimizer*>(optimizer)) {
Z
zhangjinchao01 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    optimizer = new OptimizerWithGradientClipping(optConfig, optimizer);
  }
  Regularizer* regularizer =
      Regularizer::get(optimizer->getParameterTypes(), paraConfig);
  if (!regularizer) {
    return optimizer;
  }

  if (paraConfig.num_batches_regularization() > 1) {
    if (optConfig.num_batches_per_send_parameter() > 1) {
      CHECK_EQ(optConfig.num_batches_per_send_parameter() %
                   paraConfig.num_batches_regularization(),
               0)
          << "regularization should be apply in sending batch";
    }
    CHECK(paraConfig.momentum() == 0.0f) << "Parameter cannot support momentum "
                                            "if num_batches_regularization set";

    if (optConfig.center_parameter_update_method() == "average" &&
        optConfig.num_batches_per_send_parameter() ==
            paraConfig.num_batches_regularization()) {
      LOG(INFO) << "decay in pserver and no decay in trainer";
      if (inPserver) {  // decay in pserver
        optimizer->setNoDecay();
        return new OptimizerWithRegularizer(optConfig, optimizer, regularizer);
      }
      // no decay in trainer
      optimizer->setNoDecay();
      return optimizer;
    }
    if (dynamic_cast<AddOptimizer*>(optimizer)) {
      return optimizer;  // normal average, no decay in pserver
    }
    // normal
    optimizer->setNoDecay();
171 172
    return new OptimizerWithRegularizerEveryNumBatches(
        optConfig, optimizer, regularizer);
Z
zhangjinchao01 已提交
173 174
  }
  if (isParameterSparse) {
175 176
    CHECK(paraConfig.momentum() == 0.0f)
        << "Parameter cannot support momentum if it's sparse.";
Z
zhangjinchao01 已提交
177
    optimizer->setNoDecay();
178 179
    return new OptimizerWithRegularizerSparse(
        optConfig, optimizer, regularizer);
Z
zhangjinchao01 已提交
180 181 182
  }
  // dense
  if (paraConfig.decay_rate_l1() == 0.0f ||
183
      dynamic_cast<AddOptimizer*>(optimizer)) {
Z
zhangjinchao01 已提交
184 185 186
    return optimizer;
  }
  CHECK(paraConfig.momentum() == 0.0f)
187
      << "Parameter cannot support momentum if it use L1 decay.";
Z
zhangjinchao01 已提交
188 189 190 191 192
  optimizer->setNoDecay();
  return new OptimizerWithRegularizer(optConfig, optimizer, regularizer);
}

}  // namespace paddle