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.

execution_tree.cc 12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /**
  2. * Copyright 2019 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 "dataset/engine/execution_tree.h"
  17. #include <iostream>
  18. #include <string>
  19. #include "dataset/engine/datasetops/dataset_op.h"
  20. #include "dataset/engine/datasetops/shuffle_op.h"
  21. #include "dataset/util/task_manager.h"
  22. #include "dataset/engine/opt/pass.h"
  23. #include "dataset/engine/opt/pre/removal_pass.h"
  24. #include "dataset/engine/perf/profiling.h"
  25. #include "dataset/engine/perf/monitor.h"
  26. namespace mindspore {
  27. namespace dataset {
  28. // Constructor
  29. ExecutionTree::ExecutionTree() : id_count_(0) {
  30. tg_ = std::make_unique<TaskGroup>();
  31. tree_state_ = kDeTStateInit;
  32. prepare_flags_ = kDePrepNone;
  33. perf_monitor_ = std::make_unique<Monitor>(this);
  34. profiling_manager_ = std::make_unique<ProfilingManager>(this);
  35. }
  36. // Destructor
  37. ExecutionTree::~ExecutionTree() { (void)tg_->ServiceStop(); }
  38. // Associates a DatasetOp with this tree. This assigns a valid node id to the operator and
  39. // provides it with a link to the tree. A node cannot form any relationships (parent/child) with
  40. // other nodes unless they are associated with the same tree.
  41. Status ExecutionTree::AssociateNode(const std::shared_ptr<DatasetOp> &op) {
  42. // If we are already a part of the tree, no-op
  43. if (op->tree_ == this) {
  44. return Status::OK();
  45. }
  46. if (tree_state_ != kDeTStateInit && tree_state_ != kDeTStateBuilding) {
  47. std::string err_msg =
  48. "Invalid tree state for adding a node. Current state: " + std::to_string(static_cast<int>(tree_state_)) +
  49. " Expected states: " + std::to_string(static_cast<int>(kDeTStateInit)) + " or " +
  50. std::to_string(static_cast<int>(kDeTStateBuilding));
  51. RETURN_STATUS_UNEXPECTED(err_msg);
  52. }
  53. // Enter the building state if we were not already there
  54. tree_state_ = kDeTStateBuilding;
  55. // Assign an id to the operator
  56. op->set_id(id_count_);
  57. id_count_++;
  58. // Assign our tree into the op so that each op has a link back to the tree
  59. op->set_tree(this);
  60. return Status::OK();
  61. }
  62. // Sets the root node of the tree
  63. Status ExecutionTree::AssignRoot(const std::shared_ptr<DatasetOp> &op) {
  64. // Tree must be in building state before we can assign root to it
  65. if (tree_state_ != kDeTStateBuilding) {
  66. std::string err_msg =
  67. "Invalid tree state for assigning a root node. Current state: " + std::to_string(static_cast<int>(tree_state_)) +
  68. " Expected state: " + std::to_string(static_cast<int>(kDeTStateBuilding));
  69. RETURN_STATUS_UNEXPECTED(err_msg);
  70. }
  71. // If they didn't already call AssociateNode for this node before calling AssignRoot,
  72. // then do so now.
  73. if (op->operator_id_ == DatasetOp::kInvalidOperatorId) {
  74. RETURN_IF_NOT_OK(this->AssociateNode(op));
  75. }
  76. // Then add it as the root.
  77. root_ = op;
  78. return Status::OK();
  79. }
  80. // A print method typically used for debugging
  81. void ExecutionTree::Print(std::ostream &out, const std::shared_ptr<DatasetOp> &op) const {
  82. out << "Execution tree summary:\n"
  83. << "-----------------------\n";
  84. this->PrintNode(out, op == nullptr ? root_ : op, "", true, false);
  85. out << "\nExecution tree operator details:\n"
  86. << "--------------------------------\n";
  87. this->PrintNode(out, op == nullptr ? root_ : op, "", true, true);
  88. }
  89. // A helper functions for doing the recursive printing
  90. void ExecutionTree::PrintNode(std::ostream &out, const std::shared_ptr<DatasetOp> &dataset_op, std::string indent,
  91. bool last, bool detailed) const {
  92. // Decide which printer to use based on detailed arg.
  93. if (!detailed) {
  94. out << indent << "+- " << *dataset_op;
  95. indent += (last ? " " : "| ");
  96. } else {
  97. dataset_op->Print(out, detailed);
  98. }
  99. // Descend to children
  100. for (int32_t i = 0; i < dataset_op->child_.size(); ++i) {
  101. this->PrintNode(out, dataset_op->child_[i], indent, (i == (dataset_op->child_.size() - 1)), detailed);
  102. }
  103. }
  104. // Start the execution of the tree
  105. Status ExecutionTree::Launch() {
  106. // Tree must be built and prepared before it can be launched!
  107. if (tree_state_ != kDeTStateReady) {
  108. std::string err_msg =
  109. "Invalid tree state for launching tree. Current state: " + std::to_string(static_cast<int>(tree_state_)) +
  110. " Expected state: " + std::to_string(static_cast<int>(kDeTStateReady));
  111. RETURN_STATUS_UNEXPECTED(err_msg);
  112. }
  113. std::ostringstream ss;
  114. ss << *this;
  115. // Profiling infrastructures need to be initialized before Op launching
  116. if (profiling_manager_->IsProfilingEnable()) {
  117. // Setup profiling manager
  118. RETURN_IF_NOT_OK(profiling_manager_->Initialize());
  119. // Launch Monitor Thread
  120. RETURN_IF_NOT_OK(tg_->CreateAsyncTask("Monitor Thread launched", std::ref(*perf_monitor_)));
  121. }
  122. MS_LOG(DEBUG) << "Printing the tree before launch tasks:\n" << ss.str();
  123. for (auto itr = this->begin(); itr != this->end(); ++itr) {
  124. // An inlined operator is one that has an output connector size of 0, and it does not
  125. // require a thread to execute. Instead, the work of this operator is executed inlined
  126. // from the tree node directly above it (or in the case of a root node, it runs from within
  127. // the launching tree/user thread. Do not exec any thread for an inlined op.
  128. itr->state_ = DatasetOp::OpState::kDeOpRunning;
  129. if (!itr->inlined()) {
  130. RETURN_IF_NOT_OK(tg_->CreateAsyncTask("Op launched, OperatorId:" + std::to_string(itr->id()), std::ref(*itr)));
  131. // Set the state of the Operator as running. This only matters in Leaf ops, CacheOp and TakeOp
  132. }
  133. }
  134. tree_state_ = kDeTStateExecuting;
  135. return Status::OK();
  136. }
  137. // A function that traverse the tree in postorder then save the results in nodes
  138. void ExecutionTree::Iterator::PostOrderTraverse(const std::shared_ptr<DatasetOp> &node) {
  139. if (node == nullptr) {
  140. return;
  141. }
  142. for (int32_t i = 0; i < node->child_.size(); ++i) {
  143. PostOrderTraverse(node->child_[i]);
  144. }
  145. nodes_.push_back(node);
  146. }
  147. ExecutionTree::Iterator::Iterator(const std::shared_ptr<DatasetOp> &root) : ind_(0) {
  148. // post-order traverse the tree, if root is null, it return
  149. PostOrderTraverse(root);
  150. nodes_.emplace_back(nullptr);
  151. }
  152. // Given the number of workers, launches the worker entry function for each. Essentially a
  153. // wrapper for the TaskGroup handling that is stored inside the execution tree.
  154. Status ExecutionTree::LaunchWorkers(int32_t num_workers, std::function<Status(uint32_t)> func) {
  155. // Launch the workers
  156. for (int32_t i = 0; i < num_workers; ++i) {
  157. RETURN_IF_NOT_OK(tg_->CreateAsyncTask("Parallel Op Worker", std::bind(func, i)));
  158. }
  159. return Status::OK();
  160. }
  161. // The driver of the prepare phase of the execution tree.
  162. // Prepare phase consists of three sub phases
  163. //
  164. // 1. PrepareTreePreAction()
  165. // Compulsory transformation/action pre optimization.
  166. // For example, CacheOp Insertion
  167. //
  168. // 2. Optimize()
  169. // Optimization transformation/action, optional
  170. // For example, MapOp Fusion
  171. //
  172. // 3. PrepareTreePostAction()
  173. // Compulsory transformation/action post optimization.
  174. // For example, repeatOp inlining
  175. //
  176. // @return Status - The error code return
  177. Status ExecutionTree::Prepare() {
  178. // Pre optimization compulsory transformation
  179. RETURN_IF_NOT_OK(this->PrepareTreePreAction());
  180. // Optimization transformation
  181. RETURN_IF_NOT_OK(this->Optimize());
  182. // Post optimization compulsory transformation
  183. RETURN_IF_NOT_OK(this->PrepareTreePostAction());
  184. // Existing transformation implementation, will be removed later
  185. RETURN_IF_NOT_OK(this->PrepareDeprecated());
  186. return Status::OK();
  187. }
  188. Status ExecutionTree::PrepareTreePreAction() {
  189. bool modified = false;
  190. std::vector<std::unique_ptr<Pass>> pre_actions;
  191. // Construct pre actions
  192. MS_LOG(INFO) << "Running pre pass";
  193. pre_actions.push_back(std::make_unique<RemovalPass>(RemovalPass()));
  194. // Apply pre action passes
  195. for (auto &pass : pre_actions) {
  196. RETURN_IF_NOT_OK(pass->Run(this, &modified));
  197. }
  198. return Status::OK();
  199. }
  200. Status ExecutionTree::PrepareTreePostAction() {
  201. // The tree is ready to be prepared.
  202. tree_state_ = kDeTStatePrepare;
  203. return Status::OK();
  204. }
  205. Status ExecutionTree::Optimize() {
  206. // auto pp = new PrinterPass();
  207. // bool modified = false;
  208. // pp->Run(this, &modified);
  209. return Status::OK();
  210. }
  211. // The driver of the prepare phase of the execution tree. The prepare phase will recursively
  212. // walk the tree to perform modifications to the tree or specific nodes within the tree to get
  213. // it ready for execution.
  214. //
  215. // This driver is deprecated.
  216. Status ExecutionTree::PrepareDeprecated() {
  217. // Tree must be in pending prepare state before we can assign root to it
  218. if (tree_state_ != kDeTStatePrepare) {
  219. std::string err_msg =
  220. "Invalid tree state for preparing the tree. Current state: " + std::to_string(static_cast<int>(tree_state_)) +
  221. " Expected state: " + std::to_string(static_cast<int>(kDeTStatePrepare));
  222. RETURN_STATUS_UNEXPECTED(err_msg);
  223. }
  224. // Start the recursive prepare
  225. RETURN_IF_NOT_OK(this->PrepareNode(root_));
  226. tree_state_ = kDeTStateReady;
  227. return Status::OK();
  228. }
  229. // Recursive function used during prepare phase to visit a node and drive any pre- and post-
  230. // node actions during a tree walk.
  231. Status ExecutionTree::PrepareNode(const std::shared_ptr<DatasetOp> &dataset_op) {
  232. // execute PreAction
  233. RETURN_IF_NOT_OK(dataset_op->PrepareNodePreAction());
  234. // Before going down into children, make any prepare flags updates based on this operator.
  235. uint32_t op_prep_flags = dataset_op->PrepareFlags();
  236. BitSet(&prepare_flags_, op_prep_flags);
  237. // Now, descend to children
  238. for (const auto &i : dataset_op->child_) {
  239. RETURN_IF_NOT_OK(this->PrepareNode(i));
  240. }
  241. // No more children, now we execute any prepare actions before going back up the
  242. // the tree on recursive function
  243. RETURN_IF_NOT_OK(dataset_op->PrepareNodePostAction());
  244. // Then clear the flags from this op now that we have prepared it.
  245. BitClear(&prepare_flags_, op_prep_flags);
  246. return Status::OK();
  247. }
  248. // Adds an operator to the eoe operator stack during prepare phase.
  249. void ExecutionTree::AddToEOEOpStack(std::shared_ptr<DatasetOp> dataset_op) { eoe_stack_.push(dataset_op); }
  250. // Pops an operator from the eoe operator stack during prepare phase.
  251. std::shared_ptr<DatasetOp> ExecutionTree::PopFromEOEOpStack() {
  252. std::shared_ptr<DatasetOp> top_op = nullptr;
  253. if (!eoe_stack_.empty()) {
  254. top_op = eoe_stack_.top();
  255. eoe_stack_.pop();
  256. }
  257. return top_op;
  258. }
  259. // Adds a sampler to the sampler stack during prepare phase.
  260. void ExecutionTree::AddToSamplerStack(std::shared_ptr<Sampler> sampler) { sampler_stack_.push(sampler); }
  261. // Pops an operator from the sampler stack during prepare phase.
  262. std::shared_ptr<Sampler> ExecutionTree::PopFromSamplerStack() {
  263. std::shared_ptr<Sampler> top_sampler = nullptr;
  264. if (!sampler_stack_.empty()) {
  265. top_sampler = sampler_stack_.top();
  266. sampler_stack_.pop();
  267. }
  268. return top_sampler;
  269. }
  270. } // namespace dataset
  271. } // namespace mindspore