threaded_ssa_graph_executor.cc 6.9 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//   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"

namespace paddle {
namespace framework {
namespace details {
ThreadedSSAGraphExecutor::ThreadedSSAGraphExecutor(
Y
yuyang18 已提交
21
    const ExecutionStrategy &strategy, const std::vector<Scope *> &local_scopes,
Y
Yu Yang 已提交
22
    const std::vector<platform::Place> &places,
Y
yuyang18 已提交
23
    std::unique_ptr<SSAGraph> &&graph)
Y
Yu Yang 已提交
24
    : SSAGraphExecutor(std::move(graph)),
Y
yuyang18 已提交
25 26
      pool_(strategy.num_threads_ >= 2 ? new ::ThreadPool(strategy.num_threads_)
                                       : nullptr),
Y
Yu Yang 已提交
27 28 29
      local_scopes_(local_scopes),
      places_(places),
      fetch_ctxs_(places),
X
Xin Pan 已提交
30
      running_ops_(0),
Y
yuyang18 已提交
31
      strategy_(strategy) {}
X
Xin Pan 已提交
32

Y
Yu Yang 已提交
33 34 35
FeedFetchList ThreadedSSAGraphExecutor::Run(
    const std::vector<std::string> &fetch_tensors) {
  std::unordered_map<OpHandleBase *, size_t> pending_ops;
Y
Yu Yang 已提交
36 37
  std::unordered_set<VarHandleBase *> pending_vars;
  BlockingQueue<VarHandleBase *> ready_vars;
Y
Yu Yang 已提交
38
  std::unordered_set<OpHandleBase *> ready_ops;
X
Xin Pan 已提交
39 40 41 42
  // 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 已提交
43 44
  std::unordered_set<OpHandleBase *> delayed_ops;

Y
Yu Yang 已提交
45 46 47 48
  // Transform SSAGraph to pending_ops & pending_vars
  for (auto &var_map : graph_->vars_) {
    for (auto &name_pair : var_map) {
      for (auto &version_pair : name_pair.second) {
C
chengduoZH 已提交
49
        InsertPendingVar(&pending_vars, &ready_vars, version_pair.get());
Y
Yu Yang 已提交
50 51 52 53
      }
    }
  }
  for (auto &var : graph_->dep_vars_) {
C
chengduoZH 已提交
54
    InsertPendingVar(&pending_vars, &ready_vars, var.get());
Y
Yu Yang 已提交
55 56 57
  }

  for (auto &op : graph_->ops_) {
X
Xin Pan 已提交
58
    if (op->Inputs().empty()) {  // Special case, Op has no input.
Y
Yu Yang 已提交
59 60
      ready_ops.insert(op.get());
    } else {
C
chengduoZH 已提交
61
      InsertPendingOp(&pending_ops, op.get());
Y
Yu Yang 已提交
62 63 64 65
    }
  }

  // Step 2. Insert FetchOps
Y
Yu Yang 已提交
66
  std::vector<std::unique_ptr<FetchOpHandle>> fetch_ops;
Y
Yu Yang 已提交
67
  std::unordered_set<std::unique_ptr<VarHandleBase>> fetch_dependencies;
C
chengduoZH 已提交
68
  FeedFetchList fetch_data(fetch_tensors.size());
Y
Yu Yang 已提交
69

C
chengduoZH 已提交
70 71
  InsertFetchOps(fetch_tensors, &fetch_ops, &fetch_dependencies, &pending_ops,
                 &pending_vars, &ready_vars, &fetch_data);
Y
Yu Yang 已提交
72

Y
Yu Yang 已提交
73 74
  auto run_all_ops = [&](std::unordered_set<OpHandleBase *> &set) {
    for (auto *op : set) {
X
Xin Pan 已提交
75 76
      running_ops_++;
      RunOp(&ready_vars, op);
Y
Yu Yang 已提交
77
    }
Y
Yu Yang 已提交
78
    set.clear();
Y
Yu Yang 已提交
79 80 81
  };

  // Step 3. Execution
Y
Yu Yang 已提交
82
  while (!pending_vars.empty()) {
Y
Yu Yang 已提交
83
    // 1. Run All Ready ops
Y
Yu Yang 已提交
84 85 86 87
    // Keep loop until all vars are ready.
    //
    // NOTE: DelayedOps have a lower priority. It will be scheduled after all
    // ready_ops have been performed.
Y
yuyang18 已提交
88
    if (ready_ops.empty() && strategy_.allow_op_delay_ && running_ops_ == 0) {
Y
Yu Yang 已提交
89 90 91 92
      run_all_ops(delayed_ops);
    } else {
      run_all_ops(ready_ops);
    }
Y
Yu Yang 已提交
93 94

    // 2. Find ready variable
Y
Yu Yang 已提交
95
    bool timeout;
X
Xin Pan 已提交
96
    auto cur_ready_vars = ready_vars.PopAll(1, &timeout);
Y
Yu Yang 已提交
97 98 99

    if (timeout) {
      if (exception_) {
100 101 102
        auto exp = *exception_;
        exception_.reset();
        throw exp;
Y
Yu Yang 已提交
103 104 105 106
      } else {
        continue;
      }
    }
Y
Yu Yang 已提交
107 108
    // 3. Remove the dependency of ready_var.
    // Find the ready_ops after the ready_var.
Y
Yu Yang 已提交
109 110 111 112 113 114
    for (auto ready_var : cur_ready_vars) {
      pending_vars.erase(ready_var);
      for (auto *op : ready_var->pending_ops_) {
        auto &deps = pending_ops[op];
        --deps;
        if (deps == 0) {
Y
yuyang18 已提交
115
          if (op->IsMultiDeviceTransfer() && strategy_.allow_op_delay_) {
Y
Yu Yang 已提交
116
            delayed_ops.insert(op);
X
Xin Pan 已提交
117 118 119
          } else {
            ready_ops.insert(op);
          }
Y
Yu Yang 已提交
120
        }
Y
Yu Yang 已提交
121 122 123
      }
    }
  }
X
Xin Pan 已提交
124
  PADDLE_ENFORCE(ready_ops.empty());
Y
Yu Yang 已提交
125

Y
Yu Yang 已提交
126
  // Wait FetchOps.
Y
Yu Yang 已提交
127
  if (!fetch_ops.empty()) {
Y
Yu Yang 已提交
128
    fetch_ops.clear();
Y
Yu Yang 已提交
129 130
  }

Y
Yu Yang 已提交
131 132 133
  return fetch_data;
}

C
chengduoZH 已提交
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
void ThreadedSSAGraphExecutor::InsertFetchOps(
    const std::vector<std::string> &fetch_tensors,
    std::vector<std::unique_ptr<FetchOpHandle>> *fetch_ops,
    std::unordered_set<std::unique_ptr<VarHandleBase>> *fetch_dependencies,
    std::unordered_map<OpHandleBase *, size_t> *pending_ops,
    std::unordered_set<VarHandleBase *> *pending_vars,
    BlockingQueue<VarHandleBase *> *ready_vars, FeedFetchList *fetch_data) {
  std::unordered_map<std::string, std::vector<VarHandleBase *>> fetched_vars;

  for (auto &fetch_var_name : fetch_tensors) {
    for (auto &var_map : graph_->vars_) {
      auto it = var_map.find(fetch_var_name);
      if (it != var_map.end()) {
        fetched_vars[fetch_var_name].push_back(it->second.rbegin()->get());
      }
    }
  }

  for (size_t i = 0; i < fetch_tensors.size(); ++i) {
    auto &var_name = fetch_tensors[i];
    auto &vars = fetched_vars.at(var_name);
    auto *op = new FetchOpHandle(fetch_data, i, &local_scopes_);
    fetch_ops->emplace_back(op);

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

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

    auto *fetch_dummy = new DummyVarHandle();
    op->AddOutput(fetch_dummy);
    fetch_dependencies->emplace(fetch_dummy);
    this->InsertPendingVar(pending_vars, ready_vars, fetch_dummy);
    this->InsertPendingOp(pending_ops, op);
  }
}

void ThreadedSSAGraphExecutor::InsertPendingOp(
    std::unordered_map<OpHandleBase *, size_t> *pending_ops,
    OpHandleBase *op_instance) const {
177
  pending_ops->insert({op_instance, op_instance->NoDupInputSize()});
C
chengduoZH 已提交
178 179 180 181 182 183 184 185 186 187
}

void ThreadedSSAGraphExecutor::InsertPendingVar(
    std::unordered_set<VarHandleBase *> *pending_vars,
    BlockingQueue<VarHandleBase *> *ready_vars, VarHandleBase *var) const {
  pending_vars->insert(var);
  if (var->generated_op_ == nullptr) {
    ready_vars->Push(var);
  }
}
Y
Yu Yang 已提交
188
void ThreadedSSAGraphExecutor::RunOp(
X
Xin Pan 已提交
189 190
    BlockingQueue<VarHandleBase *> *ready_var_q, details::OpHandleBase *op) {
  auto op_run = [ready_var_q, op, this] {
Y
Yu Yang 已提交
191
    try {
Y
Yu Yang 已提交
192
      VLOG(10) << op << " " << op->Name() << " : " << op->DebugString();
Y
yuyang18 已提交
193
      op->Run(strategy_.use_event_);
Y
Yu Yang 已提交
194
      VLOG(10) << op << " " << op->Name() << " Done ";
X
Xin Pan 已提交
195
      running_ops_--;
X
Xin Pan 已提交
196
      ready_var_q->Extend(op->Outputs());
Y
Yu Yang 已提交
197
      VLOG(10) << op << " " << op->Name() << "Signal posted";
Y
Yu Yang 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    } 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();
  }
}
}  // namespace details
}  // namespace framework
}  // namespace paddle