ParallelNeuralNetwork.cpp 5.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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

X
Xin Pan 已提交
15 16
#include "paddle/legacy/utils/Stat.h"
#include "paddle/legacy/utils/Util.h"
Z
zhangjinchao01 已提交
17 18 19 20 21 22 23 24 25

#include "ParallelNeuralNetwork.h"

#include <pthread.h>
#include <sched.h>

namespace paddle {

void ParallelNeuralNetwork::init(
26 27 28 29
    const ModelConfig& config,
    ParamInitCallback callback,
    const std::vector<ParameterType>& parameterTypes,
    bool useGpu) {
Z
zhangjinchao01 已提交
30 31
  NeuralNetwork::init(config, callback, parameterTypes, useGpu);

32 33
  if (config.type() == "recurrent_nn") {
    LOG(FATAL)
34 35
        << "You can not add `--parallel_nn=true` on the command line, "
        << "parallel_nn training mode does not support the recurrent_nn model.";
36 37
  }

Z
zhangjinchao01 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
  useGpu_ = useGpu;
  numDevices_ = 0;
  if (useGpu_) {
    numDevices_ = hl_get_device_count();
  }

  for (auto& layer : layers_) {
    int deviceId = layer->getDeviceId();
    CHECK_LT(deviceId, numDevices_);
    addComputeThread(deviceId);
  }
}

void ParallelNeuralNetwork::addComputeThread(int deviceId) {
  for (auto& thread : threads_) {
    if (thread->getDeviceId() == deviceId) {
      return;
    }
  }

58 59
  threads_.emplace_back(new ParallelThread(
      threads_.size(), deviceId, deviceId >= 0 ? useGpu_ : false));
Z
zhangjinchao01 已提交
60 61 62 63 64 65 66 67 68 69 70 71
}

void ParallelNeuralNetwork::waitAllThread() {
  for (auto& thread : threads_) {
    thread->jobEnqueue(NULL, TASK_END_LAYER);
  }

  for (size_t i = 0; i < threads_.size(); i++) {
    threads_[i]->queue_.waitEmpty();
  }
}

72 73
void ParallelNeuralNetwork::dispatchByDeviceId(int deviceId,
                                               LayerPtr layer,
Z
zhangjinchao01 已提交
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
                                               TaskType task) {
  for (auto& thread : threads_) {
    if (thread->getDeviceId() == deviceId) {
      thread->jobEnqueue(layer, task);
      return;
    }
  }
  LOG(FATAL) << "No specific device thread ";
}

void ParallelNeuralNetwork::forward(const std::vector<Argument>& inArgs,
                                    std::vector<Argument>* outArgs,
                                    PassType passType) {
  for (auto& thread : threads_) {
    thread->setForwardPassType(passType);
  }
  CHECK_EQ(inArgs.size(), dataLayers_.size());
  outArgs->resize(outputLayers_.size());
  for (size_t i = 0; i != dataLayers_.size(); ++i) {
    const_cast<Argument&>(inArgs[i]).deviceId = -1;
    dataLayers_[i]->setData(inArgs[i]);
  }

  for (auto& layer : layers_) {
    dispatchByDeviceId(layer->getDeviceId(), layer, TASK_FORWARD);
  }

  {
    REGISTER_TIMER("forwardTime");
    waitAllThread();
  }
  outArgs->clear();
  outArgs->reserve(outputLayers_.size());
  for (auto& layer : outputLayers_) {
    outArgs->push_back(layer->getOutput());
  }
}

void ParallelNeuralNetwork::backward(const UpdateCallback& callback) {
  for (auto& thread : threads_) {
    thread->setBackwardCallback(callback);
  }

  FOR_EACH_R(layer, layers_) {
    dispatchByDeviceId((*layer)->getDeviceId(), *layer, TASK_BACKWARD);
  }
  {
    REGISTER_TIMER("backwardTime");
    waitAllThread();
  }
}

void ParallelNeuralNetwork::forwardBackward(const std::vector<Argument>& inArgs,
                                            std::vector<Argument>* outArgs,
                                            PassType passType,
                                            const UpdateCallback& callback) {
  forward(inArgs, outArgs, passType);
  backward(callback);
}

134
void ParallelNeuralNetwork::start() {
Z
zhangjinchao01 已提交
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
  for (auto& thread : threads_) {
    thread->start();
  }
}

ParallelThread::ParallelThread(int threadId, int deviceId, bool useGpu)
    : threadId_(threadId), deviceId_(deviceId), useGpu_(useGpu) {}

ParallelThread::~ParallelThread() { stop(); }

void ParallelThread::stop() {
  if (computeThread_) {
    jobEnqueue(NULL, TASK_THREAD_FINISH);
    computeThread_->join();
    computeThread_.reset(nullptr);
  }
}

void ParallelThread::computeThread() {
  LOG(INFO) << "gradComputeThread " << threadId_;

  if (useGpu_) {
    hl_init(deviceId_);
  }

  while (true) {
    struct Job job_work = queue_.dequeue();

    if (job_work.task_ == TASK_END_LAYER) {
      continue;
    } else if (job_work.task_ == TASK_THREAD_FINISH) {
      break;
    }

    if (TASK_FORWARD == job_work.task_) {
      {
        REGISTER_TIMER_INFO("waitInputValue",
                            job_work.layer_->getName().c_str());
        job_work.layer_->waitInputValue();
      }
      {
        REGISTER_TIMER_INFO("threadForwardTimer",
                            job_work.layer_->getName().c_str());
        job_work.layer_->forward(passType_);
      }
      {
        REGISTER_TIMER_INFO("copyOutputToOtherDevice",
                            job_work.layer_->getName().c_str());
        job_work.layer_->copyOutputToOtherDevice();
      }
    } else {
      {
        REGISTER_TIMER_INFO("waitAndMergeOutputGrad",
                            job_work.layer_->getName().c_str());
        job_work.layer_->waitAndMergeOutputGrad();
      }
      {
        REGISTER_TIMER_INFO("threadBackwardTimer",
                            job_work.layer_->getName().c_str());
        job_work.layer_->backward(backwardCallback_);
      }
      hl_stream_synchronize(HPPL_STREAM_DEFAULT);
      job_work.layer_->markAllInputGrad();
    }
  }
200
  hl_fini();
Z
zhangjinchao01 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214
}

void ParallelThread::start() {
  computeThread_.reset(new std::thread([this]() { computeThread(); }));
}

void ParallelThread::jobEnqueue(LayerPtr layer, TaskType task) {
  struct Job job_work;
  job_work.layer_ = layer;
  job_work.task_ = task;
  queue_.enqueue(job_work);
}

}  // namespace paddle