section_worker.cc 30.3 KB
Newer Older
H
hutuxian 已提交
1 2 3 4 5 6 7 8 9 10 11
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
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. */

12
#if defined(PADDLE_WITH_NCCL)
L
lilong12 已提交
13 14 15 16 17
#include <float.h>
#include "paddle/fluid/framework/executor_gc_helper.h"
#include "paddle/fluid/framework/garbage_collector.h"
#include "paddle/fluid/framework/program_desc.h"

H
hutuxian 已提交
18 19 20 21 22
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"

#include "paddle/fluid/framework/device_worker.h"
H
hutuxian 已提交
23
#include "paddle/fluid/framework/fleet/box_wrapper.h"
H
hutuxian 已提交
24 25 26 27 28 29 30 31 32 33
#include "paddle/fluid/framework/tensor_util.h"
#include "paddle/fluid/framework/trainer_desc.pb.h"
#include "paddle/fluid/platform/cpu_helper.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/lodtensor_printer.h"

namespace paddle {
namespace framework {

std::atomic<int> SectionWorker::cpu_id_(0);
L
lilong12 已提交
34
std::mutex SectionWorker::thread_mutex;
S
update  
sandyhouse 已提交
35
std::mutex SectionWorker::cout_mutex;
L
lilong12 已提交
36 37 38 39
std::condition_variable SectionWorker::thread_condition;
bool SectionWorker::threads_completed = false;
uint64_t SectionWorker::batch_id_(0);

H
hutuxian 已提交
40
void SectionWorker::Initialize(const TrainerDesc& desc) {
H
hutuxian 已提交
41
  dev_ctx_ = platform::DeviceContextPool::Instance().Get(place_);
L
lilong12 已提交
42
  program_.reset(new ProgramDesc(
H
hutuxian 已提交
43
      desc.section_param().section_config(section_id_).program_desc()));
L
lilong12 已提交
44
  for (auto& op_desc : program_->Block(0).AllOps()) {
H
hutuxian 已提交
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
    ops_.push_back(OpRegistry::CreateOp(*op_desc));
  }
}

void SectionWorker::AutoSetCPUAffinity(bool reuse) {
  int thread_cpu_id = cpu_id_.fetch_add(1);

  unsigned concurrency_cap = std::thread::hardware_concurrency();
  unsigned proc = thread_cpu_id;

  if (proc >= concurrency_cap) {
    if (reuse) {
      proc %= concurrency_cap;
    } else {
      LOG(INFO) << "All " << concurrency_cap
                << " CPUs have been set affinities. Fail to set "
                << thread_cpu_id << "th thread";
      return;
    }
  }

  cpu_set_t mask;
  CPU_ZERO(&mask);
  CPU_SET(proc, &mask);

  if (-1 == sched_setaffinity(0, sizeof(mask), &mask)) {
    LOG(WARNING) << "Fail to set thread affinity to CPU " << proc;
    return;
  }

  CPU_ZERO(&mask);
  if ((0 != sched_getaffinity(0, sizeof(mask), &mask)) ||
      (0 == CPU_ISSET(proc, &mask))) {
    LOG(WARNING) << "Fail to set thread affinity to CPU " << proc;
  }
L
lilong12 已提交
80
  VLOG(3) << "Set " << thread_cpu_id << "th thread affinity to CPU " << proc;
H
hutuxian 已提交
81 82 83
}

void SectionWorker::TrainFiles() {
L
lilong12 已提交
84
  VLOG(3) << "begin section_worker TrainFiles";
H
hutuxian 已提交
85 86
  AutoSetCPUAffinity(true);

L
lilong12 已提交
87 88 89 90 91 92 93 94
  int64_t max_memory_size = 0;
  std::unique_ptr<GarbageCollector> gc;
  auto unused_vars_ = GetUnusedVars(program_->Block(0), ops_, skip_vars_);
#ifdef PADDLE_WITH_CUDA
  if (platform::is_gpu_place(place_)) {
    if (IsFastEagerDeletionModeEnabled()) {
      gc.reset(new UnsafeFastGPUGarbageCollector(
          BOOST_GET_CONST(platform::CUDAPlace, place_), max_memory_size));
H
hutuxian 已提交
95
    } else {
L
lilong12 已提交
96 97
      gc.reset(new DefaultStreamGarbageCollector(
          BOOST_GET_CONST(platform::CUDAPlace, place_), max_memory_size));
H
hutuxian 已提交
98
    }
L
lilong12 已提交
99 100 101 102 103 104 105
  } else if (platform::is_cpu_place(place_)) {
#endif
    gc.reset(new CPUGarbageCollector(
        BOOST_GET_CONST(platform::CPUPlace, place_), max_memory_size));
#ifdef PADDLE_WITH_CUDA
  }
#endif
H
hutuxian 已提交
106

S
update  
sandyhouse 已提交
107 108
  platform::Timer batch_timer;

L
lilong12 已提交
109 110 111
  if (thread_id_ == 0) {
    while (true) {
      // Start a minibatch.
112 113
      // real number of microbatches run
      int real_microbatch_num = 0;
S
update  
sandyhouse 已提交
114
      batch_timer.Start();
L
lilong12 已提交
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
      for (int i = 0; i < num_microbatches_; ++i) {
        try {
          for (auto& op : ops_) {
            int op_role = op->Attr<int>(std::string("op_role"));
            // We run op with op_role = kLRSched only for the first microbatch
            // to avoid increasing the @LR_DECAY_STEP@ multiple times.
            bool run_first_mbatch =
                op_role == static_cast<int>(OpRole::kForward) ||
                op_role == (static_cast<int>(OpRole::kForward) |
                            static_cast<int>(OpRole::kLoss)) ||
                op_role == static_cast<int>(OpRole::kLRSched);
            bool run_others = op_role == static_cast<int>(OpRole::kForward) ||
                              op_role == (static_cast<int>(OpRole::kForward) |
                                          static_cast<int>(OpRole::kLoss));
            if ((i == 0 && run_first_mbatch) || (i != 0 && run_others)) {
              VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                      << " for scope " << i;
              op->Run(*microbatch_scopes_[i], place_);
              if (gc) {
                DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                    unused_vars_, gc.get());
              }
            }
          }
        } catch (platform::EOFException&) {
          std::unique_lock<std::mutex> lk(thread_mutex);
          threads_completed = true;
          VLOG(3) << "thread " << thread_id_ << " completed.";
          VLOG(3) << "called notify all";
          thread_condition.notify_all();
          VLOG(0) << "EOF encountered";
146
          break;
L
lilong12 已提交
147
        }
148 149 150
        {
          real_microbatch_num += 1;
          batch_id_ += 1;
L
lilong12 已提交
151 152 153 154
          VLOG(3) << "called notify all";
          std::unique_lock<std::mutex> lk(thread_mutex);
          thread_condition.notify_all();
        }
H
hutuxian 已提交
155
      }
S
update  
sandyhouse 已提交
156
      dev_ctx_->Wait();
S
sandyhouse 已提交
157

158
      VLOG(0) << "real_microbatch_num for thread 0 " << real_microbatch_num;
L
lilong12 已提交
159
      // backward pass
160
      for (int i = 0; i < real_microbatch_num; ++i) {
L
lilong12 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173
        for (auto& op : ops_) {
          int op_role = op->Attr<int>(std::string("op_role"));
          if (op_role == static_cast<int>(OpRole::kBackward) ||
              op_role == (static_cast<int>(OpRole::kBackward) |
                          static_cast<int>(OpRole::kLoss))) {
            VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                    << " for scope " << i;
            op->Run(*microbatch_scopes_[i], place_);
            if (gc) {
              DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                  unused_vars_, gc.get());
            }
          }
H
hutuxian 已提交
174 175
        }
      }
S
update  
sandyhouse 已提交
176
      dev_ctx_->Wait();
177 178 179 180 181
      if (real_microbatch_num == 0) {
        batch_timer.Pause();
        VLOG(0) << "batch time: " << batch_timer.ElapsedUS();
        return;
      }
L
lilong12 已提交
182 183 184 185 186 187 188 189 190 191 192 193
      // update pass
      for (auto& op : ops_) {
        int op_role = op->Attr<int>(std::string("op_role"));
        if (op_role == static_cast<int>(OpRole::kOptimize)) {
          VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                  << " for minibatch scope";
          op->Run(*microbatch_scopes_[0], place_);
          if (gc) {
            DeleteUnusedTensors(*microbatch_scopes_[num_microbatches_ - 1],
                                op.get(), unused_vars_, gc.get());
          }
        }
H
hutuxian 已提交
194
      }
L
lilong12 已提交
195
      dev_ctx_->Wait();
S
update  
sandyhouse 已提交
196 197
      batch_timer.Pause();
      VLOG(0) << "batch time: " << batch_timer.ElapsedUS();
S
sandyhouse 已提交
198 199 200 201 202 203
      {
        std::unique_lock<std::mutex> lk(thread_mutex);
        if (threads_completed) {
          return;
        }
      }
H
hutuxian 已提交
204
    }
L
lilong12 已提交
205 206 207
  } else {
    while (true) {
      // forward pass:
S
sandyhouse 已提交
208
      bool local_completed = false;
209
      int real_microbatch_num = 0;
L
lilong12 已提交
210
      for (int i = 0; i < num_microbatches_; ++i) {
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        {
          PADDLE_ENFORCE_LE(
              local_batch_id_, batch_id_,
              platform::errors::InvalidArgument(
                  "local_batch_id_ (%d) must be less than or equal to "
                  "batch_id_ (%d)",
                  local_batch_id_, batch_id_));
          std::unique_lock<std::mutex> lk(thread_mutex);
          if (local_batch_id_ == batch_id_ && !threads_completed) {
            thread_condition.wait(lk);
          }
          VLOG(3) << "thread " << thread_id_ << " local_batch_id_ "
                  << local_batch_id_ << " batch_id_ " << batch_id_;
          if (threads_completed) {
            VLOG(3) << "thread " << thread_id_ << " completed.";
            lk.unlock();
            threads_completed = false;
S
sandyhouse 已提交
228
            local_completed = true;
229 230 231 232 233 234
            break;
          }
          lk.unlock();
          local_batch_id_ += 1;
          real_microbatch_num += 1;
        }
L
lilong12 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        for (auto& op : ops_) {
          int op_role = op->Attr<int>(std::string("op_role"));
          // We run op with op_role = kLRSched only for the first microbatch
          // to avoid increasing the @LR_DECAY_STEP@ multiple times.
          bool run_first_mbatch =
              op_role == static_cast<int>(OpRole::kForward) ||
              op_role == (static_cast<int>(OpRole::kForward) |
                          static_cast<int>(OpRole::kLoss)) ||
              op_role == static_cast<int>(OpRole::kLRSched);
          bool run_others = op_role == static_cast<int>(OpRole::kForward) ||
                            op_role == (static_cast<int>(OpRole::kForward) |
                                        static_cast<int>(OpRole::kLoss));
          if ((i == 0 && run_first_mbatch) || (i != 0 && run_others)) {
            VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                    << " for scope " << i;
            op->Run(*microbatch_scopes_[i], place_);
            if (gc) {
              DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                  unused_vars_, gc.get());
            }
          }
        }
      }
S
update  
sandyhouse 已提交
258
      dev_ctx_->Wait();
L
lilong12 已提交
259
      // backward pass
260
      for (int i = 0; i < real_microbatch_num; ++i) {
L
lilong12 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        for (auto& op : ops_) {
          int op_role = op->Attr<int>(std::string("op_role"));
          if (op_role == static_cast<int>(OpRole::kBackward) ||
              op_role == (static_cast<int>(OpRole::kBackward) |
                          static_cast<int>(OpRole::kLoss))) {
            VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                    << " for scope " << i;
            op->Run(*microbatch_scopes_[i], place_);
            if (gc) {
              DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                  unused_vars_, gc.get());
            }
          }
        }
      }
S
update  
sandyhouse 已提交
276
      dev_ctx_->Wait();
L
lilong12 已提交
277
      // update pass
278 279 280
      if (real_microbatch_num == 0) {
        return;
      }
L
lilong12 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293
      for (auto& op : ops_) {
        int op_role = op->Attr<int>(std::string("op_role"));
        if (op_role == static_cast<int>(OpRole::kOptimize)) {
          VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                  << " for minibatch scope";
          op->Run(*microbatch_scopes_[0], place_);
          if (gc) {
            DeleteUnusedTensors(*microbatch_scopes_[num_microbatches_ - 1],
                                op.get(), unused_vars_, gc.get());
          }
        }
      }
      dev_ctx_->Wait();
S
sandyhouse 已提交
294 295 296
      if (local_completed) {
        return;
      }
H
hutuxian 已提交
297 298 299 300 301
    }
  }
}

void SectionWorker::TrainFilesWithProfiler() {
L
lilong12 已提交
302
  VLOG(3) << "begin section_worker TrainFiles with profiler";
H
hutuxian 已提交
303 304
  AutoSetCPUAffinity(true);

L
lilong12 已提交
305 306
  platform::Timer batch_timer;
  platform::Timer timeline;
H
hutuxian 已提交
307 308 309

  std::vector<double> op_total_time;
  std::vector<std::string> op_name;
L
lilong12 已提交
310 311 312
  std::vector<double> op_max_time;
  std::vector<double> op_min_time;
  std::vector<uint64_t> op_count;
H
hutuxian 已提交
313 314 315 316
  for (auto& op : ops_) {
    op_name.push_back(op->Type());
  }
  op_total_time.resize(ops_.size());
L
lilong12 已提交
317 318 319 320
  op_max_time.resize(ops_.size());
  op_min_time.resize(ops_.size());
  for (size_t i = 0; i < op_min_time.size(); ++i) {
    op_min_time[i] = DBL_MAX;
H
hutuxian 已提交
321
  }
L
lilong12 已提交
322 323 324 325 326 327 328 329 330 331 332
  op_count.resize(ops_.size());

  int64_t max_memory_size = 0;
  std::unique_ptr<GarbageCollector> gc;
  // const std::vector<std::string> keep_vars;
  auto unused_vars_ = GetUnusedVars(program_->Block(0), ops_, skip_vars_);
#ifdef PADDLE_WITH_CUDA
  if (platform::is_gpu_place(place_)) {
    if (IsFastEagerDeletionModeEnabled()) {
      gc.reset(new UnsafeFastGPUGarbageCollector(
          BOOST_GET_CONST(platform::CUDAPlace, place_), max_memory_size));
H
hutuxian 已提交
333
    } else {
L
lilong12 已提交
334 335
      gc.reset(new DefaultStreamGarbageCollector(
          BOOST_GET_CONST(platform::CUDAPlace, place_), max_memory_size));
H
hutuxian 已提交
336
    }
L
lilong12 已提交
337 338 339 340 341 342 343
  } else if (platform::is_cpu_place(place_)) {
#endif
    gc.reset(new CPUGarbageCollector(
        BOOST_GET_CONST(platform::CPUPlace, place_), max_memory_size));
#ifdef PADDLE_WITH_CUDA
  }
#endif
H
hutuxian 已提交
344

L
lilong12 已提交
345
  if (thread_id_ == 0) {
S
update  
sandyhouse 已提交
346 347 348 349
    struct timeval start;
    struct timeval end;
    struct timeval micro_start;
    struct timeval micro_end;
L
lilong12 已提交
350 351 352
    while (true) {
      // Start a minibatch.
      batch_timer.Start();
353
      int real_microbatch_num = 0;
L
lilong12 已提交
354 355 356
      for (int i = 0; i < num_microbatches_; ++i) {
        try {
          int op_idx = 0;
S
update  
sandyhouse 已提交
357
          gettimeofday(&micro_start, NULL);
L
lilong12 已提交
358
          for (auto& op : ops_) {
S
update  
sandyhouse 已提交
359
            gettimeofday(&start, NULL);
L
lilong12 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
            int op_role = op->Attr<int>(std::string("op_role"));
            // We run op with op_role = kLRSched only for the first microbatch
            // to avoid increasing the @LR_DECAY_STEP@ multiple times.
            bool run_first_mbatch =
                op_role == static_cast<int>(OpRole::kForward) ||
                op_role == (static_cast<int>(OpRole::kForward) |
                            static_cast<int>(OpRole::kLoss)) ||
                op_role == static_cast<int>(OpRole::kLRSched);
            bool run_others = op_role == static_cast<int>(OpRole::kForward) ||
                              op_role == (static_cast<int>(OpRole::kForward) |
                                          static_cast<int>(OpRole::kLoss));
            if ((i == 0 && run_first_mbatch) || (i != 0 && run_others)) {
              VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                      << " for scope " << i;
              timeline.Start();
              op->Run(*microbatch_scopes_[i], place_);
              if (gc) {
                DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                    unused_vars_, gc.get());
              }
S
update  
sandyhouse 已提交
380
              cudaDeviceSynchronize();
L
lilong12 已提交
381
              timeline.Pause();
S
update  
sandyhouse 已提交
382
              gettimeofday(&end, NULL);
L
lilong12 已提交
383 384 385 386 387 388 389 390 391 392
              auto time = timeline.ElapsedUS();
              op_total_time[op_idx] += time;
              if (time > op_max_time[op_idx]) {
                op_max_time[op_idx] = time;
              }
              if (time < op_min_time[op_idx]) {
                op_min_time[op_idx] = time;
              }
              op_count[op_idx] += 1;
              op_total_time[op_idx] += time;
S
update  
sandyhouse 已提交
393 394
              {
                std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
395
                std::cout << std::fixed;
S
update  
sandyhouse 已提交
396
                std::cout.precision(0);
S
sandyhouse 已提交
397 398 399 400 401
                std::cout << "::FWD:B[" << batch_id_ << "]:SEC[" << thread_id_
                          << "]:SCOPE[" << i << "]:OP[" << op->Type()
                          << "]:START[" << start.tv_sec * 1e6 + start.tv_usec
                          << "]:END[" << end.tv_sec * 1e6 + end.tv_usec << "]"
                          << std::endl;
S
update  
sandyhouse 已提交
402
              }
L
lilong12 已提交
403 404 405
            }
            op_idx++;
          }
S
update  
sandyhouse 已提交
406 407 408
          gettimeofday(&micro_end, NULL);
          {
            std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
409
            std::cout << std::fixed;
S
update  
sandyhouse 已提交
410 411
            std::cout.precision(0);
            std::cout << "!!FWD:B[" << batch_id_ << "]:SEC[" << thread_id_
S
sandyhouse 已提交
412 413 414 415
                      << "]:START["
                      << micro_start.tv_sec * 1e6 + micro_start.tv_usec
                      << "]:END[" << micro_end.tv_sec * 1e6 + micro_end.tv_usec
                      << "]" << std::endl;
S
update  
sandyhouse 已提交
416
          }
L
lilong12 已提交
417 418 419 420 421 422 423 424 425 426 427 428 429 430
        } catch (platform::EOFException&) {
          std::unique_lock<std::mutex> lk(thread_mutex);
          threads_completed = true;
          VLOG(3) << "thread " << thread_id_ << " completed.";
          VLOG(3) << "called notify all";
          thread_condition.notify_all();
          VLOG(0) << "EOF encountered";
          VLOG(0) << "============timeline============";
          for (size_t i = 0; i < ops_.size(); ++i) {
            VLOG(0) << "op: " << op_name[i] << ", max_time: " << op_max_time[i]
                    << ", min_time: " << op_min_time[i]
                    << ", mean_time: " << op_total_time[i] / op_count[i];
          }
          VLOG(0) << "================================";
431
          break;
L
lilong12 已提交
432
        }
433
        {
L
lilong12 已提交
434 435
          VLOG(3) << "called notify all";
          std::unique_lock<std::mutex> lk(thread_mutex);
436
          real_microbatch_num += 1;
L
lilong12 已提交
437 438 439
          batch_id_ += 1;
          thread_condition.notify_all();
        }
H
hutuxian 已提交
440
      }
S
update  
sandyhouse 已提交
441
      dev_ctx_->Wait();
L
lilong12 已提交
442
      // backward pass
443
      for (int i = 0; i < real_microbatch_num; ++i) {
L
lilong12 已提交
444
        int op_idx = 0;
S
update  
sandyhouse 已提交
445
        gettimeofday(&micro_start, NULL);
L
lilong12 已提交
446
        for (auto& op : ops_) {
S
update  
sandyhouse 已提交
447
          gettimeofday(&start, NULL);
L
lilong12 已提交
448 449 450 451 452 453 454 455 456 457 458 459
          int op_role = op->Attr<int>(std::string("op_role"));
          if (op_role == static_cast<int>(OpRole::kBackward) ||
              op_role == (static_cast<int>(OpRole::kBackward) |
                          static_cast<int>(OpRole::kLoss))) {
            VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                    << " for scope " << i;
            timeline.Start();
            op->Run(*microbatch_scopes_[i], place_);
            if (gc) {
              DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                  unused_vars_, gc.get());
            }
S
update  
sandyhouse 已提交
460 461
            cudaDeviceSynchronize();
            gettimeofday(&end, NULL);
L
lilong12 已提交
462 463 464 465 466 467 468 469 470 471 472
            timeline.Pause();
            auto time = timeline.ElapsedUS();
            op_total_time[op_idx] += time;
            if (time > op_max_time[op_idx]) {
              op_max_time[op_idx] = time;
            }
            if (time < op_min_time[op_idx]) {
              op_min_time[op_idx] = time;
            }
            op_count[op_idx] += 1;
            op_total_time[op_idx] += time;
S
update  
sandyhouse 已提交
473 474
            {
              std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
475
              std::cout << std::fixed;
S
update  
sandyhouse 已提交
476
              std::cout.precision(0);
S
sandyhouse 已提交
477 478 479 480 481
              std::cout << "::BWD:B[" << batch_id_ << "]:SEC[" << thread_id_
                        << "]:SCOPE[" << i << "]:OP[" << op->Type()
                        << "]:START[" << start.tv_sec * 1e6 + start.tv_usec
                        << "]:END[" << end.tv_sec * 1e6 + end.tv_usec << "]"
                        << std::endl;
S
update  
sandyhouse 已提交
482
            }
L
lilong12 已提交
483 484
          }
          op_idx++;
H
hutuxian 已提交
485
        }
S
update  
sandyhouse 已提交
486 487 488
        gettimeofday(&micro_end, NULL);
        {
          std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
489
          std::cout << std::fixed;
S
update  
sandyhouse 已提交
490 491
          std::cout.precision(0);
          std::cout << "!!BWD:B[" << batch_id_ << "]:SEC[" << thread_id_
S
sandyhouse 已提交
492 493 494 495
                    << "]:START["
                    << micro_start.tv_sec * 1e6 + micro_start.tv_usec
                    << "]:END[" << micro_end.tv_sec * 1e6 + micro_end.tv_usec
                    << "]" << std::endl;
S
update  
sandyhouse 已提交
496
        }
H
hutuxian 已提交
497
      }
S
update  
sandyhouse 已提交
498
      dev_ctx_->Wait();
499 500 501
      if (real_microbatch_num == 0) {
        batch_timer.Pause();
        VLOG(0) << "batch time: " << batch_timer.ElapsedUS();
S
sandyhouse 已提交
502
        return;
503
      }
L
lilong12 已提交
504 505
      // update pass
      int op_idx = 0;
S
update  
sandyhouse 已提交
506
      gettimeofday(&micro_start, NULL);
L
lilong12 已提交
507
      for (auto& op : ops_) {
S
update  
sandyhouse 已提交
508
        gettimeofday(&start, NULL);
L
lilong12 已提交
509 510 511 512 513 514 515 516 517 518
        int op_role = op->Attr<int>(std::string("op_role"));
        if (op_role == static_cast<int>(OpRole::kOptimize)) {
          VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                  << " for minibatch scope";
          timeline.Start();
          op->Run(*microbatch_scopes_[0], place_);
          if (gc) {
            DeleteUnusedTensors(*microbatch_scopes_[num_microbatches_ - 1],
                                op.get(), unused_vars_, gc.get());
          }
S
update  
sandyhouse 已提交
519 520
          cudaDeviceSynchronize();
          gettimeofday(&end, NULL);
L
lilong12 已提交
521 522 523 524 525 526 527 528 529 530 531
          timeline.Pause();
          auto time = timeline.ElapsedUS();
          op_total_time[op_idx] += time;
          if (time > op_max_time[op_idx]) {
            op_max_time[op_idx] = time;
          }
          if (time < op_min_time[op_idx]) {
            op_min_time[op_idx] = time;
          }
          op_count[op_idx] += 1;
          op_total_time[op_idx] += time;
S
update  
sandyhouse 已提交
532 533
          {
            std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
534
            std::cout << std::fixed;
S
update  
sandyhouse 已提交
535
            std::cout.precision(0);
S
sandyhouse 已提交
536 537 538 539 540
            std::cout << "::UPD:B[" << batch_id_ << "]:SEC[" << thread_id_
                      << "]:SCOPE[" << num_microbatches_ << "]:OP["
                      << op->Type() << "]:START["
                      << start.tv_sec * 1e6 + start.tv_usec << "]:END["
                      << end.tv_sec * 1e6 + end.tv_usec << "]" << std::endl;
S
update  
sandyhouse 已提交
541
          }
L
lilong12 已提交
542 543 544
        }
        op_idx++;
      }
S
update  
sandyhouse 已提交
545 546 547
      gettimeofday(&micro_end, NULL);
      {
        std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
548
        std::cout << std::fixed;
S
update  
sandyhouse 已提交
549 550
        std::cout.precision(0);
        std::cout << "!!UPD:B[" << batch_id_ << "]:SEC[" << thread_id_
S
sandyhouse 已提交
551 552 553 554
                  << "]:START["
                  << micro_start.tv_sec * 1e6 + micro_start.tv_usec << "]:END["
                  << micro_end.tv_sec * 1e6 + micro_end.tv_usec << "]"
                  << std::endl;
S
update  
sandyhouse 已提交
555
      }
H
hutuxian 已提交
556
      dev_ctx_->Wait();
L
lilong12 已提交
557 558
      batch_timer.Pause();
      VLOG(0) << "batch time: " << batch_timer.ElapsedUS();
S
sandyhouse 已提交
559 560 561 562 563 564
      {
        std::unique_lock<std::mutex> lk(thread_mutex);
        if (threads_completed) {
          return;
        }
      }
H
hutuxian 已提交
565
    }
L
lilong12 已提交
566
  } else {
S
update  
sandyhouse 已提交
567 568 569 570 571 572 573
    struct timeval start;
    struct timeval end;
    struct timeval micro_start;
    struct timeval micro_end;
    cudaEvent_t cu_start, cu_stop;
    cudaEventCreate(&cu_start);
    cudaEventCreate(&cu_stop);
S
sandyhouse 已提交
574
    bool local_completed = false;
L
lilong12 已提交
575 576
    while (true) {
      // forward pass:
577
      int real_microbatch_num = 0;
L
lilong12 已提交
578
      for (int i = 0; i < num_microbatches_; ++i) {
579 580 581 582 583 584 585 586 587 588 589 590 591 592
        {
          PADDLE_ENFORCE_LE(
              local_batch_id_, batch_id_,
              platform::errors::InvalidArgument(
                  "local_batch_id_ (%d) must be less than or equal to "
                  "batch_id_ (%d)",
                  local_batch_id_, batch_id_));
          std::unique_lock<std::mutex> lk(thread_mutex);
          if (local_batch_id_ == batch_id_ && !threads_completed) {
            thread_condition.wait(lk);
          }
          VLOG(3) << "thread " << thread_id_ << " local_batch_id_ "
                  << local_batch_id_ << " batch_id_ " << batch_id_;
          if (threads_completed) {
S
sandyhouse 已提交
593
            local_completed = true;
594 595 596 597
            VLOG(3) << "thread " << thread_id_ << " completed.";
            lk.unlock();
            VLOG(0) << "============timeline============";
            for (size_t i = 0; i < ops_.size(); ++i) {
S
sandyhouse 已提交
598 599
              VLOG(0) << "op: " << op_name[i]
                      << ", max_time: " << op_max_time[i]
600 601 602 603 604 605 606 607 608 609
                      << ", min_time: " << op_min_time[i]
                      << ", mean_time: " << op_total_time[i] / op_count[i];
            }
            VLOG(0) << "================================";
            break;
          }
          lk.unlock();
          real_microbatch_num += 1;
          local_batch_id_ += 1;
        }
L
lilong12 已提交
610
        int op_idx = 0;
S
update  
sandyhouse 已提交
611
        gettimeofday(&micro_start, NULL);
L
lilong12 已提交
612
        for (auto& op : ops_) {
S
update  
sandyhouse 已提交
613
          gettimeofday(&start, NULL);
L
lilong12 已提交
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
          int op_role = op->Attr<int>(std::string("op_role"));
          // We run op with op_role = kLRSched only for the first microbatch
          // to avoid increasing the @LR_DECAY_STEP@ multiple times.
          bool run_first_mbatch =
              op_role == static_cast<int>(OpRole::kForward) ||
              op_role == (static_cast<int>(OpRole::kForward) |
                          static_cast<int>(OpRole::kLoss)) ||
              op_role == static_cast<int>(OpRole::kLRSched);
          bool run_others = op_role == static_cast<int>(OpRole::kForward) ||
                            op_role == (static_cast<int>(OpRole::kForward) |
                                        static_cast<int>(OpRole::kLoss));
          if ((i == 0 && run_first_mbatch) || (i != 0 && run_others)) {
            VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                    << " for scope " << i;
            timeline.Start();
            op->Run(*microbatch_scopes_[i], place_);
            if (gc) {
              DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                  unused_vars_, gc.get());
            }
S
update  
sandyhouse 已提交
634 635
            cudaDeviceSynchronize();
            gettimeofday(&end, NULL);
L
lilong12 已提交
636 637 638 639 640 641 642 643 644 645 646
            timeline.Pause();
            auto time = timeline.ElapsedUS();
            op_total_time[op_idx] += time;
            if (time > op_max_time[op_idx]) {
              op_max_time[op_idx] = time;
            }
            if (time < op_min_time[op_idx]) {
              op_min_time[op_idx] = time;
            }
            op_count[op_idx] += 1;
            op_total_time[op_idx] += time;
S
update  
sandyhouse 已提交
647 648
            {
              std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
649
              std::cout << std::fixed;
S
update  
sandyhouse 已提交
650
              std::cout.precision(0);
S
sandyhouse 已提交
651 652 653 654 655
              std::cout << "::FWD:B[" << local_batch_id_ << "]:SEC["
                        << thread_id_ << "]:SCOPE[" << i << "]:OP["
                        << op->Type() << "]:START["
                        << start.tv_sec * 1e6 + start.tv_usec << "]:END["
                        << end.tv_sec * 1e6 + end.tv_usec << "]" << std::endl;
S
update  
sandyhouse 已提交
656
            }
L
lilong12 已提交
657 658 659
          }
          op_idx++;
        }
S
update  
sandyhouse 已提交
660 661 662
        gettimeofday(&micro_end, NULL);
        {
          std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
663
          std::cout << std::fixed;
S
update  
sandyhouse 已提交
664 665
          std::cout.precision(0);
          std::cout << "!!FWD:B[" << batch_id_ << "]:SEC[" << thread_id_
S
sandyhouse 已提交
666 667 668 669
                    << "]:START["
                    << micro_start.tv_sec * 1e6 + micro_start.tv_usec
                    << "]:END[" << micro_end.tv_sec * 1e6 + micro_end.tv_usec
                    << "]" << std::endl;
S
update  
sandyhouse 已提交
670
        }
H
hutuxian 已提交
671
      }
S
update  
sandyhouse 已提交
672
      dev_ctx_->Wait();
L
lilong12 已提交
673
      // backward pass
674
      for (int i = 0; i < real_microbatch_num; ++i) {
L
lilong12 已提交
675
        int op_idx = 0;
S
update  
sandyhouse 已提交
676
        gettimeofday(&micro_start, NULL);
L
lilong12 已提交
677
        for (auto& op : ops_) {
S
update  
sandyhouse 已提交
678
          gettimeofday(&start, NULL);
L
lilong12 已提交
679 680 681 682 683 684 685 686 687 688 689 690
          int op_role = op->Attr<int>(std::string("op_role"));
          if (op_role == static_cast<int>(OpRole::kBackward) ||
              op_role == (static_cast<int>(OpRole::kBackward) |
                          static_cast<int>(OpRole::kLoss))) {
            VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                    << " for scope " << i;
            timeline.Start();
            op->Run(*microbatch_scopes_[i], place_);
            if (gc) {
              DeleteUnusedTensors(*microbatch_scopes_[i], op.get(),
                                  unused_vars_, gc.get());
            }
S
update  
sandyhouse 已提交
691 692
            cudaDeviceSynchronize();
            gettimeofday(&end, NULL);
L
lilong12 已提交
693 694 695 696 697 698 699 700 701 702 703
            timeline.Pause();
            auto time = timeline.ElapsedUS();
            op_total_time[op_idx] += time;
            if (time > op_max_time[op_idx]) {
              op_max_time[op_idx] = time;
            }
            if (time < op_min_time[op_idx]) {
              op_min_time[op_idx] = time;
            }
            op_count[op_idx] += 1;
            op_total_time[op_idx] += time;
S
update  
sandyhouse 已提交
704 705
            {
              std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
706
              std::cout << std::fixed;
S
update  
sandyhouse 已提交
707
              std::cout.precision(0);
S
sandyhouse 已提交
708 709 710 711 712
              std::cout << "::BWD:B[" << local_batch_id_ << "]:SEC["
                        << thread_id_ << "]:SCOPE[" << i << "]:OP["
                        << op->Type() << "]:START["
                        << start.tv_sec * 1e6 + start.tv_usec << "]:END["
                        << end.tv_sec * 1e6 + end.tv_usec << "]" << std::endl;
S
update  
sandyhouse 已提交
713
            }
L
lilong12 已提交
714 715 716
          }
          op_idx++;
        }
S
update  
sandyhouse 已提交
717 718 719
        gettimeofday(&micro_end, NULL);
        {
          std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
720
          std::cout << std::fixed;
S
update  
sandyhouse 已提交
721 722
          std::cout.precision(0);
          std::cout << "!!BWD:B[" << batch_id_ << "]:SEC[" << thread_id_
S
sandyhouse 已提交
723 724 725 726
                    << "]:START["
                    << micro_start.tv_sec * 1e6 + micro_start.tv_usec
                    << "]:END[" << micro_end.tv_sec * 1e6 + micro_end.tv_usec
                    << "]" << std::endl;
S
update  
sandyhouse 已提交
727
        }
L
lilong12 已提交
728
      }
S
update  
sandyhouse 已提交
729
      dev_ctx_->Wait();
730 731 732
      if (real_microbatch_num == 0) {
        return;
      }
L
lilong12 已提交
733 734
      // update pass
      int op_idx = 0;
S
update  
sandyhouse 已提交
735
      gettimeofday(&micro_start, NULL);
L
lilong12 已提交
736
      for (auto& op : ops_) {
S
update  
sandyhouse 已提交
737
        gettimeofday(&start, NULL);
L
lilong12 已提交
738 739 740 741 742 743 744 745 746 747
        int op_role = op->Attr<int>(std::string("op_role"));
        if (op_role == static_cast<int>(OpRole::kOptimize)) {
          VLOG(3) << "running an op " << op->Type() << " for " << thread_id_
                  << " for minibatch scope";
          timeline.Start();
          op->Run(*microbatch_scopes_[0], place_);
          if (gc) {
            DeleteUnusedTensors(*microbatch_scopes_[num_microbatches_ - 1],
                                op.get(), unused_vars_, gc.get());
          }
S
update  
sandyhouse 已提交
748 749
          cudaDeviceSynchronize();
          gettimeofday(&end, NULL);
L
lilong12 已提交
750 751 752 753 754 755 756 757 758 759 760
          timeline.Pause();
          auto time = timeline.ElapsedUS();
          op_total_time[op_idx] += time;
          if (time > op_max_time[op_idx]) {
            op_max_time[op_idx] = time;
          }
          if (time < op_min_time[op_idx]) {
            op_min_time[op_idx] = time;
          }
          op_count[op_idx] += 1;
          op_total_time[op_idx] += time;
S
update  
sandyhouse 已提交
761 762
          {
            std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
763
            std::cout << std::fixed;
S
update  
sandyhouse 已提交
764
            std::cout.precision(0);
S
sandyhouse 已提交
765 766 767 768 769
            std::cout << "::UPD:B[" << batch_id_ << "]:SEC[" << thread_id_
                      << "]:SCOPE[" << num_microbatches_ << "]:OP["
                      << op->Type() << "]:START["
                      << start.tv_sec * 1e6 + start.tv_usec << "]:END["
                      << end.tv_sec * 1e6 + end.tv_usec << "]" << std::endl;
S
update  
sandyhouse 已提交
770
          }
L
lilong12 已提交
771 772 773
        }
        op_idx++;
      }
S
update  
sandyhouse 已提交
774 775 776
      gettimeofday(&micro_end, NULL);
      {
        std::unique_lock<std::mutex> lk(cout_mutex);
S
sandyhouse 已提交
777
        std::cout << std::fixed;
S
update  
sandyhouse 已提交
778 779
        std::cout.precision(0);
        std::cout << "!!UPD:B[" << batch_id_ << "]:SEC[" << thread_id_
S
sandyhouse 已提交
780 781 782 783
                  << "]:START["
                  << micro_start.tv_sec * 1e6 + micro_start.tv_usec << "]:END["
                  << micro_end.tv_sec * 1e6 + micro_end.tv_usec << "]"
                  << std::endl;
S
update  
sandyhouse 已提交
784
      }
L
lilong12 已提交
785
      dev_ctx_->Wait();
S
sandyhouse 已提交
786 787 788
      if (local_completed) {
        return;
      }
H
hutuxian 已提交
789 790 791 792 793 794
    }
  }
}
}  // namespace framework
}  // namespace paddle
#endif