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.

step_auto_parallel.cc 53 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
6 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. /**
  2. * Copyright 2019-2020 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 "frontend/parallel/step_auto_parallel.h"
  17. #include <cinttypes>
  18. #include <ctime>
  19. #include <algorithm>
  20. #include <map>
  21. #include <memory>
  22. #include <set>
  23. #include <string>
  24. #include <unordered_map>
  25. #include <utility>
  26. #include <vector>
  27. #include <unordered_set>
  28. #include "base/core_ops.h"
  29. #include "frontend/optimizer/opt.h"
  30. #include "frontend/optimizer/optimizer.h"
  31. #include "frontend/parallel/auto_parallel/dp_algo_costmodel.h"
  32. #include "frontend/parallel/auto_parallel/edge_costmodel.h"
  33. #include "frontend/parallel/auto_parallel/graph_costmodel.h"
  34. #include "frontend/parallel/auto_parallel/rec_core/rec_generate_strategy.h"
  35. #include "frontend/parallel/auto_parallel/rec_core/rec_parse_graph.h"
  36. #include "frontend/parallel/auto_parallel/rec_core/rec_partition.h"
  37. #include "frontend/parallel/context.h"
  38. #include "frontend/parallel/graph_util/node_info.h"
  39. #include "frontend/parallel/graph_util/graph_info.h"
  40. #include "frontend/parallel/ops_info/reshape_info.h"
  41. #include "frontend/parallel/ops_info/tmp_identity_info.h"
  42. #include "frontend/parallel/step_parallel.h"
  43. #include "frontend/parallel/strategy_checkpoint/parallel_strategy_checkpoint.h"
  44. #include "ir/anf.h"
  45. #include "ir/param_info.h"
  46. #include "ir/tensor.h"
  47. #if (ENABLE_CPU && !_WIN32)
  48. #include "ps/util.h"
  49. #endif
  50. namespace mindspore {
  51. namespace parallel {
  52. bool StepAutoParallel(const FuncGraphPtr &root, const opt::OptimizerPtr &) {
  53. #if (ENABLE_CPU && !_WIN32)
  54. if (ps::Util::IsRoleOfPServer() || ps::Util::IsRoleOfScheduler()) {
  55. return false;
  56. }
  57. #endif
  58. MS_EXCEPTION_IF_NULL(root);
  59. MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
  60. std::string parallel_mode = ParallelContext::GetInstance()->parallel_mode();
  61. // assume no change to graph
  62. bool changes = false;
  63. // control whether use model_parallel mode
  64. if (!root->has_flag(AUTO_PARALLEL) || (parallel_mode != AUTO_PARALLEL) ||
  65. root->has_flag(AUTO_PARALLEL_RUN_ONCE_ONLY)) {
  66. return changes;
  67. }
  68. // check whether strategy_search_mode is valid
  69. std::string strategy_search_mode = ParallelContext::GetInstance()->strategy_search_mode();
  70. if ((strategy_search_mode != DYNAMIC_PROGRAMMING) && (strategy_search_mode != RECURSIVE_PROGRAMMING)) {
  71. // Setting searching mode: dynamic programming as default.
  72. strategy_search_mode = DYNAMIC_PROGRAMMING;
  73. MS_LOG(INFO) << "Non-idicated strategy searching mode, using DP searching mode as default";
  74. }
  75. struct timeval start_time {
  76. 0
  77. }, end_time{0};
  78. (void)gettimeofday(&start_time, nullptr);
  79. if (MsContext::GetInstance()->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG)) {
  80. draw::Draw(STEP_AUTO_PARALLEL_BEGIN, root);
  81. }
  82. MS_LOG(INFO) << "Now entering step auto parallel";
  83. TOTAL_OPS = 0;
  84. AnfNodePtr ret = root->get_return();
  85. std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret);
  86. if (ParallelInit() != SUCCESS) {
  87. MS_LOG(EXCEPTION) << "Parallel init failed";
  88. }
  89. // mark the forward cnodes, parallel only care these nodes
  90. MarkForwardCNode(root);
  91. if (!root->has_flag(TRAINING)) {
  92. InsertVirtualOutput(root, all_nodes);
  93. AnfNodePtr ret_after = root->get_return();
  94. MS_EXCEPTION_IF_NULL(ret_after);
  95. all_nodes = DeepScopedGraphSearch(ret_after);
  96. }
  97. if (FindCommunicationOp(all_nodes)) {
  98. MS_LOG(EXCEPTION) << "The graph contain communication op";
  99. }
  100. // search parallelization strategy
  101. if (strategy_search_mode == DYNAMIC_PROGRAMMING) {
  102. if (ParallelStrategySearch(all_nodes, root) != SUCCESS) {
  103. MS_LOG(EXCEPTION) << "Auto-parallel strategy search failed when using DP searching mode";
  104. }
  105. } else if (strategy_search_mode == RECURSIVE_PROGRAMMING) {
  106. if (ParallelStrategyRecSearch(all_nodes, root) != SUCCESS) {
  107. MS_LOG(EXCEPTION) << "Auto-parallel strategy search failed when using RP searching mode";
  108. }
  109. } else {
  110. MS_LOG(EXCEPTION) << "Auto-parallel strategy searching mode unexpected";
  111. }
  112. (void)gettimeofday(&end_time, nullptr);
  113. uint64_t time = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec);
  114. time += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec);
  115. MS_LOG(INFO) << "Now leaving step auto parallel, used time: " << time << " us";
  116. root->set_flag(AUTO_PARALLEL_RUN_ONCE_ONLY, true);
  117. return changes;
  118. }
  119. bool IsElementWiseOperator(const std::string &op_name) {
  120. // clang-format off
  121. static const std::set<std::string> elementwise_op = {ACTIVATION, GELU, TANH,
  122. SOFTMAX, LOG_SOFTMAX, RELU,
  123. SQRT, CAST, POW,
  124. EXP, LOG, COS,
  125. ACOS, LOGICALNOT, NEG,
  126. SQUARE, SIGMOID, ABS,
  127. ACOSH, ASIN, ASINH,
  128. ATAN, ATANH, CEIL,
  129. COSH, EXPM1, LOG1P,
  130. SIN, SINH, TAN,
  131. RSQRT, RECIPROCAL, INV,
  132. ROUND, FLOOR, SIGN,
  133. ERF, ERFC, ZEROSLIKE,
  134. ONESLIKE, BESSELI0E, MOD,
  135. ASSIGN, ASSIGN_ADD, ATAN2,
  136. DIVNONAN, LOGICALAND, ELU,
  137. LOGICALOR, RELU6, SOFTPLUS,
  138. SOFTSIGN, LESS, LESSEQUAL,
  139. BESSELI1E, GREATEREQUAL, APPROXIMATEEQUAL,
  140. REPEAT_ELEMENTS};
  141. // clang-format on
  142. auto iter = elementwise_op.find(op_name);
  143. return (iter != elementwise_op.end());
  144. }
  145. bool IsSplittableOperator(const std::string &op_name) {
  146. // clang-format off
  147. static const std::set<std::string> splittable_op =
  148. {MATMUL, TRANSPOSE, GELU, TANH, SOFTMAX, SUB, MUL, DIV, RESHAPE, GREATER, LOG_SOFTMAX, ACTIVATION, PRELU,
  149. FLOORDIV, L2_NORMALIZE, ADD, MAXPOOL, AVGPOOL, MAXPOOLV2, VIRTUAL_DATA_SET, RELU, ONEHOT, DROPOUT_DO_MASK,
  150. REDUCE_MAX, REDUCE_MIN, ARGMAXWITHVALUE, ARGMINWITHVALUE, REDUCE_SUM, CONV2D, FUSE_BATCH_NORM, POOLING,
  151. MAX_POOL_WITH_ARGMAX, SIMPLE_MEAN, FLATTEN, BATCH_NORM, LAYER_NORM, BIAS_ADD, ASSIGN_SUB, COS, ACOS, EXP, STACK,
  152. LOG, REDUCE_MEAN, REAL_DIV, SIGMOID, POW, MAXIMUM, MINIMUM, EQUAL, NOT_EQUAL, LOGICALNOT, GATHERV2, SQRT, CONCAT,
  153. STRIDEDSLICE, GET_NEXT, CAST, NEG, SQUARE, BATCH_MATMUL, EXPAND_DIMS, SQUEEZE, SPARSE_GATHERV2, TILE, DROPOUT,
  154. SOFTMAX_CROSS_ENTROPY_WITH_LOGITS, SIGMOID_CROSS_ENTROPY_WITH_LOGITS, SPARSE_SOFTMAX_CROSS_ENTROPY_WITH_LOGITS,
  155. EMBEDDING_LOOKUP, FUSE_BATCH_NORM_EX, SPLIT, BROADCAST_TO, ABS, ACOSH, ASIN, ASINH, ATAN, ATANH, CEIL, COSH,
  156. EXPM1, LOG1P, SIN, SINH, TAN, RSQRT, INV, RECIPROCAL, ROUND, FLOOR, SIGN, ERF, ERFC, ZEROSLIKE, ONESLIKE,
  157. BESSELI0E, BESSELI1E, FLOORMOD, ASSIGN, ASSIGN_ADD, ATAN2, DIVNONAN, LOGICALAND, LOGICALOR, ELU, RELU6, RELUV2,
  158. SOFTPLUS, SOFTSIGN, GREATEREQUAL, LESSEQUAL, LESS, APPROXIMATEEQUAL, MOD, UNIQUE, UNSORTED_SEGMENT_SUM,
  159. UNSORTED_SEGMENT_MIN, REPEAT_ELEMENTS, TENSOR_DOT, RANGE, UNIFORM_CANDIDATE_SAMPLER, SLICE, SELECT,
  160. UNSORTED_SEGMENT_MAX, GATHER_ND, TOPK, SCATTER_UPDATE, VIRTUAL_OUTPUT, CONV2D_BACK_PROP_INPUT, CONV2D_TRANSPOSE};
  161. // clang-format on
  162. auto iter = splittable_op.find(op_name);
  163. return (iter != splittable_op.end());
  164. }
  165. bool IsAutoParallelCareNode(const CNodePtr &cnode) {
  166. MS_EXCEPTION_IF_NULL(cnode);
  167. ValueNodePtr prim_node = cnode->input(0)->cast<ValueNodePtr>();
  168. if (prim_node == nullptr) {
  169. return false;
  170. }
  171. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_node);
  172. if (prim == nullptr) {
  173. return false;
  174. }
  175. bool bool_result = IsParallelCareNode(cnode) && !IsSplittableOperator(prim->name());
  176. if (bool_result && (prim->name() != MAKE_TUPLE) && (prim->name() != MAKE_LIST)) {
  177. MS_LOG(EXCEPTION) << "Should implementing OperatorInfo for: " << prim->name();
  178. } else if (prim->name() == CAST) {
  179. if (cnode->fullname_with_scope().find(OPTIMIZER_SUB_STRING) != std::string::npos) {
  180. // Do not care CASTs from optimizer
  181. return false;
  182. }
  183. return true;
  184. }
  185. return IsParallelCareNode(cnode) && IsSplittableOperator(prim->name());
  186. }
  187. // Recording the operators appearing in a for-loop.
  188. // Currently, we assume that the operators in different for-loops are identical, and their traversal
  189. // orderings are also identical.
  190. // Therefore, we create OperatorInfo objects for the operators in a loop (say, loop-3), and reuse them in
  191. // the rest of loops (loop-2, loop-1 and loop-0)
  192. std::set<std::string> ops_in_a_loop_;
  193. // Whether two operators are in different loops; if it is true, then return true.
  194. // If at least one of the two operators is not in the loop, then return false.
  195. // If two operators are in the same loop, the return false.
  196. bool IsOperatorsInTwoSeparateLoops(const CNodePtr &a_cnode, const CNodePtr &b_cnode) {
  197. auto a_op_info = a_cnode->user_data<OperatorInfo>();
  198. MS_EXCEPTION_IF_NULL(a_op_info);
  199. auto b_op_info = b_cnode->user_data<OperatorInfo>();
  200. MS_EXCEPTION_IF_NULL(b_op_info);
  201. if ((ops_in_a_loop_.find(a_op_info->name()) == ops_in_a_loop_.end()) ||
  202. (ops_in_a_loop_.find(b_op_info->name()) == ops_in_a_loop_.end())) {
  203. return false;
  204. }
  205. size_t a_loop_index = 0, b_loop_index = 0;
  206. const auto &a_fullname = a_cnode->fullname_with_scope();
  207. if (!GetLoopIndexFromCNode(a_cnode, &a_loop_index)) {
  208. MS_LOG(EXCEPTION) << "The operator with fullname_with_scope: " << a_fullname << " was not included in the set.";
  209. }
  210. const auto &b_fullname = b_cnode->fullname_with_scope();
  211. if (!GetLoopIndexFromCNode(b_cnode, &b_loop_index)) {
  212. MS_LOG(EXCEPTION) << "The operator with fullname_with_scope: " << b_fullname << " was not included in the set.";
  213. }
  214. if (a_loop_index == b_loop_index) {
  215. return false;
  216. }
  217. return true;
  218. }
  219. // 'configured_stra_ops_' includes all operators that are configured sharding strategies.
  220. std::map<OperatorInfoPtr, StrategyPtr> configured_stra_ops_;
  221. void InitCostGraph() {
  222. if (entire_costgraph == nullptr) {
  223. entire_costgraph = std::make_shared<CostGraph>();
  224. }
  225. MS_EXCEPTION_IF_NULL(CostModelContext::GetInstance());
  226. CostModelContext::GetInstance()->PrintCostModel();
  227. entire_costgraph->Init();
  228. configured_stra_ops_.clear();
  229. }
  230. void SetStrategyToOperator(const OperatorInfoPtr &operator_info, const PrimitivePtr &prim,
  231. std::unordered_map<std::string, ValuePtr> attrs, bool is_last_nodes, StrategyMap *stra_map,
  232. const std::string &strategy_key_name) {
  233. // In this case, the configured strategy should be extracted to help setting cost
  234. StrategyPtr strategyPtr;
  235. if (StrategyFound(attrs)) {
  236. strategyPtr = parallel::ExtractStrategy(attrs[STRATEGY]);
  237. } else {
  238. strategyPtr = (*stra_map)[strategy_key_name];
  239. }
  240. if (strategyPtr != nullptr) {
  241. if (prim->name() == RESHAPE) {
  242. MS_LOG(EXCEPTION) << "Setting strategy for Reshape goes for nothing!";
  243. }
  244. const auto fully_use_devices = CostModelContext::GetInstance()->fully_use_device();
  245. // Set cost for this configured strategy
  246. if (operator_info->SetCostUnderStrategy(strategyPtr) != SUCCESS) {
  247. MS_LOG(EXCEPTION) << "Failure: operator " << prim->name() << " SetCostUnderStrategy failed";
  248. } else if (fully_use_devices) {
  249. // If configured to fully use devices, then checking for the user-specified strategy
  250. int64_t used_devices = operator_info->used_devices();
  251. MS_EXCEPTION_IF_NULL(g_device_manager);
  252. auto total_device_num = g_device_manager->GetDeviceListByStageId(0).size();
  253. // 'used_devices == 1' means that ALL-1 strategy, which is valid in auto-parallel
  254. if (used_devices == 1) {
  255. configured_stra_ops_.insert({operator_info, strategyPtr});
  256. return;
  257. }
  258. // 'used_devices == -1' means that 'used_devices_' is not set
  259. if ((used_devices == -1) || LongToSize(used_devices) != total_device_num) {
  260. MS_LOG(EXCEPTION) << "In configuration 'FULLY_USE_DEVICES' = True, "
  261. << "but the specified strategy uses device: " << used_devices
  262. << ", total devices: " << total_device_num;
  263. }
  264. }
  265. configured_stra_ops_.insert({operator_info, strategyPtr});
  266. }
  267. }
  268. OperatorInfoPtr CreateTheOperatorInfo(const PrimitivePtr &prim, const CNodePtr &cnode, bool is_last_nodes,
  269. StrategyMap *stra_map) {
  270. MS_EXCEPTION_IF_NULL(prim);
  271. MS_EXCEPTION_IF_NULL(cnode);
  272. auto attrs = prim->attrs();
  273. std::vector<Shapes> shape_list = ExtractShape(cnode);
  274. if (shape_list.empty()) {
  275. MS_LOG(EXCEPTION) << "Failure: node " << cnode->UniqueId() << " failed to extract shape";
  276. }
  277. // Create an OperatorInfo instance
  278. OperatorInfoPtr operator_info = NewOperatorInstance(prim, attrs, shape_list);
  279. MS_EXCEPTION_IF_NULL(operator_info);
  280. // Set the parameter information for this OperatorInfo (whether the inputs are parameters or not)
  281. std::vector<bool> parameter_info = ExtractInputParameterByNode(cnode);
  282. if (operator_info->set_is_parameter(parameter_info) != SUCCESS) {
  283. MS_LOG(ERROR) << "Initializing parameter information failed for operator: " << operator_info->name();
  284. return nullptr;
  285. }
  286. // Set the data type for inputs and outputs of this OperatorInfo
  287. auto inputs_type_length = ExtractInputTypeLengthByNode(cnode);
  288. auto outputs_type = ExtractOutputTypeByNode(cnode);
  289. std::vector<size_t> outputs_type_length;
  290. outputs_type_length.reserve(outputs_type.size());
  291. std::transform(outputs_type.begin(), outputs_type.end(), std::back_inserter(outputs_type_length),
  292. GetLengthOfDataType);
  293. if (operator_info->SetInputAndOutputTypeLength(inputs_type_length, outputs_type_length) != SUCCESS) {
  294. MS_LOG(ERROR) << "Setting the lengths of inputs and outputs failed for operator: " << operator_info->name();
  295. return nullptr;
  296. }
  297. if (operator_info->set_outputs_type(outputs_type) != SUCCESS) {
  298. MS_LOG(ERROR) << "Setting the types of outputs failed for operator: " << operator_info->name();
  299. return nullptr;
  300. }
  301. // When the 'inputs' contains numerical values for some operators, these values should be extracted from
  302. // ANF graph
  303. auto &inputs = cnode->inputs();
  304. std::vector<ValuePtr> input_value;
  305. for (size_t index = 1; index < inputs.size(); ++index) {
  306. if (inputs[index]->isa<ValueNode>()) {
  307. input_value.push_back(GetValueNode(inputs[index]));
  308. } else {
  309. input_value.emplace_back(nullptr);
  310. }
  311. }
  312. operator_info->set_input_value(input_value);
  313. operator_info->set_outputs_dtype(cnode->Type());
  314. operator_info->set_cnode(cnode);
  315. // key of strategy map
  316. std::string strategy_key_name = "";
  317. auto param_names = NodeParameterName(cnode, -1, 0);
  318. if (!param_names.empty()) {
  319. strategy_key_name = prim->name() + "_" + param_names[0].first;
  320. }
  321. bool load_strategy_from_ckpt =
  322. StrategyCheckpoint::GetInstance().LoadCheckPointOn() && stra_map->find(strategy_key_name) != stra_map->end();
  323. // If no strategy has been configured for this operator, then candidate strategies are generated for
  324. // auto-strategy searching; if this primitive is CAST, we ignore the user-specified strategy.
  325. // if strategy is set to load from checkpoint, it is prefer to load strategy from checkpoint .
  326. if ((!StrategyFound(attrs) || prim->name() == CAST) && !load_strategy_from_ckpt) {
  327. // Compute split_flag_list_, indicating which input has batch dimension. This is ONLY used for preparation for
  328. // BatchParallelInfo operator
  329. operator_info->ComputeBatchSplitFlagList();
  330. if (operator_info->GenerateStrategies(0) != SUCCESS) {
  331. MS_LOG(ERROR) << "Strategy search for Operator " << operator_info->name() << " failed.";
  332. return nullptr;
  333. }
  334. if (ParallelContext::GetInstance()->sharding_propagation() &&
  335. (operator_info->name().find(VIRTUAL_DATA_SET_INFO) != std::string::npos)) {
  336. const auto &swc_vec = operator_info->GetStrategyCost();
  337. if (swc_vec.empty()) {
  338. MS_LOG(EXCEPTION) << "No available strategy for: " << operator_info->name();
  339. }
  340. MS_EXCEPTION_IF_NULL(swc_vec[0]->strategy_ptr);
  341. configured_stra_ops_.insert({operator_info, swc_vec[0]->strategy_ptr});
  342. }
  343. // If 'approximation' is enabled, the 'strategy_cost' of each operator is approximated
  344. auto approximation = CostModelContext::GetInstance()->dp_algo_enable_approxi();
  345. if (approximation) {
  346. operator_info->ApproximateStrategies();
  347. MS_LOG(INFO) << "Approximated StrategyCost for: " << operator_info->name();
  348. }
  349. } else {
  350. SetStrategyToOperator(operator_info, prim, attrs, is_last_nodes, stra_map, strategy_key_name);
  351. }
  352. return operator_info;
  353. }
  354. bool IsFindWrong(const OperatorInfoPtr current_op_ptr, const std::string &prim_name) {
  355. bool is_find_wrong = (current_op_ptr->name().find(VIRTUAL_DATA_SET_INFO) == std::string::npos) &&
  356. (current_op_ptr->name().find(BATCH_PARALLEL) == std::string::npos) &&
  357. (current_op_ptr->name().find(prim_name + "Info") == std::string::npos);
  358. if (prim_name == GATHERV2) {
  359. is_find_wrong = is_find_wrong && (current_op_ptr->name().find(prim_name + "PInfo") == std::string::npos);
  360. }
  361. return is_find_wrong;
  362. }
  363. // Using CNode's UniqueIds to construct nodes
  364. Status ConstructCostGraphNodesByUniqueId(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &root) {
  365. MS_LOG(INFO) << "Constructing nodes for cost graph begins.";
  366. // The map from CNode's UniqueId to its operatorInfo
  367. std::map<std::string, OperatorInfoPtr> from_cnode_to_info;
  368. // The operator_infos in a loop
  369. std::vector<OperatorInfoPtr> operators_in_forloop;
  370. // Key: i-th loop; Value: index of 'operators_in_forloop'
  371. std::map<size_t, size_t> loop_to_ops;
  372. // extract strategy from checkpoint for multi-train
  373. StrategyMap stra_map;
  374. if (StrategyCheckpoint::GetInstance().LoadCheckPointOn()) {
  375. if (StrategyCheckpoint::GetInstance().Load(&stra_map) != SUCCESS) {
  376. MS_LOG(EXCEPTION) << "Load strategy checkpoint failed";
  377. }
  378. }
  379. for (auto &node : all_nodes) {
  380. // NOTE: we only care about splittable Primitive operators
  381. auto cnode = node->cast<CNodePtr>();
  382. bool bool_result = (cnode == nullptr) || (!IsValueNode<Primitive>(cnode->input(0)));
  383. if (bool_result) {
  384. continue;
  385. }
  386. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  387. if (!IsAutoParallelCareNode(cnode)) {
  388. // Needed by rec_parser
  389. if (ParallelContext::GetInstance()->strategy_search_mode() == RECURSIVE_PROGRAMMING) {
  390. auto prev_cnode = GetInternalOperatorInfo(cnode, prim_anf_node);
  391. if (prev_cnode != nullptr) {
  392. entire_costgraph->add_tuple_getitem(std::make_pair(cnode->UniqueId(), prev_cnode->UniqueId()));
  393. }
  394. }
  395. continue;
  396. }
  397. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  398. MS_EXCEPTION_IF_NULL(prim);
  399. auto search_cnode = from_cnode_to_info.find(cnode->UniqueId());
  400. if (search_cnode == from_cnode_to_info.end()) {
  401. size_t loop_index = 0;
  402. bool is_in_loop = GetLoopIndexFromCNode(cnode, &loop_index);
  403. const auto single_loop = CostModelContext::GetInstance()->dp_algo_single_loop();
  404. if (single_loop && is_in_loop && (loop_to_ops[loop_index] < operators_in_forloop.size())) {
  405. const auto &current_op_ptr = operators_in_forloop[loop_to_ops[loop_index]];
  406. if (IsFindWrong(current_op_ptr, prim->name())) {
  407. MS_LOG(EXCEPTION) << "The OperatorInfo: " << current_op_ptr->name()
  408. << " does not match the Prim: " << prim->name()
  409. << ". The fullname_with_scope: " << cnode->fullname_with_scope();
  410. }
  411. loop_to_ops[loop_index]++;
  412. cnode->set_user_data<OperatorInfo>(current_op_ptr);
  413. MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId()
  414. << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy()
  415. << ", CNode fullname_with_scope: " << cnode->fullname_with_scope()
  416. << " is set OperatorInfo: " << current_op_ptr->name() << ", Primitive: " << prim->name();
  417. (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueId(), current_op_ptr));
  418. continue;
  419. }
  420. bool is_last_nodes = IsPrimitiveCNode(cnode, prim::kPrimVirtualOutput);
  421. auto operator_info = CreateTheOperatorInfo(prim, cnode, is_last_nodes, &stra_map);
  422. if (operator_info == nullptr) {
  423. return FAILED;
  424. }
  425. // Needed by rec_parser
  426. operator_info->set_type(prim->name());
  427. operator_info->set_last_node_flag(is_last_nodes);
  428. std::vector<std::string> inputs_tensor_name = ExtractInputsTensorName(cnode);
  429. entire_costgraph->AddOperator(operator_info);
  430. cnode->set_user_data<OperatorInfo>(operator_info);
  431. MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId()
  432. << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy()
  433. << ", CNode fullname_with_scope: " << cnode->fullname_with_scope()
  434. << " is set OperatorInfo: " << operator_info->name() << ", Primitive: " << prim->name();
  435. (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueId(), operator_info));
  436. if (single_loop && is_in_loop) {
  437. operators_in_forloop.push_back(operator_info);
  438. ops_in_a_loop_.insert(operator_info->name());
  439. loop_to_ops[loop_index]++;
  440. }
  441. // Needed by rec_parser
  442. entire_costgraph->add_inputs_tensor_name(inputs_tensor_name);
  443. } else {
  444. // Two CNODEs' UniqueIds should not be equal
  445. MS_LOG(EXCEPTION) << "The CNode with UniqueId: " << cnode->UniqueId()
  446. << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy()
  447. << " is set OperatorInfo: " << search_cnode->second->name() << ", Primitive: " << prim->name();
  448. }
  449. }
  450. MS_LOG(INFO) << "Constructing nodes for cost graph ends.";
  451. return SUCCESS;
  452. }
  453. void SetOperatorToCNode(const OperatorInfoPtr &current_op_ptr, const PrimitivePtr &prim, const CNodePtr &cnode) {
  454. if (current_op_ptr == nullptr) {
  455. MS_LOG(EXCEPTION) << "Find " << prim->name() << " from CostGraph failed.";
  456. } else {
  457. if (IsFindWrong(current_op_ptr, prim->name())) {
  458. MS_LOG(EXCEPTION) << "The OperatorInfo: " << current_op_ptr->name()
  459. << " does not match the Prim: " << prim->name();
  460. }
  461. // Needed by rec_parser
  462. ModifyInputsTensorNameListIfOperatorInfoCreated(current_op_ptr->name(), cnode->UniqueId());
  463. cnode->set_user_data<OperatorInfo>(current_op_ptr);
  464. MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId()
  465. << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy()
  466. << ", CNode fullname_with_scope: " << cnode->fullname_with_scope()
  467. << " is set OperatorInfo: " << current_op_ptr->name() << ", Primitive: " << prim->name();
  468. }
  469. }
  470. // Using CNode's UniqueIdThroughCopys to construct nodes
  471. Status ConstructCostGraphNodesByUniqueIdTC(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &root) {
  472. MS_LOG(INFO) << "Constructing nodes for cost graph begins.";
  473. // The map from CNode's UniqueIdThroughCopy to its operatorInfo
  474. std::map<std::string, OperatorInfoPtr> from_cnode_to_info;
  475. // The operator_infos in a loop
  476. std::vector<OperatorInfoPtr> operators_in_forloop;
  477. // Key: i-th loop; Value: index of 'operators_in_forloop'
  478. std::map<size_t, size_t> loop_to_ops;
  479. // extract strategy from checkpoint for multi-train
  480. StrategyMap stra_map;
  481. if (StrategyCheckpoint::GetInstance().LoadCheckPointOn() &&
  482. StrategyCheckpoint::GetInstance().Load(&stra_map) != SUCCESS) {
  483. MS_LOG(WARNING) << "Load strategy checkpoint failed";
  484. return FAILED;
  485. }
  486. for (auto &node : all_nodes) {
  487. // NOTE: we only care about splittable Primitive operators
  488. auto cnode = node->cast<CNodePtr>();
  489. if ((cnode == nullptr) || (!IsValueNode<Primitive>(cnode->input(0)))) {
  490. continue;
  491. }
  492. ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>();
  493. if (!IsAutoParallelCareNode(cnode)) {
  494. // Needed by rec_parser
  495. if (ParallelContext::GetInstance()->strategy_search_mode() == RECURSIVE_PROGRAMMING) {
  496. auto prev_cnode = GetInternalOperatorInfo(cnode, prim_anf_node);
  497. if (prev_cnode != nullptr) {
  498. entire_costgraph->add_tuple_getitem(std::make_pair(cnode->UniqueId(), prev_cnode->UniqueId()));
  499. }
  500. }
  501. continue;
  502. }
  503. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  504. // Find the operatorInfo if it exists
  505. auto search_cnode = from_cnode_to_info.find(cnode->UniqueIdThroughCopy());
  506. if (search_cnode == from_cnode_to_info.end()) {
  507. size_t loop_index = 0;
  508. bool is_in_loop = GetLoopIndexFromCNode(cnode, &loop_index);
  509. const auto single_loop = CostModelContext::GetInstance()->dp_algo_single_loop();
  510. bool is_op_created = single_loop && is_in_loop && (loop_to_ops[loop_index] < operators_in_forloop.size());
  511. if (is_op_created) {
  512. const auto &current_op_ptr = operators_in_forloop[loop_to_ops[loop_index]];
  513. if (IsFindWrong(current_op_ptr, prim->name())) {
  514. MS_LOG(EXCEPTION) << "The OperatorInfo: " << current_op_ptr->name()
  515. << " does not match the Prim: " << prim->name()
  516. << ". The fullname_with_scope: " << cnode->fullname_with_scope();
  517. }
  518. loop_to_ops[loop_index]++;
  519. cnode->set_user_data<OperatorInfo>(current_op_ptr);
  520. MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId()
  521. << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy()
  522. << ", CNode fullname_with_scope: " << cnode->fullname_with_scope()
  523. << " is set OperatorInfo: " << current_op_ptr->name() << ", Primitive: " << prim->name();
  524. (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueIdThroughCopy(), current_op_ptr));
  525. continue;
  526. }
  527. // In this case, the corresponding OperatorInfo is not created, create the new one.
  528. bool is_last_nodes = IsPrimitiveCNode(cnode, prim::kPrimVirtualOutput);
  529. auto operator_info = CreateTheOperatorInfo(prim, cnode, is_last_nodes, &stra_map);
  530. MS_EXCEPTION_IF_NULL(operator_info);
  531. // Needed by rec_parser
  532. operator_info->set_type(prim->name());
  533. operator_info->set_last_node_flag(is_last_nodes);
  534. std::vector<std::string> inputs_tensor_name = ExtractInputsTensorName(cnode);
  535. entire_costgraph->AddOperator(operator_info);
  536. cnode->set_user_data<OperatorInfo>(operator_info);
  537. MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId()
  538. << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy()
  539. << ", CNode fullname_with_scope: " << cnode->fullname_with_scope()
  540. << " is set OperatorInfo: " << operator_info->name() << ", Primitive: " << prim->name();
  541. (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueIdThroughCopy(), operator_info));
  542. if (single_loop && is_in_loop) {
  543. operators_in_forloop.push_back(operator_info);
  544. ops_in_a_loop_.insert(operator_info->name());
  545. loop_to_ops[loop_index]++;
  546. }
  547. // Needed by rec_parser
  548. entire_costgraph->add_inputs_tensor_name(inputs_tensor_name);
  549. } else {
  550. SetOperatorToCNode(search_cnode->second, prim, cnode);
  551. }
  552. }
  553. MS_LOG(INFO) << "Constructing nodes for cost graph ends.";
  554. return SUCCESS;
  555. }
  556. void CreateEdgeBetweenTwoOps(const OperatorInfoPtr &prev_op_info, const OperatorInfoPtr &node_op_info,
  557. const CNodePtr &cnode, const CNodePtr &prev_cnode, const PrimitivePtr &prim,
  558. const PrimitivePtr &prev_prim, size_t output_index, size_t input_index,
  559. size_t *edge_count) {
  560. std::string edge_name = prev_op_info->name() + OPERATOR_TO_OPERATOR_CONNECTOR + node_op_info->name();
  561. // If the edge between these two operators already has been added, then the edge will not be added again.
  562. if (entire_costgraph->IsEdgeInCostGraph(edge_name, output_index, input_index - 1)) {
  563. return;
  564. }
  565. EdgePtr edge_ptr;
  566. MS_LOG(INFO) << "Creating edge: " << edge_name;
  567. if (IsOperatorsInTwoSeparateLoops(prev_cnode, cnode)) {
  568. MS_LOG(INFO) << "prev_cnode_fullname: " << prev_cnode->fullname_with_scope()
  569. << ", cnode_fullname: " << cnode->fullname_with_scope();
  570. MS_LOG(INFO) << "The two operators in two separate for-loops, thus skip the edge.";
  571. return;
  572. }
  573. const auto stra_follow = CostModelContext::GetInstance()->elementwise_stra_follow();
  574. bool follow_strategy = (prim->name() == RESHAPE) || (prev_prim->name() == RESHAPE) ||
  575. (stra_follow && IsElementWiseOperator(prev_prim->name()));
  576. if (follow_strategy) {
  577. // Redistribution in not allowed on the edge.
  578. // Elementwise operators have the same strategy as their previous operators.
  579. edge_ptr =
  580. std::make_shared<Edge>(edge_name, prev_op_info, node_op_info, output_index, input_index - 1, false, true);
  581. } else {
  582. edge_ptr = std::make_shared<Edge>(edge_name, prev_op_info, node_op_info, output_index, input_index - 1, false);
  583. }
  584. // Init costs for this edge
  585. if (edge_ptr->InitEdgeCost() != SUCCESS) {
  586. MS_LOG(EXCEPTION) << "Edge cost initialization failed";
  587. }
  588. node_op_info->AddPrevEdge(edge_ptr);
  589. prev_op_info->AddSuccEdge(edge_ptr);
  590. entire_costgraph->AddEdge(prev_op_info, node_op_info, edge_ptr);
  591. if (ParallelContext::GetInstance()->sharding_propagation() && (prev_prim->name() == CAST) &&
  592. (configured_stra_ops_.find(node_op_info) != configured_stra_ops_.end())) {
  593. const auto next_op_stra = configured_stra_ops_[node_op_info];
  594. const auto cast_stra = edge_ptr->GetPrevOpStrategyByNextOpStrategyWithZeroComm(next_op_stra);
  595. if (cast_stra == nullptr) {
  596. MS_LOG(EXCEPTION) << "No available strategy for: " << prev_op_info->name();
  597. }
  598. prev_op_info->ClearStrategyCost();
  599. if (prev_op_info->SetCostUnderStrategy(cast_stra) != SUCCESS) {
  600. MS_LOG(EXCEPTION) << "Failure: operator " << prev_op_info->name() << " SetCostUnderStrategy failed";
  601. }
  602. if (edge_ptr->InitEdgeCost() != SUCCESS) {
  603. MS_LOG(EXCEPTION) << "Edge cost re-initialization failed.";
  604. }
  605. MS_LOG(INFO) << "Set strategy for: " << prev_op_info->name() << " under the strategy of: " << node_op_info->name();
  606. configured_stra_ops_.insert({prev_op_info, cast_stra});
  607. }
  608. MS_LOG(INFO) << "Successfully adding the edge between " << prev_op_info->name() << " and " << node_op_info->name();
  609. (*edge_count)++;
  610. }
  611. void ConstructCostGraphEdges(const std::vector<AnfNodePtr> &all_nodes) {
  612. // Step 2
  613. MS_LOG(INFO) << "Constructing edges for cost graph begins.";
  614. for (auto &node : all_nodes) {
  615. auto cnode = node->cast<CNodePtr>();
  616. if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) {
  617. continue;
  618. }
  619. auto &inputs = cnode->inputs();
  620. ValueNodePtr prim_anf_node = inputs[0]->cast<ValueNodePtr>();
  621. if (!IsAutoParallelCareNode(cnode)) {
  622. continue;
  623. }
  624. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  625. size_t edge_count = 0;
  626. auto node_op_info = cnode->user_data<OperatorInfo>();
  627. for (size_t i = 1; i < inputs.size(); ++i) {
  628. auto prev_cnode = inputs[i]->cast<CNodePtr>();
  629. bool bool_result_prev_cnode = (prev_cnode == nullptr) || (!IsValueNode<Primitive>(prev_cnode->input(0)));
  630. if (bool_result_prev_cnode) {
  631. continue;
  632. }
  633. ValueNodePtr prev_prim_anf_node = prev_cnode->input(0)->cast<ValueNodePtr>();
  634. PrimitivePtr prev_prim = prev_prim_anf_node->value()->cast<PrimitivePtr>();
  635. size_t output_index = 0;
  636. while ((IsAutoParallelCareNode(prev_cnode)) || (prev_prim->name() == prim::kTupleGetItem) ||
  637. (prev_prim->name() == DEPEND)) {
  638. if (IsAutoParallelCareNode(prev_cnode)) {
  639. auto prev_op_info = prev_cnode->user_data<OperatorInfo>();
  640. CreateEdgeBetweenTwoOps(prev_op_info, node_op_info, cnode, prev_cnode, prim, prev_prim, output_index, i,
  641. &edge_count);
  642. break;
  643. } else if (prev_prim->name() == prim::kTupleGetItem) {
  644. // In this case, 'prev_anf_node' is 'tuple_getitem', the actual precursor node is node before
  645. // this 'tuple_getitem'
  646. MS_LOG(INFO) << "Jumping the 'tuple_getitem' operator.";
  647. output_index = LongToSize(GetValue<int64_t>(GetValueNode(prev_cnode->input(2))));
  648. prev_cnode = prev_cnode->input(1)->cast<CNodePtr>();
  649. bool bool_result_tuple = (prev_cnode == nullptr) || (!IsValueNode<Primitive>(prev_cnode->input(0)));
  650. if (bool_result_tuple) {
  651. break;
  652. }
  653. prev_prim_anf_node = prev_cnode->input(0)->cast<ValueNodePtr>();
  654. prev_prim = prev_prim_anf_node->value()->cast<PrimitivePtr>();
  655. if (!IsAutoParallelCareNode(prev_cnode)) {
  656. MS_LOG(EXCEPTION) << "Did not create OperatorInfo for : " << prev_prim->name();
  657. }
  658. MS_LOG(INFO) << "Jumped the 'tuple_getitem' operator, "
  659. << "and creating an edge between the Operator before "
  660. << "'tuple_getitem' and the Operator after 'tuple_getitem'.";
  661. } else if (prev_prim->name() == DEPEND) {
  662. // In this case, 'prev_anf_node' is 'depend', the actual precursor node is node before
  663. // this 'depend'
  664. MS_LOG(INFO) << "Jumping the 'depend' operator.";
  665. prev_cnode = prev_cnode->input(1)->cast<CNodePtr>();
  666. bool bool_result_depend = (prev_cnode == nullptr) || (!IsValueNode<Primitive>(prev_cnode->input(0)));
  667. if (bool_result_depend) {
  668. break;
  669. }
  670. prev_prim_anf_node = prev_cnode->input(0)->cast<ValueNodePtr>();
  671. prev_prim = prev_prim_anf_node->value()->cast<PrimitivePtr>();
  672. MS_LOG(INFO) << "Jumped the 'depend' operator, "
  673. << "and creating an edge between the Operator before "
  674. << "'depend' and the Operator after 'depend'.";
  675. }
  676. }
  677. }
  678. MS_LOG(INFO) << "Successfully created " << edge_count << " edges for: " << node_op_info->name();
  679. }
  680. // If 'approximation' is enabled, the edges need to be checked have effective costs.
  681. auto approximation = CostModelContext::GetInstance()->dp_algo_enable_approxi();
  682. if (approximation) {
  683. entire_costgraph->CheckApproximateCostGraphEdges();
  684. }
  685. MS_LOG(INFO) << "Constructing edges for cost graph ends.";
  686. }
  687. void AugmentCostGraph(const std::vector<AnfNodePtr> &all_nodes) {
  688. // Step 3
  689. for (auto &node : all_nodes) {
  690. ParameterUsersInfo parameter_users_info = FindParameterUsers(node, IsAutoParallelCareNode);
  691. auto parameter_name = parameter_users_info.first;
  692. auto target_parameter = parameter_users_info.second.first;
  693. auto target_set = parameter_users_info.second.second;
  694. if (target_set.size() <= 1) {
  695. continue;
  696. }
  697. // Rule out the case when a Parameter being used by a Operator, but the Operator appears in multiple CNODEs
  698. std::set<std::string> target_without_duplicate;
  699. for (auto &target : target_set) {
  700. auto target_cnode = target.first->cast<CNodePtr>();
  701. auto input_index = target.second;
  702. (void)target_without_duplicate.insert(std::to_string(input_index) +
  703. target_cnode->user_data<OperatorInfo>()->name());
  704. }
  705. if (target_without_duplicate.size() <= 1) {
  706. continue;
  707. }
  708. // Here, it is sure that this Parameter (RefKey) is being used by multiple Operators.
  709. OperatorInfoPtr tmp_identity_ptr;
  710. bool new_identity = false;
  711. std::string tmp_identity_name;
  712. auto returned_identity = entire_costgraph->FindTmpIdentityByParameterName(parameter_name);
  713. if (returned_identity != nullptr) {
  714. // In this case, the TmpIdentityInfo instance has already been created
  715. new_identity = false;
  716. tmp_identity_ptr = returned_identity;
  717. tmp_identity_name = tmp_identity_ptr->name();
  718. } else {
  719. // In the case, the TmpIdentityInfo instance has NOT been created. Thus, a new one is created.
  720. new_identity = true;
  721. // 1) extract input shape from this Parameter
  722. MS_EXCEPTION_IF_NULL(target_parameter);
  723. AbstractBasePtr abstract = target_parameter->abstract();
  724. if (abstract == nullptr) {
  725. MS_LOG(EXCEPTION) << "Failure: abstract is nullptr";
  726. }
  727. auto input_shape = dyn_cast<abstract::Shape>(abstract->GetShapeTrack());
  728. if (input_shape == nullptr) {
  729. MS_LOG(EXCEPTION) << "Failure: input_shape is nullptr";
  730. }
  731. Shape shape = input_shape->shape();
  732. Shapes inputs_shape = {shape};
  733. Shapes outputs_shape = {shape};
  734. // 2) init the attr
  735. std::unordered_map<std::string, ValuePtr> attr = {};
  736. // Create the TmpIdentity instance
  737. tmp_identity_ptr = std::make_shared<TmpIdentityInfo>(inputs_shape, outputs_shape, attr);
  738. tmp_identity_ptr->set_name(tmp_identity_ptr->name() + std::to_string(TOTAL_OPS));
  739. TOTAL_OPS++;
  740. tmp_identity_ptr->set_refkey_parameter_name(parameter_name);
  741. // Set the parameter and type lengths for inputs and outputs
  742. std::vector<bool> is_parameter;
  743. auto casted_target_parameter = target_parameter->cast<ParameterPtr>();
  744. MS_EXCEPTION_IF_NULL(casted_target_parameter);
  745. is_parameter.push_back(ParameterRequireGrad(casted_target_parameter));
  746. if (tmp_identity_ptr->set_is_parameter(is_parameter) != SUCCESS) {
  747. MS_LOG(EXCEPTION) << "Setting parameter for TmpIdentityInfo failed";
  748. }
  749. auto node_type = target_parameter->Type();
  750. if (node_type->isa<mindspore::TensorType>()) {
  751. auto input_element_type = node_type->cast<mindspore::TensorTypePtr>()->element();
  752. std::vector<size_t> type_length = {GetLengthOfDataType(input_element_type)};
  753. if (tmp_identity_ptr->SetInputAndOutputTypeLength(type_length, type_length) != SUCCESS) {
  754. MS_LOG(EXCEPTION) << "Setting input and output type length for TmpIdentityInfo failed";
  755. }
  756. } else {
  757. MS_LOG(EXCEPTION) << "Unknown type: " << node_type->type_name();
  758. }
  759. // Generate strategies for this TmpIdentityInfo instance;
  760. if (tmp_identity_ptr->GenerateStrategies(0) != SUCCESS) {
  761. MS_LOG(EXCEPTION) << "Strategy search for Operator failed : " << tmp_identity_ptr->name();
  762. }
  763. }
  764. // A flag recording whether new edges have been created or not
  765. bool add_identity_edge = false;
  766. // Create edges between this TmpIdentityInfo instance and subsequent Operator instances
  767. for (auto &target : target_set) {
  768. auto target_cnode = target.first->cast<CNodePtr>();
  769. auto input_index = target.second;
  770. auto target_op_info = target_cnode->user_data<OperatorInfo>();
  771. std::string edge_name = std::string(IDENTITY_INFO) + OPERATOR_TO_OPERATOR_CONNECTOR + target_op_info->name();
  772. // If the edge between these two operators already has been added, then the edge will not be added again.
  773. if (entire_costgraph->IsEdgeInCostGraph(edge_name, 0, LongToSize(input_index - 1))) {
  774. continue;
  775. }
  776. std::shared_ptr<Edge> edge_ptr =
  777. std::make_shared<Edge>(edge_name, tmp_identity_ptr, target_op_info, 0, input_index - 1, false, true);
  778. // If 'approximation' is enabled, the edges need to be checked have effective costs.
  779. auto approximation = CostModelContext::GetInstance()->dp_algo_enable_approxi();
  780. if (approximation) {
  781. target_op_info->ExactStrategiesAndRelatedEdges();
  782. }
  783. if (edge_ptr->InitEdgeCost() != SUCCESS) {
  784. MS_LOG(EXCEPTION) << "Edge cost initialization failed";
  785. }
  786. target_op_info->AddPrevEdge(edge_ptr);
  787. tmp_identity_ptr->AddSuccEdge(edge_ptr);
  788. entire_costgraph->AddEdge(tmp_identity_ptr, target_op_info, edge_ptr);
  789. MS_LOG(INFO) << "Successfully adding the edge between " << tmp_identity_ptr->name() << " and "
  790. << target_op_info->name();
  791. add_identity_edge = true;
  792. }
  793. if (new_identity && add_identity_edge) {
  794. // Add the TmpIdentityInfo to CostGraph if BOTH two conditions are satisfied
  795. entire_costgraph->AddOperator(tmp_identity_ptr);
  796. }
  797. }
  798. }
  799. void ReshapeCostCompute(const std::vector<AnfNodePtr> &all_nodes) {
  800. std::unordered_set<std::string> op_cache;
  801. for (auto node : all_nodes) {
  802. auto cnode = node->cast<CNodePtr>();
  803. if (!FindReshape(cnode, &op_cache)) {
  804. continue;
  805. }
  806. MS_ASSERT(cnode->inputs().size() == 3);
  807. // get previous node's strategy_cost_
  808. auto pre_node = cnode->input(1);
  809. if (IsPrimitiveCNode(pre_node, prim::kPrimLoad)) {
  810. pre_node = pre_node->cast<CNodePtr>()->input(1);
  811. }
  812. int64_t out_index = 0;
  813. OperatorInfoPtr pre_operator_info;
  814. std::vector<std::shared_ptr<StrategyWithCost>> pre_stra_costs;
  815. auto operator_info = cnode->user_data<OperatorInfo>();
  816. if (pre_node->isa<Parameter>()) {
  817. auto reshape_info1 = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  818. reshape_info1->SetCostForReshapeWithParameter();
  819. pre_operator_info = reshape_info1;
  820. pre_stra_costs = reshape_info1->strategy_cost();
  821. } else {
  822. if (!FindReshapePreNodeStraCosts(pre_node, &pre_operator_info, &out_index, 0)) {
  823. MS_LOG(EXCEPTION) << "FindReshapePreNodeStraCosts for reshape failed";
  824. }
  825. pre_stra_costs = pre_operator_info->strategy_cost();
  826. }
  827. // get next node's strategy_cost_
  828. int64_t in_index = 0;
  829. OperatorInfoPtr next_operator_info;
  830. std::vector<std::shared_ptr<StrategyWithCost>> next_stra_costs;
  831. bool find_next_node = FindReshapeNextNodeStraCosts(cnode, &next_operator_info, &in_index, 0);
  832. if (!find_next_node) {
  833. MS_LOG(INFO) << "FindReshapeNextNodeStraCosts for reshape failed";
  834. }
  835. // set input_layout and output_layout for reshape.
  836. // init reshape and set cost for each input_layout and output_layout.
  837. auto reshape_info = std::dynamic_pointer_cast<ReshapeInfo>(operator_info);
  838. reshape_info->set_pre_operator_name(pre_operator_info->name());
  839. reshape_info->set_pre_operator_index(out_index);
  840. if (find_next_node) {
  841. next_stra_costs = next_operator_info->strategy_cost();
  842. reshape_info->set_next_operator_name(next_operator_info->name());
  843. reshape_info->set_next_operator_index(in_index);
  844. }
  845. bool is_prev_param = pre_node->isa<Parameter>();
  846. if (reshape_info->GenetateStrategyCosts(pre_stra_costs, next_stra_costs, out_index, in_index, is_prev_param) !=
  847. SUCCESS) {
  848. MS_LOG(EXCEPTION) << "reshape generate strategy_costs failed!";
  849. }
  850. }
  851. }
  852. Status ParallelStrategySearch(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &root) {
  853. // There are 4 meta-steps to determine the parallelization strategy for the ANF graph.
  854. // Step 1: Traverse the ANF graph, and create NODEs for costgraph:
  855. // create the OperatorInfo object for each primitive, and enumerate the parallelization strategies
  856. // for each OperatorInfo;
  857. // Step 1.1: Deal with 'Reshape':
  858. // For 'Reshape', it takes its previous operator's layout as its input layout, and takes its next operator's
  859. // layout as its output layout.
  860. // Step 2: Traverse the ANF graph, and create EDGES for costgraph:
  861. // create the Edge object for each pair of OperatorInfo, and enumerate the parallelization strategies
  862. // for each edge, based on the strategies of two OperatorInfos;
  863. // Step 3: Augment the costgraph:
  864. // taking care for the case of a single Parameter being used by multiple operators. Create a TmpIdentity
  865. // operator for this Parameter, and add an edge for the use of this Parameter by each
  866. // subsequent operator;
  867. // Step 3.1: Calculate memory usage:
  868. // note the memory usage calculation is different in training phase and inference phase.
  869. // Step 4: Run the strategy searching algorithm:
  870. // If 'sharding_propagation' is configured to be true, then the configured-sharding-strategies will propagate
  871. // to the non-configured operators, with the goal of minimizing redistribution cost.
  872. // Otherwise, DP algorithm is used to search strategy of the costgraph. Note that there may be several connected
  873. // components in the costgraph, and the DP algorithm runs on each of them.
  874. //
  875. // OUTPUT: the determined strategy for each operator.
  876. InitCostGraph();
  877. // Step 1
  878. if (CostModelContext::GetInstance()->is_multi_subgraphs()) {
  879. if (ConstructCostGraphNodesByUniqueIdTC(all_nodes, root) == SUCCESS) {
  880. MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are "
  881. << entire_costgraph->GetOperators().size() << " operators.";
  882. } else {
  883. MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed.";
  884. }
  885. } else {
  886. if (ConstructCostGraphNodesByUniqueId(all_nodes, root) == SUCCESS) {
  887. MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are "
  888. << entire_costgraph->GetOperators().size() << " operators.";
  889. } else {
  890. MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed.";
  891. }
  892. }
  893. // Step 1.1
  894. ReshapeCostCompute(all_nodes);
  895. // Step 2
  896. ConstructCostGraphEdges(all_nodes);
  897. MS_LOG(INFO) << "Constructing edges for cost graph succeeded. There are " << entire_costgraph->GetOperators().size()
  898. << " operators, and " << entire_costgraph->GetNumEdges() << " edges.";
  899. // Step 3: Augment the costgraph.
  900. AugmentCostGraph(all_nodes);
  901. auto num_ops = entire_costgraph->GetOperators().size();
  902. SetOpsNumToExecutor(num_ops);
  903. auto num_edges = entire_costgraph->GetNumEdges();
  904. MS_LOG(INFO) << "After the augmenting procedure, there are " << num_ops << " operators, and " << num_edges
  905. << " edges.";
  906. // Step 3.1: Calculate the memory usage
  907. if (entire_costgraph->CalculateMemoryCost() != SUCCESS) {
  908. MS_LOG(EXCEPTION) << "Calculating memory cost failed.";
  909. }
  910. // Step 4: run the strategy searching algorithm
  911. if (ParallelContext::GetInstance()->sharding_propagation()) {
  912. entire_costgraph->StrategyPropagate(configured_stra_ops_);
  913. configured_stra_ops_.clear();
  914. } else if (GetStrategy(entire_costgraph) != SUCCESS) {
  915. MS_LOG(ERROR) << "Strategy search for cost-graph fails";
  916. return FAILED;
  917. }
  918. MS_LOG(INFO) << "Searching strategy succeeded.";
  919. if (entire_costgraph->InitSelectedStrategy() == SUCCESS) {
  920. MS_LOG(INFO) << "Init selected strategy succeeded.";
  921. } else {
  922. MS_LOG(EXCEPTION) << "Init selected strategy failed.";
  923. }
  924. // print the selected strategy
  925. for (auto &op : entire_costgraph->GetOperators()) {
  926. StrategyPtr s_strategy = op->selected_strategy();
  927. MS_LOG(INFO) << op->name() << " : The strategy is:";
  928. PrintStrategy(s_strategy);
  929. }
  930. ops_in_a_loop_.clear();
  931. return SUCCESS;
  932. }
  933. std::vector<std::vector<std::string>> RecInputTensorNames(const std::map<std::string, std::string>::iterator &it,
  934. std::vector<std::vector<std::string>> input_tensor_names) {
  935. for (size_t j = 0; j < input_tensor_names.size(); j++) {
  936. for (size_t k = 0; k < input_tensor_names[j].size(); k++) {
  937. if (it->first == input_tensor_names[j][k]) {
  938. input_tensor_names[j][k] = it->second;
  939. break;
  940. }
  941. }
  942. }
  943. return input_tensor_names;
  944. }
  945. CNodePtr GetInternalOperatorInfo(const CNodePtr &cnode, const ValueNodePtr &prim_anf_node) {
  946. PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node);
  947. if (prim->name() == prim::kTupleGetItem || prim->name() == DEPEND) {
  948. auto prev_cnode = cnode->input(1)->cast<CNodePtr>();
  949. if (prev_cnode == nullptr || !IsValueNode<Primitive>(prev_cnode->input(0))) {
  950. return nullptr;
  951. }
  952. auto prev_prim = prev_cnode->input(0)->cast<ValueNodePtr>()->value()->cast<PrimitivePtr>();
  953. while (prev_prim->name() == prim::kTupleGetItem || prev_prim->name() == DEPEND) {
  954. prev_cnode = prev_cnode->input(1)->cast<CNodePtr>();
  955. if (prev_cnode == nullptr || !IsValueNode<Primitive>(prev_cnode->input(0))) {
  956. return nullptr;
  957. }
  958. prev_prim = prev_cnode->input(0)->cast<ValueNodePtr>()->value()->cast<PrimitivePtr>();
  959. }
  960. return prev_cnode;
  961. }
  962. return nullptr;
  963. }
  964. void ModifyInputsTensorNameListIfOperatorInfoCreated(const std::string &name, const std::string &uniqueid) {
  965. size_t iter_ops = 0;
  966. for (auto op : entire_costgraph->GetOperators()) {
  967. if (op->name() == name) {
  968. break;
  969. }
  970. iter_ops = iter_ops + 1;
  971. }
  972. std::vector<std::vector<std::string>> input_tensor_names = entire_costgraph->get_inputs_tensor_name_list();
  973. for (size_t i = 0; i < input_tensor_names.size(); i++) {
  974. for (size_t j = 0; j < input_tensor_names[i].size(); j++) {
  975. if (input_tensor_names[i][j] == uniqueid) {
  976. input_tensor_names[i][j] = input_tensor_names[iter_ops][0];
  977. }
  978. }
  979. }
  980. entire_costgraph->set_inputs_tensor_name_list(input_tensor_names);
  981. }
  982. Status ParallelStrategyRecSearch(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &root) {
  983. InitCostGraph();
  984. if (CostModelContext::GetInstance()->is_multi_subgraphs()) {
  985. if (ConstructCostGraphNodesByUniqueIdTC(all_nodes, root) == SUCCESS) {
  986. MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are "
  987. << entire_costgraph->GetOperators().size() << " operators.";
  988. } else {
  989. MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed.";
  990. }
  991. } else {
  992. if (ConstructCostGraphNodesByUniqueId(all_nodes, root) == SUCCESS) {
  993. MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are "
  994. << entire_costgraph->GetOperators().size() << " operators.";
  995. } else {
  996. MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed.";
  997. }
  998. }
  999. ReshapeCostCompute(all_nodes);
  1000. auto ops = entire_costgraph->GetOperators();
  1001. std::vector<std::vector<std::string>> input_tensor_names = entire_costgraph->get_inputs_tensor_name_list();
  1002. auto tuple_getitem_list = entire_costgraph->get_tuple_getitem_list();
  1003. for (auto it = tuple_getitem_list.begin(); it != tuple_getitem_list.end();) {
  1004. input_tensor_names = RecInputTensorNames(it++, input_tensor_names);
  1005. }
  1006. std::shared_ptr<Graph> graph = ParseGraph(ops, input_tensor_names);
  1007. std::shared_ptr<std::vector<std::vector<size_t>>> eli_list(new std::vector<std::vector<size_t>>);
  1008. std::shared_ptr<std::vector<size_t>> index_list(new std::vector<size_t>);
  1009. graph = EliminateGraph(graph, eli_list, index_list);
  1010. size_t num_device = g_device_manager->DeviceNum();
  1011. const auto device_memory = CostModelContext::GetInstance()->device_memory_capacity();
  1012. if (PartitionForAllDevices(num_device, device_memory, graph) == SUCCESS) {
  1013. MS_LOG(INFO) << "Partition Success With " << num_device << " devices.";
  1014. } else {
  1015. MS_LOG(ERROR) << "PartitionForAllDevices failed.";
  1016. return FAILED;
  1017. }
  1018. bool is_training = true;
  1019. if (!root->has_flag(TRAINING)) {
  1020. is_training = false;
  1021. }
  1022. GenerateStrategy(graph, ops, eli_list, input_tensor_names, index_list, is_training);
  1023. if (entire_costgraph->InitSelectedStrategy() == SUCCESS) {
  1024. MS_LOG(INFO) << "Init selected strategy succeeded.";
  1025. } else {
  1026. MS_LOG(ERROR) << "Init selected strategy failed.";
  1027. return FAILED;
  1028. }
  1029. // print the selected strategy
  1030. for (auto &op : entire_costgraph->GetOperators()) {
  1031. StrategyPtr s_strategy = op->selected_strategy();
  1032. MS_LOG(INFO) << op->name() << " : The strategy is:";
  1033. PrintStrategy(s_strategy);
  1034. }
  1035. return SUCCESS;
  1036. }
  1037. } // namespace parallel
  1038. } // namespace mindspore