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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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_OPTIMIZER_AD_D_FUNCTOR_H_
  19. #define MINDSPORE_CCSRC_OPTIMIZER_AD_D_FUNCTOR_H_
  20. #include <memory>
  21. #include <string>
  22. #include <unordered_map>
  23. #include <vector>
  24. #include <iostream>
  25. #include "ir/anf.h"
  26. #include "ir/meta_func_graph.h"
  27. #include "ir/func_graph_cloner.h"
  28. #include "pipeline/resource.h"
  29. #include "optimizer/ad/adjoint.h"
  30. #include "operator/ops.h"
  31. #include "debug/trace.h"
  32. namespace mindspore {
  33. namespace ad {
  34. using Registry = std::unordered_map<PrimitivePtr, FuncGraphPtr>;
  35. class KPrim;
  36. extern KPrim g_k_prims;
  37. class DFunctor;
  38. using DFunctorPtr = std::shared_ptr<DFunctor>;
  39. // D Functor's rules to map closure object and morphisms.
  40. class DFunctor {
  41. public:
  42. DFunctor(const FuncGraphPtr &primal_graph, const pipeline::ResourceBasePtr &resources);
  43. ~DFunctor() = default;
  44. // Map object in D category to K category.
  45. void MapObject();
  46. // Map morphism in D category to K category.
  47. void MapMorphism();
  48. FuncGraphPtr k_graph();
  49. // Construct user defined k object.
  50. FuncGraphPtr KUserDefined(const FuncGraphPtr &primal);
  51. // Register functor objects to form a global view.
  52. void Init(const DFunctorPtr &functor, bool is_top = false);
  53. // Clear resources.
  54. static void Clear();
  55. private:
  56. // Map one morphism.
  57. AdjointPtr MapMorphism(const AnfNodePtr &morph);
  58. bool IsFreeMorphism(const AnfNodePtr &node);
  59. // Map morphism that's not attached to output.
  60. void MapFreeMorphism();
  61. void BackPropagateFv(const AnfNodePtr &fv, const AnfNodePtr &din);
  62. void BackPropagate(const CNodePtr &cnode_morph, const CNodePtr &k_app, const AdjointPtr &node_adjoint);
  63. AnfNodePtr AttachFvDoutToTape(const AnfNodePtr &grad_fv);
  64. AnfNodePtr AttachIndirectFvDoutToTape(const AnfNodePtr &grad_fv);
  65. // Map Anfnode object from D category to K category.
  66. AnfNodePtr MapToK(const AnfNodePtr &primal);
  67. // Map FuncGraph object from D category to K category.
  68. AnfNodePtr MapToK(const FuncGraphPtr &primal);
  69. // MapObject impls.
  70. void MapFvObject();
  71. void MapValueObject();
  72. void MapParamObject();
  73. // Find adjoint with its primary k.
  74. AdjointPtr FindAdjoint(const AnfNodePtr &primal);
  75. // Broadcast stop flags.
  76. void BroadCastStopFlag();
  77. bool AllReferencesStopped(const CNodePtr &node);
  78. // Update k hole with adjoint_definition, only applied in recursive case.
  79. void UpdateAdjoint(const AdjointPtr &adjoint_definition);
  80. void CallDoutHoleOnTape();
  81. std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_;
  82. // Cache for indirect fv backpropagation, K o K can only do backprop layer by layer.
  83. std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_indirect_fv_;
  84. FuncGraphPtr primal_graph_;
  85. // K object for primal_graph_;
  86. FuncGraphPtr k_graph_;
  87. // The Backprop part of k_graph_.
  88. FuncGraphPtr tape_;
  89. // Dout parameter for primal_graph_.
  90. AnfNodePtr dout_;
  91. pipeline::ResourceBasePtr resources_;
  92. // Cut off stopped objects in category D.
  93. bool need_cut_;
  94. bool is_top_;
  95. static std::unordered_map<FuncGraphPtr, std::shared_ptr<DFunctor>> func_graph_to_functor_;
  96. static std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_definition_;
  97. };
  98. // D Functor's rules to map primitive object.
  99. class KPrim {
  100. public:
  101. KPrim() = default;
  102. ~KPrim() = default;
  103. FuncGraphPtr KPrimitive(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  104. MetaFuncGraphPtr KMetaFuncGraph(const PrimitivePtr &prim);
  105. FuncGraphPtr KUserDefinedCellBprop(FuncGraphPtr bprop);
  106. void clear() {
  107. bprop_registry_meta_.clear();
  108. bprop_registry_.clear();
  109. }
  110. private:
  111. FuncGraphPtr GetBprop(const PrimitivePtr &prim);
  112. FuncGraphPtr FakeBprop(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  113. // Given a bprop rule, do the K mapping.
  114. template <typename T>
  115. FuncGraphPtr BpropToK(const T &primal, const FuncGraphPtr &bprop_g);
  116. AnfNodePtr BuildOutput(const FuncGraphPtr &bprop_fg);
  117. void TransformArgs(const FuncGraphManagerPtr &mng, const FuncGraphPtr &bprop_fg, const FuncGraphPtr &outer,
  118. std::vector<AnfNodePtr> *const transf_args);
  119. void CheckBprop(const FuncGraphPtr &bprop_fg, const string &prim_to_check);
  120. Registry bprop_registry_;
  121. std::unordered_map<PrimitivePtr, MetaFuncGraphPtr> bprop_registry_meta_;
  122. };
  123. template <typename T>
  124. FuncGraphPtr KPrim::BpropToK(const T &primal, const FuncGraphPtr &bprop_fg) {
  125. MS_EXCEPTION_IF_NULL(primal);
  126. MS_EXCEPTION_IF_NULL(bprop_fg);
  127. CheckBprop(bprop_fg, primal->ToString());
  128. auto debug_info = std::make_shared<GraphDebugInfo>();
  129. debug_info->set_name(primal->ToString());
  130. auto cloned_bprop_fg = BasicClone(bprop_fg);
  131. MS_EXCEPTION_IF_NULL(cloned_bprop_fg);
  132. cloned_bprop_fg->debug_info()->set_name("");
  133. cloned_bprop_fg->debug_info()->set_trace_info(std::make_shared<TraceGradBprop>(debug_info));
  134. AnfNodePtr bout = BuildOutput(cloned_bprop_fg);
  135. cloned_bprop_fg->set_output(bout);
  136. TraceManager::DebugTrace(std::make_shared<TraceGradFprop>(debug_info));
  137. auto outer = std::make_shared<FuncGraph>();
  138. (void)outer->transforms().emplace("primal", FuncGraphTransform(primal));
  139. outer->set_output(NewValueNode(kNone));
  140. TraceManager::EndTrace();
  141. auto mng = Manage({cloned_bprop_fg, outer}, false);
  142. // Make sure (out, dout) provided.
  143. if (cloned_bprop_fg->parameters().size() < 2) {
  144. MS_LOG(EXCEPTION) << "Primitive or Cell " << primal->ToString()
  145. << " bprop requires out and dout at least, but only got " << cloned_bprop_fg->parameters().size()
  146. << " params. NodeInfo: " << trace::GetDebugInfo(cloned_bprop_fg->debug_info());
  147. }
  148. // In a bprop definition, the last two param should be out and dout.
  149. auto dout = cloned_bprop_fg->parameters()[cloned_bprop_fg->parameters().size() - 1];
  150. auto out_param = cloned_bprop_fg->parameters()[cloned_bprop_fg->parameters().size() - 2];
  151. std::vector<AnfNodePtr> transf_args;
  152. TransformArgs(mng, cloned_bprop_fg, outer, &transf_args);
  153. TraceManager::DebugTrace(std::make_shared<TraceEquiv>(dout->debug_info()));
  154. (void)transf_args.insert(transf_args.begin(), NewValueNode(primal));
  155. auto out_value = outer->NewCNode(transf_args);
  156. TraceManager::EndTrace();
  157. (void)mng->Replace(out_param, out_value);
  158. TraceManager::DebugTrace(std::make_shared<TraceGradSens>(out_param->debug_info()));
  159. auto new_dout = cloned_bprop_fg->add_parameter();
  160. (void)mng->Replace(dout, new_dout);
  161. // We remove all parameters except new_dout.
  162. std::vector<AnfNodePtr> newBpropParams = {new_dout};
  163. cloned_bprop_fg->set_parameters(newBpropParams);
  164. TraceManager::EndTrace();
  165. outer->set_output(outer->NewCNode({NewValueNode(prim::kPrimMakeTuple), out_value, NewValueNode(cloned_bprop_fg)}));
  166. return BasicClone(outer);
  167. }
  168. } // namespace ad
  169. } // namespace mindspore
  170. #endif // MINDSPORE_CCSRC_OPTIMIZER_AD_D_FUNCTOR_H_