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 15 kB

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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 "runtime/device/kernel_runtime_manager.h"
  21. #include "utils/comm_manager.h"
  22. #include "utils/scoped_long_running.h"
  23. #ifdef ENABLE_DUMP_IR
  24. #include "debug/rdr/running_data_recorder.h"
  25. #endif
  26. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  27. #include "ps/ps_cache/ps_cache_manager.h"
  28. #endif
  29. namespace mindspore {
  30. namespace session {
  31. namespace {
  32. void UpdateOutputTensors(const VectorRef *outputs,
  33. const std::map<tensor::TensorPtr, session::KernelWithIndex> &tensor_to_node) {
  34. MS_EXCEPTION_IF_NULL(outputs);
  35. for (auto item : *outputs) {
  36. if (utils::isa<VectorRefPtr>(item)) {
  37. auto vector_ref = utils::cast<VectorRef>(item);
  38. UpdateOutputTensors(&vector_ref, tensor_to_node);
  39. } else if (utils::isa<tensor::TensorPtr>(item)) {
  40. auto tensor = utils::cast<tensor::TensorPtr>(item);
  41. MS_EXCEPTION_IF_NULL(tensor);
  42. auto iter = tensor_to_node.find(tensor);
  43. if (iter != tensor_to_node.end()) {
  44. auto &node = iter->second.first;
  45. auto &output_index = iter->second.second;
  46. auto address = AnfAlgo::GetMutableOutputAddr(node, output_index);
  47. tensor->set_device_address(address);
  48. if (AnfAlgo::IsDynamicShape(node)) {
  49. auto updated_shape = AnfAlgo::GetOutputInferShape(node, output_index);
  50. ShapeVector int_shape;
  51. std::transform(updated_shape.begin(), updated_shape.end(), std::back_inserter(int_shape), SizeToInt);
  52. tensor->set_shape(int_shape);
  53. }
  54. }
  55. if (tensor->NeedSyncDeviceToHostImmediately()) {
  56. tensor->data_sync(false);
  57. tensor->set_device_address(nullptr);
  58. tensor->set_sync_status(kNeedSyncHostToDevice);
  59. }
  60. }
  61. }
  62. }
  63. void NotifyOutputTensors(const VectorRef *outputs) {
  64. MS_EXCEPTION_IF_NULL(outputs);
  65. for (auto item : *outputs) {
  66. if (utils::isa<VectorRefPtr>(item)) {
  67. auto vector_ref = utils::cast<VectorRef>(item);
  68. NotifyOutputTensors(&vector_ref);
  69. } else if (utils::isa<tensor::TensorPtr>(item)) {
  70. auto tensor = utils::cast<tensor::TensorPtr>(item);
  71. MS_EXCEPTION_IF_NULL(tensor);
  72. tensor->SetNeedWait(false);
  73. }
  74. }
  75. }
  76. bool TensorInVector(const VectorRef *outputs) {
  77. MS_EXCEPTION_IF_NULL(outputs);
  78. for (auto item : *outputs) {
  79. if (utils::isa<VectorRefPtr>(item)) {
  80. auto vector_ref = utils::cast<VectorRef>(item);
  81. if (TensorInVector(&vector_ref)) {
  82. return true;
  83. }
  84. } else if (utils::isa<tensor::TensorPtr>(item)) {
  85. return true;
  86. }
  87. }
  88. return false;
  89. }
  90. } // namespace
  91. void CompileNodesTask::Run() {
  92. MS_EXCEPTION_IF_NULL(session_);
  93. MS_EXCEPTION_IF_NULL(segment_);
  94. graph_id_ = session_->CompileGraphImpl(segment_->nodes_, output_nodes_);
  95. }
  96. void CompileGraphTask::Run() {
  97. MS_EXCEPTION_IF_NULL(session_);
  98. graph_id_ = session_->CompileGraphImpl(NOT_NULL(func_graph_));
  99. }
  100. void BuildGraphTask::Run() {
  101. MS_EXCEPTION_IF_NULL(session_);
  102. session_->BuildGraphImpl(graph_id_);
  103. }
  104. void RunGraphTask::Run() {
  105. MS_EXCEPTION_IF_NULL(session_);
  106. MS_LOG(INFO) << "Start run graph " << graph_id_;
  107. auto graph = session_->GetGraph(graph_id_);
  108. if (graph == nullptr) {
  109. MS_LOG(ERROR) << "Invalid graph id " << graph_id_;
  110. return;
  111. }
  112. graph->ResetGraphRunningStatus();
  113. try {
  114. session_->RunGraphImpl(graph_id_, input_tensors_, &outputs_);
  115. UpdateOutputTensors(&outputs_, tensor_to_node_);
  116. } catch (const std::exception &e) {
  117. ExecutorManager::Instance().OnEvent(ExecutorEvent::kException);
  118. MsException::Instance().SetException();
  119. }
  120. MS_LOG(INFO) << "End run graph " << graph_id_;
  121. graph->OnRunGraphFinished();
  122. for (auto &tensor : input_need_lock_tensors_) {
  123. tensor->SetNeedWait(false);
  124. }
  125. NotifyOutputTensors(&outputs_);
  126. ExecutorManager::Instance().OnEvent(ExecutorEvent::kRunGraphFinished);
  127. }
  128. void RunOpTask::Run() {
  129. MS_EXCEPTION_IF_NULL(session_);
  130. session_->RunOpImpl(graph_info_, op_run_info_, input_tensors_, &outputs_, tensors_mask_);
  131. }
  132. void RunOpsInGraphTask::Run() {
  133. MS_EXCEPTION_IF_NULL(session_);
  134. session_->RunOpsInGraphImpl(graph_id_, input_tensors_, &outputs_);
  135. }
  136. void CreateCommGroupTask::Run() { result_ = CommManager::GetInstance().CreateGroupSync(group_name_, ranks_); }
  137. void DestroyCommGroupTask::Run() { result_ = CommManager::GetInstance().DestroyGroup(group_name_); }
  138. Executor::Executor(const std::string &device_name, uint32_t device_id) {
  139. device_name_ = device_name;
  140. device_id_ = device_id;
  141. worker_ = std::make_shared<std::thread>(&Executor::WorkerLoop, this);
  142. }
  143. Executor::~Executor() { WorkerJoin(); }
  144. void Executor::WorkerJoin() {
  145. // Avoid worker thread join itself which will cause deadlock
  146. if (worker_->joinable() && worker_->get_id() != std::this_thread::get_id()) {
  147. {
  148. std::lock_guard<std::mutex> lock(task_mutex_);
  149. auto task = std::make_shared<ExitTask>();
  150. ready_tasks_.push(task);
  151. task_cond_var_.notify_all();
  152. }
  153. worker_->join();
  154. }
  155. }
  156. void Executor::WorkerLoop() {
  157. while (true) {
  158. std::shared_ptr<Task> task;
  159. {
  160. std::unique_lock<std::mutex> lock(task_mutex_);
  161. task_cond_var_.wait(lock, [this] { return !ready_tasks_.empty(); });
  162. task = ready_tasks_.front();
  163. ready_tasks_.pop();
  164. }
  165. if (task->type_ == kExit) {
  166. OnWorkerExit();
  167. return;
  168. }
  169. try {
  170. task->Run();
  171. } catch (const std::exception &e) {
  172. ExecutorManager::Instance().OnEvent(ExecutorEvent::kException);
  173. MsException::Instance().SetException();
  174. }
  175. {
  176. std::lock_guard<std::mutex> lock(done_task_mutex_);
  177. done_tasks_.emplace_back(task);
  178. }
  179. if (task->type_ != kRunGraph || task->sync_run_) {
  180. sync_run_task_finished_ = true;
  181. sync_cond_var_.notify_all();
  182. }
  183. }
  184. }
  185. std::vector<std::shared_ptr<RunGraphTask>> Executor::GetNewReadyTasks() {
  186. std::vector<std::shared_ptr<RunGraphTask>> new_ready_tasks;
  187. std::lock_guard<std::mutex> lock(pending_task_mutex_);
  188. for (auto iter = pending_tasks_.begin(); iter != pending_tasks_.end();) {
  189. auto task = *iter;
  190. if (IsTaskReady(task)) {
  191. new_ready_tasks.emplace_back(task);
  192. pending_tasks_.erase(iter++);
  193. } else {
  194. iter++;
  195. }
  196. }
  197. return new_ready_tasks;
  198. }
  199. void Executor::OnEvent(const ExecutorEvent &event) {
  200. if (event == ExecutorEvent::kRunGraphFinished) {
  201. OnRunGraphFinished();
  202. } else if (event == ExecutorEvent::kClear) {
  203. WorkerJoin();
  204. } else if (event == ExecutorEvent::kException) {
  205. OnException();
  206. }
  207. }
  208. void Executor::OnException() {
  209. std::vector<std::shared_ptr<Task>> new_done_tasks;
  210. {
  211. std::lock_guard<std::mutex> lock(task_mutex_);
  212. while (!ready_tasks_.empty()) {
  213. new_done_tasks.emplace_back(ready_tasks_.front());
  214. ready_tasks_.pop();
  215. }
  216. }
  217. {
  218. std::lock_guard<std::mutex> lock(pending_task_mutex_);
  219. std::copy(pending_tasks_.begin(), pending_tasks_.end(), std::back_inserter(new_done_tasks));
  220. pending_tasks_.clear();
  221. }
  222. {
  223. std::lock_guard<std::mutex> lock(done_task_mutex_);
  224. (void)done_tasks_.insert(done_tasks_.end(), new_done_tasks.begin(), new_done_tasks.end());
  225. }
  226. }
  227. void Executor::OnRunGraphFinished() {
  228. auto new_ready_tasks = GetNewReadyTasks();
  229. std::lock_guard<std::mutex> lock(task_mutex_);
  230. for (auto &task : new_ready_tasks) {
  231. ready_tasks_.push(task);
  232. }
  233. if (!new_ready_tasks.empty()) {
  234. task_cond_var_.notify_all();
  235. }
  236. reenter_cond_var_.notify_all();
  237. }
  238. bool Executor::IsTaskReady(const std::shared_ptr<RunGraphTask> &task) {
  239. MS_EXCEPTION_IF_NULL(task);
  240. for (auto &input : task->input_need_wait_tensors_) {
  241. MS_EXCEPTION_IF_NULL(input);
  242. if (input->NeedWait()) {
  243. return false;
  244. }
  245. }
  246. auto session = task->session_;
  247. MS_EXCEPTION_IF_NULL(session);
  248. auto graph = session->GetGraph(task->graph_id_);
  249. if (graph != nullptr) {
  250. return graph->IsPreGraphFinished();
  251. }
  252. return true;
  253. }
  254. void Executor::ClearDoneTasks() {
  255. std::lock_guard<std::mutex> lock(done_task_mutex_);
  256. done_tasks_.clear();
  257. }
  258. void Executor::RunTask(const std::shared_ptr<Task> &task, bool sync, bool long_run) {
  259. {
  260. std::lock_guard<std::mutex> lock(task_mutex_);
  261. ready_tasks_.push(task);
  262. }
  263. sync_run_task_finished_ = false;
  264. task_cond_var_.notify_all();
  265. if (sync && !sync_run_task_finished_) {
  266. std::unique_lock<std::mutex> lock(task_mutex_);
  267. if (long_run) {
  268. mindspore::ScopedLongRunning long_running;
  269. sync_cond_var_.wait(lock, [this] { return sync_run_task_finished_; });
  270. } else {
  271. sync_cond_var_.wait(lock, [this] { return sync_run_task_finished_; });
  272. }
  273. }
  274. ClearDoneTasks();
  275. MsException::Instance().CheckException();
  276. }
  277. GraphId Executor::CompileGraph(const SessionPtr &session, const GraphSegmentPtr &segment,
  278. const AnfNodePtrList &outputs) {
  279. auto task = std::make_shared<CompileNodesTask>();
  280. task->session_ = session;
  281. task->segment_ = segment;
  282. task->output_nodes_ = outputs;
  283. RunTask(task, true);
  284. return task->graph_id_;
  285. }
  286. GraphId Executor::CompileGraph(const SessionPtr &session, NotNull<FuncGraphPtr> func_graph) {
  287. auto task = std::make_shared<CompileGraphTask>();
  288. task->session_ = session;
  289. task->func_graph_ = func_graph.get();
  290. RunTask(task, true);
  291. return task->graph_id_;
  292. }
  293. void Executor::BuildGraph(const SessionPtr &session, GraphId graphId) {
  294. auto task = std::make_shared<BuildGraphTask>();
  295. task->session_ = session;
  296. task->graph_id_ = graphId;
  297. RunTask(task, true);
  298. }
  299. void Executor::RunGraph(const SessionPtr &session, const GraphId &graph_id,
  300. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  301. MS_EXCEPTION_IF_NULL(session);
  302. MS_EXCEPTION_IF_NULL(outputs);
  303. auto task = std::make_shared<RunGraphTask>();
  304. task->session_ = session;
  305. task->graph_id_ = graph_id;
  306. task->input_tensors_ = inputs;
  307. session->CreateOutputTensors(graph_id, inputs, outputs, &task->tensor_to_node_);
  308. task->outputs_ = *outputs;
  309. task->sync_run_ = true;
  310. RunTask(task, true, true);
  311. }
  312. void Executor::WaitTaskGraphAvailable(const SessionPtr &session, const std::shared_ptr<RunGraphTask> &task) {
  313. bool need_lock = false;
  314. for (auto &tensor : task->input_tensors_) {
  315. if (tensor->NeedWait()) {
  316. if (tensor->IsGraphOutput()) {
  317. task->input_need_wait_tensors_.emplace_back(tensor);
  318. } else {
  319. need_lock = true;
  320. }
  321. }
  322. }
  323. if (need_lock) {
  324. mindspore::ScopedLongRunning long_running;
  325. for (auto &tensor : task->input_tensors_) {
  326. if (tensor->NeedWait() && !tensor->IsGraphOutput()) {
  327. tensor->Wait();
  328. }
  329. }
  330. MsException::Instance().CheckException();
  331. }
  332. // need lock input parameters for optimizer
  333. for (auto &tensor : task->input_need_lock_tensors_) {
  334. tensor->SetNeedWait(true);
  335. }
  336. }
  337. void Executor::RunGraphAsync(const SessionPtr &session, const GraphId &graph_id,
  338. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  339. MS_EXCEPTION_IF_NULL(session);
  340. MS_EXCEPTION_IF_NULL(outputs);
  341. auto task = std::make_shared<RunGraphTask>();
  342. task->session_ = session;
  343. task->graph_id_ = graph_id;
  344. task->input_tensors_ = inputs;
  345. task->input_need_lock_tensors_ = session->GetInputNeedLockTensors(graph_id, inputs);
  346. auto graph = session->GetGraph(task->graph_id_);
  347. if (graph != nullptr && !graph->IsPostGraphFinished()) {
  348. mindspore::ScopedLongRunning long_running;
  349. std::unique_lock<std::mutex> lock(reenter_mutex_);
  350. reenter_cond_var_.wait(lock, [&graph] { return graph->IsPostGraphFinished(); });
  351. MsException::Instance().CheckException();
  352. }
  353. session->CreateOutputTensors(graph_id, inputs, outputs, &task->tensor_to_node_);
  354. // maintain a copy of output vector
  355. task->outputs_ = *outputs;
  356. // sync run graph without output tensor(int dataset graph)
  357. if (!TensorInVector(outputs)) {
  358. task->sync_run_ = true;
  359. RunTask(task, true, true);
  360. return;
  361. }
  362. WaitTaskGraphAvailable(session, task);
  363. if (!IsTaskReady(task)) {
  364. std::lock_guard<std::mutex> lock(pending_task_mutex_);
  365. pending_tasks_.push_back(task);
  366. return;
  367. }
  368. RunTask(task, false);
  369. }
  370. void Executor::RunOp(const SessionPtr &session, OpRunInfo *op_run_info, const GraphInfo &graph_info,
  371. std::vector<tensor::TensorPtr> *input_tensors, VectorRef *outputs,
  372. const std::vector<int64_t> &tensors_mask) {
  373. auto task = std::make_shared<RunOpTask>();
  374. task->session_ = session;
  375. task->op_run_info_ = op_run_info;
  376. task->graph_info_ = graph_info;
  377. task->input_tensors_ = input_tensors;
  378. task->tensors_mask_ = tensors_mask;
  379. for (auto &tensor : *input_tensors) {
  380. if (tensor->NeedWait()) {
  381. tensor->Wait();
  382. }
  383. }
  384. RunTask(task, true, true);
  385. *outputs = task->outputs_;
  386. }
  387. void Executor::RunOpsInGraph(const SessionPtr &session, const GraphId &graph_id,
  388. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  389. MS_EXCEPTION_IF_NULL(session);
  390. MS_EXCEPTION_IF_NULL(outputs);
  391. auto task = std::make_shared<RunOpsInGraphTask>();
  392. task->session_ = session;
  393. task->graph_id_ = graph_id;
  394. task->input_tensors_ = inputs;
  395. RunTask(task, true, true);
  396. *outputs = task->outputs_;
  397. }
  398. bool Executor::CreateCommGroup(const std::string &group_name, std::vector<uint32_t> ranks) {
  399. auto task = std::make_shared<CreateCommGroupTask>();
  400. task->group_name_ = group_name;
  401. task->ranks_ = ranks;
  402. RunTask(task, true);
  403. return task->result_;
  404. }
  405. bool Executor::DestroyCommGroup(const std::string &group_name) {
  406. auto task = std::make_shared<DestroyCommGroupTask>();
  407. task->group_name_ = group_name;
  408. RunTask(task, true);
  409. return task->result_;
  410. }
  411. void Executor::OnWorkerExit() {
  412. if (device_name_ == kAscendDevice) {
  413. device::KernelRuntimeManager::Instance().ReleaseKernelRuntime(kAscendDevice, device_id_);
  414. }
  415. }
  416. } // namespace session
  417. } // namespace mindspore