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.

arithmetic_simplify.cc 8.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * Copyright 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/optimizer/irpass/arithmetic_simplify.h"
  17. namespace mindspore {
  18. namespace opt {
  19. namespace irpass {
  20. AnfNodePtr ArithmeticSimplify::operator()(const OptimizerPtr &, const AnfNodePtr &node) {
  21. PatternNode x, y, z, xs;
  22. PConstant one_(node, false, 1);
  23. PConstant one_scalar_(node, false, 1, true);
  24. PConstant zero_(node, false, 0);
  25. PConstant zero_scalar_(node, false, 0, true);
  26. PConstant const_(node);
  27. PConstant const_2(node);
  28. PConstant any_const(node);
  29. if (MsContext::GetInstance()->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode) {
  30. MATCH_REPLACE(node, x + zero_, x); // Add by zero
  31. MATCH_REPLACE(node, x + zero_scalar_, x); // Add by zero
  32. MATCH_REPLACE(node, PBinOperation(prim::kPrimScalarAdd, x, zero_scalar_, true), x); // Scalar Add by zero
  33. MATCH_REPLACE_IF(node, x * one_, any_const.WithValueOf(x), !one_.CheckFunc(IsParam, node)); // Multiply by one
  34. MATCH_REPLACE(node, PBinOperation(prim::kPrimScalarMul, x, one_scalar_, true), x); // Scalar Mul by one
  35. // Scalar Mul by zero
  36. MATCH_REPLACE(node, PBinOperation(prim::kPrimScalarMul, x, zero_scalar_, true), zero_scalar_.NewValue());
  37. }
  38. // Prim Eliminate (identity)
  39. MATCH_REPLACE(node, PPrimitive(prim::kPrimIdentity, x), x);
  40. if (MsContext::GetInstance()->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode) {
  41. return nullptr;
  42. }
  43. // ConstantDuplicateMul
  44. auto const_dup_lambda = [&node, &x, &const_, &const_2]() -> AnfNodePtr {
  45. auto new_mul_tensor = const_.MulByPatternConst(const_2, x.GetNode(node));
  46. auto mul_node = node->cast<CNodePtr>()->inputs()[0];
  47. if (new_mul_tensor == nullptr) {
  48. auto ttmul = NewCNode({mul_node, const_.GetNode(node), const_2.GetNode(node)}, node->func_graph());
  49. return NewCNode({mul_node, x.GetNode(node), ttmul}, node->func_graph());
  50. }
  51. auto new_cnode = NewCNode({mul_node, x.GetNode(node), new_mul_tensor}, node->func_graph());
  52. new_cnode->set_abstract(node->abstract());
  53. return new_cnode;
  54. };
  55. MATCH_REPLACE_LAMBDA(node, const_ * (const_2 * x), const_dup_lambda);
  56. if (node->func_graph() == nullptr) {
  57. return nullptr;
  58. }
  59. // OptUpdateZeroTensor: {kPrimMomentum, {kPrimZerosLike, x}, y, z, xs} -> {kPrimMakeTuple, z, y}
  60. MATCH_REPLACE(node, PPrimitive(prim::kPrimMomentum, PPrimitive(prim::kPrimZerosLike, x), y, z).MinExtraNodes(0),
  61. PPrimitive(prim::kPrimMakeTuple, z, y));
  62. // PowerOneEliminate
  63. MATCH_REPLACE_IF(node, PPrimitive(prim::kPrimPow, x, one_scalar_), x,
  64. one_scalar_.CheckFunc(IsValueNode<Scalar>, node));
  65. return nullptr;
  66. }
  67. AnfNodePtr ArithmeticSimplify2::operator()(const OptimizerPtr &, const AnfNodePtr &node) {
  68. if (MsContext::GetInstance()->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode) {
  69. return nullptr;
  70. }
  71. PatternNode x, y;
  72. PConstant zero_(node, false, 0);
  73. // Multiply by zero
  74. MATCH_REPLACE_IF(node, x * zero_, zero_.WithShapeAs(node),
  75. !zero_.CheckFunc(IsParam, node) && x.GetNode(node)->func_graph() == node->func_graph());
  76. auto zero_prim = PPrimitive(prim::kPrimZerosLike, y);
  77. MATCH_REPLACE_IF(node, x * zero_prim, zero_.WithShapeAs(node),
  78. !zero_prim.CheckFunc(IsParam, node) && x.GetNode(node)->func_graph() == node->func_graph());
  79. return nullptr;
  80. }
  81. // grad = AllReduce(grad) / worker_number
  82. // grad = grad + weight * decy
  83. // ->
  84. // grad = grad + weight * decy
  85. // grad = AllReduce(grad) / worker_number
  86. // {prim::kPrimAddN, {prim::kPrimMakeTuple, {prim::kPrimMul, {prim::kPrimAllReduce, X}, Y}, Z}} ->
  87. // {prim::kPrimMul, {prim::kPrimAllReduce, {prim::kPrimAddN,{prim::kPrimMakeTuple, Z, X}}}, Y}
  88. AnfNodePtr AdjustAllReduceMulAdd::operator()(const OptimizerPtr &, const AnfNodePtr &node) {
  89. PatternNode x, y, z;
  90. auto all_reduce_pat = PPrimitive(prim::kPrimAllReduce, x);
  91. auto mul_pat = PBinOperation(prim::kPrimMul, all_reduce_pat, y, true);
  92. auto admktup_pat = PBinOperation(prim::kPrimMakeTuple, mul_pat, z, true);
  93. auto addn_pat = PPrimitive(prim::kPrimAddN, admktup_pat);
  94. auto adjust_lambda = [&node, &x, &y, &z, &addn_pat, &all_reduce_pat, &admktup_pat, &mul_pat, this]() -> AnfNodePtr {
  95. auto fg = all_reduce_pat.GetFuncGraph();
  96. auto z_ = z.GetNode(node);
  97. auto x_ = x.GetNode(node);
  98. // If addn inputs cross the graph, make the inputs same as allreduce node.
  99. if (z_->isa<CNode>() && fg != z_->func_graph()) {
  100. auto cnode_z = z_->cast<CNodePtr>();
  101. z_ = NewCNode(cnode_z->inputs(), fg);
  102. }
  103. auto addn_cnode = addn_pat.GetOriginalNode()->cast<CNodePtr>();
  104. auto addn_op_node = addn_cnode->input(0);
  105. auto make_tuple_op_node = addn_cnode->input(1)->cast<CNodePtr>()->input(0);
  106. auto all_reduce_prim = all_reduce_pat.GetOriginalNode()->cast<CNodePtr>()->input(0);
  107. mul_cnode_ = mul_pat.GetOriginalNode();
  108. auto mul_prim = mul_cnode_->cast<CNodePtr>()->input(0);
  109. auto addn_maketuple = admktup_pat.GetOriginalNode();
  110. ShapeVector x_shape, z_shape;
  111. if (!x_->isa<ValueNode>()) {
  112. if ((x_->abstract() == nullptr) || !x_->abstract()->isa<abstract::AbstractTensor>()) {
  113. return nullptr;
  114. }
  115. auto x_abstract = x_->abstract()->cast<abstract::AbstractTensorPtr>();
  116. x_shape = x_abstract->shape()->shape();
  117. } else {
  118. ValuePtr x_value = x_->cast<ValueNodePtr>()->value();
  119. if (!x_value->isa<tensor::Tensor>()) {
  120. return nullptr;
  121. }
  122. auto x_tensor = GetValueNode<tensor::TensorPtr>(x_->cast<ValueNodePtr>());
  123. x_shape = x_tensor->shape();
  124. }
  125. if (!z_->isa<ValueNode>()) {
  126. if ((z_->abstract() == nullptr) || !z_->abstract()->isa<abstract::AbstractTensor>()) {
  127. return nullptr;
  128. }
  129. auto z_abstract = z_->abstract()->cast<abstract::AbstractTensorPtr>();
  130. z_shape = z_abstract->shape()->shape();
  131. } else {
  132. ValuePtr z_value = z_->cast<ValueNodePtr>()->value();
  133. if (!z_value->isa<tensor::Tensor>()) {
  134. return nullptr;
  135. }
  136. auto z_tensor = GetValueNode<tensor::TensorPtr>(z_->cast<ValueNodePtr>());
  137. z_shape = z_tensor->shape();
  138. }
  139. if (x_shape != z_shape) {
  140. // AddN requires x_ and z_ have the same shape.
  141. // If broadcasting TensorAdd is supported then can use this
  142. // AnfNodePtr add = NewCNode({NewValueNode(prim::kPrimTensorAdd), z_, x_}, fg);
  143. return nullptr;
  144. }
  145. AnfNodePtr tuple = NewCNode({make_tuple_op_node, z_, x_}, fg);
  146. AnfNodePtr add = NewCNode({addn_op_node, tuple}, fg);
  147. AnfNodePtr all_reduce = NewCNode({all_reduce_prim, add}, fg);
  148. AnfNodePtr mul = NewCNode({mul_prim, all_reduce, y.GetNode(node)}, fg);
  149. ProcessDependEdge(fg, addn_maketuple, all_reduce);
  150. return mul;
  151. };
  152. MATCH_REPLACE_LAMBDA(node, addn_pat, adjust_lambda);
  153. return nullptr;
  154. }
  155. void AdjustAllReduceMulAdd::ProcessDependEdge(const FuncGraphPtr &fg, const AnfNodePtr &addn_maketuple,
  156. const AnfNodePtr &new_node) {
  157. // If has dynamic loss scale.
  158. auto &users_map = fg->manager()->node_users();
  159. auto it = users_map.find(mul_cnode_);
  160. if (it != users_map.end()) {
  161. auto users = it->second;
  162. for (auto &user_pair : users) {
  163. auto node = user_pair.first;
  164. if (node != addn_maketuple) {
  165. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  166. fg->manager()->SetEdge(node, user_pair.second, new_node);
  167. }
  168. }
  169. }
  170. }
  171. }
  172. } // namespace irpass
  173. } // namespace opt
  174. } // namespace mindspore