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

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