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.

reshape_info.cc 18 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /**
  2. * Copyright 2019 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 "parallel/ops_info/reshape_info.h"
  17. #include <memory>
  18. #include <vector>
  19. #include "parallel/device_manager.h"
  20. #include "parallel/device_matrix.h"
  21. #include "parallel/step_parallel.h"
  22. #include "parallel/auto_parallel/graph_costmodel.h"
  23. #include "utils/convert_utils.h"
  24. #include "utils/log_adapter.h"
  25. namespace mindspore {
  26. namespace parallel {
  27. Status ReshapeInfo::CheckStrategy(const StrategyPtr &strategy) {
  28. if (CheckStrategyValue(strategy, inputs_shape_, is_auto_parallel_) != SUCCESS) {
  29. if (is_auto_parallel_) {
  30. MS_LOG(DEBUG) << name_ << ": Invalid strategy.";
  31. } else {
  32. MS_LOG(ERROR) << name_ << ": Invalid strategy.";
  33. }
  34. return FAILED;
  35. }
  36. size_t strategy_size = strategy->GetInputNumber();
  37. if (strategy_size != 1) {
  38. if (is_auto_parallel_) {
  39. MS_LOG(DEBUG) << name_ << ": Invalid strategy size " << strategy_size;
  40. } else {
  41. MS_LOG(ERROR) << name_ << ": Invalid strategy size " << strategy_size;
  42. }
  43. return FAILED;
  44. }
  45. return SUCCESS;
  46. }
  47. /*
  48. * support parallel degree smaller than device number, set the duplicate device dimension to the first dimension of
  49. * device matrix
  50. * only support batch parallel reshape operator in ReID (batch parallel degree can be smaller than device number)
  51. */
  52. Status ReshapeInfo::InferDevMatrixShape() {
  53. std::vector<Dimensions> stra = strategy_->GetInputDim();
  54. input_strategy_ = stra.at(0);
  55. dev_matrix_shape_.push_back(input_strategy_[0]);
  56. return SUCCESS;
  57. }
  58. /*
  59. * there is no Parameter for Reshape Primitive, so no need to do allreduce
  60. */
  61. Status ReshapeInfo::InferMirrorOps() {
  62. mirror_ops_.clear();
  63. Shape input_tensor_map = input_layout_.tensor_map().array();
  64. std::vector<Group> input_group;
  65. if (CreateGroupByTensorMap(input_tensor_map, &input_group) != SUCCESS) {
  66. MS_LOG(ERROR) << name_ << ": Infer MirrorOps failed.";
  67. return FAILED;
  68. }
  69. OperatorVector op_for_input;
  70. if (input_group.empty()) {
  71. MS_LOG(INFO) << name_ << ": The mirror ops is empty.";
  72. return SUCCESS;
  73. }
  74. if (!input_group.empty()) {
  75. op_for_input = CreateMirrorOps(input_group[0].name(), input_group[0].GetDevNum());
  76. std::string group_name = input_group[0].name();
  77. MS_LOG(INFO) << name_ << ": Create the mirror ops for input_a success, group is " << group_name;
  78. }
  79. mirror_ops_.push_back(op_for_input);
  80. OperatorVector op_for_input_empty;
  81. mirror_ops_.push_back(op_for_input_empty);
  82. return SUCCESS;
  83. }
  84. /*
  85. * there is no reduction dimension for forward computation of Reshape Primitive, so no need to do allreduce
  86. */
  87. Status ReshapeInfo::InferForwardCommunication() { return SUCCESS; }
  88. /*
  89. * get shape input of Reshape Primitive
  90. * the result is saved in parameter_input_v_
  91. * not support -1
  92. */
  93. Status ReshapeInfo::GetParameterInput() {
  94. if (input_value_[1] == nullptr) {
  95. MS_LOG(ERROR) << name_ << ": input_value_[1] is nullptr.";
  96. return FAILED;
  97. }
  98. std::vector<ValuePtr> elements;
  99. ValueTuplePtr dim_tuple = input_value_[1]->cast<ValueTuplePtr>();
  100. if (dim_tuple == nullptr) {
  101. MS_LOG(ERROR) << name_ << ": Input_value_[1] must be ValueTuplePtr.";
  102. return FAILED;
  103. }
  104. elements = dim_tuple->value();
  105. if (elements.size() != outputs_shape_[0].size()) {
  106. MS_LOG(ERROR) << name_ << ": Elements size must equal to outputs shape[0] size.";
  107. return FAILED;
  108. }
  109. for (auto &element : elements) {
  110. MS_EXCEPTION_IF_NULL(element);
  111. if (element->isa<Int32Imm>()) {
  112. int32_t axis = element->cast<Int32ImmPtr>()->value();
  113. parameter_input_v_.push_back(axis);
  114. } else {
  115. MS_LOG(ERROR) << name_ << ": The value of axis must be int32.";
  116. return FAILED;
  117. }
  118. }
  119. return SUCCESS;
  120. }
  121. Status ReshapeInfo::ComputeReplaceOp() {
  122. RankList dev_list = global_device_list();
  123. TensorRedistribution tensor_redistribution(!is_generating_costs_, true);
  124. if (tensor_redistribution.Init(input_layout_, output_layout_, dev_list) == FAILED) {
  125. if (is_generating_costs_) {
  126. MS_LOG(DEBUG) << name_ << ": tensor_redistribution init failed.";
  127. } else {
  128. MS_LOG(ERROR) << name_ << ": tensor_redistribution init failed.";
  129. }
  130. return FAILED;
  131. }
  132. MS_LOG(DEBUG) << name_ << ": input " << input_layout_.ToString();
  133. MS_LOG(DEBUG) << name_ << ": output " << output_layout_.ToString();
  134. MS_LOG(DEBUG) << name_ << ": dev_list " << dev_list.size();
  135. RedistributionOpListPtr redistribution_oplist_ptr = tensor_redistribution.InferTensorRedistributionOperatorList();
  136. if (redistribution_oplist_ptr == nullptr) {
  137. if (is_generating_costs_) {
  138. MS_LOG(DEBUG) << name_ << "InferTensorRedistribution failed.";
  139. } else {
  140. MS_LOG(ERROR) << name_ << "InferTensorRedistribution failed.";
  141. }
  142. return FAILED;
  143. }
  144. replace_op_ = redistribution_oplist_ptr->first;
  145. replace_op_info_ = redistribution_oplist_ptr->second;
  146. MS_LOG(DEBUG) << name_ << ": replace op size = " << replace_op_.size();
  147. return SUCCESS;
  148. }
  149. /*
  150. * the first dimension of input tensor map and output tensor map is set to the last dimension of device arrangement,
  151. * all other dimension is set to None
  152. * only support batch parallel reshape operator in ReID (batch parallel degree can be smaller than device number)
  153. */
  154. Status ReshapeInfo::InferTensorMap() {
  155. if ((inputs_shape_.size() != 1) || (outputs_shape_.size() != 1)) {
  156. MS_LOG(ERROR) << name_ << ": inputs shape and outputs shape size must be 1. inputs shape and outputs shape are "
  157. << inputs_shape_.size() << " and " << outputs_shape_.size();
  158. return FAILED;
  159. }
  160. std::vector<int32_t> tensor_map_index_input;
  161. tensor_map_index_input.push_back(0);
  162. for (size_t j = 1; j < inputs_shape_[0].size(); ++j) {
  163. tensor_map_index_input.push_back(MAP_NONE);
  164. }
  165. inputs_tensor_map_.push_back(tensor_map_index_input);
  166. std::vector<int32_t> tensor_map_index_output;
  167. tensor_map_index_output.push_back(0);
  168. for (size_t j = 1; j < outputs_shape_[0].size(); ++j) {
  169. tensor_map_index_output.push_back(MAP_NONE);
  170. }
  171. outputs_tensor_map_.push_back(tensor_map_index_output);
  172. return SUCCESS;
  173. }
  174. /*
  175. * the output tensor strategy is the same as input tensor strategy
  176. * only support batch parallel reshape operator in ReID (batch parallel degree can be smaller than device number)
  177. */
  178. Strategys ReshapeInfo::GetOutputsStrategy() {
  179. Strategys outputs_strategy;
  180. std::vector<int32_t> strategy;
  181. strategy.push_back(input_strategy_[0]);
  182. for (size_t j = 1; j < outputs_shape_[0].size(); ++j) {
  183. strategy.push_back(1);
  184. }
  185. outputs_strategy.push_back(strategy);
  186. return outputs_strategy;
  187. }
  188. Status ReshapeInfo::InferTensorLayout(TensorLayouts *inputs_layout, TensorLayouts *outputs_layout) {
  189. if (inputs_layout == nullptr || outputs_layout == nullptr) {
  190. MS_LOG(ERROR) << name_ << ": InferTensorLayout: the layout is null.";
  191. return FAILED;
  192. }
  193. Arrangement dev_matrix;
  194. Status status = dev_matrix.Init(dev_matrix_shape_);
  195. if (status != Status::SUCCESS) {
  196. return status;
  197. }
  198. // infer input tensor info
  199. Shape shape_array_in = inputs_shape_.at(0);
  200. TensorMap tensor_map_array_in = inputs_tensor_map_.at(0);
  201. TensorLayout tensor_layout_in;
  202. Map tensor_map_in;
  203. status = tensor_map_in.Init(tensor_map_array_in);
  204. if (status != Status::SUCCESS) {
  205. return status;
  206. }
  207. Arrangement shape_in;
  208. status = shape_in.Init(shape_array_in);
  209. if (status != Status::SUCCESS) {
  210. return status;
  211. }
  212. (void)tensor_layout_in.Init(dev_matrix, tensor_map_in, shape_in);
  213. inputs_layout->push_back(tensor_layout_in);
  214. // infer output tensor info
  215. Shape shape_array_out = outputs_shape_.at(0);
  216. TensorMap tensor_map_array_out = outputs_tensor_map_.at(0);
  217. TensorLayout tensor_layout_out;
  218. Map tensor_map_out;
  219. status = tensor_map_out.Init(tensor_map_array_out);
  220. if (status != Status::SUCCESS) {
  221. return status;
  222. }
  223. Arrangement shape_out;
  224. status = shape_out.Init(shape_array_out);
  225. if (status != Status::SUCCESS) {
  226. return status;
  227. }
  228. (void)tensor_layout_out.Init(dev_matrix, tensor_map_out, shape_out);
  229. outputs_layout->push_back(tensor_layout_out);
  230. input_layout_ = tensor_layout_in;
  231. output_layout_ = tensor_layout_out;
  232. return SUCCESS;
  233. }
  234. Status ReshapeInfo::InferTensorInfo() {
  235. Shapes inputs_slice_shape, outputs_slice_shape;
  236. Strategys inputs_strategy = strategy_->GetInputDim();
  237. Strategys outputs_strategy = GetOutputsStrategy();
  238. if (InferSliceShape(inputs_strategy, outputs_strategy, &inputs_slice_shape, &outputs_slice_shape) != SUCCESS) {
  239. return FAILED;
  240. }
  241. TensorLayouts inputs_layout, outputs_layout;
  242. if (InferTensorLayout(&inputs_layout, &outputs_layout) != SUCCESS) {
  243. return FAILED;
  244. }
  245. TensorLayout tensor_layout_in = inputs_layout.at(0);
  246. TensorLayout tensor_layout_out = outputs_layout.at(0);
  247. Shape shape_array_in = inputs_shape_.at(0);
  248. Shape slice_shape_in = inputs_slice_shape.at(0);
  249. Shape shape_array_out = outputs_shape_.at(0);
  250. Shape slice_shape_out = outputs_slice_shape.at(0);
  251. TensorInfo tensor_info_in(tensor_layout_in, shape_array_in, slice_shape_in);
  252. TensorInfo tensor_info_out(tensor_layout_out, shape_array_out, slice_shape_out);
  253. inputs_tensor_info_.push_back(tensor_info_in);
  254. outputs_tensor_info_.push_back(tensor_info_out);
  255. return SUCCESS;
  256. }
  257. void ReshapeInfo::InferTensorInfoByLayout() {
  258. TensorInfo tensor_info_in(input_layout_);
  259. TensorInfo tensor_info_out(output_layout_);
  260. inputs_tensor_info_.push_back(tensor_info_in);
  261. outputs_tensor_info_.push_back(tensor_info_out);
  262. }
  263. /*
  264. * compute parameter_input_v_ during this method
  265. */
  266. Status ReshapeInfo::GetAttrs() { return GetParameterInput(); }
  267. void ReshapeInfo::device_number(const StrategyPtr &strategy) {
  268. int32_t stage = 0;
  269. if (strategy != nullptr) {
  270. stage = strategy->GetInputStage();
  271. }
  272. CheckGlobalDeviceManager();
  273. global_device_list_ = g_device_manager->GetDeviceListByStageId(stage);
  274. dev_num_ = SizeToInt(global_device_list_.size());
  275. MS_ASSERT(dev_num_ > 0);
  276. }
  277. Status ReshapeInfo::InferDefaultLayout(const Shape &shape, TensorLayout *const layout) {
  278. std::vector<int32_t> tensor_map_index;
  279. for (size_t i = 0; i < shape.size(); i++) {
  280. tensor_map_index.push_back(MAP_NONE);
  281. }
  282. Status status = layout->InitFromVector({dev_num_}, tensor_map_index, shape);
  283. if (status != Status::SUCCESS) {
  284. MS_LOG(ERROR) << name_ << ": InferDefaultLayout failed.";
  285. return status;
  286. }
  287. return Status::SUCCESS;
  288. }
  289. Status ReshapeInfo::Init(const StrategyPtr &strategy) {
  290. ResetQueueMember();
  291. device_number(strategy);
  292. if (strategy) {
  293. if (InitWithAutoRepeatCalc(strategy) != SUCCESS) {
  294. MS_LOG(ERROR) << name_ << ": Init failed.";
  295. return FAILED;
  296. }
  297. } else {
  298. if (!input_layout_set_flag_) {
  299. MS_ASSERT(inputs_shape_.size() == 1);
  300. Status status = InferDefaultLayout(inputs_shape_.at(0), &input_layout_);
  301. if (status != SUCCESS) {
  302. MS_LOG(ERROR) << name_ << ": infer input default layout failed.";
  303. return status;
  304. }
  305. }
  306. if (!output_layout_set_flag_) {
  307. MS_ASSERT(output_layout_.size() == 1);
  308. Status status = InferDefaultLayout(outputs_shape_.at(0), &output_layout_);
  309. if (status != SUCCESS) {
  310. MS_LOG(ERROR) << name_ << ": infer output default layout failed.";
  311. return status;
  312. }
  313. }
  314. inputs_tensor_map_.push_back(input_layout_.tensor_map().array());
  315. outputs_tensor_map_.push_back(output_layout_.tensor_map().array());
  316. InferTensorInfoByLayout();
  317. // change dev_matrix_shape_ to input_layout_ device_arrangement before InferMirrorOps
  318. dev_matrix_shape_ = input_layout_.device_arrangement().array();
  319. if (InferMirrorOps() != SUCCESS) {
  320. MS_LOG(ERROR) << name_ << ": InferMirrorOps failed.";
  321. return FAILED;
  322. }
  323. // change dev_matrix_shape_ to output_layout_ device_arrangement before InferVirtualDivOps
  324. dev_matrix_shape_ = output_layout_.device_arrangement().array();
  325. if (InferVirtualDivOps() != SUCCESS) {
  326. MS_LOG(ERROR) << name_ << ": InferVirtualDivOps failed.";
  327. return FAILED;
  328. }
  329. }
  330. Status status = ComputeReplaceOp();
  331. if (status != SUCCESS) {
  332. MS_LOG(ERROR) << name_ << ": ComputeReplaceOp failed.";
  333. return status;
  334. }
  335. return SUCCESS;
  336. }
  337. Status ReshapeInfo::InitForCostModel(const StrategyPtr &strategy) {
  338. if (InitForCostModelWithAutoRepeatCalc(strategy) != SUCCESS) {
  339. if (is_auto_parallel_) {
  340. MS_LOG(DEBUG) << name_ << ": Init for cost model failed.";
  341. } else {
  342. MS_LOG(ERROR) << name_ << ": Init for cost model failed.";
  343. }
  344. return FAILED;
  345. }
  346. MS_LOG(INFO) << name_ << ": Init for cost model success.";
  347. return SUCCESS;
  348. }
  349. Status ReshapeInfo::SetCostUnderStrategy(const mindspore::parallel::StrategyPtr &strategy) {
  350. if (SetCostUnderStrategyBase(strategy) != SUCCESS) {
  351. if (is_auto_parallel_) {
  352. MS_LOG(DEBUG) << name_ << ": Set cost under strategy failed.";
  353. } else {
  354. MS_LOG(ERROR) << name_ << ": Set cost under strategy failed.";
  355. }
  356. return FAILED;
  357. }
  358. return SUCCESS;
  359. }
  360. void ReshapeInfo::SetCostForReshapeWithParameter() {
  361. size_t success = 0;
  362. for (auto &sp : sp_vector_) {
  363. if (SetCostUnderStrategy(sp) == SUCCESS) {
  364. success++;
  365. MS_LOG(INFO) << name_ << ": Successfully generated " << success << " strategy.";
  366. PrintStrategy(sp);
  367. }
  368. }
  369. }
  370. void ReshapeInfo::SetCostForReshape(const mindspore::parallel::StrategyPtr &strategy) {
  371. MS_EXCEPTION_IF_NULL(strategy);
  372. int32_t stage_id = strategy->GetInputStage();
  373. double computation_cost =
  374. operator_cost()->GetForwardComputationCost(inputs_tensor_info_, outputs_tensor_info_, stage_id);
  375. double communication_cost = operator_cost()->GetCommCost(inputs_tensor_info_, outputs_tensor_info_, stage_id);
  376. std::shared_ptr<Cost> result = std::make_shared<Cost>(computation_cost, communication_cost);
  377. result->communication_without_parameter_ =
  378. operator_cost()->GetForwardCommCost(inputs_tensor_info_, outputs_tensor_info_, stage_id);
  379. result->communication_with_partial_para_ =
  380. result->communication_without_parameter_ +
  381. COST_MODEL_GAMMA * (communication_cost - result->communication_without_parameter_);
  382. // Breaking ties for preferring data parallelization
  383. BreakingTiesForPerferringDataParallel(strategy, result);
  384. // refine communication cost calculation for practice
  385. RefineForPracticalCost(result, false);
  386. std::shared_ptr<StrategyWithCost> swc =
  387. std::make_shared<StrategyWithCost>(strategy, inputs_tensor_info_, outputs_tensor_info_);
  388. swc->cost_list.push_back(result);
  389. strategy_cost_.emplace_back(swc);
  390. }
  391. Status ReshapeInfo::GenerateStrategies(int32_t stage_id) {
  392. if (GetAttrs() != SUCCESS) {
  393. MS_LOG(ERROR) << name_ << ": GetAttrs failed.";
  394. return FAILED;
  395. }
  396. if ((inputs_shape_.size() != 1) || (outputs_shape_.size() != 1)) {
  397. MS_LOG(ERROR) << name_ << ": Inputs shape size or outputs shape size is wrong, " << inputs_shape_.size() << ", "
  398. << outputs_shape_.size();
  399. return FAILED;
  400. }
  401. is_auto_parallel_ = true;
  402. Shape input0_split;
  403. (void)input0_split.insert(input0_split.end(), inputs_shape_[0].size(), 1);
  404. Shapes splittable_inputs = {input0_split};
  405. // strategy used only in the input node is parameter,
  406. // in other case, use the input node's output_layout as input_layout.
  407. if (GenerateStrategiesForIndependentInputs(stage_id, inputs_shape_, splittable_inputs, &sp_vector_) != SUCCESS) {
  408. MS_LOG(ERROR) << name_ << ": GenerateStrategiesForIndependentInputs failed.";
  409. return FAILED;
  410. }
  411. return SUCCESS;
  412. }
  413. Status ReshapeInfo::GenetateStrategyCosts(const std::vector<std::shared_ptr<StrategyWithCost>> &pre_stra_costs,
  414. const std::vector<std::shared_ptr<StrategyWithCost>> &next_stra_costs,
  415. int32_t out_index, int32_t in_index, bool is_prev_param) {
  416. is_generating_costs_ = true;
  417. for (auto pre_stra_cost : pre_stra_costs) {
  418. std::vector<TensorInfo> pre_out_tensor_infos;
  419. if (is_prev_param) {
  420. pre_out_tensor_infos = pre_stra_cost->inputs_ptr;
  421. } else {
  422. pre_out_tensor_infos = pre_stra_cost->outputs_ptr;
  423. }
  424. if (pre_out_tensor_infos.size() <= IntToSize(out_index)) {
  425. MS_LOG(ERROR) << "out_index is out of range of the tensor_infos in setting reshape's input_layout";
  426. return FAILED;
  427. }
  428. TensorInfo pre_out_tensor_info = pre_out_tensor_infos[out_index];
  429. SetInputLayout(pre_out_tensor_info.tensor_layout());
  430. // infer pre_node output strategy from output_layout.
  431. Dimensions stra = pre_out_tensor_info.InferStrategy();
  432. if (stra.empty()) {
  433. MS_LOG(ERROR) << "Infer strategy by tensor_info failed";
  434. return FAILED;
  435. }
  436. std::vector<Dimensions> stra_inputs = {stra};
  437. StrategyPtr reshape_stra = std::make_shared<Strategy>(pre_stra_cost->strategy_ptr->GetInputStage(), stra_inputs);
  438. if (next_stra_costs.empty()) {
  439. if (Init(nullptr) == FAILED) {
  440. MS_LOG(ERROR) << "Failure:operator reshape init failed";
  441. return FAILED;
  442. }
  443. SetCostForReshape(reshape_stra);
  444. continue;
  445. }
  446. for (auto next_stra_cost : next_stra_costs) {
  447. std::vector<TensorInfo> next_in_tensor_infos = next_stra_cost->inputs_ptr;
  448. if (next_in_tensor_infos.size() <= IntToSize(in_index)) {
  449. MS_LOG(ERROR) << "in_index is out of range of the tensor_infos in setting reshape's output_layout";
  450. return FAILED;
  451. }
  452. TensorInfo next_in_tensor_info = next_in_tensor_infos[in_index];
  453. SetOutputLayout(next_in_tensor_info.tensor_layout());
  454. if (Init(nullptr) == FAILED) {
  455. MS_LOG(DEBUG) << "Failure:operator reshape init failed";
  456. continue;
  457. }
  458. SetCostForReshape(reshape_stra);
  459. }
  460. }
  461. is_generating_costs_ = false;
  462. if (strategy_cost_.empty()) {
  463. return FAILED;
  464. }
  465. return SUCCESS;
  466. }
  467. } // namespace parallel
  468. } // namespace mindspore