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.

gradient_eliminate.cc 5.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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/gradient_eliminate.h"
  17. #include "pipeline/pynative/pynative_execute.h"
  18. namespace mindspore {
  19. namespace opt {
  20. namespace irpass {
  21. namespace internal {
  22. AnfNodePtr ExpandJPrimitive(const ValueNodePtr &vnode, const pipeline::ResourceBasePtr &resource) {
  23. ScopeGuard scope_guard(vnode->scope());
  24. auto newg = ad::Kprim(vnode, resource);
  25. if (newg != nullptr) {
  26. return NewValueNode(newg);
  27. }
  28. // when find in J failed, try in Jmeta
  29. auto prim = GetValueNode<PrimitivePtr>(vnode);
  30. MetaFuncGraphPtr meta = ad::Kmeta(prim, resource);
  31. if (meta != nullptr) {
  32. return NewValueNode(meta);
  33. }
  34. return nullptr;
  35. }
  36. bool CheckIfEmbedJ(const CNodePtr &j_node) {
  37. auto &value_node = j_node->input(1);
  38. if (IsValueNode<Primitive>(value_node)) {
  39. return false;
  40. }
  41. auto func_graph = GetValueNode<FuncGraphPtr>(value_node);
  42. if (func_graph == nullptr) {
  43. MS_LOG(EXCEPTION) << "Unexpected j node:" << j_node->DebugString();
  44. }
  45. auto func_graph_manager = func_graph->manager();
  46. MS_EXCEPTION_IF_NULL(func_graph_manager);
  47. return func_graph_manager->func_graph_j_total(func_graph);
  48. }
  49. bool IsSideEffectOp(const AnfNodePtr &node) {
  50. if (!node->isa<CNode>()) {
  51. return false;
  52. }
  53. auto effect_info = GetPrimEffectInfo(GetCNodePrimitive(node));
  54. return effect_info.memory || effect_info.io;
  55. }
  56. void CheckSwitchWithSideEffect(const FuncGraphPtr &fg) {
  57. AnfNodePtr switch_node = nullptr;
  58. AnfNodePtr side_effect_node = nullptr;
  59. auto all_graphs = fg->func_graphs_used_total();
  60. all_graphs.add(fg);
  61. for (auto &child_fg : all_graphs) {
  62. for (const auto &node : child_fg->nodes()) {
  63. if (switch_node == nullptr && IsPrimitiveCNode(node, prim::kPrimSwitch)) {
  64. switch_node = node;
  65. }
  66. if (side_effect_node == nullptr && IsSideEffectOp(node)) {
  67. side_effect_node = node;
  68. }
  69. if (switch_node != nullptr && side_effect_node != nullptr) {
  70. MS_LOG(ERROR)
  71. << "Control flow with side effect op[" << GetCNodeFuncName(side_effect_node->cast<CNodePtr>())
  72. << "] in training situation is not supported and grads may be wrong. Please remove the control flow "
  73. "statement or the side effect op.\n"
  74. << " Side effect node:" << side_effect_node->DebugString();
  75. return;
  76. }
  77. }
  78. }
  79. }
  80. AnfNodePtr ExpandJ(const ValueNodePtr &vnode, const pipeline::ResourceBasePtr &resource) {
  81. if (IsValueNode<FuncGraph>(vnode)) {
  82. ScopeGuard scope_guard(vnode->scope());
  83. auto func_graph = GetValueNode<FuncGraphPtr>(vnode);
  84. // If a control flow network has side effect ops inside, which is not supported now, a error will be raised to
  85. // alert wrong grads.
  86. CheckSwitchWithSideEffect(func_graph);
  87. MS_EXCEPTION_IF_NULL(func_graph);
  88. MS_LOG(DEBUG) << "Funcgraph: " << func_graph->ToString() << " will expandJ now";
  89. auto newfg = ad::Grad(func_graph, resource);
  90. return NewValueNode(newfg);
  91. }
  92. if (IsValueNode<Primitive>(vnode)) {
  93. return ExpandJPrimitive(vnode, resource);
  94. }
  95. return nullptr;
  96. }
  97. } // namespace internal
  98. bool ExpandJPrim::operator()(const FuncGraphPtr &func_graph, const OptimizerPtr &optimizer) {
  99. // Search all j nodes.
  100. GetJPrim(func_graph);
  101. // Get j nodes that don't have embed j nodes.
  102. std::vector<CNodePtr> todo;
  103. // If graph also contains J(FuncGraph) or J(Primitive), then ignore this graph.
  104. // ExpandJ innermost graph or primitive first.
  105. std::copy_if(j_nodes_.begin(), j_nodes_.end(), std::back_inserter(todo),
  106. [](const CNodePtr &j_node) { return !internal::CheckIfEmbedJ(j_node); });
  107. // Check whether need to eliminate forward cnodes in pynative mode.
  108. if (MsContext::GetInstance()->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode) {
  109. auto pynative_exec = pynative::PynativeExecutor::GetInstance();
  110. auto grad_exec = pynative_exec->grad_executor();
  111. bool eliminate_forward = grad_exec->eliminate_forward();
  112. grad_exec->set_eliminate_forward(eliminate_forward && todo.empty());
  113. }
  114. // Expand j nodes that don't have embed j nodes.
  115. bool change = false;
  116. auto manager = optimizer->manager();
  117. for (auto &j_node : todo) {
  118. auto expanded_j = internal::ExpandJ(j_node->input(1)->cast<ValueNodePtr>(), optimizer->resource());
  119. manager->Replace(j_node, expanded_j);
  120. change = true;
  121. }
  122. return change;
  123. }
  124. void ExpandJPrim::GetJPrim(const FuncGraphPtr &func_graph) {
  125. j_nodes_.clear();
  126. AnfNodePtr ret = func_graph->get_return();
  127. MS_EXCEPTION_IF_NULL(ret);
  128. std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret);
  129. for (auto &node : all_nodes) {
  130. if (IsPrimitiveCNode(node, prim::kPrimJ)) {
  131. j_nodes_.push_back(node->cast<CNodePtr>());
  132. }
  133. }
  134. }
  135. } // namespace irpass
  136. } // namespace opt
  137. } // namespace mindspore