You need to sign in or sign up before continuing.
parallel_executor.cc 16.2 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
#include "lod_tensor.h"
Y
Yu Yang 已提交
18
#include "lod_tensor_array.h"
Y
Yu Yang 已提交
19
#include "op_registry.h"
Y
Yu Yang 已提交
20
#include "paddle/fluid/framework/details/computation_op_handle.h"
Y
Yu Yang 已提交
21
#include "paddle/fluid/framework/details/fetch_op_handle.h"
Y
Yu Yang 已提交
22
#include "paddle/fluid/framework/details/nccl_all_reduce_op_handle.h"
Y
Yu Yang 已提交
23
#include "paddle/fluid/framework/details/op_handle_base.h"
Y
Yu Yang 已提交
24
#include "paddle/fluid/framework/details/scale_loss_grad_op_handle.h"
Y
Yu Yang 已提交
25
#include "paddle/fluid/framework/details/var_handle.h"
Y
Yu Yang 已提交
26
#include "paddle/fluid/platform/nccl_helper.h"
Y
Yang Yang 已提交
27 28

namespace paddle {
Y
Yu Yang 已提交
29 30
namespace framework {

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

Y
Yu Yang 已提交
40 41 42 43 44 45
struct SSAGraph {
  std::vector<std::unordered_map<std::string, std::map<int, VarHandle>>> vars_;
  std::unordered_set<std::unique_ptr<VarHandleBase>> dep_vars_;
  std::vector<std::unique_ptr<OpHandleBase>> ops_;
};

Y
Yu Yang 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
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 已提交
64
        }
Y
Yu Yang 已提交
65 66 67 68 69 70 71 72 73
        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 已提交
74 75 76
            continue;
          }

Y
Yu Yang 已提交
77 78 79 80 81 82 83 84 85 86 87 88
          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 已提交
89 90 91 92 93
        }
      }
    }
  }

Y
Yu Yang 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  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 已提交
112 113
  }

Y
Yu Yang 已提交
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
  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 已提交
251

Y
Yu Yang 已提交
252 253
class ParallelExecutorPrivate {
 public:
Y
Yu Yang 已提交
254 255 256 257
  explicit ParallelExecutorPrivate(size_t num_threads,
                                   const std::vector<platform::Place> &places)
      : places_(places),
        fetch_dev_ctxs_(places),
Y
Yu Yang 已提交
258
        pool_(num_threads <= 1 ? nullptr : new ThreadPool(num_threads)) {}
Y
Yu Yang 已提交
259

Y
Stash  
Yu Yang 已提交
260
  std::vector<platform::Place> places_;
Y
Yu Yang 已提交
261
  platform::DeviceContextPool fetch_dev_ctxs_;
Y
Yu Yang 已提交
262
  std::vector<Scope *> local_scopes_;
Y
Yu Yang 已提交
263
  Scope *global_scope_;
Y
Yu Yang 已提交
264

Y
Yu Yang 已提交
265
  std::unique_ptr<platform::NCCLContextMap> nccl_ctxs_;
Y
Yu Yang 已提交
266

Y
Yu Yang 已提交
267
  SSAGraph graph_;
Y
Yu Yang 已提交
268

Y
Yu Yang 已提交
269
  // Use a simpler thread pool, might be faster.
Y
Yu Yang 已提交
270
  std::unique_ptr<ThreadPool> pool_;
Y
Yu Yang 已提交
271 272

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

Y
Yu Yang 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
  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 已提交
304 305
};

Y
Yu Yang 已提交
306
ParallelExecutor::ParallelExecutor(
Y
Yu Yang 已提交
307
    size_t num_threads, const std::vector<platform::Place> &places,
Y
Yu Yang 已提交
308 309 310
    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 已提交
311
    : member_(new ParallelExecutorPrivate(num_threads, places)) {
Y
Yu Yang 已提交
312
  member_->global_scope_ = scope;
Y
Yu Yang 已提交
313

Y
Yu Yang 已提交
314 315 316 317
  // 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 已提交
318 319
  for (size_t i = 0; i < member_->places_.size(); ++i) {
    member_->local_scopes_.push_back(&scope->NewScope());
Y
Yu Yang 已提交
320 321 322
  }

  // Bcast Parameters to all GPUs
Y
Yu Yang 已提交
323
  BuildNCCLCommunicator();
Y
Yu Yang 已提交
324
  if (platform::is_gpu_place(places[0]) &&
Y
Yu Yang 已提交
325 326
      member_->local_scopes_.size() != 1) {  // Is CUDA
    BCastParamsToGPUs(startup_program);
Y
Yu Yang 已提交
327 328 329 330 331
  }
  // 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 已提交
332 333 334 335
  MultiDevSSAGraphBuilder builder(member_->places_, loss_var_name, params,
                                  member_->local_scopes_,
                                  member_->nccl_ctxs_.get());
  builder.Build(main_program, &member_->graph_);
Y
Yu Yang 已提交
336 337

  // Step 3. Create vars in each scope;
Y
Yu Yang 已提交
338
  for (auto *scope : member_->local_scopes_) {
Y
Yu Yang 已提交
339 340 341 342 343 344 345 346
    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 已提交
347 348 349 350
}

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

Y
Yu Yang 已提交
354 355 356 357
  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 已提交
358
      ncclDataType_t data_type = platform::ToNCCLDataType(main_tensor.type());
Y
Yu Yang 已提交
359 360 361
      auto &dims = main_tensor.dims();
      size_t numel = main_tensor.numel();

Y
Yu Yang 已提交
362
      platform::NCCLGroupGuard guard;
Y
Yu Yang 已提交
363

Y
Update  
Yu Yang 已提交
364 365 366 367 368 369
      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 已提交
370
          auto local_scope = member_->local_scopes_[i];
Y
Update  
Yu Yang 已提交
371 372 373 374 375
          auto *t = local_scope->Var(var_desc->Name())->GetMutable<LoDTensor>();
          t->Resize(dims);
          buffer = t->mutable_data(place, main_tensor.type());
        }

Y
Yu Yang 已提交
376
        auto &nccl_ctx = member_->nccl_ctxs_->at(place);
Y
Yu Yang 已提交
377 378
        platform::dynload::ncclBcast(buffer, numel, data_type, 0,
                                     nccl_ctx.comm_, nccl_ctx.stream());
Y
Yu Yang 已提交
379
      }
Y
Stash  
Yu Yang 已提交
380
    }
Y
Yu Yang 已提交
381
    member_->nccl_ctxs_->WaitAll();
Y
Stash  
Yu Yang 已提交
382
  }
Y
Yu Yang 已提交
383 384 385 386
#else
  PADDLE_THROW("Not compiled with CUDA");
#endif
}
Y
Yu Yang 已提交
387

Y
Yu Yang 已提交
388 389
void ParallelExecutor::BuildNCCLCommunicator() const {
#ifdef PADDLE_WITH_CUDA
Y
Yu Yang 已提交
390
  member_->nccl_ctxs_.reset(new platform::NCCLContextMap(member_->places_));
Y
Yu Yang 已提交
391
#endif
Y
Yu Yang 已提交
392 393
}

Y
Yu Yang 已提交
394 395
void ParallelExecutor::Run(const std::vector<std::string> &fetch_tensors,
                           const std::string &fetched_var_name) {
Y
Yu Yang 已提交
396
  bool use_event = true;
Y
Debug  
Yu Yang 已提交
397
  FeedFetchList fetched_data(fetch_tensors.size());
Y
Yu Yang 已提交
398
  // Version --> VarHandle
Y
Yu Yang 已提交
399
  member_->exception_.reset();
Y
Yu Yang 已提交
400
  std::unordered_map<VarHandleBase *, std::atomic<bool>> pending_vars;
Y
Yu Yang 已提交
401
  std::unordered_map<OpHandleBase *, size_t> pending_ops;
Y
Yu Yang 已提交
402
  std::vector<DummyVarHandle> dummy_vars;
Y
Yu Yang 已提交
403

Y
Yu Yang 已提交
404
  for (auto &var_map : member_->graph_.vars_) {
Y
Yu Yang 已提交
405
    for (auto &name_pair : var_map) {
Y
Yu Yang 已提交
406
      for (auto &version_pair : name_pair.second) {
Y
Yu Yang 已提交
407 408
        pending_vars[&version_pair.second] =
            version_pair.second.generated_op_ == nullptr;
Y
Yu Yang 已提交
409 410 411 412
      }
    }
  }

Y
Yu Yang 已提交
413
  for (auto &var : member_->graph_.dep_vars_) {
Y
Yu Yang 已提交
414
    pending_vars[var.get()] = var->generated_op_ == nullptr;
Y
Yu Yang 已提交
415 416
  }

Y
Yu Yang 已提交
417
  std::vector<OpHandleBase *> to_run;
Y
Yu Yang 已提交
418

Y
Yu Yang 已提交
419
  for (auto &op : member_->graph_.ops_) {
Y
Yu Yang 已提交
420 421 422 423 424 425 426
    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 已提交
427 428 429
  std::unordered_map<std::string, std::vector<VarHandleBase *>> fetched_vars;

  for (auto &fetch_var_name : fetch_tensors) {
Y
Yu Yang 已提交
430
    for (auto &var_map : member_->graph_.vars_) {
Y
Yu Yang 已提交
431 432
      auto it = var_map.find(fetch_var_name);
      if (it != var_map.end()) {
Y
Yu Yang 已提交
433 434 435 436 437 438 439 440 441 442
        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 已提交
443
    fetch_ops.emplace_back(&fetched_data, i, &member_->local_scopes_);
Y
Yu Yang 已提交
444
    FetchOpHandle *op = &fetch_ops.back();
Y
Yu Yang 已提交
445 446

    // FIXME: Use new device context
Y
Yu Yang 已提交
447
    for (auto &p : member_->places_) {
Y
Yu Yang 已提交
448
      op->dev_ctx_[p] = member_->fetch_dev_ctxs_.Get(p);
Y
Yu Yang 已提交
449 450 451
    }

    for (auto *var : vars) {
Y
Yu Yang 已提交
452
      op->AddInput(var);
Y
Yu Yang 已提交
453
    }
Y
Yu Yang 已提交
454 455 456

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

Y
Yu Yang 已提交
460 461 462
    pending_ops.insert({op, op->inputs_.size()});
  }

Y
Yu Yang 已提交
463
  for (auto *op : to_run) {
Y
Yu Yang 已提交
464
    member_->RunOp(use_event, pending_vars, op);
Y
Yu Yang 已提交
465 466
  }

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

Y
Debug  
Yu Yang 已提交
496 497 498 499 500 501
  for (auto &fetch_op : fetch_ops) {
    fetch_op.WaitAndMergeCPUTensors();
  }

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

Y
Yu Yang 已提交
504
}  // namespace framework
Y
Yang Yang 已提交
505
}  // namespace paddle