parallel_executor.cc 15.9 KB
Newer Older
Y
Yang Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 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. */

#include "paddle/fluid/framework/parallel_executor.h"
Y
Yu Yang 已提交
16
#include "ThreadPool.h"
Y
Yu Yang 已提交
17 18
#include "lod_tensor.h"
#include "op_registry.h"
Y
Yu Yang 已提交
19
#include "paddle/fluid/framework/details/computation_op_handle.h"
Y
Yu Yang 已提交
20
#include "paddle/fluid/framework/details/fetch_op_handle.h"
Y
Yu Yang 已提交
21
#include "paddle/fluid/framework/details/nccl_all_reduce_op_handle.h"
Y
Yu Yang 已提交
22
#include "paddle/fluid/framework/details/scale_loss_grad_op_handle.h"
Y
Yu Yang 已提交
23
#include "paddle/fluid/framework/details/ssa_graph.h"
Y
Yang Yang 已提交
24 25

namespace paddle {
Y
Yu Yang 已提交
26 27
namespace framework {

Y
Yu Yang 已提交
28
using details::ComputationOpHandle;
Y
Yu Yang 已提交
29
using details::DummyVarHandle;
Y
Yu Yang 已提交
30
using details::FetchOpHandle;
Y
Yu Yang 已提交
31
using details::NCCLAllReduceOpHandle;
Y
Yu Yang 已提交
32
using details::OpHandleBase;
Y
Yu Yang 已提交
33
using details::ScaleLossGradOpHandle;
Y
Yu Yang 已提交
34
using details::SSAGraph;
Y
Yu Yang 已提交
35 36
using details::VarHandle;
using details::VarHandleBase;
Y
Yu Yang 已提交
37

Y
Yu Yang 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
class SSAGraphBuilder {
 public:
  virtual ~SSAGraphBuilder() {}
  virtual void Build(const ProgramDesc &program, SSAGraph *graph) const = 0;

 protected:
  /**
   * We only handle write after read(WAR), since it should not have a write
   * after write in program. If there are write after write operators, we need
   * prune them.
   *
   * https://en.wikipedia.org/wiki/Hazard_(computer_architecture)#Write_after_read_(WAR)
   */
  static void PolishGraphToSupportDataHazards(SSAGraph *graph) {
    for (auto &var_map : graph->vars_) {
      for (auto &name_pair : var_map) {
        if (name_pair.second.size() <= 1) {
          return;
Y
Yu Yang 已提交
56
        }
Y
Yu Yang 已提交
57 58 59 60 61 62 63 64 65
        auto it_new = name_pair.second.rbegin();
        auto it_old = name_pair.second.rbegin();
        ++it_old;
        for (; it_old != name_pair.second.rend(); it_new = it_old, ++it_old) {
          auto *write_op = it_new->second.generated_op_;
          auto &read_ops = it_old->second.pending_ops_;
          auto *ex_write_op = it_old->second.generated_op_;

          if (ex_write_op == nullptr) {  // Nobody write this var.
Y
Yu Yang 已提交
66 67 68
            continue;
          }

Y
Yu Yang 已提交
69 70 71 72 73 74 75 76 77 78 79 80
          for (auto *read_op : read_ops) {
            // Manually add a dependency var from read_op to write_op;
            if (read_op == write_op) {
              // Read Write is the same op.
              continue;
            }

            auto *dep_var = new DummyVarHandle();
            read_op->AddOutput(dep_var);
            write_op->AddInput(dep_var);
            graph->dep_vars_.emplace(dep_var);
          }
Y
Yu Yang 已提交
81 82 83 84 85
        }
      }
    }
  }

Y
Yu Yang 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
  static VarHandle *CreateOrGetLatestVarHandle(SSAGraph *graph,
                                               const std::string &each_var_name,
                                               const platform::Place &place,
                                               size_t place_offset) {
    auto &var_holders = graph->vars_[place_offset];
    auto &var_holder = var_holders[each_var_name];
    VarHandle *var = nullptr;
    if (var_holder.empty()) {
      auto &init_var = var_holder[0];
      init_var.place_ = place;
      init_var.name_ = each_var_name;
      init_var.generated_op_ = nullptr;
      init_var.version_ = 0;
      var = &init_var;
    } else {
      var = &var_holder.rbegin()->second;
    }
    return var;
Y
Yu Yang 已提交
104 105
  }

Y
Yu Yang 已提交
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
  static void CreateOpOutput(SSAGraph *graph, OpHandleBase *op_handle,
                             const std::string &each_var_name,
                             const platform::Place &place,
                             size_t place_offset) {
    auto &vars = graph->vars_[place_offset][each_var_name];
    size_t version = vars.size();
    auto &var = vars[version];
    var.version_ = version;
    var.name_ = each_var_name;
    var.place_ = place;
    op_handle->AddOutput(&var);
  }
};

class MultiDevSSAGraphBuilder : public SSAGraphBuilder {
 public:
  MultiDevSSAGraphBuilder(const std::vector<platform::Place> &places,
                          const std::string &loss_var_name,
                          const std::unordered_set<std::string> &params,
                          const std::vector<Scope *> &local_scopes,
                          platform::NCCLContextMap *nccl_ctxs)
      : loss_var_name_(loss_var_name),
        places_(places),
        local_scopes_(local_scopes),
        nccl_ctxs_(nccl_ctxs) {
    for (auto &p : params) {
      grad_names_.insert(GradVarName(p));
    }
  }

  void Build(const ProgramDesc &program, SSAGraph *graph) const override {
    SSAGraph &result = *graph;
    result.vars_.resize(places_.size());

    bool is_forwarding = true;
    for (auto *op : program.Block(0).AllOps()) {
      bool change_forward = false;
      if (!is_forwarding) {
        // FIXME(yy): Do not hard code like this
        if (op->OutputArgumentNames().size() == 1 &&
            op->OutputArgumentNames()[0] == GradVarName(loss_var_name_)) {
          continue;  // Drop fill 1. for backward coeff;
        }
      }

      for (size_t i = 0; i < places_.size(); ++i) {
        auto &p = places_[i];
        auto *s = local_scopes_[i];

        result.ops_.emplace_back(new ComputationOpHandle(*op, s, p));
        auto *op_handle = result.ops_.back().get();
        op_handle->dev_ctx_[p] = const_cast<platform::DeviceContext *>(
            platform::DeviceContextPool::Instance().Get(p));

        auto var_names = op->InputArgumentNames();

        for (auto &each_var_name : var_names) {
          VarHandle *var =
              CreateOrGetLatestVarHandle(&result, each_var_name, p, i);
          op_handle->AddInput(var);
        }
        var_names = op->OutputArgumentNames();

        for (auto &each_var_name : var_names) {
          CreateOpOutput(&result, op_handle, each_var_name, p, i);
        }

        if (is_forwarding) {
          if (var_names.size() == 1 && var_names[0] == loss_var_name_) {
            // Insert ScaleCost OpHandle
            op_handle = new ScaleLossGradOpHandle(local_scopes_.size(), s, p,
                                                  nccl_ctxs_->DevCtx(p));
            result.ops_.emplace_back(op_handle);

            // FIXME: Currently ScaleLossGradOp only use device_count as scale
            // factor. So it does not depend on any other operators.
            // VarHandle *loss = GetVarHandle(loss_var_name, place);
            // loss->pending_ops_.emplace_back(op_handle);
            // op_handle->inputs_.emplace_back(loss);

            CreateOpOutput(&result, op_handle, GradVarName(loss_var_name_), p,
                           i);
            change_forward = true;
          }
        }
      }

      if (change_forward) {
        is_forwarding = false;
      }

      if (!is_forwarding) {
        auto var_names = op->OutputArgumentNames();
        for (auto &og : var_names) {
          if (grad_names_.count(og) != 0) {  // is param grad
            // Insert NCCL AllReduce Op
            result.ops_.emplace_back(
                new NCCLAllReduceOpHandle(local_scopes_, places_, *nccl_ctxs_));
            auto *op_handle = result.ops_.back().get();

            for (size_t i = 0; i < places_.size(); ++i) {
              auto &p = places_[i];
              auto &vars = result.vars_[i][og];

              if (vars.empty()) {  // This device has no data. continue.
                continue;
              }
              auto *prev_grad = &vars[vars.size() - 1];
              op_handle->AddInput(prev_grad);

              auto &var = vars[vars.size()];
              var.place_ = p;
              var.name_ = og;
              var.version_ = vars.size() - 1;

              op_handle->AddOutput(&var);
            }
          }
        }
      }
    }

    /*
      Dependency graph has been constructed. However, there are still data
      harzaeds need to be handled.
     */
    PolishGraphToSupportDataHazards(&result);
  }

 private:
  std::string loss_var_name_;
  const std::vector<platform::Place> &places_;
  const std::vector<Scope *> &local_scopes_;
  platform::NCCLContextMap *nccl_ctxs_;

  std::unordered_set<std::string> grad_names_;
};
Y
Yu Yang 已提交
243

Y
Yu Yang 已提交
244 245
class ParallelExecutorPrivate {
 public:
Y
Yu Yang 已提交
246 247 248 249
  explicit ParallelExecutorPrivate(size_t num_threads,
                                   const std::vector<platform::Place> &places)
      : places_(places),
        fetch_dev_ctxs_(places),
Y
Yu Yang 已提交
250
        pool_(num_threads <= 1 ? nullptr : new ThreadPool(num_threads)) {}
Y
Yu Yang 已提交
251

Y
Stash  
Yu Yang 已提交
252
  std::vector<platform::Place> places_;
Y
Yu Yang 已提交
253
  platform::DeviceContextPool fetch_dev_ctxs_;
Y
Yu Yang 已提交
254
  std::vector<Scope *> local_scopes_;
Y
Yu Yang 已提交
255
  Scope *global_scope_;
Y
Yu Yang 已提交
256

Y
Yu Yang 已提交
257
  std::unique_ptr<platform::NCCLContextMap> nccl_ctxs_;
Y
Yu Yang 已提交
258

Y
Yu Yang 已提交
259
  SSAGraph graph_;
Y
Yu Yang 已提交
260

Y
Yu Yang 已提交
261
  // Use a simpler thread pool, might be faster.
Y
Yu Yang 已提交
262
  std::unique_ptr<ThreadPool> pool_;
Y
Yu Yang 已提交
263 264

  std::unique_ptr<platform::EnforceNotMet> exception_;
Y
Yu Yang 已提交
265

Y
Yu Yang 已提交
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 291 292 293 294 295
  void RunOp(
      bool use_event,
      std::unordered_map<VarHandleBase *, std::atomic<bool>> &pending_vars,
      OpHandleBase *op) {
    std::vector<std::atomic<bool> *> *ready_buffer =
        new std::vector<std::atomic<bool> *>();
    for (auto *var : op->outputs_) {
      ready_buffer->emplace_back(&pending_vars[var]);
    }

    auto op_run = [ready_buffer, op, this, use_event] {
      try {
        VLOG(10) << op->DebugString();
        op->Run(use_event);
        for (auto *ready : *ready_buffer) {
          ready->store(true, std::memory_order_release);
        }
        delete ready_buffer;
      } catch (platform::EnforceNotMet ex) {
        exception_.reset(new platform::EnforceNotMet(ex));
      } catch (...) {
        LOG(FATAL) << "Unknown exception catched";
      }
    };
    if (pool_) {
      pool_->enqueue(op_run);
    } else {
      op_run();
    }
  }
Y
Yu Yang 已提交
296 297
};

Y
Yu Yang 已提交
298
ParallelExecutor::ParallelExecutor(
Y
Yu Yang 已提交
299
    size_t num_threads, const std::vector<platform::Place> &places,
Y
Yu Yang 已提交
300 301 302
    const std::unordered_set<std::string> &params,
    const ProgramDesc &startup_program, const ProgramDesc &main_program,
    const std::string &loss_var_name, Scope *scope)
Y
Yu Yang 已提交
303
    : member_(new ParallelExecutorPrivate(num_threads, places)) {
Y
Yu Yang 已提交
304
  member_->global_scope_ = scope;
Y
Yu Yang 已提交
305

Y
Yu Yang 已提交
306 307 308 309
  // Step 1. RunStartupProgram and Bcast the params to devs.
  Executor exe(places[0]);
  exe.Run(startup_program, scope, 0);
  // Create local scopes
Y
Yu Yang 已提交
310 311
  for (size_t i = 0; i < member_->places_.size(); ++i) {
    member_->local_scopes_.push_back(&scope->NewScope());
Y
Yu Yang 已提交
312 313 314
  }

  // Bcast Parameters to all GPUs
Y
Yu Yang 已提交
315
  BuildNCCLCommunicator();
Y
Yu Yang 已提交
316
  if (platform::is_gpu_place(places[0]) &&
Y
Yu Yang 已提交
317 318
      member_->local_scopes_.size() != 1) {  // Is CUDA
    BCastParamsToGPUs(startup_program);
Y
Yu Yang 已提交
319 320 321 322 323
  }
  // Startup Program has been run. All local scopes has correct parameters.

  // Step 2. Convert main_program to SSA form and dependency graph. Also, insert
  // ncclOp
Y
Yu Yang 已提交
324 325 326 327
  MultiDevSSAGraphBuilder builder(member_->places_, loss_var_name, params,
                                  member_->local_scopes_,
                                  member_->nccl_ctxs_.get());
  builder.Build(main_program, &member_->graph_);
Y
Yu Yang 已提交
328 329

  // Step 3. Create vars in each scope;
Y
Yu Yang 已提交
330
  for (auto *scope : member_->local_scopes_) {
Y
Yu Yang 已提交
331 332 333 334 335 336 337 338
    for (auto *var : main_program.Block(0).AllVars()) {
      if (scope->FindVar(var->Name()) != nullptr) {
        continue;
      }

      InitializeVariable(scope->Var(var->Name()), var->GetType());
    }
  }
Y
Yu Yang 已提交
339 340 341 342
}

void ParallelExecutor::BCastParamsToGPUs(
    const ProgramDesc &startup_program) const {
Y
Yu Yang 已提交
343
#ifdef PADDLE_WITH_CUDA
Y
Yu Yang 已提交
344
  auto *main_scope = member_->local_scopes_[0];
Y
Yu Yang 已提交
345

Y
Yu Yang 已提交
346 347 348 349
  for (auto *var_desc : startup_program.Block(0).AllVars()) {
    if (var_desc->GetType() == proto::VarType::LOD_TENSOR) {
      auto &main_tensor =
          main_scope->FindVar(var_desc->Name())->Get<LoDTensor>();
Y
Yu Yang 已提交
350
      ncclDataType_t data_type = platform::ToNCCLDataType(main_tensor.type());
Y
Yu Yang 已提交
351 352 353
      auto &dims = main_tensor.dims();
      size_t numel = main_tensor.numel();

Y
Yu Yang 已提交
354
      platform::NCCLGroupGuard guard;
Y
Yu Yang 已提交
355

Y
Update  
Yu Yang 已提交
356 357 358 359 360 361
      for (size_t i = 0; i < member_->places_.size(); ++i) {
        auto place = member_->places_[i];
        void *buffer;
        if (i == 0) {
          buffer = const_cast<void *>(main_tensor.data<void>());
        } else {
Y
Yu Yang 已提交
362
          auto local_scope = member_->local_scopes_[i];
Y
Update  
Yu Yang 已提交
363 364 365 366 367
          auto *t = local_scope->Var(var_desc->Name())->GetMutable<LoDTensor>();
          t->Resize(dims);
          buffer = t->mutable_data(place, main_tensor.type());
        }

Y
Yu Yang 已提交
368
        auto &nccl_ctx = member_->nccl_ctxs_->at(place);
Y
Yu Yang 已提交
369 370
        platform::dynload::ncclBcast(buffer, numel, data_type, 0,
                                     nccl_ctx.comm_, nccl_ctx.stream());
Y
Yu Yang 已提交
371
      }
Y
Stash  
Yu Yang 已提交
372
    }
Y
Yu Yang 已提交
373
    member_->nccl_ctxs_->WaitAll();
Y
Stash  
Yu Yang 已提交
374
  }
Y
Yu Yang 已提交
375 376 377 378
#else
  PADDLE_THROW("Not compiled with CUDA");
#endif
}
Y
Yu Yang 已提交
379

Y
Yu Yang 已提交
380 381
void ParallelExecutor::BuildNCCLCommunicator() const {
#ifdef PADDLE_WITH_CUDA
Y
Yu Yang 已提交
382
  member_->nccl_ctxs_.reset(new platform::NCCLContextMap(member_->places_));
Y
Yu Yang 已提交
383
#endif
Y
Yu Yang 已提交
384 385
}

Y
Yu Yang 已提交
386 387
void ParallelExecutor::Run(const std::vector<std::string> &fetch_tensors,
                           const std::string &fetched_var_name) {
Y
Yu Yang 已提交
388
  bool use_event = true;
Y
Debug  
Yu Yang 已提交
389
  FeedFetchList fetched_data(fetch_tensors.size());
Y
Yu Yang 已提交
390
  // Version --> VarHandle
Y
Yu Yang 已提交
391
  member_->exception_.reset();
Y
Yu Yang 已提交
392
  std::unordered_map<VarHandleBase *, std::atomic<bool>> pending_vars;
Y
Yu Yang 已提交
393
  std::unordered_map<OpHandleBase *, size_t> pending_ops;
Y
Yu Yang 已提交
394
  std::vector<DummyVarHandle> dummy_vars;
Y
Yu Yang 已提交
395

Y
Yu Yang 已提交
396
  for (auto &var_map : member_->graph_.vars_) {
Y
Yu Yang 已提交
397
    for (auto &name_pair : var_map) {
Y
Yu Yang 已提交
398
      for (auto &version_pair : name_pair.second) {
Y
Yu Yang 已提交
399 400
        pending_vars[&version_pair.second] =
            version_pair.second.generated_op_ == nullptr;
Y
Yu Yang 已提交
401 402 403 404
      }
    }
  }

Y
Yu Yang 已提交
405
  for (auto &var : member_->graph_.dep_vars_) {
Y
Yu Yang 已提交
406
    pending_vars[var.get()] = var->generated_op_ == nullptr;
Y
Yu Yang 已提交
407 408
  }

Y
Yu Yang 已提交
409
  std::vector<OpHandleBase *> to_run;
Y
Yu Yang 已提交
410

Y
Yu Yang 已提交
411
  for (auto &op : member_->graph_.ops_) {
Y
Yu Yang 已提交
412 413 414 415 416 417 418
    if (op->inputs_.empty()) {  // Special case, Op has no input.
      to_run.emplace_back(op.get());
    } else {
      pending_ops.insert({op.get(), op->inputs_.size()});
    }
  }

Y
Yu Yang 已提交
419 420 421
  std::unordered_map<std::string, std::vector<VarHandleBase *>> fetched_vars;

  for (auto &fetch_var_name : fetch_tensors) {
Y
Yu Yang 已提交
422
    for (auto &var_map : member_->graph_.vars_) {
Y
Yu Yang 已提交
423 424
      auto it = var_map.find(fetch_var_name);
      if (it != var_map.end()) {
Y
Yu Yang 已提交
425 426 427 428 429 430 431 432 433 434
        fetched_vars[fetch_var_name].push_back(&it->second.rbegin()->second);
      }
    }
  }

  std::vector<FetchOpHandle> fetch_ops;

  for (size_t i = 0; i < fetch_tensors.size(); ++i) {
    auto &var_name = fetch_tensors[i];
    auto &vars = fetched_vars[var_name];
Y
Yu Yang 已提交
435
    fetch_ops.emplace_back(&fetched_data, i, &member_->local_scopes_);
Y
Yu Yang 已提交
436
    FetchOpHandle *op = &fetch_ops.back();
Y
Yu Yang 已提交
437 438

    // FIXME: Use new device context
Y
Yu Yang 已提交
439
    for (auto &p : member_->places_) {
Y
Yu Yang 已提交
440
      op->dev_ctx_[p] = member_->fetch_dev_ctxs_.Get(p);
Y
Yu Yang 已提交
441 442 443
    }

    for (auto *var : vars) {
Y
Yu Yang 已提交
444
      op->AddInput(var);
Y
Yu Yang 已提交
445
    }
Y
Yu Yang 已提交
446 447 448

    dummy_vars.emplace_back();
    auto *var = &dummy_vars.back();
Y
Yu Yang 已提交
449
    op->AddOutput(var);
Y
Yu Yang 已提交
450 451
    pending_vars[var] = false;

Y
Yu Yang 已提交
452 453 454
    pending_ops.insert({op, op->inputs_.size()});
  }

Y
Yu Yang 已提交
455
  for (auto *op : to_run) {
Y
Yu Yang 已提交
456
    member_->RunOp(use_event, pending_vars, op);
Y
Yu Yang 已提交
457 458
  }

Y
Yu Yang 已提交
459
  while (!pending_vars.empty()) {
Y
Yu Yang 已提交
460
    VarHandleBase *ready_var = nullptr;
Y
Yu Yang 已提交
461
    for (auto &pair : pending_vars) {
Y
Yu Yang 已提交
462
      if (pair.second.load(std::memory_order_acquire)) {
Y
Yu Yang 已提交
463
        ready_var = pair.first;
Y
Yu Yang 已提交
464 465
      }
    }
Y
Yu Yang 已提交
466
    if (ready_var == nullptr) {
Y
Yu Yang 已提交
467 468 469 470
      // FIXME use conditional var instead of busy wait.
      if (member_->exception_) {
        throw * member_->exception_;
      }
Y
Yu Yang 已提交
471
      continue;
Y
Yu Yang 已提交
472
    }
Y
Yu Yang 已提交
473
    pending_vars.erase(ready_var);
Y
Yu Yang 已提交
474
    to_run.clear();
Y
Yu Yang 已提交
475 476 477 478 479
    for (auto *op : ready_var->pending_ops_) {
      auto &deps = pending_ops[op];
      --deps;
      if (deps == 0) {
        to_run.emplace_back(op);
Y
Yu Yang 已提交
480 481 482 483
      }
    }
    for (auto *op : to_run) {
      pending_ops.erase(op);
Y
Yu Yang 已提交
484
      member_->RunOp(use_event, pending_vars, op);
Y
Yu Yang 已提交
485 486
    }
  }
Y
Yu Yang 已提交
487

Y
Debug  
Yu Yang 已提交
488 489 490 491 492 493
  for (auto &fetch_op : fetch_ops) {
    fetch_op.WaitAndMergeCPUTensors();
  }

  *member_->global_scope_->Var(fetched_var_name)->GetMutable<FeedFetchList>() =
      fetched_data;
Y
Yu Yang 已提交
494
}
Y
Yu Yang 已提交
495

Y
Yu Yang 已提交
496
}  // namespace framework
Y
Yang Yang 已提交
497
}  // namespace paddle