You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

step_auto_parallel.cc 53 kB

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