ThreadParameterUpdater.cpp 9.6 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

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

#include "paddle/utils/Logging.h"

#include "paddle/math/SparseRowMatrix.h"
20
#include "paddle/parameter/ThreadLocalBuffer.h"
Z
zhangjinchao01 已提交
21 22
#include "paddle/utils/Thread.h"

23
DECLARE_int32(trainer_count);
24

Z
zhangjinchao01 已提交
25 26 27 28 29 30 31 32 33 34 35
namespace paddle {

SgdThreadUpdater::SgdThreadUpdater(const OptimizationConfig& optConfig)
    : config_(optConfig), numSamplesProcessed_(0) {
  // fill types
  auto types = sgdOptimizerGetTypes(optConfig, false /*inPserver*/);
  for (auto type : types) {
    addParameterType(type);
  }
}

Y
Yu Yang 已提交
36
void SgdThreadUpdater::init(const std::vector<ParameterPtr>& parameters) {
Z
zhangjinchao01 已提交
37 38 39 40 41 42 43 44 45 46 47
  ParameterUpdater::init(parameters);

  // calc max parameter id
  size_t maxId = 0;
  for (auto& para : parameters_) {
    maxId = std::max(maxId, para->getID());
  }

  optimizers_.resize(maxId + 1);
  for (auto& para : parameters_) {
    int pid = para->getID();
48 49
    optimizers_[pid].reset(sgdOptimizerCreate(config_,
                                              para->getConfig(),
Z
zhangjinchao01 已提交
50 51 52 53
                                              para->isGradSparseUpdate(),
                                              false /*inPserver*/));
    size_t numRows = para->isGradSparseUpdate() ? para->getConfig().dims(0) : 0;
    optimizers_[pid]->init(numRows, &para->getConfig());
54 55 56 57 58
    if (para->isGradSparseUpdate() && FLAGS_trainer_count == 1) {
      // For trainer_count=1, the gradient machine is NeuralNetwork, which does
      // not create parameter buf for PARAMETER_GRADIENT for sparse update in
      // Parameter::enableType(). But gradient parameter buf is still used
      // in SgdThreadUpdater. We need to explicitly create it.
59 60 61
      //
      // The AverageOptimizer::restore/apply method will use PARAMETER_GRADIENT
      // as a temp buffer.
62 63
      para->enableBufType(PARAMETER_GRADIENT);
    }
Z
zhangjinchao01 已提交
64 65 66 67 68 69 70 71 72 73
  }
}

void SgdThreadUpdater::startPass() {
  for (auto& para : parameters_) {
    int pid = para->getID();
    optimizers_[pid]->startPass();
  }
}

74
bool SgdThreadUpdater::finishPass() {
Z
zhangjinchao01 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  catchUpWith();

  for (auto& para : parameters_) {
    int pid = para->getID();
    optimizers_[pid]->finishPass();
  }
  return true;
}

void SgdThreadUpdater::updateImpl(Parameter* para) {
  if (!para->useGpu()) return;
  SetDevice setDevice(para->getDeviceId());
  ParameterOptimizer* optimizer = optimizers_[para->getID()].get();
  optimizer->update(para->getBufs(), para->getConfig());
  if (auto callback = optimizer->needSpecialTraversal(para->getConfig())) {
    callback(para->getBufs(), para->getConfig(), -1LU);
  }

  para->setValueUpdated();
  para->clearGradient();
}

void SgdThreadUpdater::threadTraverse(
98 99 100 101
    const ParameterOptimizer::TraverseCallback& callback,
    int tid,
    size_t numThreads,
    Parameter* para) {
102
  VectorPtr* vecs = parameter::getThreadLocalBuffer();
Z
zhangjinchao01 已提交
103 104 105 106 107 108 109 110 111 112 113 114
  if (para->isGradSparseUpdate()) {
    size_t height = para->getConfig().dims(0);
    size_t width = para->getConfig().dims(1);
    for (size_t i = tid; i < height; i += numThreads) {
      // setup sub bufs
      for (auto type : parameterTypes_) {
        vecs[type]->subVecFrom(*para->getBuf(type), i * width, width);
      }
      callback(vecs, para->getConfig(), i);
    }
  } else {  // dense
    // setup sub bufs
115 116
    auto interval = calcSplitArrayInterval(
        para->getSize(), (size_t)tid, numThreads, 8LU /*for avx*/);
Z
zhangjinchao01 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    for (auto type : parameterTypes_) {
      vecs[type]->subVecFrom(*para->getBuf(type), interval);
    }

    callback(vecs, para->getConfig(), -1LU);
  }
}

void SgdThreadUpdater::traverse(GetTraverseCallback getTraverseCallback) {
  bool hasCpuPara = false;
  bool hasGpuPara = false;
  for (auto& para : parameters_) {
    if (para->useGpu()) {
      hasGpuPara = true;
    } else {
      hasCpuPara = true;
    }
  }

  auto cpuTraverse = [&](int tid, size_t numThreads) {
    for (auto& para : parameters_) {
      if (auto callback = getTraverseCallback(para.get())) {
        threadTraverse(callback, tid, numThreads, para.get());
      }
    }
  };
  auto gpuTraverse = [&](int tid, size_t numThreads) {
    for (auto& para : parameters_) {
      if (para->useGpu()) {
        if (auto callback = getTraverseCallback(para.get())) {
          SetDevice setDevice(para->getDeviceId());
          callback(para->getBufs(), para->getConfig(), -1LU);
        }
      }
    }
  };

  if (hasCpuPara && hasGpuPara) {
    getGlobalSyncThreadPool()->exec(cpuTraverse, gpuTraverse);
  } else if (hasCpuPara) {
    getGlobalSyncThreadPool()->exec(cpuTraverse);
  } else if (hasGpuPara) {
159
    gpuTraverse(0, 0);
Z
zhangjinchao01 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  }
}

void SgdThreadUpdater::catchUpWith() {
  traverse([this](Parameter* para) {
    return optimizers_[para->getID()]->startCatchUpWith();
  });

  for (auto& para : parameters_) {
    int pid = para->getID();
    optimizers_[pid]->finishCatchUpWith();
  }
}

void SgdThreadUpdater::apply() {
  catchUpWith();

177 178
  traverse(
      [this](Parameter* para) { return optimizers_[para->getID()]->apply(); });
Z
zhangjinchao01 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
}

void SgdThreadUpdater::restore() {
  traverse([this](Parameter* para) {
    return optimizers_[para->getID()]->restore();
  });
}

PassType SgdThreadUpdater::startBatch(int64_t batchSize) {
  numSamplesProcessed_ += batchSize;
  for (auto& para : parameters_) {
    int pid = para->getID();
    optimizers_[pid]->startBatch(numSamplesProcessed_);
  }
  return PASS_TRAIN;
}

void SgdThreadUpdater::finishBatch(real cost) {
  getGlobalSyncThreadPool()->exec([&](int tid, size_t numThreads) {
    for (auto& para : parameters_) {
      if (para->isGradSparseUpdate()) {
        threadUpdateSparse(tid, numThreads, para.get());
      } else if (!para->useGpu()) {
        threadUpdateDense(tid, numThreads, para.get());
      }
    }
  });

  for (auto& para : parameters_) {
    int pid = para->getID();
    optimizers_[pid]->finishBatch();
  }
}

213 214 215
void SgdThreadUpdater::threadUpdateSparse(int tid,
                                          size_t numThreads,
                                          Parameter* para) {
Z
zhangjinchao01 已提交
216 217
  int pid = para->getID();
  ParameterOptimizer* optimizer = optimizers_[pid].get();
218
  VectorPtr* vecs = parameter::getThreadLocalBuffer();
Z
zhangjinchao01 已提交
219 220 221 222 223

  size_t height = para->getConfig().dims(0);
  size_t width = para->getConfig().dims(1);

  if (dynamic_cast<SparseRowIdsCpuMatrix*>(
224
          para->getMat(PARAMETER_GRADIENT).get())) {
Z
zhangjinchao01 已提交
225 226
    // From MultiGradientMachine
    SparseRowIdsCpuMatrix* mainMat = dynamic_cast<SparseRowIdsCpuMatrix*>(
227
        para->getMat(PARAMETER_GRADIENT).get());
228
    std::vector<uint32_t>& sparseIds = mainMat->getIds(tid);
Z
zhangjinchao01 已提交
229 230 231 232 233 234 235 236 237

    for (auto id : sparseIds) {
      // setup sub bufs
      for (auto type : parameterTypes_) {
        vecs[type]->subVecFrom(*para->getBuf(type), id * width, width);
      }
      optimizer->update(vecs, para->getConfig(), id);
      vecs[PARAMETER_GRADIENT]->zeroMem();
    }
238
    sparseIds.clear();
Z
zhangjinchao01 已提交
239
  } else if (dynamic_cast<SparseRowCpuMatrix*>(
240
                 para->getMat(PARAMETER_GRADIENT).get())) {
Z
zhangjinchao01 已提交
241 242
    // From NeuralNetwork
    SparseRowCpuMatrix* mainMat = dynamic_cast<SparseRowCpuMatrix*>(
243
        para->getMat(PARAMETER_GRADIENT).get());
Z
zhangjinchao01 已提交
244 245 246 247

    std::vector<unsigned int>& localIndices =
        mainMat->getIndexDictHandle()->localIndices;

248 249
    auto interval =
        calcSplitArrayInterval(localIndices.size(), tid, numThreads);
Z
zhangjinchao01 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263
    for (size_t i = interval.first; i < interval.second; ++i) {
      auto id = localIndices[i];
      real* row = mainMat->getLocalRow(i);
      // setup sub bufs
      for (auto type : parameterTypes_) {
        if (type == PARAMETER_GRADIENT) {
          vecs[type]->subVecFrom(row, 0, width);
        } else {
          vecs[type]->subVecFrom(*para->getBuf(type), id * width, width);
        }
      }
      optimizer->update(vecs, para->getConfig(), id);
      vecs[PARAMETER_GRADIENT]->zeroMem();
    }
264 265
    // For numThreads > 1, MultiGradientMachine is used, which goes
    // to the above branch.
L
luotao1 已提交
266
    CHECK_EQ(numThreads, 1UL);
267
    mainMat->clearIndices();
Z
zhangjinchao01 已提交
268
  } else {
269
    auto& m = *para->getMat(PARAMETER_GRADIENT).get();
Z
zhangjinchao01 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    LOG(FATAL) << "Internal error: " << para->getName() << " "
               << typeid(m).name();
  }

  if (auto callback = optimizer->needSpecialTraversal(para->getConfig())) {
    for (size_t i = tid; i < height; i += numThreads) {
      // setup sub bufs
      for (auto type : parameterTypes_) {
        vecs[type]->subVecFrom(*para->getBuf(type), i * width, width);
      }
      callback(vecs, para->getConfig(), i);
    }
  }
}

285 286
void SgdThreadUpdater::threadUpdateDense(int tid,
                                         size_t numThreads,
Z
zhangjinchao01 已提交
287 288 289
                                         Parameter* para) {
  int pid = para->getID();
  ParameterOptimizer* optimizer = optimizers_[pid].get();
290
  VectorPtr* vecs = parameter::getThreadLocalBuffer();
Z
zhangjinchao01 已提交
291

292 293
  auto interval = calcSplitArrayInterval(
      para->getSize(), (size_t)tid, numThreads, 8LU /*for avx*/);
Z
zhangjinchao01 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

  // setup sub bufs
  for (auto type : parameterTypes_) {
    vecs[type]->subVecFrom(*para->getBuf(type), interval);
  }

  // update
  optimizer->update(vecs, para->getConfig());
  vecs[PARAMETER_GRADIENT]->zeroMem();

  if (auto callback = optimizer->needSpecialTraversal(para->getConfig())) {
    callback(vecs, para->getConfig(), -1LU);
  }
}

}  // namespace paddle