threaded_ssa_graph_executor.cc 9.3 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//   Copyright (c) 2018 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/details/threaded_ssa_graph_executor.h"

X
Xin Pan 已提交
17
#include "paddle/fluid/framework/ir/graph_helper.h"
18
#include "paddle/fluid/platform/profiler.h"
X
Xin Pan 已提交
19

Y
Yu Yang 已提交
20 21 22 23
namespace paddle {
namespace framework {
namespace details {
ThreadedSSAGraphExecutor::ThreadedSSAGraphExecutor(
Y
yuyang18 已提交
24
    const ExecutionStrategy &strategy, const std::vector<Scope *> &local_scopes,
X
Xin Pan 已提交
25 26
    const std::vector<platform::Place> &places, ir::Graph *graph)
    : graph_(graph),
Y
yuyang18 已提交
27 28
      pool_(strategy.num_threads_ >= 2 ? new ::ThreadPool(strategy.num_threads_)
                                       : nullptr),
29
      prepare_pool_(1),
Y
Yu Yang 已提交
30 31 32
      local_scopes_(local_scopes),
      places_(places),
      fetch_ctxs_(places),
33 34 35 36
      strategy_(strategy) {
  PrepareOpDeps();
  CopyOpDeps();
}
X
Xin Pan 已提交
37

Y
Yu Yang 已提交
38 39
FeedFetchList ThreadedSSAGraphExecutor::Run(
    const std::vector<std::string> &fetch_tensors) {
40
  std::unique_ptr<platform::RecordEvent> event(
41
      new platform::RecordEvent("ThreadedSSAGraphExecutorPrepare"));
42 43 44 45 46 47 48 49 50
  std::unique_ptr<OpDependentData> op_deps = op_deps_futures_.get();
  CopyOpDeps();
  VLOG(10) << "ThreadedSSAGraphExecutor::Run";
  std::shared_ptr<BlockingQueue<VarHandleBase *>> ready_vars(
      new BlockingQueue<VarHandleBase *>);
  auto &pending_ops = op_deps->pending_ops_;
  auto &pending_vars = op_deps->pending_vars_;
  auto &ready_ops = op_deps->ready_ops_;

X
Xin Pan 已提交
51 52 53 54
  // For ops (e.g. nccl_all_reduce) that need to coordinate multiple
  // streams from multiple GPUs, it's faster to buffer them and schedule
  // together since we currently cannot overlap computation and memcpy streams.
  // Should revisit it if overlapping is available.
X
Xin Pan 已提交
55 56
  std::unordered_set<OpHandleBase *> delayed_ops;

Y
Yu Yang 已提交
57
  // Step 2. Insert FetchOps
X
clean1  
Xin Pan 已提交
58 59
  std::vector<FetchOpHandle *> fetch_ops;
  std::unordered_set<VarHandleBase *> fetch_dependencies;
C
chengduoZH 已提交
60
  FeedFetchList fetch_data(fetch_tensors.size());
Y
Yu Yang 已提交
61

62 63
  InsertFetchOps(fetch_tensors, &fetch_ops, &fetch_dependencies, &ready_ops,
                 &pending_ops, &pending_vars, &fetch_data);
Y
Yu Yang 已提交
64

Y
Yu Yang 已提交
65 66
  auto run_all_ops = [&](std::unordered_set<OpHandleBase *> &set) {
    for (auto *op : set) {
67
      RunOp(ready_vars, op);
Y
Yu Yang 已提交
68
    }
Y
Yu Yang 已提交
69
    set.clear();
Y
Yu Yang 已提交
70
  };
71
  auto run_all_op = [&](OpHandleBase *op) { RunOp(ready_vars, op); };
Y
yuyang18 已提交
72 73
  // Clean run context
  run_op_futures_.clear();
74
  exception_holder_.Clear();
75
  event.reset(nullptr);
Y
Yu Yang 已提交
76
  // Step 3. Execution
Y
Yu Yang 已提交
77
  while (!pending_vars.empty()) {
Y
Yu Yang 已提交
78
    // 1. Run All Ready ops
Y
Yu Yang 已提交
79
    // Keep loop until all vars are ready.
80
    run_all_ops(ready_ops);
Y
Yu Yang 已提交
81 82

    // 2. Find ready variable
Y
Yu Yang 已提交
83
    bool timeout;
84
    auto cur_ready_vars = ready_vars->PopAll(1, &timeout);
Y
Yu Yang 已提交
85
    if (timeout) {
Y
yuyang18 已提交
86
      if (exception_holder_.IsCaught()) {
Y
yuyang18 已提交
87 88 89
        for (auto &run_op_future : run_op_futures_) {
          run_op_future.wait();
        }
X
Xin Pan 已提交
90
        ClearFetchOp(graph_, &fetch_ops);
Y
yuyang18 已提交
91
        exception_holder_.ReThrow();
Y
Yu Yang 已提交
92 93 94 95
      } else {
        continue;
      }
    }
96

Y
Yu Yang 已提交
97 98
    // 3. Remove the dependency of ready_var.
    // Find the ready_ops after the ready_var.
Y
Yu Yang 已提交
99 100
    for (auto ready_var : cur_ready_vars) {
      pending_vars.erase(ready_var);
X
Xin Pan 已提交
101
      for (auto *op : ready_var->PendingOps()) {
Y
Yu Yang 已提交
102 103 104
        auto &deps = pending_ops[op];
        --deps;
        if (deps == 0) {
105
          run_all_op(op);
Y
Yu Yang 已提交
106
        }
Y
Yu Yang 已提交
107 108 109
      }
    }
  }
X
Xin Pan 已提交
110
  PADDLE_ENFORCE(ready_ops.empty());
Y
Yu Yang 已提交
111
  // Wait FetchOps.
X
Xin Pan 已提交
112
  ClearFetchOp(graph_, &fetch_ops);
Y
Yu Yang 已提交
113

Y
Yu Yang 已提交
114 115 116
  return fetch_data;
}

C
chengduoZH 已提交
117 118
void ThreadedSSAGraphExecutor::InsertFetchOps(
    const std::vector<std::string> &fetch_tensors,
X
clean1  
Xin Pan 已提交
119 120
    std::vector<FetchOpHandle *> *fetch_ops,
    std::unordered_set<VarHandleBase *> *fetch_dependencies,
121
    std::unordered_set<OpHandleBase *> *ready_ops,
C
chengduoZH 已提交
122 123
    std::unordered_map<OpHandleBase *, size_t> *pending_ops,
    std::unordered_set<VarHandleBase *> *pending_vars,
124
    FeedFetchList *fetch_data) {
C
chengduoZH 已提交
125
  std::unordered_map<std::string, std::vector<VarHandleBase *>> fetched_vars;
126
  std::unordered_set<VarHandleBase *> local_ready_vars;
C
chengduoZH 已提交
127
  for (auto &fetch_var_name : fetch_tensors) {
X
Xin Pan 已提交
128
    for (auto &var_map : graph_->Get<details::GraphVars>(details::kGraphVars)) {
C
chengduoZH 已提交
129 130
      auto it = var_map.find(fetch_var_name);
      if (it != var_map.end()) {
131
        fetched_vars[fetch_var_name].emplace_back(*it->second.rbegin());
C
chengduoZH 已提交
132 133 134 135 136 137
      }
    }
  }

  for (size_t i = 0; i < fetch_tensors.size(); ++i) {
    auto &var_name = fetch_tensors[i];
Y
yuyang18 已提交
138 139
    auto fetched_var_it = fetched_vars.find(var_name);
    PADDLE_ENFORCE(fetched_var_it != fetched_vars.end(),
140 141 142
                   "Cannot find fetched variable(%s).(Perhaps the main_program "
                   "is not set to ParallelExecutor)",
                   var_name);
Y
yuyang18 已提交
143 144

    auto &vars = fetched_var_it->second;
X
Xin Pan 已提交
145

X
Xin Pan 已提交
146 147 148
    ir::Node *fetch_node =
        graph_->CreateEmptyNode("fetch", ir::Node::Type::kOperation);
    auto *op = new FetchOpHandle(fetch_node, fetch_data, i, &local_scopes_);
C
chengduoZH 已提交
149 150 151 152 153 154 155 156 157 158
    fetch_ops->emplace_back(op);

    for (auto &p : places_) {
      op->SetDeviceContext(p, fetch_ctxs_.Get(p));
    }

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

X
Xin Pan 已提交
159 160 161
    ir::Node *fetch_var =
        graph_->CreateEmptyNode("fetch", ir::Node::Type::kVariable);
    auto *fetch_dummy = new DummyVarHandle(fetch_var);
C
chengduoZH 已提交
162 163
    op->AddOutput(fetch_dummy);
    fetch_dependencies->emplace(fetch_dummy);
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178

    this->InsertPendingVar(pending_vars, &local_ready_vars, fetch_dummy);

    size_t wait_input_num = 0;
    std::unordered_set<VarHandleBase *> input_set(vars.begin(), vars.end());
    for (auto *var : input_set) {
      if (pending_vars->count(var)) {
        ++wait_input_num;
      }
    }
    if (wait_input_num) {
      pending_ops->insert({op, wait_input_num});
    } else {
      ready_ops->insert(static_cast<OpHandleBase *>(op));
    }
C
chengduoZH 已提交
179
  }
180
  PADDLE_ENFORCE_EQ(local_ready_vars.size(), 0);
C
chengduoZH 已提交
181 182 183 184 185
}

void ThreadedSSAGraphExecutor::InsertPendingOp(
    std::unordered_map<OpHandleBase *, size_t> *pending_ops,
    OpHandleBase *op_instance) const {
186
  pending_ops->insert({op_instance, op_instance->NoDupInputSize()});
C
chengduoZH 已提交
187 188 189 190
}

void ThreadedSSAGraphExecutor::InsertPendingVar(
    std::unordered_set<VarHandleBase *> *pending_vars,
191
    std::unordered_set<VarHandleBase *> *ready_vars, VarHandleBase *var) const {
C
chengduoZH 已提交
192
  pending_vars->insert(var);
X
Xin Pan 已提交
193
  if (var->GeneratedOp() == nullptr) {
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
    ready_vars->insert(var);
  }
}

void ThreadedSSAGraphExecutor::PrepareOpDeps() {
  op_deps_.reset(new OpDependentData());
  std::unordered_map<OpHandleBase *, size_t> &pending_ops =
      op_deps_->pending_ops_;
  std::unordered_set<VarHandleBase *> &pending_vars = op_deps_->pending_vars_;
  std::unordered_set<OpHandleBase *> &ready_ops = op_deps_->ready_ops_;
  std::unordered_set<VarHandleBase *> ready_vars;

  // Transform SSAGraph to pending_ops & pending_vars
  for (auto &var_map : graph_->Get<details::GraphVars>(details::kGraphVars)) {
    for (auto &name_pair : var_map) {
      for (auto &version_pair : name_pair.second) {
        InsertPendingVar(&pending_vars, &ready_vars, version_pair);
      }
    }
  }
  for (auto &var : graph_->Get<details::GraphDepVars>(details::kGraphDepVars)) {
    InsertPendingVar(&pending_vars, &ready_vars, var);
  }

  for (auto &op : ir::FilterByNodeWrapper<OpHandleBase>(*graph_)) {
    if (op->Inputs().empty()) {  // Special case, Op has no input.
      ready_ops.insert(op);
    } else {
      InsertPendingOp(&pending_ops, op);
    }
C
chengduoZH 已提交
224
  }
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  for (auto ready_var : ready_vars) {
    pending_vars.erase(ready_var);
    for (auto *op : ready_var->PendingOps()) {
      auto &deps = pending_ops[op];
      --deps;
      if (deps == 0) {
        ready_ops.insert(op);
      }
    }
  }
}

void ThreadedSSAGraphExecutor::CopyOpDeps() {
  op_deps_futures_ = prepare_pool_.enqueue([&] {
    auto *op_deps = new OpDependentData();
    op_deps->pending_ops_.insert(op_deps_->pending_ops_.begin(),
                                 op_deps_->pending_ops_.end());
    op_deps->pending_vars_.insert(op_deps_->pending_vars_.begin(),
                                  op_deps_->pending_vars_.end());
    op_deps->ready_ops_.insert(op_deps_->ready_ops_.begin(),
                               op_deps_->ready_ops_.end());
    return std::unique_ptr<OpDependentData>(op_deps);
  });
C
chengduoZH 已提交
248
}
C
chengduoZH 已提交
249

Y
Yu Yang 已提交
250
void ThreadedSSAGraphExecutor::RunOp(
251 252
    const std::shared_ptr<BlockingQueue<VarHandleBase *>> &ready_var_q,
    details::OpHandleBase *op) {
X
Xin Pan 已提交
253
  auto op_run = [ready_var_q, op, this] {
Y
Yu Yang 已提交
254
    try {
M
minqiyang 已提交
255 256
      if (VLOG_IS_ON(10)) {
        VLOG(10) << op << " " << op->Name() << " : " << op->DebugString();
Y
yuyang18 已提交
257
      }
258 259 260
      if (LIKELY(!strategy_.dry_run_)) {
        op->Run(strategy_.use_cuda_);
      }
M
minqiyang 已提交
261
      VLOG(10) << op << " " << op->Name() << " Done ";
X
Xin Pan 已提交
262
      ready_var_q->Extend(op->Outputs());
Y
Yancey1989 已提交
263
      VLOG(10) << op << " " << op->Name() << " Signal posted";
Y
Yu Yang 已提交
264
    } catch (...) {
Y
yuyang18 已提交
265
      exception_holder_.Catch(std::current_exception());
Y
Yu Yang 已提交
266 267 268
    }
  };
  if (pool_) {
Y
yuyang18 已提交
269
    run_op_futures_.emplace_back(pool_->enqueue(op_run));
Y
Yu Yang 已提交
270 271 272 273 274 275 276
  } else {
    op_run();
  }
}
}  // namespace details
}  // namespace framework
}  // namespace paddle