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.cc 32 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. /**
  2. * Copyright 2021-2022 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. #include "runtime/graph_scheduler/graph_compiler.h"
  17. #include <numeric>
  18. #include <map>
  19. #include <utility>
  20. #include <algorithm>
  21. #include "runtime/graph_scheduler/graph_scheduler.h"
  22. #include "runtime/pynative/op_executor.h"
  23. #include "runtime/device/device_address.h"
  24. #include "runtime/device/ms_device_shape_transfer.h"
  25. #include "runtime/pynative/op_runtime_info.h"
  26. #include "include/common/utils/convert_utils.h"
  27. #include "include/common/utils/context/graph_kernel_flags.h"
  28. #include "utils/ms_context.h"
  29. #include "ir/tensor.h"
  30. #include "backend/common/optimizer/helper.h"
  31. #include "base/base_ref_utils.h"
  32. #include "debug/dump_proto.h"
  33. #ifdef ENABLE_DEBUGGER
  34. #include "debug/debugger/debugger.h"
  35. #endif
  36. #ifdef ENABLE_DUMP_IR
  37. #include "debug/anf_ir_dump.h"
  38. #include "debug/rdr/running_data_recorder.h"
  39. #endif
  40. #ifndef ENABLE_SECURITY
  41. #include "debug/data_dump/dump_json_parser.h"
  42. #endif
  43. namespace mindspore {
  44. namespace runtime {
  45. namespace {
  46. // Whether device address of anf node is valid and device address type
  47. // is consistent with device type, for example, device address type
  48. // DeviceAddressType::kGPU should be used on GPU device
  49. bool NodeDeviceAddressExist(const DeviceContext *device_context, const AnfNodePtr &kernel, size_t index) {
  50. MS_EXCEPTION_IF_NULL(kernel);
  51. MS_EXCEPTION_IF_NULL(device_context);
  52. if (AnfAlgo::OutputAddrExist(kernel, index)) {
  53. const auto &address = AnfAlgo::GetOutputAddr(kernel, index, false);
  54. MS_EXCEPTION_IF_NULL(address);
  55. return address->DeviceType() == device_context->GetDeviceAddressType();
  56. }
  57. return false;
  58. }
  59. void CreateParameterDeviceAddress(const DeviceContext *device_context, const KernelGraphPtr &graph) {
  60. MS_EXCEPTION_IF_NULL(device_context);
  61. MS_EXCEPTION_IF_NULL(graph);
  62. std::vector<AnfNodePtr> graph_inputs = graph->inputs();
  63. const std::vector<bool> &graph_valid_input = graph->valid_inputs();
  64. (void)graph_inputs.insert(graph_inputs.end(), graph->child_graph_result().begin(), graph->child_graph_result().end());
  65. // Anf nodes which need create device address.
  66. std::vector<AnfNodePtr> nodes_list;
  67. for (size_t i = 0; i < graph_inputs.size(); ++i) {
  68. AnfNodePtr item = graph_inputs[i];
  69. MS_EXCEPTION_IF_NULL(item);
  70. if (i < graph_valid_input.size() && !graph_valid_input[i]) {
  71. continue;
  72. }
  73. if (common::AnfAlgo::CheckPrimitiveType(item, prim::kPrimMakeTuple)) {
  74. std::vector<AnfNodePtr> outs = common::AnfAlgo::GetAllOutput(item);
  75. for (const auto &out : outs) {
  76. MS_EXCEPTION_IF_NULL(out);
  77. if (!out->isa<Parameter>() || NodeDeviceAddressExist(device_context, out, 0)) {
  78. continue;
  79. }
  80. nodes_list.push_back(out);
  81. }
  82. }
  83. if (!item->isa<Parameter>() || NodeDeviceAddressExist(device_context, item, 0)) {
  84. continue;
  85. }
  86. nodes_list.push_back(item);
  87. }
  88. // Create device address for anf node in nodes_list
  89. for (const auto &item : nodes_list) {
  90. auto output_size = common::AnfAlgo::GetOutputTensorNum(item);
  91. for (size_t index = 0; index < output_size; index++) {
  92. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  93. if (output_type_id == kTypeUnknown) {
  94. output_type_id = common::AnfAlgo::GetOutputInferDataType(item, index);
  95. }
  96. size_t tensor_size = AnfAlgo::GetOutputTensorMemSize(item, index);
  97. auto device_address =
  98. device_context->CreateDeviceAddress(nullptr, tensor_size, AnfAlgo::GetOutputFormat(item, index), output_type_id,
  99. trans::GetRuntimePaddingShape(item, index));
  100. device_address->set_from_persistent_mem(item->isa<Parameter>());
  101. MS_LOG(DEBUG) << "Create addr for node:" << common::AnfAlgo::GetNodeDebugString(item)
  102. << " addr:" << device_address;
  103. AnfAlgo::SetOutputAddr(device_address, index, item.get());
  104. }
  105. }
  106. }
  107. void CreateDeviceAddressForTensorValue(const DeviceContext *device_context, const ValuePtr &node_value,
  108. size_t output_idx, const ValueNodePtr &value_node, const KernelGraphPtr &graph) {
  109. MS_EXCEPTION_IF_NULL(device_context);
  110. MS_EXCEPTION_IF_NULL(node_value);
  111. MS_EXCEPTION_IF_NULL(value_node);
  112. const auto &ms_context = MsContext::GetInstance();
  113. MS_EXCEPTION_IF_NULL(ms_context);
  114. std::vector<TensorPtr> tensors;
  115. TensorValueToTensor(node_value, &tensors);
  116. for (const auto &tensor : tensors) {
  117. if (tensor == nullptr) {
  118. MS_LOG(WARNING) << "Tensor is null";
  119. return;
  120. }
  121. auto output_address = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address());
  122. if (output_address != nullptr && output_address->DeviceType() == device_context->GetDeviceAddressType()) {
  123. // The input of PyNative bprop graph is ValueNode.
  124. // Setting the address to the ValueNode will lead to memory leak.
  125. if (!graph->is_bprop()) {
  126. AnfAlgo::SetOutputAddr(std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address()), output_idx++,
  127. value_node.get());
  128. }
  129. continue;
  130. }
  131. size_t tensor_size = AnfAlgo::GetOutputTensorMemSize(value_node, output_idx);
  132. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(value_node, output_idx);
  133. if (output_type_id == kTypeUnknown) {
  134. output_type_id = common::AnfAlgo::GetOutputInferDataType(value_node, output_idx);
  135. }
  136. std::string output_format = AnfAlgo::GetOutputFormat(value_node, output_idx);
  137. device::DeviceAddressPtr address = device_context->CreateDeviceAddress(
  138. nullptr, tensor_size, output_format, output_type_id, trans::GetRuntimePaddingShape(value_node, output_idx));
  139. MS_LOG(DEBUG) << "Create addr for node:" << common::AnfAlgo::GetNodeDebugString(value_node) << " addr:" << address;
  140. MS_EXCEPTION_IF_NULL(address);
  141. address->set_from_persistent_mem(true);
  142. AnfAlgo::SetOutputAddr(address, output_idx++, value_node.get());
  143. }
  144. }
  145. void CreateValueNodeDeviceAddress(const DeviceContext *device_context, const KernelGraphPtr &graph) {
  146. MS_EXCEPTION_IF_NULL(device_context);
  147. MS_EXCEPTION_IF_NULL(graph);
  148. for (const ValueNodePtr &value_node : graph->graph_value_nodes()) {
  149. MS_EXCEPTION_IF_NULL(value_node);
  150. if (NodeDeviceAddressExist(device_context, value_node, 0)) {
  151. continue;
  152. }
  153. const auto &node_value = value_node->value();
  154. MS_EXCEPTION_IF_NULL(node_value);
  155. if (node_value->isa<tensor::Tensor>() || node_value->isa<ValueTuple>()) {
  156. CreateDeviceAddressForTensorValue(device_context, node_value, 0, value_node, graph);
  157. } else if (node_value->isa<StringImm>()) {
  158. auto value = GetValue<std::string>(node_value);
  159. size_t tensor_size = value.size();
  160. auto address =
  161. device_context->CreateDeviceAddress(nullptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeUInt8, ShapeVector());
  162. MS_EXCEPTION_IF_NULL(address);
  163. address->set_from_persistent_mem(true);
  164. MS_LOG(DEBUG) << "Create addr for node:" << common::AnfAlgo::GetNodeDebugString(value_node)
  165. << " addr:" << address;
  166. AnfAlgo::SetOutputAddr(address, 0, value_node.get());
  167. }
  168. }
  169. }
  170. void CreateKernelOutputDeviceAddress(const DeviceContext *device_context, const KernelGraphPtr &graph,
  171. bool is_gradient_out) {
  172. MS_EXCEPTION_IF_NULL(device_context);
  173. MS_EXCEPTION_IF_NULL(graph);
  174. const std::vector<CNodePtr> &kernels = graph->execution_order();
  175. for (const auto &kernel : kernels) {
  176. MS_EXCEPTION_IF_NULL(kernel);
  177. if (common::AnfAlgo::IsControlOpExecInBackend(kernel)) {
  178. continue;
  179. }
  180. auto output_size = AnfAlgo::GetOutputAddressNum(kernel);
  181. for (size_t i = 0; i < output_size; ++i) {
  182. if (AnfAlgo::OutputAddrExist(kernel, i)) {
  183. continue;
  184. }
  185. auto output_format = AnfAlgo::GetOutputFormat(kernel, i);
  186. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  187. auto address_size = AnfAlgo::GetOutputTensorMemSize(kernel, i);
  188. auto device_address = device_context->CreateDeviceAddress(nullptr, address_size, output_format, output_type,
  189. trans::GetRuntimePaddingShape(kernel, i));
  190. if (is_gradient_out) {
  191. device_address->set_from_persistent_mem(true);
  192. }
  193. MS_LOG(DEBUG) << "Create addr for node:" << common::AnfAlgo::GetNodeDebugString(kernel)
  194. << " addr:" << device_address;
  195. AnfAlgo::SetOutputAddr(device_address, i, kernel.get());
  196. }
  197. }
  198. }
  199. void CreateKernelWorkspaceDeviceAddress(const DeviceContext *device_context, const KernelGraphPtr &graph) {
  200. MS_EXCEPTION_IF_NULL(device_context);
  201. MS_EXCEPTION_IF_NULL(graph);
  202. const std::vector<CNodePtr> &kernels = graph->execution_order();
  203. for (const auto &kernel : kernels) {
  204. MS_EXCEPTION_IF_NULL(kernel);
  205. if (common::AnfAlgo::IsControlOpExecInBackend(kernel)) {
  206. continue;
  207. }
  208. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  209. MS_EXCEPTION_IF_NULL(kernel_mod);
  210. auto workspace_sizes = kernel_mod->GetWorkspaceSizeList();
  211. for (size_t i = 0; i < workspace_sizes.size(); ++i) {
  212. if (AnfAlgo::WorkspaceAddrExist(kernel, i)) {
  213. break;
  214. }
  215. auto device_address =
  216. device_context->CreateDeviceAddress(nullptr, workspace_sizes[i], "", kTypeUnknown, ShapeVector());
  217. MS_LOG(DEBUG) << "Create addr for node:" << common::AnfAlgo::GetNodeDebugString(kernel)
  218. << " addr:" << device_address;
  219. AnfAlgo::SetWorkspaceAddr(device_address, i, kernel.get());
  220. }
  221. }
  222. }
  223. void UpdateDeviceAddressForInplaceNode(const KernelGraphPtr &graph) {
  224. MS_EXCEPTION_IF_NULL(graph);
  225. // Collect the inplace groups.
  226. std::map<uint32_t, std::vector<CNodePtr>> inplace_groups;
  227. const std::vector<CNodePtr> &kernels = graph->execution_order();
  228. for (const auto &kernel : kernels) {
  229. if (!common::AnfAlgo::IsInplaceNode(kernel, "inplace_algo")) {
  230. continue;
  231. }
  232. auto primitive = common::AnfAlgo::GetCNodePrimitive(kernel);
  233. MS_EXCEPTION_IF_NULL(primitive);
  234. auto inplace_group_attr = primitive->GetAttr("inplace_group");
  235. MS_EXCEPTION_IF_NULL(inplace_group_attr);
  236. auto group_id = GetValue<uint32_t>(inplace_group_attr);
  237. (void)inplace_groups[group_id].emplace_back(kernel);
  238. }
  239. const size_t kMinInplaceGroupSize = 2;
  240. for (const auto &inplace_group : inplace_groups) {
  241. auto &group_nodes = inplace_group.second;
  242. if (group_nodes.size() < kMinInplaceGroupSize) {
  243. continue;
  244. }
  245. // Get the device address of the first node in the inplace group.
  246. auto node_primitive = common::AnfAlgo::GetCNodePrimitive(group_nodes[0]);
  247. MS_EXCEPTION_IF_NULL(node_primitive);
  248. auto output_index = GetValue<uint32_t>(node_primitive->GetAttr("inplace_output_index"));
  249. auto device_address = AnfAlgo::GetMutableOutputAddr(group_nodes[0], output_index, false);
  250. MS_EXCEPTION_IF_NULL(device_address);
  251. // Update the device address of other nodes using device address of the first node in the inplace group.
  252. for (size_t i = 1; i < group_nodes.size(); ++i) {
  253. auto &group_node = group_nodes[i];
  254. auto prim = common::AnfAlgo::GetCNodePrimitive(group_node);
  255. MS_EXCEPTION_IF_NULL(prim);
  256. auto index = GetValue<uint32_t>(prim->GetAttr("inplace_output_index"));
  257. AnfAlgo::SetOutputAddr(device_address, index, group_node.get());
  258. // Update the reference count of device address.
  259. device_address->IncreaseOriginalRefCount();
  260. device_address->ResetRefCount();
  261. }
  262. }
  263. }
  264. void UpdateDeviceAddressForRefNode(const KernelGraphPtr &graph) {
  265. MS_EXCEPTION_IF_NULL(graph);
  266. auto &kernels = graph->execution_order();
  267. for (auto &kernel : kernels) {
  268. MS_EXCEPTION_IF_NULL(kernel);
  269. auto output_num = common::AnfAlgo::GetOutputTensorNum(kernel);
  270. if (output_num == 0) {
  271. MS_LOG(DEBUG) << "This kernel has no output size.";
  272. continue;
  273. }
  274. for (size_t i = 0; i < output_num; ++i) {
  275. session::AnfWithOutIndex out_pair(kernel, i);
  276. if (graph->IsInRefOutputMap(out_pair)) {
  277. auto origin_pair = graph->GetRefCorrespondOutput(out_pair);
  278. MS_EXCEPTION_IF_NULL(origin_pair.first);
  279. auto origin_node_output_addr = AnfAlgo::GetMutableOutputAddr(origin_pair.first, origin_pair.second, false);
  280. MS_EXCEPTION_IF_NULL(origin_node_output_addr);
  281. auto cur_node_output_addr = AnfAlgo::GetMutableOutputAddr(kernel, i, false);
  282. if (origin_node_output_addr.get() != cur_node_output_addr.get()) {
  283. MS_LOG(DEBUG) << "REF address is not same, ref node output need address update";
  284. MS_LOG(DEBUG) << "REF origin op is " << origin_pair.first->DebugString() << ", output index is "
  285. << origin_pair.second << ", cur op is " << kernel->DebugString() << ", out index is " << i;
  286. AnfAlgo::SetOutputAddr(origin_node_output_addr, i, kernel.get());
  287. // Update the reference count of device address.
  288. cur_node_output_addr->DecreaseOriginalRefCount();
  289. cur_node_output_addr->ResetRefCount();
  290. origin_node_output_addr->IncreaseOriginalRefCount();
  291. origin_node_output_addr->ResetRefCount();
  292. }
  293. }
  294. }
  295. }
  296. }
  297. void SetSummaryNodesRefCount(const KernelGraph *graph) {
  298. MS_EXCEPTION_IF_NULL(graph);
  299. if (!graph->summary_node_exist()) {
  300. return;
  301. }
  302. const std::map<std::string, std::pair<AnfNodePtr, int>> &summary_nodes = graph->summary_nodes();
  303. if (summary_nodes.empty()) {
  304. return;
  305. }
  306. for (const auto &item : summary_nodes) {
  307. const AnfNodePtr &node = item.second.first;
  308. size_t index = IntToSize(item.second.second);
  309. auto device_address = AnfAlgo::GetMutableOutputAddr(node, index, false);
  310. MS_EXCEPTION_IF_NULL(device_address);
  311. device_address->set_original_ref_count(SIZE_MAX);
  312. device_address->ResetRefCount();
  313. }
  314. }
  315. void UpdateRefCountForGraphOutput(const std::vector<KernelWithIndex> &output_with_index) {
  316. for (const auto &item_with_index : output_with_index) {
  317. if (!AnfAlgo::OutputAddrExist(item_with_index.first, item_with_index.second, false)) {
  318. continue;
  319. }
  320. auto device_address = AnfAlgo::GetMutableOutputAddr(item_with_index.first, item_with_index.second, false);
  321. MS_EXCEPTION_IF_NULL(device_address);
  322. device_address->set_original_ref_count(SIZE_MAX);
  323. device_address->ResetRefCount();
  324. }
  325. }
  326. } // namespace
  327. GraphCompilerInfo::~GraphCompilerInfo() {
  328. GraphScheduler::GetInstance().Clear(name_, graphs_, origin_parameters_order_, control_node_parser_);
  329. }
  330. GraphId GraphCompiler::CompileGraph(const GraphSegmentPtr &segment, const AnfNodePtrList &outputs,
  331. const DeviceContext *device_context, bool run_in_pynative) {
  332. MS_EXCEPTION_IF_NULL(session_);
  333. MS_EXCEPTION_IF_NULL(segment);
  334. MS_LOG(INFO) << "Status record: start compile graph.";
  335. auto nodes = segment->nodes_;
  336. auto device_terget = device_context->GetDeviceAddressType();
  337. // Generate kernel graph.
  338. KernelGraphPtr graph = session_->ConstructKernelGraph(nodes, outputs, device_terget);
  339. MS_EXCEPTION_IF_NULL(graph);
  340. opt::EliminateIllegalDataTypePass(graph);
  341. SetGraphDependency(graph, segment);
  342. // Unify the MindIR, must be before of the graph optimization.
  343. device_context->UnifyMindIR(graph);
  344. // The graph common optimization.
  345. graph->UpdateGraphAquireGilAttr();
  346. opt::BackendCommonOptimization(graph);
  347. graph->SetInputNodes();
  348. auto manager = MakeManager({graph});
  349. if (manager) {
  350. manager->AddFuncGraph(graph);
  351. graph->set_manager(manager);
  352. }
  353. session_->SetInputNodeUsage(graph, manager);
  354. graph->SetOptimizerFlag();
  355. GraphId graph_id;
  356. if (run_in_pynative) {
  357. MS_EXCEPTION_IF_NULL(session_);
  358. // Graphkernel does not support pynative mode now, print a warning here.
  359. graphkernel::GraphKernelFlags::GetInstance().CheckSupport();
  360. session_->InitAllBucket(graph, device_context);
  361. graph_id = graph->graph_id();
  362. } else {
  363. graph_id = CompileGraphImpl(graph, device_context);
  364. }
  365. session_->DumpGraphs({graph});
  366. // Cache the backend graph output nodes to front nodes with output index.
  367. auto backend_node = graph->output();
  368. MS_EXCEPTION_IF_NULL(backend_node);
  369. graph->CacheGraphOutputToFrontNodeWithIndex({backend_node}, outputs);
  370. auto ms_context = MsContext::GetInstance();
  371. MS_EXCEPTION_IF_NULL(ms_context);
  372. std::string device_target = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  373. if (device_target == kGPUDevice) {
  374. graph->set_root_graph_id(graph_id);
  375. }
  376. AnfAlgo::UpdateGraphValidRefPair(graph);
  377. MS_LOG(INFO) << "Status record: end compile graph. graph id: " << graph_id;
  378. return graph_id;
  379. }
  380. GraphId GraphCompiler::CompileGraph(const FuncGraphPtr &func_graph, const DeviceContext *device_context) {
  381. MS_EXCEPTION_IF_NULL(session_);
  382. MS_EXCEPTION_IF_NULL(func_graph);
  383. MS_LOG(INFO) << "Status record: start compile graph.";
  384. // Generate kernel graph.
  385. std::vector<KernelGraphPtr> all_graphs;
  386. auto device_target = device_context->GetDeviceAddressType();
  387. KernelGraphPtr root_graph = session_->ConstructKernelGraph(func_graph, &all_graphs, device_target);
  388. MS_EXCEPTION_IF_NULL(root_graph);
  389. for (const auto &graph : all_graphs) {
  390. MS_EXCEPTION_IF_NULL(graph);
  391. graph->set_root_graph_id(root_graph->graph_id());
  392. }
  393. // Unify the MindIR, must be before of the graph optimization.
  394. device_context->UnifyMindIR(root_graph);
  395. // The graph common optimization.
  396. opt::BackendCommonOptimization(root_graph);
  397. auto graph_id = CompileGraphImpl(root_graph, device_context);
  398. // dump all graphs.
  399. // for ascend mindRT.
  400. session_->DumpGraphs(all_graphs);
  401. // Cache the backend graph output nodes to front nodes with output index.
  402. auto output = func_graph->output();
  403. MS_EXCEPTION_IF_NULL(output);
  404. auto backend_node = root_graph->output();
  405. MS_EXCEPTION_IF_NULL(backend_node);
  406. root_graph->CacheGraphOutputToFrontNodeWithIndex({backend_node}, {output});
  407. AnfAlgo::UpdateGraphValidRefPair(root_graph);
  408. MS_LOG(INFO) << "Status record: end compile graph. graph id: " << graph_id;
  409. return graph_id;
  410. }
  411. GraphId GraphCompiler::CompileGraphImpl(const KernelGraphPtr &graph, const DeviceContext *device_context) const {
  412. MS_EXCEPTION_IF_NULL(graph);
  413. MS_EXCEPTION_IF_NULL(device_context);
  414. const auto &ms_context = MsContext::GetInstance();
  415. MS_EXCEPTION_IF_NULL(ms_context);
  416. #ifdef ENABLE_DUMP_IR
  417. bool save_graphs = ms_context->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG);
  418. // Dump .pb graph before graph optimization.
  419. if (save_graphs) {
  420. DumpIRProto(graph, "before_opt_" + std::to_string(graph->graph_id()));
  421. }
  422. #endif
  423. // Set the graph sink flag.
  424. auto is_executing_sink = device_context->IsExecutingSink(graph);
  425. auto is_loop_count_sink = device_context->IsLoopCountSink(graph);
  426. graph->set_is_executing_sink(is_executing_sink);
  427. graph->set_is_loop_count_sink(is_loop_count_sink);
  428. // Execute optimization pass.
  429. device_context->OptimizeGraph(graph);
  430. // Generate 'KernelMod' for all kernels and set 'KernelMod' into kernel,
  431. // 'KernelMod' is real executive object of kernel.
  432. device_context->CreateKernel(graph->execution_order());
  433. // Read the output and input ref map and set to the kernel graph.
  434. AddOutInRefToGraph(graph);
  435. #ifndef ENABLE_SECURITY
  436. session_->SetSummaryNodes(graph.get());
  437. // Update needed dump kernels for mindRT.
  438. DumpJsonParser::GetInstance().UpdateNeedDumpKernels(*graph.get());
  439. #endif
  440. // Adjust kernel graph before run graph.
  441. device_context->PreprocessBeforeRunGraph(graph);
  442. // Create device address for all anf nodes of graph.
  443. CreateDeviceAddress(graph, device_context, false);
  444. graph->set_is_all_nop_node(opt::IsAllNopNode(graph.get()));
  445. MS_EXCEPTION_IF_NULL(session_);
  446. session_->InitAllBucket(graph, device_context);
  447. SetSummaryNodesRefCount(graph.get());
  448. #ifdef ENABLE_DUMP_IR
  449. // Dump .pb graph after graph optimization.
  450. if (save_graphs) {
  451. DumpIRProto(graph, "after_opt_" + std::to_string(graph->graph_id()));
  452. }
  453. #endif
  454. #ifdef ENABLE_DEBUGGER
  455. auto debugger = Debugger::GetInstance();
  456. // Dump graph for GPU mindRT if dump is enabled.
  457. debugger->DumpInGraphCompiler(graph);
  458. if (debugger && debugger->DebuggerBackendEnabled()) {
  459. // Load graphs for GPU and Ascend mindRT.
  460. debugger->LoadGraphs(graph);
  461. }
  462. #endif
  463. graph->EnableRuntimeCache();
  464. return graph->graph_id();
  465. }
  466. GraphId GraphCompiler::CompileGraph(const session::OpRunInfo &op_run_info, bool *single_op_cache_hit,
  467. const DeviceContext *device_context) {
  468. // Check if the graph cache exists.
  469. auto iter = run_op_graphs_.find(op_run_info.graph_info);
  470. auto &op_executor = runtime::OpExecutor::GetInstance();
  471. if (iter != run_op_graphs_.end() && op_executor.BuildQueueEmpty()) {
  472. const auto &graph = iter->second;
  473. MS_EXCEPTION_IF_NULL(graph);
  474. *single_op_cache_hit = true;
  475. return graph->graph_id();
  476. }
  477. *single_op_cache_hit = false;
  478. // Generate kernel graph.
  479. MS_EXCEPTION_IF_NULL(session_);
  480. KernelGraphPtr graph =
  481. session_->ConstructSingleOpGraph(op_run_info, op_run_info.input_tensors, op_run_info.tensor_mask,
  482. device_context->GetDeviceAddressType() == device::DeviceAddressType::kAscend);
  483. MS_EXCEPTION_IF_NULL(graph);
  484. // session_ is SessionBasic, AscendUnifyMindIR has not been executed.
  485. device_context->UnifyMindIR(graph);
  486. MS_EXCEPTION_IF_NULL(device_context);
  487. device_context->OptimizeSingleOpGraph(graph);
  488. // Create device address for all anf nodes of graph.
  489. CreateDeviceAddressWithoutWorkspace(graph, device_context, op_run_info.is_gradient_out);
  490. graph->set_is_all_nop_node(opt::IsAllNopNode(graph.get()));
  491. run_op_graphs_[op_run_info.graph_info] = graph;
  492. auto output_nodes = graph->outputs();
  493. auto &outputs_with_index = run_op_graph_output_nodes_[graph->graph_id()];
  494. for (auto &node : output_nodes) {
  495. MS_EXCEPTION_IF_NULL(node);
  496. (void)outputs_with_index.emplace_back(common::AnfAlgo::VisitKernelWithReturnType(node, 0, false));
  497. }
  498. UpdateRefCountForGraphOutput(outputs_with_index);
  499. AnfAlgo::UpdateGraphValidRefPair(graph);
  500. return graph->graph_id();
  501. }
  502. void GraphCompiler::BuildSingleOpGraphs(const std::vector<KernelGraphPtr> &graphs,
  503. const DeviceContext *device_context) const {
  504. MS_EXCEPTION_IF_NULL(device_context);
  505. std::vector<CNodePtr> node_to_build;
  506. for (const auto &graph : graphs) {
  507. const auto &nodes = graph->execution_order();
  508. std::copy(nodes.begin(), nodes.end(), std::back_inserter(node_to_build));
  509. }
  510. device_context->CreateKernel(node_to_build);
  511. for (const auto &graph : graphs) {
  512. device_context->PreprocessBeforeRunSingleOpGraph(graph);
  513. CreateKernelWorkspaceDeviceAddress(device_context, graph);
  514. // Need to execute after PreprocessBeforeRunSingleOpGraph
  515. runtime::OpRuntimeInfo::CacheGraphOpRuntimeInfo(graph);
  516. }
  517. }
  518. KernelGraphPtr GraphCompiler::Fetch(GraphId graph_id) const {
  519. MS_EXCEPTION_IF_NULL(session_);
  520. return session_->GetGraph(graph_id);
  521. }
  522. KernelGraphPtr GraphCompiler::Fetch(const GraphInfo &graph_info) const {
  523. auto iter = run_op_graphs_.find(graph_info);
  524. if (iter == run_op_graphs_.end()) {
  525. MS_LOG(ERROR) << "Can't find graph for: " << graph_info;
  526. return nullptr;
  527. }
  528. return iter->second;
  529. }
  530. void GraphCompiler::AddOutInRefToGraph(const KernelGraphPtr &graph) const {
  531. MS_EXCEPTION_IF_NULL(graph);
  532. for (const auto &cnode : graph->execution_order()) {
  533. MS_EXCEPTION_IF_NULL(cnode);
  534. auto kernel_info = dynamic_cast<device::KernelInfo *>(cnode->kernel_info());
  535. MS_EXCEPTION_IF_NULL(kernel_info);
  536. for (const auto &ref : kernel_info->out_in_ref_map()) {
  537. size_t output_index = ref.first;
  538. size_t input_index = ref.second;
  539. auto final_pair = std::make_pair(cnode, output_index);
  540. auto origin_pair = common::AnfAlgo::VisitKernel(common::AnfAlgo::GetInputNode(cnode, input_index), 0);
  541. MS_LOG(INFO) << "The reference relation output " << final_pair.first->fullname_with_scope()
  542. << ", output index: " << final_pair.second << " to input "
  543. << origin_pair.first->fullname_with_scope() << ", output index: " << origin_pair.second;
  544. // Add to graph only if the input is not a monad.
  545. if (!HasAbstractUMonad(origin_pair.first) && !HasAbstractIOMonad(origin_pair.first)) {
  546. graph->AddRefCorrespondPairs(final_pair, origin_pair);
  547. }
  548. }
  549. }
  550. }
  551. void GraphCompiler::CreateDeviceAddress(const KernelGraphPtr &graph, const DeviceContext *device_context,
  552. bool is_gradient_out) const {
  553. MS_LOG(INFO) << "Status record: start create device address. graph id: " << graph->graph_id();
  554. CreateParameterDeviceAddress(device_context, graph);
  555. CreateValueNodeDeviceAddress(device_context, graph);
  556. CreateKernelOutputDeviceAddress(device_context, graph, is_gradient_out);
  557. CreateKernelWorkspaceDeviceAddress(device_context, graph);
  558. UpdateDeviceAddressForInplaceNode(graph);
  559. UpdateDeviceAddressForRefNode(graph);
  560. MS_LOG(INFO) << "Status record: end create device address. graph id: " << graph->graph_id();
  561. }
  562. void GraphCompiler::CreateDeviceAddressWithoutWorkspace(const KernelGraphPtr &graph,
  563. const DeviceContext *device_context,
  564. bool is_gradient_out) const {
  565. CreateParameterDeviceAddress(device_context, graph);
  566. CreateValueNodeDeviceAddress(device_context, graph);
  567. CreateKernelOutputDeviceAddress(device_context, graph, is_gradient_out);
  568. UpdateDeviceAddressForInplaceNode(graph);
  569. UpdateDeviceAddressForRefNode(graph);
  570. }
  571. void GraphCompiler::GetParamAndOutputIndex(
  572. const KernelGraphPtr &graph, const std::vector<TensorPtr> &inputs, VectorRef *const outputs,
  573. std::map<AnfNodePtr, size_t> *parameter_index,
  574. std::map<KernelWithIndex, std::vector<std::vector<size_t>>> *output_indexes) {
  575. MS_EXCEPTION_IF_NULL(session_);
  576. session_->GetParameterIndex(graph.get(), inputs, parameter_index);
  577. session_->CreateOutputPlaceholder(graph, inputs, outputs, output_indexes);
  578. }
  579. void GraphCompiler::GetSingleOpInputTensors(const CNodePtr &kernel,
  580. const std::map<KernelWithIndex, TensorPtr> &op_output,
  581. const std::map<AnfNodePtr, size_t> &parameter_index,
  582. const std::vector<TensorPtr> &graph_inputs,
  583. InputTensorInfo *const input_tensor_info) {
  584. MS_EXCEPTION_IF_NULL(session_);
  585. session_->GetOpInputTensors(kernel, op_output, parameter_index, graph_inputs, input_tensor_info);
  586. }
  587. TensorPtr GraphCompiler::GetSingleOpInputTensorByIndex(const CNodePtr &kernel,
  588. const std::map<KernelWithIndex, TensorPtr> &op_output,
  589. const std::map<AnfNodePtr, size_t> &parameter_index,
  590. const std::vector<TensorPtr> &graph_inputs,
  591. InputTensorInfo *const input_tensor_info, size_t input_index) {
  592. MS_EXCEPTION_IF_NULL(session_);
  593. return session_->GetOpInputTensorByIndex(kernel, op_output, parameter_index, graph_inputs, input_tensor_info,
  594. input_index);
  595. }
  596. void GraphCompiler::GetSingleOpRunInfoAndGraphInfo(const CNodePtr &kernel, const InputTensorInfo &tensor_info,
  597. OpRunInfo *run_info, GraphInfo *graph_info,
  598. GraphOutputInfo *const graph_output_info) {
  599. MS_EXCEPTION_IF_NULL(session_);
  600. MS_EXCEPTION_IF_NULL(graph_info);
  601. *graph_info = session_->GetSingleOpGraphInfo(kernel, tensor_info.input_tensors);
  602. *run_info = session_->GetSingleOpRunInfo(kernel, *graph_info, tensor_info, graph_output_info);
  603. }
  604. void GraphCompiler::CalculateRefCount(const KernelGraphPtr &graph, std::map<KernelWithIndex, size_t> *ref_count) const {
  605. MS_EXCEPTION_IF_NULL(session_);
  606. session_->GetRefCount(graph.get(), ref_count);
  607. }
  608. void GraphCompiler::CalculateForwardOpOutputCount(const KernelGraphPtr &graph,
  609. const std::vector<tensor::TensorPtr> &inputs,
  610. std::map<std::string, size_t> *forward_op_output_tensor_id) const {
  611. MS_EXCEPTION_IF_NULL(session_);
  612. forward_op_output_tensor_id->clear();
  613. session_->GetForwardOpOutputRefCount(graph.get(), inputs, forward_op_output_tensor_id);
  614. }
  615. void GraphCompiler::UpdateRefCount(const std::set<KernelWithIndex> &input_kernels_with_index,
  616. std::map<KernelWithIndex, size_t> *ref_count,
  617. std::map<KernelWithIndex, tensor::TensorPtr> *op_output_map) const {
  618. MS_EXCEPTION_IF_NULL(session_);
  619. session_->HandleOpInputs(input_kernels_with_index, ref_count, op_output_map);
  620. }
  621. void GraphCompiler::UpdateForwardOpOutputRefCount(const std::vector<tensor::TensorPtr> &input_tensor,
  622. std::map<std::string, size_t> *forward_op_output_tensor_id) const {
  623. MS_EXCEPTION_IF_NULL(session_);
  624. MS_EXCEPTION_IF_NULL(forward_op_output_tensor_id);
  625. session_->ReleaseForwardOpOutput(input_tensor, forward_op_output_tensor_id);
  626. }
  627. void GraphCompiler::RecoverGraphOutput(const AnfNodePtr &kernel, const VectorRef &op_outputs,
  628. const std::map<KernelWithIndex, size_t> &ref_count,
  629. std::map<KernelWithIndex, TensorPtr> *op_output_map,
  630. GraphOutputInfo *const graph_output_info) const {
  631. MS_EXCEPTION_IF_NULL(session_);
  632. session_->HandleOpOutputs(kernel, op_outputs, ref_count, op_output_map, graph_output_info);
  633. }
  634. void GraphCompiler::AddGradAddrToBucket(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &grad_tensor) {
  635. MS_EXCEPTION_IF_NULL(session_);
  636. session_->AddGradAddrToBucket(graph_id, grad_tensor);
  637. }
  638. void GraphCompiler::ClearAllBucket(const GraphId &graph_id) {
  639. MS_EXCEPTION_IF_NULL(session_);
  640. session_->ClearAllBucket(graph_id);
  641. }
  642. const std::vector<KernelWithIndex> &GraphCompiler::GetGraphOutputNodes(GraphId graph_id) const {
  643. const auto &iter = run_op_graph_output_nodes_.find(graph_id);
  644. if (iter == run_op_graph_output_nodes_.end()) {
  645. MS_LOG(EXCEPTION) << "Can not find output nodes for graph id: " << graph_id;
  646. }
  647. return iter->second;
  648. }
  649. void GraphCompiler::RegisterSummaryCallBackFunc(const CallBackFunc &callback) const {
  650. MS_EXCEPTION_IF_NULL(session_);
  651. #ifndef ENABLE_SECURITY
  652. session_->RegisterSummaryCallBackFunc(callback);
  653. #endif
  654. }
  655. void GraphCompiler::Summary(const std::vector<KernelGraphPtr> &graphs) const {
  656. MS_EXCEPTION_IF_NULL(session_);
  657. for (const auto &graph : graphs) {
  658. #ifndef ENABLE_SECURITY
  659. session_->Summary(graph.get());
  660. #endif
  661. }
  662. }
  663. void GraphCompiler::EraseSingleOpCache(const GraphInfo &graph_info, const GraphId &graph_id) {
  664. (void)run_op_graphs_.erase(graph_info);
  665. (void)run_op_graph_output_nodes_.erase(graph_id);
  666. }
  667. void GraphCompiler::SetGraphDependency(const KernelGraphPtr &graph, const GraphSegmentPtr &segment) const {
  668. MS_EXCEPTION_IF_NULL(graph);
  669. MS_EXCEPTION_IF_NULL(segment);
  670. segment->graph_id_ = graph->graph_id();
  671. for (auto &pre_segment : segment->pre_segments_) {
  672. MS_EXCEPTION_IF_NULL(pre_segment);
  673. auto pre_graph = Fetch(pre_segment->graph_id_);
  674. MS_EXCEPTION_IF_NULL(pre_graph);
  675. pre_graph->AddPostGraph(graph);
  676. graph->AddPreGraph(pre_graph);
  677. MS_LOG(INFO) << "Link graph " << pre_segment->graph_id_ << " to " << graph->graph_id();
  678. }
  679. }
  680. } // namespace runtime
  681. } // namespace mindspore