ThreadParameterUpdater.cpp 8.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 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 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 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 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 171 172 173 174 175 176 177 178 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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
/* 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. */


#include "ThreadParameterUpdater.h"

#include "paddle/utils/Logging.h"

#include "paddle/math/SparseRowMatrix.h"
#include "paddle/utils/Thread.h"

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);
  }
}

void SgdThreadUpdater::init(std::vector<ParameterPtr>& parameters) {
  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();
    optimizers_[pid].reset(sgdOptimizerCreate(config_, para->getConfig(),
                                              para->isGradSparseUpdate(),
                                              false /*inPserver*/));
    size_t numRows = para->isGradSparseUpdate() ? para->getConfig().dims(0) : 0;
    optimizers_[pid]->init(numRows, &para->getConfig());
  }
}

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

bool SgdThreadUpdater::finishPass(real cost) {
  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(
    const ParameterOptimizer::TraverseCallback& callback, int tid,
    size_t numThreads, Parameter* para) {
  VectorPtr* vecs = Parameter::getTlsTempBufs();
  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
    auto interval = calcSplitArrayInterval(para->getSize(), (size_t)tid,
                                           numThreads, 8LU /*for avx*/);
    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) {
    cpuTraverse(0, 0);
  }
}

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();

  traverse([this](Parameter* para) {
    return optimizers_[para->getID()]->apply();
  });
}

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();
  }
}

void SgdThreadUpdater::threadUpdateSparse(
    int tid, size_t numThreads, Parameter* para) {

  int pid = para->getID();
  ParameterOptimizer* optimizer = optimizers_[pid].get();
  VectorPtr* vecs = Parameter::getTlsTempBufs();

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

  if (dynamic_cast<SparseRowIdsCpuMatrix*>(
        para->getMat(PARAMETER_GRADIENT).get())) {
    // From MultiGradientMachine
    SparseRowIdsCpuMatrix* mainMat = dynamic_cast<SparseRowIdsCpuMatrix*>(
      para->getMat(PARAMETER_GRADIENT).get());
    const std::vector<uint32_t>& sparseIds = mainMat->getIds(tid);

    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();
    }
  } else if (dynamic_cast<SparseRowCpuMatrix*>(
               para->getMat(PARAMETER_GRADIENT).get())) {
    // From NeuralNetwork
    SparseRowCpuMatrix* mainMat = dynamic_cast<SparseRowCpuMatrix*>(
      para->getMat(PARAMETER_GRADIENT).get());

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

    auto interval = calcSplitArrayInterval(
      localIndices.size(), tid, numThreads);
    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();
    }
  } else {
    auto & m = *para->getMat(PARAMETER_GRADIENT).get();
    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);
    }
  }
}

void SgdThreadUpdater::threadUpdateDense(int tid, size_t numThreads,
                                         Parameter* para) {
  int pid = para->getID();
  ParameterOptimizer* optimizer = optimizers_[pid].get();
  VectorPtr* vecs = Parameter::getTlsTempBufs();

  auto interval = calcSplitArrayInterval(para->getSize(), (size_t)tid,
                                         numThreads, 8LU /*for avx*/);

  // 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