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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. FuncGraphPtr tape();
  58. // Construct user defined k object.
  59. FuncGraphPtr KUserDefined(const FuncGraphPtr &primal);
  60. // Register functor objects to form a global view.
  61. void Init(bool is_top = false);
  62. void Finish();
  63. bool IsInScope(const AnfNodePtr &node);
  64. // Clear resources.
  65. static void Clear();
  66. private:
  67. // Map one morphism.
  68. AdjointPtr MapMorphism(const AnfNodePtr &morph);
  69. bool IsFreeMorphism(const AnfNodePtr &node);
  70. // Map morphism that's not attached to output.
  71. void MapFreeMorphism();
  72. void BackPropagateFv(const AnfNodePtr &fv, const AnfNodePtr &din);
  73. void BackPropagateSwitchLayer(const CNodePtr &cnode_morph, const CNodePtr &env);
  74. void BackPropagate(const CNodePtr &cnode_morph, const CNodePtr &k_app, const AdjointPtr &node_adjoint);
  75. AnfNodePtr AttachFvDoutToTape(const AnfNodePtr &grad_fv);
  76. AnfNodePtr AttachIndirectFvDoutToTape(const AnfNodePtr &grad_fv);
  77. // Map CNode/Index of Primitive to K.
  78. AnfNodePtr MapPrimitiveToK(const CNodePtr &primitive_user, size_t index);
  79. // Map ValueNode of FuncGraph to K.
  80. AnfNodePtr MapFuncGraphToK(const AnfNodePtr &primal);
  81. // Map ValueNode of Parameter to K.
  82. AnfNodePtr MapParameterToK(const AnfNodePtr &primal);
  83. // MapObject impls.
  84. void MapFvObject();
  85. void MapValueObject();
  86. void MapParamObject();
  87. // Find adjoint with its primary k.
  88. AdjointPtr FindAdjoint(const AnfNodePtr &primal);
  89. // Broadcast stop flags.
  90. void BroadCastStopFlag();
  91. bool AllReferencesStopped(const CNodePtr &node);
  92. // Update k hole with adjoint_definition, only applied in recursive case.
  93. void UpdateAdjoint(const AdjointPtr &adjoint_definition);
  94. void CallDoutHoleOnTape();
  95. // Replace the primal graph with k graph
  96. void EliminatePrimalGraph();
  97. // Pynative specialize
  98. void ReplaceEquivdout(const CNodePtr &cnode, const CNodePtr &cnode_morph);
  99. ValuePtr GenNewTensorInner(const ValuePtr &value);
  100. ValuePtr GenNewTensor(const FuncGraphManagerPtr &mng, const AnfNodePtr &node, const ValuePtr &value,
  101. bool need_replace_forward);
  102. std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_;
  103. // Cache for indirect fv backpropagation, K o K can only do backprop layer by layer.
  104. std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_indirect_fv_;
  105. // Cache for fv node -> pair<embed<fv_node>, zeros_like<fv_node>>, so EnvGetItemTransform in optimizer
  106. // can hit its cache if fv_node is same.
  107. std::unordered_map<AnfNodePtr, std::pair<CNodePtr, CNodePtr>> anfnode_to_envitem_;
  108. FuncGraphPtr primal_graph_;
  109. // K object for primal_graph_;
  110. FuncGraphPtr k_graph_;
  111. // The Backprop part of k_graph_.
  112. FuncGraphPtr tape_;
  113. // Dout parameter for primal_graph_.
  114. AnfNodePtr dout_;
  115. pipeline::ResourceBasePtr resources_;
  116. // Cut off stopped objects in category D.
  117. bool need_cut_;
  118. bool is_top_;
  119. static std::unordered_map<FuncGraphPtr, std::shared_ptr<DFunctor>> func_graph_to_functor_;
  120. static std::unordered_map<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_definition_;
  121. static FuncGraphSet scope_;
  122. };
  123. // D Functor's rules to map primitive object.
  124. class KPrim {
  125. public:
  126. KPrim() = default;
  127. ~KPrim() = default;
  128. FuncGraphPtr KPrimitive(const CNodePtr &primal_user, const ValueNodePtr &value_node,
  129. const pipeline::ResourceBasePtr &resources);
  130. MetaFuncGraphPtr KMetaFuncGraph(const PrimitivePtr &prim);
  131. // bprop_fg and primal_fg in bprop_fg's transforms are FuncGraph just after convert.
  132. // current_primal_fg is the specialized and AutoMonaded primal_fg.
  133. FuncGraphPtr KUserDefinedCellBprop(const FuncGraphPtr &bprop_fg, const FuncGraphPtr &current_primal_fg);
  134. void clear() {
  135. bprop_registry_meta_.clear();
  136. bprop_registry_.clear();
  137. }
  138. private:
  139. FuncGraphPtr GetBprop(const PrimitivePtr &prim);
  140. FuncGraphPtr GetFprop(const PrimitivePtr &prim);
  141. FuncGraphPtr FakeBprop(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  142. FuncGraphPtr BpropCut(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  143. // Given a bprop rule, do the K mapping.
  144. // current_primal_fg is only valid for user defined bprop for Cell, not for Primitive.
  145. // Refer the comment in KUserDefinedCellBprop.
  146. template <typename T>
  147. FuncGraphPtr BpropToK(const T &primal, const FuncGraphPtr &bprop_g, const FuncGraphPtr &current_primal_fg,
  148. const CNodePtr &cnode);
  149. AnfNodePtr BuildOutput(const FuncGraphPtr &bprop_fg, const FuncGraphPtr &current_primal_fg);
  150. void TransformArgsForPrimitive(const FuncGraphManagerPtr &mng, const FuncGraphPtr &bprop_fg,
  151. const PrimitivePtr &primitive, const FuncGraphPtr &outer,
  152. std::vector<AnfNodePtr> *const transf_args);
  153. template <typename T>
  154. void TransformArgsForFuncGraph(const FuncGraphManagerPtr &mng, const FuncGraphPtr &bprop_fg,
  155. const T &current_primal_fg, const FuncGraphPtr &outer,
  156. std::vector<AnfNodePtr> *const transf_args);
  157. void CheckBprop(const FuncGraphPtr &bprop_fg, const string &prim_to_check);
  158. Registry bprop_registry_;
  159. std::unordered_map<PrimitivePtr, MetaFuncGraphPtr> bprop_registry_meta_;
  160. };
  161. template <typename T>
  162. FuncGraphPtr KPrim::BpropToK(const T &primal, const FuncGraphPtr &bprop_fg, const FuncGraphPtr &current_primal_fg,
  163. const CNodePtr &cnode) {
  164. MS_EXCEPTION_IF_NULL(primal);
  165. MS_EXCEPTION_IF_NULL(bprop_fg);
  166. CheckBprop(bprop_fg, primal->ToString());
  167. auto debug_info = std::make_shared<GraphDebugInfo>();
  168. debug_info->set_name(primal->ToString());
  169. auto cloned_bprop_fg = BasicClone(bprop_fg);
  170. MS_EXCEPTION_IF_NULL(cloned_bprop_fg);
  171. cloned_bprop_fg->debug_info()->set_name("");
  172. cloned_bprop_fg->debug_info()->set_trace_info(std::make_shared<TraceGradBprop>(debug_info));
  173. // Make sure (out, dout) provided.
  174. if (cloned_bprop_fg->parameters().size() < 2) {
  175. MS_LOG(EXCEPTION) << "Primitive or Cell " << primal->ToString()
  176. << " bprop requires out and dout at least, but only got " << cloned_bprop_fg->parameters().size()
  177. << " params. NodeInfo: " << trace::GetDebugInfo(cloned_bprop_fg->debug_info());
  178. }
  179. AnfNodePtr bout = BuildOutput(cloned_bprop_fg, current_primal_fg);
  180. cloned_bprop_fg->set_output(bout);
  181. FuncGraphPtr outer = nullptr;
  182. {
  183. TraceGuard guard(std::make_shared<TraceGradFprop>(debug_info));
  184. outer = std::make_shared<FuncGraph>();
  185. (void)outer->transforms().emplace("primal", FuncGraphTransform(primal));
  186. outer->set_output(NewValueNode(kNone));
  187. }
  188. auto mng = Manage({cloned_bprop_fg, outer}, false);
  189. // In a bprop definition, the last two param should be out and dout.
  190. auto param_size = cloned_bprop_fg->parameters().size();
  191. auto param_num = param_size - 1;
  192. auto dout = cloned_bprop_fg->parameters()[param_num];
  193. param_num--;
  194. auto out_param = cloned_bprop_fg->parameters()[param_num];
  195. std::vector<AnfNodePtr> transf_args;
  196. if constexpr (std::is_same<T, PrimitivePtr>::value) {
  197. PrimitivePtr primitive = primal;
  198. TransformArgsForPrimitive(mng, cloned_bprop_fg, primal, outer, &transf_args);
  199. (void)transf_args.insert(transf_args.begin(), NewValueNode(primal));
  200. } else {
  201. TransformArgsForFuncGraph(mng, cloned_bprop_fg, current_primal_fg, outer, &transf_args);
  202. (void)transf_args.insert(transf_args.begin(), NewValueNode(current_primal_fg));
  203. }
  204. CNodePtr out_value = nullptr;
  205. if (cnode != nullptr) { // Set equiv debug info. for Primitive CNode out.
  206. TraceGuard trace_guard(std::make_shared<TraceEquiv>(cnode->debug_info()));
  207. out_value = outer->NewCNode(transf_args);
  208. if constexpr (std::is_same<T, PrimitivePtr>::value) {
  209. out_value->CloneUserData(cnode);
  210. }
  211. } else {
  212. out_value = outer->NewCNode(transf_args);
  213. }
  214. (void)mng->Replace(out_param, out_value);
  215. TraceGuard guard(std::make_shared<TraceGradSens>(out_param->debug_info()));
  216. auto new_dout = cloned_bprop_fg->add_parameter();
  217. (void)mng->Replace(dout, new_dout);
  218. // We remove all parameters except new_dout.
  219. std::vector<AnfNodePtr> newBpropParams = {new_dout};
  220. cloned_bprop_fg->set_parameters(newBpropParams);
  221. outer->set_output(outer->NewCNode({NewValueNode(prim::kPrimMakeTuple), out_value, NewValueNode(cloned_bprop_fg)}));
  222. return BasicClone(outer);
  223. }
  224. } // namespace ad
  225. } // namespace mindspore
  226. #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_D_FUNCTOR_H_