parallel_executor.cc 10.7 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/fetch_op_handle.h"
Y
Yu Yang 已提交
20
#include "paddle/fluid/framework/details/multi_devices_graph_builder.h"
Y
Yu Yang 已提交
21
#include "paddle/fluid/framework/details/ssa_graph.h"
Y
Yu Yang 已提交
22
#include "paddle/fluid/platform/nccl_helper.h"
Y
Yang Yang 已提交
23 24

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

Y
Yu Yang 已提交
27 28 29 30 31 32 33 34 35
using details::DummyVarHandle;
using details::FetchOpHandle;
using details::OpHandleBase;
using details::SSAGraph;
using details::VarHandleBase;

class SSAGraphExecutor {
  DISABLE_COPY_AND_ASSIGN(SSAGraphExecutor);

Y
Yu Yang 已提交
36
 public:
Y
Yu Yang 已提交
37 38 39
  // Steal graph inside
  explicit SSAGraphExecutor(std::unique_ptr<SSAGraph> &&graph)
      : graph_(std::move(graph)) {}
Y
Yu Yang 已提交
40

Y
Yu Yang 已提交
41
  virtual ~SSAGraphExecutor() {}
Y
Yu Yang 已提交
42

Y
Yu Yang 已提交
43
  virtual FeedFetchList Run(const std::vector<std::string> &fetch_tensors) = 0;
Y
Yu Yang 已提交
44

Y
Yu Yang 已提交
45
 protected:
Y
Yu Yang 已提交
46
  std::unique_ptr<SSAGraph> graph_;
Y
Yu Yang 已提交
47
};
Y
Yu Yang 已提交
48

Y
Yu Yang 已提交
49 50 51 52 53
class ThreadedSSAGraphExecutor : public SSAGraphExecutor {
 public:
  ThreadedSSAGraphExecutor(size_t num_threads, bool use_event,
                           const std::vector<Scope *> &local_scopes,
                           const std::vector<platform::Place> &places,
Y
Yu Yang 已提交
54 55
                           std::unique_ptr<SSAGraph> &&graph)
      : SSAGraphExecutor(std::move(graph)),
Y
Yu Yang 已提交
56 57 58 59 60 61
        pool_(num_threads >= 2 ? new ::ThreadPool(num_threads) : nullptr),
        local_scopes_(local_scopes),
        places_(places),
        fetch_ctxs_(places),
        use_event_(use_event) {}

Y
Yu Yang 已提交
62 63 64
  // Run a SSAGraph by a thread pool
  // Use topological sort algorithm
  FeedFetchList Run(const std::vector<std::string> &fetch_tensors) override {
Y
Yu Yang 已提交
65 66 67 68 69 70 71
    std::unordered_map<OpHandleBase *, size_t> pending_ops;
    std::unordered_map<VarHandleBase *, std::atomic<bool>> pending_vars;
    std::unordered_set<OpHandleBase *> ready_ops;

    auto InsertPendingVar = [&pending_vars](VarHandleBase &var) {
      pending_vars[&var] = var.generated_op_ == nullptr;
    };
Y
Yu Yang 已提交
72

Y
Yu Yang 已提交
73 74 75 76 77
    auto InsertPendingOp = [&pending_ops](OpHandleBase &op_instance) {
      pending_ops.insert({&op_instance, op_instance.inputs_.size()});
    };

    // Transform SSAGraph to pending_ops & pending_vars
Y
Yu Yang 已提交
78
    for (auto &var_map : graph_->vars_) {
Y
Yu Yang 已提交
79 80 81 82 83 84
      for (auto &name_pair : var_map) {
        for (auto &version_pair : name_pair.second) {
          InsertPendingVar(version_pair.second);
        }
      }
    }
Y
Yu Yang 已提交
85
    for (auto &var : graph_->dep_vars_) {
Y
Yu Yang 已提交
86 87 88
      InsertPendingVar(*var);
    }

Y
Yu Yang 已提交
89
    for (auto &op : graph_->ops_) {
Y
Yu Yang 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
      if (op->inputs_.empty()) {  // Special case, Op has no input.
        ready_ops.insert(op.get());
      } else {
        InsertPendingOp(*op);
      }
    }

    // Step 2. Insert FetchOps
    std::vector<FetchOpHandle> fetch_ops;
    std::vector<DummyVarHandle> dummy_vars;
    FeedFetchList fetch_data(fetch_tensors.size());

    std::unordered_map<std::string, std::vector<VarHandleBase *>> fetched_vars;

    for (auto &fetch_var_name : fetch_tensors) {
Y
Yu Yang 已提交
105
      for (auto &var_map : graph_->vars_) {
Y
Yu Yang 已提交
106 107 108 109 110 111
        auto it = var_map.find(fetch_var_name);
        if (it != var_map.end()) {
          fetched_vars[fetch_var_name].push_back(&it->second.rbegin()->second);
        }
      }
    }
Y
Yu Yang 已提交
112

Y
Yu Yang 已提交
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
    for (size_t i = 0; i < fetch_tensors.size(); ++i) {
      auto &var_name = fetch_tensors[i];
      auto &vars = fetched_vars[var_name];
      fetch_ops.emplace_back(&fetch_data, i, &local_scopes_);
      details::FetchOpHandle *op = &fetch_ops.back();

      // FIXME: Use new device context
      for (auto &p : places_) {
        op->dev_ctx_[p] = fetch_ctxs_.Get(p);
      }

      for (auto *var : vars) {
        op->AddInput(var);
      }

      dummy_vars.emplace_back();
      auto *var = &dummy_vars.back();
      var->generated_op_ = nullptr;
      op->AddOutput(var);
      InsertPendingVar(*var);
      InsertPendingOp(*op);
    }

    auto run_all_ready_ops = [&] {
      for (auto *op : ready_ops) {
        RunOp(pending_vars, op);
      }
      ready_ops.clear();
    };

    // Step 3. Execution
    while (!pending_vars.empty()) {
      // 1. Run All Ready ops
      run_all_ready_ops();

      // 2. Find ready variable
      VarHandleBase *ready_var = nullptr;
      for (auto &pair : pending_vars) {
        if (pair.second.load(std::memory_order_acquire)) {
          ready_var = pair.first;
          break;
        }
      }

      // if there is no variable ready
      if (ready_var == nullptr) {
        // FIXME use conditional var instead of busy wait.
        // if there is an exception, throw it
        if (exception_) {
          throw * exception_;
        }
        // keep waiting the ready variables
        continue;
      }

      // 3. Remove the dependency of ready_var.
      // Find the ready_ops after the ready_var.
      pending_vars.erase(ready_var);
      for (auto *op : ready_var->pending_ops_) {
        auto &deps = pending_ops[op];
        --deps;
        if (deps == 0) {
          ready_ops.insert(op);
        }
      }
      // Keep loop until all vars are ready.
    }

    // Wait FetchOps.
    for (auto &fetch_op : fetch_ops) {
      fetch_op.WaitAndMergeCPUTensors();
    }

Y
Yu Yang 已提交
186
    return fetch_data;
Y
Yu Yang 已提交
187 188 189 190 191 192 193 194
  }

  ~ThreadedSSAGraphExecutor() {}

 private:
  void RunOp(
      std::unordered_map<VarHandleBase *, std::atomic<bool>> &pending_vars,
      details::OpHandleBase *op) {
Y
Yu Yang 已提交
195 196 197 198 199 200
    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]);
    }

Y
Yu Yang 已提交
201
    auto op_run = [ready_buffer, op, this] {
Y
Yu Yang 已提交
202 203
      try {
        VLOG(10) << op->DebugString();
Y
Yu Yang 已提交
204
        op->Run(use_event_);
Y
Yu Yang 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        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 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

 private:
  std::unique_ptr<::ThreadPool> pool_;
  std::vector<Scope *> local_scopes_;
  std::vector<platform::Place> places_;
  platform::DeviceContextPool fetch_ctxs_;
  const bool use_event_;
  std::unique_ptr<platform::EnforceNotMet> exception_;
};

class ParallelExecutorPrivate {
 public:
  explicit ParallelExecutorPrivate(const std::vector<platform::Place> &places)
      : places_(places), fetch_dev_ctxs_(places) {}

  std::vector<platform::Place> places_;
  platform::DeviceContextPool fetch_dev_ctxs_;
  std::vector<Scope *> local_scopes_;
  Scope *global_scope_;

  std::unique_ptr<platform::NCCLContextMap> nccl_ctxs_;

  std::unique_ptr<SSAGraphExecutor> executor_;
Y
Yu Yang 已提交
244 245
};

Y
Yu Yang 已提交
246
ParallelExecutor::ParallelExecutor(
Y
Yu Yang 已提交
247
    size_t num_threads, const std::vector<platform::Place> &places,
Y
Yu Yang 已提交
248 249 250
    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 已提交
251
    : member_(new ParallelExecutorPrivate(places)) {
Y
Yu Yang 已提交
252
  member_->global_scope_ = scope;
Y
Yu Yang 已提交
253

Y
Yu Yang 已提交
254 255 256 257
  // 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 已提交
258 259
  for (size_t i = 0; i < member_->places_.size(); ++i) {
    member_->local_scopes_.push_back(&scope->NewScope());
Y
Yu Yang 已提交
260 261 262
  }

  // Bcast Parameters to all GPUs
Y
Yu Yang 已提交
263
  BuildNCCLCommunicator();
Y
Yu Yang 已提交
264
  if (platform::is_gpu_place(places[0]) &&
Y
Yu Yang 已提交
265 266
      member_->local_scopes_.size() != 1) {  // Is CUDA
    BCastParamsToGPUs(startup_program);
Y
Yu Yang 已提交
267 268 269 270 271
  }
  // 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 已提交
272 273 274
  details::MultiDevSSAGraphBuilder builder(member_->places_, loss_var_name,
                                           params, member_->local_scopes_,
                                           member_->nccl_ctxs_.get());
Y
Yu Yang 已提交
275
  auto graph = builder.Build(main_program);
Y
Yu Yang 已提交
276

Y
Yu Yang 已提交
277
  member_->executor_.reset(new ThreadedSSAGraphExecutor(
Y
Yu Yang 已提交
278
      num_threads, true, member_->local_scopes_, places, std::move(graph)));
Y
Yu Yang 已提交
279

Y
Yu Yang 已提交
280
  // Step 3. Create vars in each scope;
Y
Yu Yang 已提交
281
  for (auto *scope : member_->local_scopes_) {
Y
Yu Yang 已提交
282 283 284 285 286 287 288 289
    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 已提交
290 291 292 293
}

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

Y
Yu Yang 已提交
297 298 299 300
  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 已提交
301
      ncclDataType_t data_type = platform::ToNCCLDataType(main_tensor.type());
Y
Yu Yang 已提交
302 303 304
      auto &dims = main_tensor.dims();
      size_t numel = main_tensor.numel();

Y
Yu Yang 已提交
305
      platform::NCCLGroupGuard guard;
Y
Yu Yang 已提交
306

Y
Update  
Yu Yang 已提交
307 308 309 310 311 312
      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 已提交
313
          auto local_scope = member_->local_scopes_[i];
Y
Update  
Yu Yang 已提交
314 315 316 317 318
          auto *t = local_scope->Var(var_desc->Name())->GetMutable<LoDTensor>();
          t->Resize(dims);
          buffer = t->mutable_data(place, main_tensor.type());
        }

Y
Yu Yang 已提交
319
        auto &nccl_ctx = member_->nccl_ctxs_->at(place);
Y
Yu Yang 已提交
320 321
        platform::dynload::ncclBcast(buffer, numel, data_type, 0,
                                     nccl_ctx.comm_, nccl_ctx.stream());
Y
Yu Yang 已提交
322
      }
Y
Stash  
Yu Yang 已提交
323
    }
Y
Yu Yang 已提交
324
    member_->nccl_ctxs_->WaitAll();
Y
Stash  
Yu Yang 已提交
325
  }
Y
Yu Yang 已提交
326 327 328 329
#else
  PADDLE_THROW("Not compiled with CUDA");
#endif
}
Y
Yu Yang 已提交
330

Y
Yu Yang 已提交
331 332
void ParallelExecutor::BuildNCCLCommunicator() const {
#ifdef PADDLE_WITH_CUDA
Y
Yu Yang 已提交
333
  member_->nccl_ctxs_.reset(new platform::NCCLContextMap(member_->places_));
Y
Yu Yang 已提交
334
#endif
Y
Yu Yang 已提交
335 336
}

Y
Yu Yang 已提交
337 338
void ParallelExecutor::Run(const std::vector<std::string> &fetch_tensors,
                           const std::string &fetched_var_name) {
Y
Yu Yang 已提交
339 340 341
  auto fetch_data = member_->executor_->Run(fetch_tensors);
  *member_->global_scope_->Var(fetched_var_name)->GetMutable<FeedFetchList>() =
      fetch_data;
Y
Yu Yang 已提交
342
}
Y
Yu Yang 已提交
343

Y
Yu Yang 已提交
344
}  // namespace framework
Y
Yang Yang 已提交
345
}  // namespace paddle