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.

gpu_session.cc 15 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /**
  2. * Copyright 2019-2020 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 "debug/anf_ir_utils.h"
  17. #include "backend/session/gpu_session.h"
  18. #include "runtime/device/gpu/kernel_info_setter.h"
  19. #include "runtime/device/gpu/gpu_kernel_build.h"
  20. #include "runtime/device/gpu/gpu_kernel_runtime.h"
  21. #include "runtime/device/gpu/gpu_stream_assign.h"
  22. #include "backend/optimizer/common/optimizer.h"
  23. #include "backend/optimizer/common/pass_manager.h"
  24. #include "backend/optimizer/common/helper.h"
  25. #include "backend/optimizer/pass/communication_op_fusion.h"
  26. #include "backend/optimizer/pass/getitem_tuple.h"
  27. #include "backend/optimizer/gpu/adam_weight_decay_fusion.h"
  28. #include "backend/optimizer/gpu/adam_fusion.h"
  29. #include "backend/optimizer/gpu/replace_bn_cast_fusion.h"
  30. #include "backend/optimizer/gpu/replace_bn_grad_cast_fusion.h"
  31. #include "backend/optimizer/gpu/replace_momentum_cast_fusion.h"
  32. #include "backend/optimizer/gpu/replace_addn_fusion.h"
  33. #include "runtime/device/kernel_runtime_manager.h"
  34. #include "common/utils.h"
  35. #include "common/trans.h"
  36. #include "utils/context/ms_context.h"
  37. #include "utils/base_ref_extends.h"
  38. #include "debug/tensor_load.h"
  39. namespace mindspore {
  40. namespace session {
  41. namespace gpu {
  42. using AnfAlgo = mindspore::session::AnfRuntimeAlgorithm;
  43. void GPUSession::SelectKernel(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  44. MS_EXCEPTION_IF_NULL(kernel_graph);
  45. for (const auto &kernel_node : kernel_graph->execution_order()) {
  46. MS_EXCEPTION_IF_NULL(kernel_node);
  47. device::gpu::SetKernelInfo(kernel_node);
  48. }
  49. }
  50. void GPUSession::StartKernelRT() const {
  51. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  52. MS_EXCEPTION_IF_NULL(runtime_instance);
  53. if (!runtime_instance->Init()) {
  54. MS_LOG(EXCEPTION) << "GPU start kernel runtime failed";
  55. }
  56. }
  57. void GPUSession::Optimize(const std::shared_ptr<KernelGraph> &kernel_graph) {
  58. MS_EXCEPTION_IF_NULL(kernel_graph);
  59. auto optimizer = std::make_shared<opt::GraphOptimizer>();
  60. auto pm = std::make_shared<opt::PassManager>();
  61. pm->AddPass(std::make_shared<opt::AdamWeightDecayFusion>());
  62. pm->AddPass(std::make_shared<opt::AdamFusion>());
  63. pm->AddPass(std::make_shared<opt::ReplaceBNCastFusion>());
  64. pm->AddPass(std::make_shared<opt::ReplaceBNGradCastFusion>());
  65. pm->AddPass(std::make_shared<opt::ReplaceMomentumCastFusion>());
  66. pm->AddPass(std::make_shared<opt::ReplaceAddNFusion>());
  67. optimizer->AddPassManager(pm);
  68. (void)optimizer->Optimize(kernel_graph);
  69. kernel_graph->SetExecOrderByDefault();
  70. }
  71. void GPUSession::HardwareOptimize(const std::shared_ptr<KernelGraph> &kernel_graph) {
  72. auto optimizer = std::make_shared<opt::GraphOptimizer>();
  73. auto pm = std::make_shared<opt::PassManager>();
  74. pm->AddPass(std::make_shared<opt::AllReduceFusion>());
  75. pm->AddPass(std::make_shared<opt::GetitemTuple>());
  76. optimizer->AddPassManager(pm);
  77. (void)optimizer->Optimize(kernel_graph);
  78. kernel_graph->SetExecOrderByDefault();
  79. }
  80. void GPUSession::AssignStream(const std::shared_ptr<KernelGraph> &kernel_graph) {
  81. MS_EXCEPTION_IF_NULL(kernel_graph);
  82. device::gpu::AssignGpuStream(kernel_graph);
  83. }
  84. void GPUSession::BuildKernel(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  85. device::gpu::GpuBuild(kernel_graph);
  86. }
  87. void GPUSession::AllocateMemory(KernelGraph *kernel_graph) const {
  88. MS_EXCEPTION_IF_NULL(kernel_graph);
  89. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  90. MS_EXCEPTION_IF_NULL(runtime_instance);
  91. runtime_instance->AssignMemory(kernel_graph);
  92. }
  93. void GPUSession::RunOpAllocateMemory(const ValuePtr &pre_output_value,
  94. const std::vector<tensor::TensorPtr> &input_tensors,
  95. KernelGraph *kernel_graph) const {
  96. MS_EXCEPTION_IF_NULL(kernel_graph);
  97. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  98. MS_EXCEPTION_IF_NULL(runtime_instance);
  99. runtime_instance->RunOpAssignMemory(pre_output_value, input_tensors, kernel_graph);
  100. }
  101. void GPUSession::RunOpClearMemory(KernelGraph *kernel_graph) const {
  102. MS_EXCEPTION_IF_NULL(kernel_graph);
  103. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  104. MS_EXCEPTION_IF_NULL(runtime_instance);
  105. runtime_instance->RunOpClearMemory(kernel_graph);
  106. }
  107. void GPUSession::LoadInputData(const std::shared_ptr<KernelGraph> &kernel_graph,
  108. const std::vector<tensor::TensorPtr> &inputs_const) const {
  109. std::vector<tensor::TensorPtr> inputs(inputs_const);
  110. MS_EXCEPTION_IF_NULL(kernel_graph);
  111. auto input_nodes = kernel_graph->inputs();
  112. auto ms_context = MsContext::GetInstance();
  113. MS_EXCEPTION_IF_NULL(ms_context);
  114. for (size_t i = 0; i < inputs.size(); ++i) {
  115. auto tensor = inputs[i];
  116. MS_EXCEPTION_IF_NULL(tensor);
  117. auto input_node = input_nodes[i];
  118. MS_EXCEPTION_IF_NULL(input_node);
  119. if (input_node->isa<Parameter>() && AnfAlgo::OutputAddrExist(input_node, 0)) {
  120. auto pk_node = input_node->cast<ParameterPtr>();
  121. auto device_address = AnfAlgo::GetMutableOutputAddr(pk_node, 0);
  122. auto tensor_address = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address());
  123. bool need_sync = false;
  124. if (ms_context->enable_pynative_infer()) {
  125. if (tensor_address == nullptr || tensor_address != device_address) {
  126. need_sync = true;
  127. }
  128. } else if (tensor->is_dirty() || tensor_address == nullptr) {
  129. need_sync = true;
  130. } else if (tensor_address != device_address) {
  131. if (tensor_address->DeviceType() == device_address->DeviceType()) {
  132. AnfAlgo::SetOutputAddr(tensor_address, 0, pk_node.get());
  133. } else {
  134. need_sync = true;
  135. }
  136. }
  137. if (need_sync) {
  138. tensor->set_device_address(device_address);
  139. MS_EXCEPTION_IF_NULL(device_address);
  140. if (!device_address->SyncHostToDevice(trans::GetRuntimePaddingShape(pk_node, 0),
  141. LongToSize(tensor->data().nbytes()), tensor->data_type(),
  142. tensor->data_c())) {
  143. MS_LOG(EXCEPTION) << "SyncHostToDevice failed.";
  144. }
  145. }
  146. }
  147. tensor->set_dirty(false);
  148. }
  149. }
  150. void GPUSession::Execute(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  151. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  152. MS_EXCEPTION_IF_NULL(runtime_instance);
  153. #ifdef ENABLE_DEBUGGER
  154. if (!runtime_instance->Run(kernel_graph.get(), debugger_.get())) {
  155. #else
  156. if (!runtime_instance->Run(kernel_graph.get())) {
  157. #endif
  158. MS_LOG(EXCEPTION) << "GPU execute graph failed!";
  159. }
  160. }
  161. GraphId GPUSession::CompileGraph(const AnfNodePtrList &lst, const AnfNodePtrList &outputs) {
  162. // Construct graph, if successfully, graph_sum_ + 1
  163. auto graph_id = graph_sum_;
  164. auto graph = ConstructKernelGraph(lst, outputs);
  165. MS_EXCEPTION_IF_NULL(graph);
  166. // Prepare ms context info for dump .pb graph
  167. auto context_ptr = MsContext::GetInstance();
  168. MS_EXCEPTION_IF_NULL(context_ptr);
  169. bool save_graphs = context_ptr->save_graphs_flag();
  170. // Optimize
  171. Optimize(graph);
  172. // Select kernel build info
  173. SelectKernel(graph);
  174. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  175. // Assign parameter keys.
  176. AssignParamKey(graph);
  177. #endif
  178. // Start gpu kernel runtime
  179. StartKernelRT();
  180. // Dump .pb graph before hardware optimization
  181. if (save_graphs) {
  182. DumpIRProto(graph, "before_hwopt_" + std::to_string(graph_id));
  183. }
  184. // HardwareOptimize
  185. HardwareOptimize(graph);
  186. // Dump .pb graph after hardware optimization
  187. if (save_graphs) {
  188. DumpIRProto(graph, "after_hwopt_" + std::to_string(graph_id));
  189. }
  190. // Assign CUDA streams
  191. AssignStream(graph);
  192. // Hide NoOp from execution graph
  193. opt::HideNopNode(graph.get());
  194. // Build kernel if node is cnode
  195. BuildKernel(graph);
  196. // Set graph execution order before memory alloc, ensure that memory alloc is according to the reorder graph
  197. auto execution_order = graph->execution_order();
  198. Reorder(&execution_order);
  199. graph->set_execution_order(execution_order);
  200. // Get summary nodes.
  201. SetSummaryNodes(graph.get());
  202. // Remove NoOp from execution graph
  203. opt::RemoveNopNode(graph.get());
  204. // Set graph manager.
  205. MS_EXCEPTION_IF_NULL(context_);
  206. FuncGraphManagerPtr manager = MakeManager({graph});
  207. context_->AddManager(manager);
  208. if (manager) {
  209. manager->AddFuncGraph(graph);
  210. graph->set_manager(manager);
  211. }
  212. // Alloc memory, including static memory and dynamic memory
  213. AllocateMemory(graph.get());
  214. return graph_id;
  215. }
  216. void GPUSession::RunGraph(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  217. auto &kernel_graph = graphs_[graph_id];
  218. #ifdef ENABLE_DEBUGGER
  219. PreIterationDbg(kernel_graph);
  220. #endif
  221. // Load input data from user input
  222. LoadInputData(kernel_graph, inputs);
  223. #if (ENABLE_CPU && (ENABLE_D || ENABLE_GPU))
  224. // Initialize parameter server
  225. if (!ps_init_) {
  226. InitPSParamAndOptim(kernel_graph, inputs);
  227. }
  228. #endif
  229. MS_EXCEPTION_IF_NULL(kernel_graph);
  230. {
  231. py::gil_scoped_release gil_release;
  232. // Run graph on GPU
  233. Execute(kernel_graph);
  234. }
  235. #ifdef ENABLE_DEBUGGER
  236. PostLoadTensor(kernel_graph);
  237. #endif
  238. // Get result from GPU
  239. UpdateOutputs(kernel_graph, outputs, inputs);
  240. // Summary
  241. auto context_ptr = MsContext::GetInstance();
  242. MS_EXCEPTION_IF_NULL(context_ptr);
  243. if (context_ptr->enable_gpu_summary()) {
  244. Summary(kernel_graph.get());
  245. }
  246. #ifdef ENABLE_DEBUGGER
  247. PostIterationDbg(kernel_graph);
  248. #endif
  249. }
  250. void GPUSession::BuildOp(const OpRunInfo &op_run_info, const GraphInfo &graph_info,
  251. const std::vector<tensor::TensorPtr> &input_tensors, const std::vector<int> &tensors_mask) {
  252. // Check if the graph cache exists.
  253. if (run_op_graphs_.find(graph_info) != run_op_graphs_.end()) {
  254. return;
  255. }
  256. // Prepare the graph
  257. auto kernel_graph = ConstructSingleOpGraph(op_run_info, input_tensors, tensors_mask);
  258. MS_EXCEPTION_IF_NULL(kernel_graph);
  259. SelectKernel(kernel_graph);
  260. StartKernelRT();
  261. // Hide NoOp from execution graph
  262. opt::HideNopNode(kernel_graph.get());
  263. BuildKernel(kernel_graph);
  264. run_op_graphs_[graph_info] = kernel_graph;
  265. }
  266. py::tuple GPUSession::RunOp(const OpRunInfo &op_run_info, const GraphInfo &graph_info,
  267. const std::vector<tensor::TensorPtr> &input_tensors) {
  268. auto kernel_graph = run_op_graphs_[graph_info];
  269. MS_EXCEPTION_IF_NULL(kernel_graph);
  270. // Remove NoOp from execution graph
  271. opt::RemoveNopNode(kernel_graph.get());
  272. RunOpAllocateMemory(op_run_info.value, input_tensors, kernel_graph.get());
  273. // Execute the computation
  274. LoadInputData(kernel_graph, input_tensors);
  275. {
  276. py::gil_scoped_release gil_release;
  277. Execute(kernel_graph);
  278. }
  279. // Fetch outputs
  280. VectorRef outputs;
  281. UpdateOutputs(kernel_graph, &outputs, input_tensors);
  282. // Trans output to tuple
  283. auto output_tensors = TransformBaseRefListToTuple(outputs);
  284. if (!utils::isa<PyObjectRef>(output_tensors) ||
  285. !py::isinstance<py::tuple>(utils::cast<PyObjectRef>(output_tensors).object_)) {
  286. MS_EXCEPTION(NotSupportError) << "The output tensors should be a tuple !";
  287. }
  288. py::object tuple_obj = utils::cast<PyObjectRef>(output_tensors).object_;
  289. py::tuple tuple_tensors = py::cast<py::tuple>(tuple_obj);
  290. RunOpClearMemory(kernel_graph.get());
  291. return tuple_tensors;
  292. }
  293. #ifdef ENABLE_DEBUGGER
  294. void GPUSession::Dump(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  295. #ifdef ENABLE_DUMP_E2E
  296. MS_EXCEPTION_IF_NULL(kernel_graph);
  297. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  298. MS_EXCEPTION_IF_NULL(runtime_instance);
  299. (void)runtime_instance->DumpData(kernel_graph.get(), debugger_.get());
  300. #endif
  301. }
  302. bool GPUSession::DumpDataEnabledIteration() const {
  303. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  304. MS_EXCEPTION_IF_NULL(runtime_instance);
  305. return runtime_instance->DumpDataEnabledIteration();
  306. }
  307. void GPUSession::PreIterationDbg(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  308. if (debugger_) {
  309. debugger_->PreExecute(kernel_graph);
  310. }
  311. PreLoadTensor(kernel_graph);
  312. }
  313. void GPUSession::PostIterationDbg(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  314. bool dump_enabled = DumpDataEnabledIteration();
  315. // debug used for dump
  316. if (debugger_ && dump_enabled) {
  317. Dump(kernel_graph);
  318. }
  319. if (debugger_) {
  320. debugger_->PostExecute();
  321. }
  322. }
  323. void GPUSession::PreLoadTensor(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  324. bool dump_enabled = DumpDataEnabledIteration();
  325. if (!(debugger_ && (debugger_->debugger_enabled() || dump_enabled))) {
  326. return;
  327. }
  328. MS_EXCEPTION_IF_NULL(kernel_graph);
  329. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  330. MS_EXCEPTION_IF_NULL(runtime_instance);
  331. DebugServices *debug_services = debugger_->debug_services();
  332. TensorLoader *tensor_loader = debug_services->tensor_loader();
  333. tensor_loader->EmptyTensor();
  334. uint32_t iter_num = tensor_loader->GetIterNum();
  335. tensor_loader->set_iter_num(++iter_num);
  336. }
  337. void GPUSession::PostLoadTensor(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  338. bool dump_enabled = DumpDataEnabledIteration();
  339. if (!(debugger_ && (debugger_->debugger_enabled() || dump_enabled))) {
  340. return;
  341. }
  342. MS_EXCEPTION_IF_NULL(kernel_graph);
  343. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  344. MS_EXCEPTION_IF_NULL(runtime_instance);
  345. DebugServices *debug_services = debugger_->debug_services();
  346. TensorLoader *tensor_loader = debug_services->tensor_loader();
  347. tensor_loader->EmptyPrevTensor();
  348. }
  349. #endif
  350. } // namespace gpu
  351. } // namespace session
  352. } // namespace mindspore