You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

executor.cc 16 kB

5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /**
  2. * Copyright 2020-2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "backend/session/executor.h"
  17. #include "backend/session/executor_manager.h"
  18. #include <algorithm>
  19. #include <exception>
  20. #include <set>
  21. #include "runtime/device/kernel_runtime_manager.h"
  22. #include "pipeline/pynative/pynative_profiling.h"
  23. #include "utils/comm_manager.h"
  24. #include "utils/scoped_long_running.h"
  25. #include "pybind_api/ir/tensor_py.h"
  26. #if ((defined ENABLE_CPU) && (!defined _WIN32))
  27. #include "ps/ps_cache/ps_cache_manager.h"
  28. #endif
  29. using mindspore::tensor::TensorPy;
  30. namespace mindspore {
  31. namespace session {
  32. namespace {
  33. void GetNeedNotifyTensors(const VectorRef *outputs, std::set<TensorPtr> *result) {
  34. MS_EXCEPTION_IF_NULL(outputs);
  35. MS_EXCEPTION_IF_NULL(result);
  36. for (auto &item : *outputs) {
  37. if (utils::isa<VectorRefPtr>(item)) {
  38. auto vector_ref = utils::cast<VectorRef>(item);
  39. GetNeedNotifyTensors(&vector_ref, result);
  40. } else if (utils::isa<tensor::TensorPtr>(item)) {
  41. auto tensor = utils::cast<tensor::TensorPtr>(item);
  42. result->emplace(tensor);
  43. }
  44. }
  45. }
  46. bool TensorInVector(const VectorRef *outputs) {
  47. MS_EXCEPTION_IF_NULL(outputs);
  48. for (auto &item : *outputs) {
  49. if (utils::isa<VectorRefPtr>(item)) {
  50. auto vector_ref = utils::cast<VectorRef>(item);
  51. if (TensorInVector(&vector_ref)) {
  52. return true;
  53. }
  54. } else if (utils::isa<tensor::TensorPtr>(item)) {
  55. return true;
  56. }
  57. }
  58. return false;
  59. }
  60. bool IsTaskReady(const std::shared_ptr<RunGraphTask> &task) {
  61. MS_EXCEPTION_IF_NULL(task);
  62. for (auto &input : task->input_need_wait_tensors_) {
  63. MS_EXCEPTION_IF_NULL(input);
  64. if (input->NeedWait()) {
  65. return false;
  66. }
  67. }
  68. auto session = task->session_;
  69. MS_EXCEPTION_IF_NULL(session);
  70. auto graph = session->GetGraph(task->graph_id_);
  71. if (graph != nullptr) {
  72. return graph->IsPreGraphFinished();
  73. }
  74. return true;
  75. }
  76. void WaitLockedInputs(const std::shared_ptr<RunGraphTask> &task) {
  77. bool need_lock = false;
  78. for (auto &tensor : task->input_tensors_) {
  79. if (tensor->NeedWait()) {
  80. if (tensor->IsGraphOutput()) {
  81. task->input_need_wait_tensors_.emplace_back(tensor);
  82. } else {
  83. need_lock = true;
  84. }
  85. }
  86. }
  87. if (need_lock) {
  88. mindspore::ScopedLongRunning long_running;
  89. for (auto &input_tensor : task->input_tensors_) {
  90. if (input_tensor->NeedWait() && !input_tensor->IsGraphOutput()) {
  91. MsException::Instance().CheckException();
  92. input_tensor->Wait();
  93. }
  94. }
  95. MsException::Instance().CheckException();
  96. }
  97. // need lock input parameters for optimizer
  98. for (auto &need_lock_tensor : task->input_need_lock_tensors_) {
  99. need_lock_tensor->SetNeedWait(true);
  100. }
  101. }
  102. } // namespace
  103. void CompileNodesTask::Run() {
  104. MS_EXCEPTION_IF_NULL(session_);
  105. MS_EXCEPTION_IF_NULL(segment_);
  106. graph_id_ = session_->CompileGraphImpl(segment_->nodes_, output_nodes_);
  107. }
  108. void CompileGraphTask::Run() {
  109. MS_EXCEPTION_IF_NULL(session_);
  110. graph_id_ = session_->CompileGraphImpl(NOT_NULL(func_graph_));
  111. }
  112. void BuildGraphTask::Run() {
  113. MS_EXCEPTION_IF_NULL(session_);
  114. session_->BuildGraphImpl(graph_id_);
  115. }
  116. void RunGraphTask::Run() {
  117. MS_EXCEPTION_IF_NULL(session_);
  118. MS_LOG(INFO) << "Start run graph " << graph_id_;
  119. auto graph = session_->GetGraph(graph_id_);
  120. if (graph == nullptr) {
  121. MS_LOG(ERROR) << "Invalid graph id " << graph_id_;
  122. return;
  123. }
  124. graph->ResetGraphRunningStatus();
  125. try {
  126. session_->LoadInputs(graph_id_, input_tensors_);
  127. session_->RunGraphImpl(graph_id_, input_tensors_, &outputs_);
  128. std::map<DeviceAddressPtr, DeviceAddressPtr> new_to_old_device_address;
  129. session_->UpdateOutputTensors(&outputs_, tensor_to_node_, &new_to_old_device_address);
  130. } catch (const std::exception &e) {
  131. session_->ReportErrorMessage();
  132. ExecutorManager::Instance().OnEvent(ExecutorEvent::kException);
  133. MsException::Instance().SetException();
  134. }
  135. MS_LOG(INFO) << "End run graph " << graph_id_;
  136. graph->OnRunGraphFinished();
  137. std::set<TensorPtr> need_notify_tensors(input_need_lock_tensors_.begin(), input_need_lock_tensors_.end());
  138. GetNeedNotifyTensors(&outputs_, &need_notify_tensors);
  139. for (auto &tensor : need_notify_tensors) {
  140. if (tensor != nullptr) {
  141. tensor->SetNeedWait(false);
  142. }
  143. }
  144. ExecutorManager::Instance().OnEvent(ExecutorEvent::kRunGraphFinished);
  145. }
  146. void RunOpTask::Run() {
  147. PynativeProfiler::SetForwardTimePoint("ForwardRunOpImpl", "Start");
  148. MS_EXCEPTION_IF_NULL(session_);
  149. session_->RunOpImpl(graph_info_, op_run_info_, input_tensors_, &outputs_, tensors_mask_);
  150. PynativeProfiler::SetForwardTimePoint("ForwardRunOpImpl", "End");
  151. }
  152. void RunOpsInGraphTask::Run() {
  153. PynativeProfiler::SetBackwardTimePoint("BackwardRunOpsInGraphImpl", "Start");
  154. MS_EXCEPTION_IF_NULL(session_);
  155. session_->RunOpsInGraphImpl(graph_id_, input_tensors_, &outputs_);
  156. PynativeProfiler::SetBackwardTimePoint("BackwardRunOpsInGraphImpl", "End");
  157. }
  158. void CreateCommGroupTask::Run() { result_ = CommManager::GetInstance().CreateGroupSync(group_name_, ranks_); }
  159. void DestroyCommGroupTask::Run() { result_ = CommManager::GetInstance().DestroyGroup(group_name_); }
  160. Executor::Executor(const std::string &device_name, uint32_t device_id) {
  161. device_name_ = device_name;
  162. device_id_ = device_id;
  163. worker_ = std::make_shared<std::thread>(&Executor::WorkerLoop, this);
  164. }
  165. Executor::~Executor() {
  166. try {
  167. WorkerJoin();
  168. } catch (const std::exception &e) {
  169. MS_LOG(ERROR) << "Executor call destructor failed: " << e.what();
  170. } catch (...) {
  171. MS_LOG(ERROR) << "KernelGraph call destructor failed";
  172. }
  173. }
  174. void Executor::WorkerJoin() {
  175. // Avoid worker thread join itself which will cause deadlock
  176. if (worker_->joinable() && worker_->get_id() != std::this_thread::get_id()) {
  177. {
  178. std::lock_guard<std::mutex> lock(task_mutex_);
  179. auto task = std::make_shared<ExitTask>();
  180. ready_tasks_.push(task);
  181. task_cond_var_.notify_all();
  182. }
  183. worker_->join();
  184. }
  185. }
  186. void Executor::WorkerLoop() {
  187. while (true) {
  188. std::shared_ptr<Task> task;
  189. {
  190. std::unique_lock<std::mutex> lock(task_mutex_);
  191. task_cond_var_.wait(lock, [this] { return !ready_tasks_.empty(); });
  192. task = ready_tasks_.front();
  193. ready_tasks_.pop();
  194. }
  195. if (task->type_ == kExit) {
  196. OnWorkerExit();
  197. return;
  198. }
  199. try {
  200. task->Run();
  201. if (task->session_ != nullptr) {
  202. task->session_->ReportWarningMessage();
  203. }
  204. } catch (const std::exception &e) {
  205. if (task->session_ != nullptr) {
  206. task->session_->ReportErrorMessage();
  207. }
  208. ExecutorManager::Instance().OnEvent(ExecutorEvent::kException);
  209. MsException::Instance().SetException();
  210. }
  211. {
  212. std::lock_guard<std::mutex> lock(done_task_mutex_);
  213. done_tasks_.emplace_back(task);
  214. }
  215. if (task->type_ != kRunGraph || task->sync_run_) {
  216. std::lock_guard<std::mutex> lock(task_mutex_);
  217. sync_run_task_finished_ = true;
  218. sync_cond_var_.notify_all();
  219. }
  220. }
  221. }
  222. std::vector<std::shared_ptr<RunGraphTask>> Executor::GetReadyTasksFromPendingList() {
  223. std::vector<std::shared_ptr<RunGraphTask>> ready_tasks;
  224. std::lock_guard<std::mutex> lock(pending_task_mutex_);
  225. for (auto iter = pending_tasks_.begin(); iter != pending_tasks_.end();) {
  226. auto task = *iter;
  227. if (IsTaskReady(task)) {
  228. (void)ready_tasks.emplace_back(task);
  229. pending_tasks_.erase(iter++);
  230. } else {
  231. ++iter;
  232. }
  233. }
  234. return ready_tasks;
  235. }
  236. void Executor::OnEvent(const ExecutorEvent &event) {
  237. if (event == ExecutorEvent::kRunGraphFinished) {
  238. OnRunGraphFinished();
  239. } else if (event == ExecutorEvent::kClear) {
  240. OnClear();
  241. } else if (event == ExecutorEvent::kException) {
  242. OnException();
  243. }
  244. }
  245. void Executor::OnClear() {
  246. {
  247. mindspore::ScopedLongRunning long_running;
  248. WorkerJoin();
  249. }
  250. ClearDoneTasks();
  251. }
  252. void Executor::OnException() {
  253. std::vector<std::shared_ptr<Task>> done_tasks;
  254. {
  255. std::lock_guard<std::mutex> lock(task_mutex_);
  256. while (!ready_tasks_.empty()) {
  257. (void)done_tasks.emplace_back(ready_tasks_.front());
  258. ready_tasks_.pop();
  259. }
  260. }
  261. {
  262. std::lock_guard<std::mutex> lock(pending_task_mutex_);
  263. (void)std::copy(pending_tasks_.begin(), pending_tasks_.end(), std::back_inserter(done_tasks));
  264. pending_tasks_.clear();
  265. }
  266. {
  267. std::lock_guard<std::mutex> lock(done_task_mutex_);
  268. (void)done_tasks_.insert(done_tasks_.end(), done_tasks.begin(), done_tasks.end());
  269. }
  270. }
  271. void Executor::OnRunGraphFinished() {
  272. auto ready_tasks = GetReadyTasksFromPendingList();
  273. std::lock_guard<std::mutex> lock(task_mutex_);
  274. for (auto &task : ready_tasks) {
  275. ready_tasks_.push(task);
  276. }
  277. if (!ready_tasks.empty()) {
  278. task_cond_var_.notify_all();
  279. }
  280. reenter_cond_var_.notify_all();
  281. }
  282. void Executor::ClearDoneTasks() {
  283. std::lock_guard<std::mutex> lock(done_task_mutex_);
  284. done_tasks_.clear();
  285. }
  286. void Executor::RunTask(const std::shared_ptr<Task> &task, bool sync, bool long_run) {
  287. if (sync) {
  288. ClearDoneTasks();
  289. }
  290. {
  291. std::lock_guard<std::mutex> lock(task_mutex_);
  292. sync_run_task_finished_ = false;
  293. ready_tasks_.push(task);
  294. }
  295. task_cond_var_.notify_all();
  296. if (sync && !sync_run_task_finished_) {
  297. std::unique_lock<std::mutex> lock(task_mutex_);
  298. if (sync && long_run) {
  299. mindspore::ScopedLongRunning long_running;
  300. sync_cond_var_.wait(lock, [this] { return sync_run_task_finished_; });
  301. } else {
  302. sync_cond_var_.wait(lock, [this] { return sync_run_task_finished_; });
  303. }
  304. }
  305. ClearDoneTasks();
  306. MsException::Instance().CheckException();
  307. }
  308. GraphId Executor::CompileGraph(const SessionPtr &session, const GraphSegmentPtr &segment,
  309. const AnfNodePtrList &outputs) {
  310. auto task = std::make_shared<CompileNodesTask>();
  311. task->session_ = session;
  312. task->segment_ = segment;
  313. task->output_nodes_ = outputs;
  314. RunTask(task, true);
  315. return task->graph_id_;
  316. }
  317. GraphId Executor::CompileGraph(const SessionPtr &session, NotNull<FuncGraphPtr> func_graph) {
  318. auto task = std::make_shared<CompileGraphTask>();
  319. task->session_ = session;
  320. task->func_graph_ = func_graph.get();
  321. RunTask(task, true);
  322. return task->graph_id_;
  323. }
  324. void Executor::BuildGraph(const SessionPtr &session, GraphId graphId) {
  325. auto task = std::make_shared<BuildGraphTask>();
  326. task->session_ = session;
  327. task->graph_id_ = graphId;
  328. RunTask(task, true);
  329. }
  330. void Executor::RunGraph(const SessionPtr &session, const GraphId &graph_id,
  331. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  332. MS_EXCEPTION_IF_NULL(session);
  333. MS_EXCEPTION_IF_NULL(outputs);
  334. auto task = std::make_shared<RunGraphTask>();
  335. task->session_ = session;
  336. task->graph_id_ = graph_id;
  337. task->input_tensors_ = inputs;
  338. session->CreateOutputTensors(graph_id, inputs, outputs, &task->tensor_to_node_);
  339. task->outputs_ = *outputs;
  340. task->sync_run_ = true;
  341. RunTask(task, true, true);
  342. }
  343. void Executor::RunGraphAsync(const SessionPtr &session, const GraphId &graph_id,
  344. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  345. MS_EXCEPTION_IF_NULL(session);
  346. MS_EXCEPTION_IF_NULL(outputs);
  347. auto task = std::make_shared<RunGraphTask>();
  348. task->session_ = session;
  349. task->graph_id_ = graph_id;
  350. task->input_tensors_ = inputs;
  351. task->input_need_lock_tensors_ = session->GetInputNeedLockTensors(graph_id, inputs);
  352. auto graph = session->GetGraph(task->graph_id_);
  353. if (graph != nullptr && !graph->IsPostGraphFinished()) {
  354. mindspore::ScopedLongRunning long_running;
  355. std::unique_lock<std::mutex> lock(reenter_mutex_);
  356. reenter_cond_var_.wait(lock, [&graph] { return graph->IsPostGraphFinished(); });
  357. MsException::Instance().CheckException();
  358. }
  359. session->CreateOutputTensors(graph_id, inputs, outputs, &task->tensor_to_node_);
  360. // maintain a copy of output vector
  361. task->outputs_ = *outputs;
  362. // Run graph synchronously when the graph require gil.
  363. if (graph != nullptr && graph->is_need_gil()) {
  364. std::unique_lock<std::mutex> lock(reenter_mutex_);
  365. reenter_cond_var_.wait(lock, [&graph] { return graph->IsPreGraphFinished(); });
  366. MsException::Instance().CheckException();
  367. task->sync_run_ = true;
  368. RunTask(task, true, true);
  369. return;
  370. }
  371. // sync run graph without output tensor(int dataset graph)
  372. if ((!TensorInVector(outputs) && !graph->HasPostGraph())) {
  373. task->sync_run_ = true;
  374. RunTask(task, true, true);
  375. return;
  376. }
  377. WaitLockedInputs(task);
  378. {
  379. std::lock_guard<std::mutex> lock(pending_task_mutex_);
  380. if (!IsTaskReady(task)) {
  381. ClearDoneTasks();
  382. pending_tasks_.push_back(task);
  383. return;
  384. }
  385. }
  386. RunTask(task, false);
  387. }
  388. void Executor::RunOp(const SessionPtr &session, OpRunInfo *op_run_info, const GraphInfo &graph_info,
  389. std::vector<tensor::TensorPtr> *input_tensors, VectorRef *outputs,
  390. const std::vector<int64_t> &tensors_mask) {
  391. MS_EXCEPTION_IF_NULL(session);
  392. auto ms_context = MsContext::GetInstance();
  393. auto target = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  394. if (target == kGPUDevice) {
  395. for (auto &tensor : *input_tensors) {
  396. if (tensor->NeedWait()) {
  397. tensor->Wait();
  398. }
  399. }
  400. {
  401. // Release GIL before calling into (potentially long-running) C++ code
  402. if (Py_IsInitialized()) {
  403. py::gil_scoped_release release;
  404. session->RunOpImpl(graph_info, op_run_info, input_tensors, outputs, tensors_mask);
  405. } else {
  406. session->RunOpImpl(graph_info, op_run_info, input_tensors, outputs, tensors_mask);
  407. }
  408. }
  409. } else {
  410. auto task = std::make_shared<RunOpTask>();
  411. task->session_ = session;
  412. task->op_run_info_ = op_run_info;
  413. task->graph_info_ = graph_info;
  414. task->input_tensors_ = input_tensors;
  415. task->tensors_mask_ = tensors_mask;
  416. for (auto &tensor : *input_tensors) {
  417. if (tensor->NeedWait()) {
  418. tensor->Wait();
  419. }
  420. }
  421. RunTask(task, true, true);
  422. *outputs = task->outputs_;
  423. }
  424. }
  425. void Executor::RunOpsInGraph(const SessionPtr &session, const GraphId &graph_id,
  426. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  427. MS_EXCEPTION_IF_NULL(session);
  428. MS_EXCEPTION_IF_NULL(outputs);
  429. auto task = std::make_shared<RunOpsInGraphTask>();
  430. task->session_ = session;
  431. task->graph_id_ = graph_id;
  432. task->input_tensors_ = inputs;
  433. RunTask(task, true, true);
  434. *outputs = task->outputs_;
  435. }
  436. bool Executor::CreateCommGroup(const std::string &group_name, const std::vector<uint32_t> &ranks) {
  437. auto task = std::make_shared<CreateCommGroupTask>();
  438. task->group_name_ = group_name;
  439. task->ranks_ = ranks;
  440. RunTask(task, true);
  441. return task->result_;
  442. }
  443. bool Executor::DestroyCommGroup(const std::string &group_name) {
  444. auto task = std::make_shared<DestroyCommGroupTask>();
  445. task->group_name_ = group_name;
  446. RunTask(task, true);
  447. return task->result_;
  448. }
  449. void Executor::OnWorkerExit() {
  450. if (device_name_ == kAscendDevice) {
  451. device::KernelRuntimeManager::Instance().ReleaseKernelRuntime(kAscendDevice, device_id_);
  452. }
  453. }
  454. } // namespace session
  455. } // namespace mindspore