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