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

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