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.

graph_compiler.h 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /**
  2. * Copyright 2021 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. #ifndef MINDSPORE_CCSRC_RUNTIME_FRAMEWORK_GRAPH_COMPILER_H_
  17. #define MINDSPORE_CCSRC_RUNTIME_FRAMEWORK_GRAPH_COMPILER_H_
  18. #include <vector>
  19. #include <memory>
  20. #include <string>
  21. #include <map>
  22. #include <set>
  23. #include "utils/hash_map.h"
  24. #include "runtime/hardware/device_context.h"
  25. #include "runtime/framework/actor/actor_common.h"
  26. #include "runtime/framework/control_node_parser.h"
  27. #include "backend/session/session_basic.h"
  28. #include "backend/session/session_factory.h"
  29. #include "ir/tensor.h"
  30. namespace mindspore {
  31. using device::DeviceContext;
  32. using session::CallBackFunc;
  33. using session::GraphOutputInfo;
  34. using session::InputTensorInfo;
  35. using session::KernelGraph;
  36. using session::KernelWithIndex;
  37. using session::OpRunInfo;
  38. using tensor::TensorPtr;
  39. namespace runtime {
  40. // Position of kernel with index, the value pair<branch_id, vector<pos>> means the branch id of the kernel and the pos
  41. // of the kernel. Generally, there is only one branch, and the branch id is 0 at this time. In control flow, there are
  42. // multiple branch scenarios, and pos represents the position of the kernel in the branch.
  43. using KernelMapPosition = std::map<KernelWithIndex, std::vector<size_t>, session::KernelWithIndexCmp>;
  44. // The graph compiler info generated by graph compiler is the express of executable graph.
  45. // The device context is unified interface of interaction with device of corresponding graph.
  46. // The tensors mask is used to distinguish input tensor's type.
  47. // The input tensor is used to link graphs in the dynamic build scenario.
  48. // The control node is used to link graphs in the control flow scenario.
  49. // The control node parser is used to parse the edge info in control nodes.
  50. // The origin parameters order is used to correspond to the input args.
  51. // The origin outputs order is used to correspond to the output args.
  52. // The need_erase means need erase this GraphCompilerInfo object after run actor set.
  53. struct GraphCompilerInfo {
  54. GraphCompilerInfo(const std::vector<KernelGraphPtr> &graphs, const std::vector<DeviceContext *> &device_contexts,
  55. const std::vector<std::vector<int64_t> *> &tensors_mask,
  56. const std::vector<std::vector<TensorPtr> *> &input_tensors,
  57. const std::vector<AnfNodePtr> &control_nodes,
  58. const std::vector<AnfNodePtr> &origin_parameters_order, const ControlNodeParserPtr &parser,
  59. const KernelMapPosition &origin_outputs_order, const size_t outputs_num, const std::string &name,
  60. bool need_erase, GraphExecutionStrategy strategy)
  61. : graphs_(graphs),
  62. device_contexts_(device_contexts),
  63. tensors_mask_(tensors_mask),
  64. input_tensors_(input_tensors),
  65. control_nodes_(control_nodes),
  66. control_node_parser_(parser),
  67. origin_parameters_order_(origin_parameters_order),
  68. origin_outputs_order_(origin_outputs_order),
  69. outputs_num_(outputs_num),
  70. name_(name),
  71. need_erase_(need_erase),
  72. strategy_(strategy) {}
  73. ~GraphCompilerInfo();
  74. std::vector<KernelGraphPtr> graphs_;
  75. std::vector<DeviceContext *> device_contexts_;
  76. std::vector<std::vector<int64_t> *> tensors_mask_;
  77. std::vector<std::vector<TensorPtr> *> input_tensors_;
  78. std::vector<AnfNodePtr> control_nodes_;
  79. ControlNodeParserPtr control_node_parser_;
  80. std::vector<AnfNodePtr> origin_parameters_order_;
  81. KernelMapPosition origin_outputs_order_;
  82. size_t outputs_num_;
  83. std::string name_;
  84. bool need_erase_;
  85. GraphExecutionStrategy strategy_;
  86. };
  87. class GraphCompiler {
  88. public:
  89. GraphCompiler() { session_ = session::SessionFactory::Get().Create(kSessionBasic); }
  90. ~GraphCompiler() = default;
  91. // Construct kernel graph from anf nodes list and compile kernel graph in Graph mode,
  92. // the detailed implementation of compiling graph is in 'CompileGraphImpl'.
  93. GraphId CompileGraph(const GraphSegmentPtr &segment, const AnfNodePtrList &outputs,
  94. const DeviceContext *device_context, bool run_in_pynative = false);
  95. // Construct kernel graph from function graph and compile kernel graph in Graph mode,
  96. // the detailed implementation of compiling graph is in 'CompileGraphImpl'.
  97. GraphId CompileGraph(const FuncGraphPtr &func_graph, const DeviceContext *device_context);
  98. // Construct single op kernel graph and compile the kernel graph in PyNative mode.
  99. GraphId CompileGraph(const session::OpRunInfo &op_run_info, bool *single_op_cache_hit,
  100. const DeviceContext *device_context);
  101. // Create kernel and Create workspace for graphs in PyNative mode.
  102. void BuildSingleOpGraphs(const std::vector<KernelGraphPtr> &graphs, const DeviceContext *device_context) const;
  103. // Get graph by graph id, if not exist return nullptr, used in Graph mode.
  104. KernelGraphPtr Fetch(GraphId graph_id) const;
  105. // Get graph by graph info, if not exist return nullptr, used in PyNative mode.
  106. KernelGraphPtr Fetch(const GraphInfo &graph_info) const;
  107. // The following four methods used in PyNative back propagation to split complete kernel graph to single
  108. // op graph, and these methods will be removed to class MindRTBackend after deleting session module.
  109. // Cache index for all parameter and output nodes of kernel graph, used to get parameter of single op and
  110. // recover output of original complete back propagation kernel graph.
  111. void GetParamAndOutputIndex(const KernelGraphPtr &graph, const std::vector<TensorPtr> &inputs,
  112. VectorRef *const outputs, std::map<AnfNodePtr, size_t> *parameter_index,
  113. std::map<KernelWithIndex, std::vector<std::vector<size_t>>> *output_indexes);
  114. // Get input tensors for single op compile and run, input tensors may convert from value node and parameter in graph
  115. // and prev kernel node's output.
  116. void GetSingleOpInputTensors(const CNodePtr &kernel, const std::map<KernelWithIndex, TensorPtr> &op_output,
  117. const std::map<AnfNodePtr, size_t> &parameter_index,
  118. const std::vector<TensorPtr> &graph_inputs, InputTensorInfo *const input_tensor_info);
  119. // Get one input tensor for single control op, such as bprop_cut.
  120. TensorPtr GetSingleOpInputTensorByIndex(const CNodePtr &kernel, const std::map<KernelWithIndex, TensorPtr> &op_output,
  121. const std::map<AnfNodePtr, size_t> &parameter_index,
  122. const std::vector<TensorPtr> &graph_inputs,
  123. InputTensorInfo *const input_tensor_info, size_t input_index);
  124. // Get OpRunInfo and GraphInfo for single op compile and run.
  125. void GetSingleOpRunInfoAndGraphInfo(const CNodePtr &kernel, const InputTensorInfo &tensor_info, OpRunInfo *run_info,
  126. GraphInfo *graph_info, GraphOutputInfo *const graph_output_info);
  127. // Calculate ref count of PyNative back propagation operators.
  128. void CalculateRefCount(const KernelGraphPtr &graph, std::map<KernelWithIndex, size_t> *ref_count) const;
  129. // Calculate forward op output ref count of PyNative back graph.
  130. void CalculateForwardOpOutputCount(const KernelGraphPtr &graph, const std::vector<tensor::TensorPtr> &inputs,
  131. std::map<std::string, size_t> *forward_op_output_tensor_id) const;
  132. // Update ref count of PyNative back propagation operators.
  133. void UpdateRefCount(const std::set<KernelWithIndex> &input_kernels_with_index,
  134. std::map<KernelWithIndex, size_t> *ref_count,
  135. std::map<KernelWithIndex, tensor::TensorPtr> *op_output_map) const;
  136. // Update forward op output ref count of PyNative back graph.
  137. void UpdateForwardOpOutputRefCount(const std::vector<tensor::TensorPtr> &input_tensor,
  138. std::map<std::string, size_t> *forward_op_output_tensor_id) const;
  139. // Handle single op output tensor and recover output of original complete kernel graph.
  140. void RecoverGraphOutput(const AnfNodePtr &kernel, const VectorRef &op_outputs,
  141. const std::map<KernelWithIndex, size_t> &ref_count,
  142. std::map<KernelWithIndex, TensorPtr> *op_output_map,
  143. GraphOutputInfo *const graph_output_info) const;
  144. // Collect output tensors of back propagation graph for allreduce operators to average gradient,
  145. // used in PyNative distributed training mode.
  146. void AddGradAddrToBucket(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &grad_tensor);
  147. // Clear resource in bucket, such as useless tensors and device memory of all communication operators,
  148. // Bucket is used in PyNative distributed training mode, one bucket handles all resource to launch and sync allreduce
  149. // operator.
  150. void ClearAllBucket(const GraphId &graph_id);
  151. const std::vector<KernelWithIndex> &GetGraphOutputNodes(GraphId graph_id) const;
  152. // Register a summary callback function, which is called in the final stages of summary.
  153. void RegisterSummaryCallBackFunc(const CallBackFunc &callback) const;
  154. // Execute graph summary.
  155. void Summary(const std::vector<KernelGraphPtr> &graphs) const;
  156. // Remove single op kernel graph cache and output nodes cache.
  157. void EraseSingleOpCache(const GraphInfo &graph_info, const GraphId &graph_id);
  158. private:
  159. DISABLE_COPY_AND_ASSIGN(GraphCompiler);
  160. // The implementation of compiling graph in Graph Mode, including optimizing graph,
  161. // setting operator info, creating kernel and transforming kernel graph to ActorSet.
  162. GraphId CompileGraphImpl(const KernelGraphPtr &graph, const DeviceContext *device_context) const;
  163. // Create device address for all anf nodes of graph.
  164. void CreateDeviceAddress(const KernelGraphPtr &graph, const DeviceContext *device_context,
  165. bool is_gradient_out) const;
  166. // Create device address for input and output of ops.
  167. void CreateDeviceAddressWithoutWorkspace(const KernelGraphPtr &graph, const DeviceContext *device_context,
  168. bool is_gradient_out) const;
  169. // Set Graph's dependencies for pre_graph and post_graph.
  170. void SetGraphDependency(const KernelGraphPtr &graph, const GraphSegmentPtr &segment) const;
  171. // Single op kernel graph cache for PyNative mode.
  172. mindspore::HashMap<GraphInfo, KernelGraphPtr> run_op_graphs_;
  173. // Single op kernel graph output nodes cache for PyNative mode.
  174. mindspore::HashMap<GraphId, std::vector<KernelWithIndex>> run_op_graph_output_nodes_;
  175. // The member variable 'session_' will be removed after removing session module.
  176. // Now all the GraphCompiler share the same 'session_'.
  177. session::SessionPtr session_;
  178. };
  179. } // namespace runtime
  180. } // namespace mindspore
  181. #endif // MINDSPORE_CCSRC_RUNTIME_FRAMEWORK_GRAPH_COMPILER_H_