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

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2020-2021 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 <vector>
  23. #include <iostream>
  24. #include <utility>
  25. #include "utils/hash_map.h"
  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/optimizer/ad/pynative_dfunctor.h"
  32. #include "frontend/operator/ops.h"
  33. #include "debug/trace.h"
  34. #include "utils/utils.h"
  35. namespace mindspore {
  36. namespace ad {
  37. using Registry = mindspore::HashMap<PrimitivePtr, FuncGraphPtr, PrimitiveHasher, PrimitiveTotalEqual>;
  38. class KPrim;
  39. extern KPrim g_k_prims;
  40. class DFunctor;
  41. using DFunctorPtr = std::shared_ptr<DFunctor>;
  42. // Flag to control if fv should be lifted before grad. If this lift_fv feature is mature, then this flag can be removed.
  43. extern bool lift_fv_before_grad;
  44. // D Functor's rules to map closure object and morphisms.
  45. class DFunctor : public std::enable_shared_from_this<DFunctor> {
  46. public:
  47. DFunctor(const FuncGraphPtr &primal_graph, const pipeline::ResourceBasePtr &resources);
  48. ~DFunctor() = default;
  49. // Map object in D category to K category.
  50. void MapObject();
  51. // Map morphism in D category to K category.
  52. void MapMorphism();
  53. FuncGraphPtr k_graph();
  54. FuncGraphPtr tape();
  55. // Construct user defined k object.
  56. FuncGraphPtr KUserDefined(const FuncGraphPtr &primal);
  57. // Register functor objects to form a global view.
  58. void Init(bool is_top = false);
  59. void Finish();
  60. // Clear resources.
  61. static void Clear();
  62. friend class PynativeDFunctor;
  63. private:
  64. // Map one morphism.
  65. AdjointPtr MapMorphism(const AnfNodePtr &morph);
  66. bool IsFreeMorphism(const AnfNodePtr &node);
  67. // Map morphism that's not attached to output.
  68. void MapFreeMorphism();
  69. void BackPropagateFv(const AnfNodePtr &fv, const AnfNodePtr &din);
  70. void BackPropagateSwitchLayer(const CNodePtr &cnode_morph, const CNodePtr &env);
  71. void BackPropagate(const CNodePtr &cnode_morph, const CNodePtr &k_app, const AdjointPtr &node_adjoint);
  72. AnfNodePtr AttachFvDoutToTape(const AnfNodePtr &grad_fv);
  73. AnfNodePtr AttachIndirectFvDoutToTape(const AnfNodePtr &grad_fv);
  74. // Map CNode/Index of Primitive to K.
  75. AnfNodePtr MapPrimitiveToK(const CNodePtr &primitive_user, size_t index);
  76. // Map ValueNode of FuncGraph to K.
  77. AnfNodePtr MapFuncGraphToK(const AnfNodePtr &primal);
  78. // Map ValueNode of Parameter to K.
  79. AnfNodePtr MapParameterToK(const AnfNodePtr &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. // Replace the primal graph with k graph
  93. void EliminatePrimalGraph();
  94. // Pynative specialize
  95. ValueNodePtr GenNewTensor(const CNodePtr &forward_node);
  96. tensor::TensorPtr GenNewTensorInner(const TypePtr &type_elem, const BaseShapePtr &shape_elem);
  97. void GetForwardOutNodeAndBpropGraph(const CNodePtr &k_app, CNodePtr *forward_node, FuncGraphPtr *bprop_graph,
  98. FuncGraphPtr *fprop_graph);
  99. std::vector<AnfNodePtr> RunOutputReplace(const CNodePtr &forward_node, const FuncGraphPtr &bprop_graph,
  100. const FuncGraphPtr &fprop_graph, const CNodePtr &cnode_morph);
  101. std::vector<AnfNodePtr> RunInputReplace(const FuncGraphPtr &bprop_graph, const FuncGraphPtr &fprop_graph,
  102. const CNodePtr &cnode_morph);
  103. void ReplaceEquivdout(const CNodePtr &k_app, const CNodePtr &cnode_morph);
  104. mindspore::HashMap<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_;
  105. // Cache for indirect fv backpropagation, K o K can only do backprop layer by layer.
  106. mindspore::HashMap<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_indirect_fv_;
  107. // Cache for fv node -> pair<embed<fv_node>, zeros_like<fv_node>>, so EnvGetItemTransform in optimizer
  108. // can hit its cache if fv_node is same.
  109. mindspore::HashMap<AnfNodePtr, std::pair<CNodePtr, CNodePtr>> anfnode_to_envitem_;
  110. FuncGraphPtr primal_graph_;
  111. // K object for primal_graph_;
  112. FuncGraphPtr k_graph_;
  113. // The Backprop part of k_graph_.
  114. FuncGraphPtr tape_;
  115. // Dout parameter for primal_graph_.
  116. AnfNodePtr dout_;
  117. pipeline::ResourceBasePtr resources_;
  118. // Cut off stopped objects in category D.
  119. bool need_cut_;
  120. bool is_top_;
  121. static mindspore::HashMap<FuncGraphPtr, std::shared_ptr<DFunctor>> func_graph_to_functor_;
  122. static mindspore::HashMap<AnfNodePtr, AdjointPtr> anfnode_to_adjoin_definition_;
  123. };
  124. // D Functor's rules to map primitive object.
  125. class KPrim {
  126. public:
  127. KPrim() = default;
  128. ~KPrim() = default;
  129. FuncGraphPtr KPrimitive(const CNodePtr &primal_user, const ValueNodePtr &value_node,
  130. const pipeline::ResourceBasePtr &resources);
  131. MetaFuncGraphPtr KMetaFuncGraph(const PrimitivePtr &prim);
  132. // bprop_fg and primal_fg in bprop_fg's transforms are FuncGraph just after convert.
  133. // current_primal_fg is the specialized and AutoMonaded primal_fg.
  134. FuncGraphPtr KUserDefinedCellBprop(const FuncGraphPtr &bprop_fg, const FuncGraphPtr &current_primal_fg);
  135. void clear() {
  136. bprop_registry_meta_.clear();
  137. bprop_registry_.clear();
  138. }
  139. FuncGraphPtr GetPossibleBprop(const PrimitivePtr &prim);
  140. #ifndef _WIN32
  141. static void ExportBpropMindir(const py::object &obj);
  142. #endif
  143. private:
  144. FuncGraphPtr GetBprop(const PrimitivePtr &prim, const pipeline::ResourceBasePtr &resources = nullptr);
  145. FuncGraphPtr GetFprop(const PrimitivePtr &prim);
  146. FuncGraphPtr FakeBprop(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  147. FuncGraphPtr BpropCut(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources);
  148. // Given a bprop rule, do the K mapping.
  149. // current_primal_fg is only valid for user defined bprop for Cell, not for Primitive.
  150. // Refer the comment in KUserDefinedCellBprop.
  151. template <typename T>
  152. FuncGraphPtr BpropToK(const T &primal, const FuncGraphPtr &bprop_g, const FuncGraphPtr &current_primal_fg,
  153. const CNodePtr &cnode, const mindspore::HashMap<std::string, ValuePtr> &primal_attrs,
  154. const std::vector<NodeDebugInfoPtr> &primal_debug_infos);
  155. AnfNodePtr BuildOutput(const FuncGraphPtr &bprop_fg, const FuncGraphPtr &current_primal_fg);
  156. void TransformArgsForPrimitive(const FuncGraphManagerPtr &mng, const FuncGraphPtr &bprop_fg,
  157. const PrimitivePtr &primitive, const FuncGraphPtr &outer,
  158. std::vector<AnfNodePtr> *const transf_args);
  159. template <typename T>
  160. void TransformArgsForFuncGraph(const FuncGraphManagerPtr &mng, const FuncGraphPtr &bprop_fg,
  161. const T &current_primal_fg, const FuncGraphPtr &outer,
  162. std::vector<AnfNodePtr> *const transf_args);
  163. void CheckBprop(const FuncGraphPtr &bprop_fg, const string &prim_to_check);
  164. Registry bprop_registry_;
  165. mindspore::HashMap<PrimitivePtr, MetaFuncGraphPtr> bprop_registry_meta_;
  166. };
  167. template <typename T>
  168. FuncGraphPtr KPrim::BpropToK(const T &primal, const FuncGraphPtr &bprop_fg, const FuncGraphPtr &current_primal_fg,
  169. const CNodePtr &cnode, const mindspore::HashMap<std::string, ValuePtr> &primal_attrs,
  170. const std::vector<NodeDebugInfoPtr> &primal_debug_infos) {
  171. MS_EXCEPTION_IF_NULL(primal);
  172. MS_EXCEPTION_IF_NULL(bprop_fg);
  173. CheckBprop(bprop_fg, primal->ToString());
  174. FuncGraphPtr cloned_bprop_fg;
  175. {
  176. PrimalAttrGuard primal_attr_guard(primal_attrs);
  177. PrimalDebugInfoGuard primal_debug_info_guard(primal_debug_infos);
  178. cloned_bprop_fg = BasicClone(bprop_fg);
  179. }
  180. MS_EXCEPTION_IF_NULL(cloned_bprop_fg);
  181. GraphDebugInfoPtr debug_info = nullptr;
  182. {
  183. TraceGuard guard(std::make_shared<TraceCopy>(bprop_fg->debug_info()));
  184. debug_info = std::make_shared<GraphDebugInfo>();
  185. }
  186. if (debug_info->trace_info() != nullptr && debug_info->trace_info()->debug_info() != nullptr) {
  187. debug_info->trace_info()->debug_info()->set_name(primal->ToString());
  188. }
  189. cloned_bprop_fg->debug_info()->set_name("");
  190. cloned_bprop_fg->debug_info()->set_trace_info(std::make_shared<TraceGradBprop>(debug_info));
  191. // Make sure (out, dout) provided.
  192. if (cloned_bprop_fg->parameters().size() < 2) {
  193. MS_LOG(EXCEPTION)
  194. << "The function 'bprop' of Primitive or Cell requires at least 2 params 'out' and 'dout', but got only "
  195. << cloned_bprop_fg->parameters().size() << ".\n"
  196. << trace::GetDebugInfo(cloned_bprop_fg->debug_info());
  197. }
  198. AnfNodePtr bout = BuildOutput(cloned_bprop_fg, current_primal_fg);
  199. cloned_bprop_fg->set_output(bout);
  200. FuncGraphPtr outer = nullptr;
  201. {
  202. auto outer_debug_info = std::make_shared<GraphDebugInfo>();
  203. outer_debug_info->set_name(primal->ToString());
  204. TraceGuard guard(std::make_shared<TraceGradFprop>(outer_debug_info));
  205. outer = std::make_shared<FuncGraph>();
  206. (void)outer->transforms().emplace("primal", FuncGraphTransform(primal));
  207. outer->set_output(NewValueNode(kNone));
  208. }
  209. auto mng = Manage({cloned_bprop_fg, outer}, false);
  210. // In a bprop definition, the last two param should be out and dout.
  211. auto param_size = cloned_bprop_fg->parameters().size();
  212. auto param_num = param_size - 1;
  213. auto dout = cloned_bprop_fg->parameters()[param_num];
  214. param_num--;
  215. auto out_param = cloned_bprop_fg->parameters()[param_num];
  216. std::vector<AnfNodePtr> transf_args;
  217. if constexpr (std::is_same<T, PrimitivePtr>::value) {
  218. PrimitivePtr primitive = primal;
  219. TransformArgsForPrimitive(mng, cloned_bprop_fg, primal, outer, &transf_args);
  220. (void)transf_args.insert(transf_args.begin(), NewValueNode(primal));
  221. } else {
  222. TransformArgsForFuncGraph(mng, cloned_bprop_fg, current_primal_fg, outer, &transf_args);
  223. (void)transf_args.insert(transf_args.begin(), NewValueNode(current_primal_fg));
  224. }
  225. CNodePtr out_value = nullptr;
  226. if (cnode != nullptr) { // Set equiv debug info. for Primitive CNode out.
  227. TraceGuard trace_guard(std::make_shared<TraceEquiv>(cnode->debug_info()));
  228. out_value = outer->NewCNode(transf_args);
  229. if constexpr (std::is_same<T, PrimitivePtr>::value) {
  230. out_value->CloneCNodeInfo(cnode);
  231. }
  232. } else {
  233. out_value = outer->NewCNode(transf_args);
  234. }
  235. (void)mng->Replace(out_param, out_value);
  236. TraceGuard guard(std::make_shared<TraceGradSens>(out_param->debug_info()));
  237. auto new_dout = cloned_bprop_fg->add_parameter();
  238. (void)mng->Replace(dout, new_dout);
  239. // We remove all parameters except new_dout.
  240. std::vector<AnfNodePtr> newBpropParams = {new_dout};
  241. cloned_bprop_fg->set_parameters(newBpropParams);
  242. outer->set_output(outer->NewCNode({NewValueNode(prim::kPrimMakeTuple), out_value, NewValueNode(cloned_bprop_fg)}));
  243. return BasicClone(outer);
  244. }
  245. // Handle bprob of op which input dtype is real number and output dtype is complex number.
  246. // If the dtype of a gradient(din) is complex number and the input of that is real number,
  247. // only the real part of the gradient make sense in back propagate. So we handle it by
  248. // insert a Real() ops after the gradient.
  249. // input: AnfNode with input of op which input dtype is real number and output dtype is complex number.
  250. // din: CNodePtr with gradient of input.
  251. // fg: Funcgraph witch input and din belong to.
  252. // return: New din with inserted real op if necessarily.
  253. AnfNodePtr HandleRealToComplex(const AnfNodePtr &input, const CNodePtr &din, FuncGraphPtr fg);
  254. } // namespace ad
  255. } // namespace mindspore
  256. #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_D_FUNCTOR_H_