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

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