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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 <unordered_map>
  22. #include <map>
  23. #include <set>
  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 AnfNodePtrList &nodes, const AnfNodePtrList &outputs, const DeviceContext *device_context);
  94. // Construct kernel graph from function graph and compile kernel graph in Graph mode,
  95. // the detailed implementation of compiling graph is in 'CompileGraphImpl'.
  96. GraphId CompileGraph(const FuncGraphPtr &func_graph, const DeviceContext *device_context);
  97. // Construct single op kernel graph and compile the kernel graph in PyNative mode.
  98. GraphId CompileGraph(const session::OpRunInfo &op_run_info, const GraphInfo &graph_info,
  99. const std::vector<int64_t> *tensors_mask, std::vector<TensorPtr> *const input_tensors,
  100. bool *single_op_cache_hit, const DeviceContext *device_context);
  101. // Get graph by graph id, if not exist return nullptr, used in Graph mode.
  102. KernelGraphPtr Fetch(GraphId graph_id) const;
  103. // Get graph by graph info, if not exist return nullptr, used in PyNative mode.
  104. KernelGraphPtr Fetch(const GraphInfo &graph_info) const;
  105. // The following four methods used in PyNative back propagation to split complete kernel graph to single
  106. // op graph, and these methods will be removed to class MindRTBackend after deleting session module.
  107. // Cache index for all parameter and output nodes of kernel graph, used to get parameter of single op and
  108. // recover output of original complete back propagation kernel graph.
  109. void GetParamAndOutputIndex(const KernelGraphPtr &graph, const std::vector<TensorPtr> &inputs,
  110. VectorRef *const outputs, std::map<AnfNodePtr, size_t> *parameter_index,
  111. std::map<KernelWithIndex, std::vector<std::vector<size_t>>> *output_indexes);
  112. // Get input tensors for single op compile and run, input tensors may convert from value node and parameter in graph
  113. // and prev kernel node's output.
  114. void GetSingleOpInputTensors(const CNodePtr &kernel, const std::map<KernelWithIndex, TensorPtr> &op_output,
  115. const std::map<AnfNodePtr, size_t> &parameter_index,
  116. const std::vector<TensorPtr> &graph_inputs, InputTensorInfo *const input_tensor_info);
  117. // Get one input tensor for single control op, such as bprop_cut.
  118. TensorPtr GetSingleOpInputTensorByIndex(const CNodePtr &kernel, const std::map<KernelWithIndex, TensorPtr> &op_output,
  119. const std::map<AnfNodePtr, size_t> &parameter_index,
  120. const std::vector<TensorPtr> &graph_inputs,
  121. InputTensorInfo *const input_tensor_info, size_t input_index);
  122. // Get OpRunInfo and GraphInfo for single op compile and run.
  123. void GetSingleOpRunInfoAndGraphInfo(const CNodePtr &kernel, const std::vector<TensorPtr> &input_tensors,
  124. OpRunInfo *const run_info, GraphInfo *const graph_info);
  125. // Calculate ref count of PyNative back propagation operators.
  126. void CalculateRefCount(const KernelGraphPtr &graph, std::map<KernelWithIndex, size_t> *ref_count) const;
  127. // Update ref count of PyNative back propagation operators.
  128. void UpdateRefCount(const std::set<KernelWithIndex> &input_kernels_with_index,
  129. std::map<KernelWithIndex, size_t> *ref_count,
  130. std::map<KernelWithIndex, tensor::TensorPtr> *op_output_map) const;
  131. // Handle single op output tensor and recover output of original complete kernel graph.
  132. void RecoverGraphOutput(const AnfNodePtr &kernel, const VectorRef &op_outputs,
  133. const std::map<KernelWithIndex, size_t> &ref_count,
  134. std::map<KernelWithIndex, TensorPtr> *op_output_map,
  135. GraphOutputInfo *const graph_output_info) const;
  136. // Collect output tensors of back propagation graph for allreduce operators to average gradient,
  137. // used in PyNative distributed training mode.
  138. void AddGradAddrToBucket(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &grad_tensor);
  139. // Clear resource in bucket, such as useless tensors and device memory of all communication operators,
  140. // Bucket is used in PyNative distributed training mode, one bucket handles all resource to launch and sync allreduce
  141. // operator.
  142. void ClearAllBucket(const GraphId &graph_id);
  143. const std::vector<KernelWithIndex> &GetGraphOutputNodes(GraphId graph_id) const;
  144. // Register a summary callback function, which is called in the final stages of summary.
  145. void RegisterSummaryCallBackFunc(const CallBackFunc &callback) const;
  146. // Execute graph summary.
  147. void Summary(const std::vector<KernelGraphPtr> &graphs) const;
  148. // Remove single op kernel graph cache and output nodes cache.
  149. void EraseSingleOpCache(const GraphInfo &graph_info, const GraphId &graph_id);
  150. private:
  151. DISABLE_COPY_AND_ASSIGN(GraphCompiler);
  152. // The implementation of compiling graph in Graph Mode, including optimizing graph,
  153. // setting operator info, creating kernel and transforming kernel graph to ActorSet.
  154. GraphId CompileGraphImpl(const KernelGraphPtr &graph, const DeviceContext *device_context) const;
  155. // Create device address for all anf nodes of graph.
  156. void CreateDeviceAddress(const KernelGraphPtr &graph, const DeviceContext *device_context) const;
  157. // Single op kernel graph cache for PyNative mode.
  158. std::unordered_map<GraphInfo, KernelGraphPtr> run_op_graphs_;
  159. // Single op kernel graph output nodes cache for PyNative mode.
  160. std::unordered_map<GraphId, std::vector<KernelWithIndex>> run_op_graph_output_nodes_;
  161. // The member variable 'session_' will be removed after removing session module.
  162. // Now all the GraphCompiler share the same 'session_'.
  163. session::SessionPtr session_;
  164. };
  165. } // namespace runtime
  166. } // namespace mindspore
  167. #endif // MINDSPORE_CCSRC_RUNTIME_FRAMEWORK_GRAPH_COMPILER_H_