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