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.

dfunctor.h 8.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2020 Huawei Technologies Co., Ltd
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_D_FUNCTOR_H_
  19. #define MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_D_FUNCTOR_H_
  20. #include <memory>
  21. #include <string>
  22. #include <unordered_map>
  23. #include <vector>
  24. #include <iostream>
  25. #include <utility>
  26. #include "ir/anf.h"
  27. #include "ir/meta_func_graph.h"
  28. #include "ir/func_graph_cloner.h"
  29. #include "pipeline/jit/resource.h"
  30. #include "frontend/optimizer/ad/adjoint.h"
  31. #include "frontend/operator/ops.h"
  32. #include "debug/trace.h"
  33. namespace mindspore {
  34. namespace ad {
  35. struct PrimitiveTotalEqual {
  36. bool operator()(PrimitivePtr const &t1, PrimitivePtr const &t2) const {
  37. MS_EXCEPTION_IF_NULL(t1);
  38. MS_EXCEPTION_IF_NULL(t2);
  39. return *t1 == *t2;
  40. }
  41. };
  42. using Registry = std::unordered_map<PrimitivePtr, FuncGraphPtr, PrimitiveHasher, PrimitiveTotalEqual>;
  43. class KPrim;
  44. extern KPrim g_k_prims;
  45. class DFunctor;
  46. using DFunctorPtr = std::shared_ptr<DFunctor>;
  47. // D Functor's rules to map closure object and morphisms.
  48. class DFunctor : public std::enable_shared_from_this<DFunctor> {
  49. public:
  50. DFunctor(const FuncGraphPtr &primal_graph, const pipeline::ResourceBasePtr &resources);
  51. ~DFunctor() = default;
  52. // Map object in D category to K category.
  53. void MapObject();
  54. // Map morphism in D category to K category.
  55. void MapMorphism();
  56. FuncGraphPtr k_graph();
  57. // Construct user defined k object.
  58. FuncGraphPtr KUserDefined(const FuncGraphPtr &primal);
  59. // Register functor objects to form a global view.
  60. void Init(bool is_top = false);
  61. void Finish();
  62. bool IsInScope(const AnfNodePtr &node);
  63. // Clear resources.
  64. static void Clear();
  65. private:
  66. // Map one morphism.
  67. AdjointPtr MapMorphism(const AnfNodePtr &morph);
  68. bool IsFreeMorphism(const AnfNodePtr &node);
  69. // Map morphism that's not attached to output.
  70. void MapFreeMorphism();
  71. void BackPropagateFv(const AnfNodePtr &fv, const AnfNodePtr &din);
  72. void BackPropagateSwitchLayer(const CNodePtr &cnode_morph, const CNodePtr &env);
  73. void BackPropagate(const CNodePtr &cnode_morph, const CNodePtr &k_app, const AdjointPtr &node_adjoint);
  74. AnfNodePtr AttachFvDoutToTape(const AnfNodePtr &grad_fv);
  75. AnfNodePtr AttachIndirectFvDoutToTape(const AnfNodePtr &grad_fv);
  76. // Map Anfnode object from D category to K category.
  77. AnfNodePtr MapToK(const AnfNodePtr &primal);
  78. // Map FuncGraph object from D category to K category.
  79. AnfNodePtr MapToK(const FuncGraphPtr &primal);
  80. // MapObject impls.
  81. void MapFvObject();
  82. void MapValueObject();
  83. void MapParamObject();
  84. // Find adjoint with its primary k.
  85. AdjointPtr FindAdjoint(const AnfNodePtr &primal);
  86. // Broadcast stop flags.
  87. void BroadCastStopFlag();
  88. bool AllReferencesStopped(const CNodePtr &node);
  89. // Update k hole with adjoint_definition, only applied in recursive case.
  90. void UpdateAdjoint(const AdjointPtr &adjoint_definition);
  91. void CallDoutHoleOnTape();
  92. void ReplaceEquivdout(const CNodePtr &cnode, const CNodePtr &cnode_morph);
  93. // Replace the primal graph with k graph
  94. void EliminatePrimalGraph();
  95. std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_;
  96. // Cache for indirect fv backpropagation, K o K can only do backprop layer by layer.
  97. std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_indirect_fv_;
  98. // Cache for fv node -> pair<embed<fv_node>, zeros_like<fv_node>>, so EnvGetItemTransform in optimizer
  99. // can hit its cache if fv_node is same.
  100. std::unordered_map<AnfNodePtr, std::pair<CNodePtr, CNodePtr>> anfnode_to_envitem_;
  101. FuncGraphPtr primal_graph_;
  102. // K object for primal_graph_;
  103. FuncGraphPtr k_graph_;
  104. // The Backprop part of k_graph_.
  105. FuncGraphPtr tape_;
  106. // Dout parameter for primal_graph_.
  107. AnfNodePtr dout_;
  108. pipeline::ResourceBasePtr resources_;
  109. // Cut off stopped objects in category D.
  110. bool need_cut_;
  111. bool is_top_;
  112. static std::unordered_map<FuncGraphPtr, std::shared_ptr<DFunctor>> func_graph_to_functor_;
  113. static std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_definition_;
  114. static FuncGraphSet scope_;
  115. };
  116. // D Functor's rules to map primitive object.
  117. class KPrim {
  118. public:
  119. KPrim() = default;
  120. ~KPrim() = default;
  121. FuncGraphPtr KPrimitive(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  122. MetaFuncGraphPtr KMetaFuncGraph(const PrimitivePtr &prim);
  123. FuncGraphPtr KUserDefinedCellBprop(FuncGraphPtr bprop);
  124. void clear() {
  125. bprop_registry_meta_.clear();
  126. bprop_registry_.clear();
  127. }
  128. private:
  129. FuncGraphPtr GetBprop(const PrimitivePtr &prim);
  130. FuncGraphPtr GetFprop(const PrimitivePtr &prim);
  131. FuncGraphPtr FakeBprop(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  132. FuncGraphPtr BpropCut(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  133. // Given a bprop rule, do the K mapping.
  134. template <typename T>
  135. FuncGraphPtr BpropToK(const T &primal, const FuncGraphPtr &bprop_g);
  136. AnfNodePtr BuildOutput(const FuncGraphPtr &bprop_fg);
  137. void TransformArgs(const FuncGraphManagerPtr &mng, const FuncGraphPtr &bprop_fg, const FuncGraphPtr &outer,
  138. std::vector<AnfNodePtr> *const transf_args);
  139. void CheckBprop(const FuncGraphPtr &bprop_fg, const string &prim_to_check);
  140. Registry bprop_registry_;
  141. std::unordered_map<PrimitivePtr, MetaFuncGraphPtr> bprop_registry_meta_;
  142. };
  143. template <typename T>
  144. FuncGraphPtr KPrim::BpropToK(const T &primal, const FuncGraphPtr &bprop_fg) {
  145. MS_EXCEPTION_IF_NULL(primal);
  146. MS_EXCEPTION_IF_NULL(bprop_fg);
  147. CheckBprop(bprop_fg, primal->ToString());
  148. auto debug_info = std::make_shared<GraphDebugInfo>();
  149. debug_info->set_name(primal->ToString());
  150. auto cloned_bprop_fg = BasicClone(bprop_fg);
  151. MS_EXCEPTION_IF_NULL(cloned_bprop_fg);
  152. cloned_bprop_fg->debug_info()->set_name("");
  153. cloned_bprop_fg->debug_info()->set_trace_info(std::make_shared<TraceGradBprop>(debug_info));
  154. AnfNodePtr bout = BuildOutput(cloned_bprop_fg);
  155. cloned_bprop_fg->set_output(bout);
  156. TraceManager::DebugTrace(std::make_shared<TraceGradFprop>(debug_info));
  157. auto outer = std::make_shared<FuncGraph>();
  158. (void)outer->transforms().emplace("primal", FuncGraphTransform(primal));
  159. outer->set_output(NewValueNode(kNone));
  160. TraceManager::EndTrace();
  161. auto mng = Manage({cloned_bprop_fg, outer}, false);
  162. // Make sure (out, dout) provided.
  163. if (cloned_bprop_fg->parameters().size() < 2) {
  164. MS_LOG(EXCEPTION) << "Primitive or Cell " << primal->ToString()
  165. << " bprop requires out and dout at least, but only got " << cloned_bprop_fg->parameters().size()
  166. << " params. NodeInfo: " << trace::GetDebugInfo(cloned_bprop_fg->debug_info());
  167. }
  168. // In a bprop definition, the last two param should be out and dout.
  169. auto dout = cloned_bprop_fg->parameters()[cloned_bprop_fg->parameters().size() - 1];
  170. auto out_param = cloned_bprop_fg->parameters()[cloned_bprop_fg->parameters().size() - 2];
  171. std::vector<AnfNodePtr> transf_args;
  172. TransformArgs(mng, cloned_bprop_fg, outer, &transf_args);
  173. TraceManager::DebugTrace(std::make_shared<TraceEquiv>(dout->debug_info()));
  174. (void)transf_args.insert(transf_args.begin(), NewValueNode(primal));
  175. auto out_value = outer->NewCNode(transf_args);
  176. TraceManager::EndTrace();
  177. (void)mng->Replace(out_param, out_value);
  178. TraceManager::DebugTrace(std::make_shared<TraceGradSens>(out_param->debug_info()));
  179. auto new_dout = cloned_bprop_fg->add_parameter();
  180. (void)mng->Replace(dout, new_dout);
  181. // We remove all parameters except new_dout.
  182. std::vector<AnfNodePtr> newBpropParams = {new_dout};
  183. cloned_bprop_fg->set_parameters(newBpropParams);
  184. TraceManager::EndTrace();
  185. outer->set_output(outer->NewCNode({NewValueNode(prim::kPrimMakeTuple), out_value, NewValueNode(cloned_bprop_fg)}));
  186. return BasicClone(outer);
  187. }
  188. } // namespace ad
  189. } // namespace mindspore
  190. #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_D_FUNCTOR_H_