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

5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. /**
  2. * Copyright 2019-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. #include "backend/session/gpu_session.h"
  17. #include <string>
  18. #include <utility>
  19. #include "backend/optimizer/common/helper.h"
  20. #include "backend/optimizer/common/optimizer.h"
  21. #include "backend/optimizer/common/pass_manager.h"
  22. #include "backend/optimizer/common/common_backend_optimization.h"
  23. #include "backend/optimizer/gpu/adam_weight_decay_fusion.h"
  24. #include "backend/optimizer/gpu/adam_fusion.h"
  25. #include "backend/optimizer/gpu/alltoall_fusion.h"
  26. #include "backend/optimizer/gpu/apply_momentum_weight_scale_fusion.h"
  27. #include "backend/optimizer/gpu/apply_momentum_scale_fusion.h"
  28. #include "backend/optimizer/gpu/apply_momentum_weight_fusion.h"
  29. #include "backend/optimizer/gpu/batch_norm_relu_fusion.h"
  30. #include "backend/optimizer/gpu/batch_norm_relu_grad_fusion.h"
  31. #include "backend/optimizer/gpu/batch_norm_add_relu_fusion.h"
  32. #include "backend/optimizer/gpu/post_batch_norm_add_relu_fusion.h"
  33. #include "backend/optimizer/gpu/batch_norm_add_relu_grad_fusion.h"
  34. #include "backend/optimizer/gpu/combine_momentum_fusion.h"
  35. #include "backend/optimizer/gpu/combine_cast_fusion.h"
  36. #include "backend/optimizer/gpu/cudnn_inplace_fusion.h"
  37. #include "backend/optimizer/gpu/insert_format_transform_op.h"
  38. #include "backend/optimizer/gpu/replace_momentum_cast_fusion.h"
  39. #include "backend/optimizer/gpu/replace_addn_fusion.h"
  40. #include "backend/optimizer/gpu/print_reduce_fusion.h"
  41. #include "backend/optimizer/gpu/bce_with_logits_loss_fusion.h"
  42. #include "backend/optimizer/gpu/remove_format_transform_pair.h"
  43. #include "backend/optimizer/gpu/remove_redundant_format_transform.h"
  44. #include "backend/optimizer/gpu/reduce_precision_fusion.h"
  45. #include "backend/optimizer/gpu/insert_cast_gpu.h"
  46. #include "backend/optimizer/gpu/relu_v2_pass.h"
  47. #include "backend/optimizer/gpu/add_relu_v2_fusion.h"
  48. #include "backend/optimizer/gpu/add_relu_grad_v2_fusion.h"
  49. #include "backend/optimizer/gpu/matmul_biasadd_fusion.h"
  50. #ifdef ENABLE_GPU_INFER
  51. #include "backend/optimizer/trt_pass/graph_converter.h"
  52. #endif
  53. #include "backend/optimizer/graph_kernel/graph_kernel_optimization.h"
  54. #include "backend/optimizer/pass/communication_op_fusion.h"
  55. #include "backend/optimizer/gpu/concat_outputs_for_all_gather.h"
  56. #include "backend/optimizer/pass/getitem_tuple.h"
  57. #include "backend/optimizer/pass/optimize_updatestate.h"
  58. #include "backend/optimizer/gpu/adjust_depend_for_parallel_optimizer_recompute_all_gather_fusion.h"
  59. #include "common/trans.h"
  60. #include "debug/anf_ir_dump.h"
  61. #include "debug/dump_proto.h"
  62. #ifdef ENABLE_DEBUGGER
  63. #include "debug/data_dump/e2e_dump.h"
  64. #include "debug/data_dump/dump_json_parser.h"
  65. #include "debug/debugger/proto_exporter.h"
  66. #include "debug/data_dump/dump_utils.h"
  67. #include "debug/tensor_load.h"
  68. #else
  69. #include "debug/debugger/proto_exporter_stub.h"
  70. #endif
  71. #include "runtime/device/gpu/gpu_kernel_build.h"
  72. #include "runtime/device/gpu/gpu_kernel_runtime.h"
  73. #include "runtime/device/gpu/gpu_stream_assign.h"
  74. #include "runtime/device/gpu/kernel_info_setter.h"
  75. #include "runtime/device/kernel_runtime_manager.h"
  76. #include "runtime/device/gpu/cuda_driver.h"
  77. #include "runtime/device/gpu/distribution/collective_init.h"
  78. #include "runtime/device/gpu/gpu_bucket.h"
  79. #include "runtime/device/gpu/gpu_device_address.h"
  80. #include "utils/ms_utils.h"
  81. #include "utils/config_manager.h"
  82. #include "utils/ms_context.h"
  83. #include "utils/context/graph_kernel_flags.h"
  84. #include "utils/utils.h"
  85. #include "abstract/utils.h"
  86. #if ENABLE_CPU && ENABLE_GPU
  87. #include "ps/util.h"
  88. #include "ps/ps_cache/ps_cache_manager.h"
  89. #endif
  90. #ifdef ENABLE_DUMP_IR
  91. #include "debug/rdr/running_data_recorder.h"
  92. #endif
  93. namespace mindspore {
  94. namespace session {
  95. namespace gpu {
  96. using AnfAlgo = mindspore::session::AnfRuntimeAlgorithm;
  97. using CollectiveInitializer = device::gpu::CollectiveInitializer;
  98. using GetLocalRankId = device::gpu::GetLocalRankId;
  99. using InitNCCLComm = device::gpu::InitNCCLComm;
  100. void GPUSession::Init(uint32_t device_id) {
  101. if (CollectiveInitializer::instance().collective_inited()) {
  102. device_id = CollectiveInitializer::instance().local_rank_id();
  103. }
  104. bool ret = device::gpu::CudaDriver::SetDevice(UintToInt(device_id));
  105. if (!ret) {
  106. MS_LOG(EXCEPTION) << "GPUSession failed to set current device id:" << device_id;
  107. }
  108. auto ms_context = MsContext::GetInstance();
  109. MS_EXCEPTION_IF_NULL(ms_context);
  110. ms_context->set_param<uint32_t>(MS_CTX_DEVICE_ID, device_id);
  111. if (CollectiveInitializer::instance().collective_inited()) {
  112. auto collective_handle = CollectiveInitializer::instance().collective_handle();
  113. if (collective_handle != nullptr) {
  114. MS_LOG(INFO) << "Start initializing NCCL communicator for device " << device_id;
  115. auto init_nccl_comm_funcptr =
  116. reinterpret_cast<InitNCCLComm>(dlsym(const_cast<void *>(collective_handle), "InitNCCLComm"));
  117. MS_EXCEPTION_IF_NULL(init_nccl_comm_funcptr);
  118. (*init_nccl_comm_funcptr)();
  119. MS_LOG(INFO) << "End initializing NCCL communicator.";
  120. rank_id_ = GetRankId();
  121. }
  122. }
  123. #ifndef ENABLE_SECURITY
  124. auto &json_parser = DumpJsonParser::GetInstance();
  125. // Dump json config file if dump is enabled
  126. json_parser.CopyDumpJsonToDir(rank_id_);
  127. json_parser.CopyMSCfgJsonToDir(rank_id_);
  128. #endif
  129. MS_LOG(INFO) << "Set device id " << device_id << " for gpu session.";
  130. InitExecutor(kGPUDevice, device_id);
  131. }
  132. void GPUSession::SelectKernel(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  133. MS_EXCEPTION_IF_NULL(kernel_graph);
  134. device::gpu::FormatTransformChecker::GetInstance().CheckSupportFormatTransform(kernel_graph);
  135. for (const auto &kernel_node : kernel_graph->execution_order()) {
  136. MS_EXCEPTION_IF_NULL(kernel_node);
  137. device::gpu::SetKernelInfo(kernel_node);
  138. }
  139. }
  140. void GPUSession::StartKernelRT() const {
  141. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  142. MS_EXCEPTION_IF_NULL(runtime_instance);
  143. if (!runtime_instance->Init()) {
  144. MS_LOG(EXCEPTION) << "GPU start kernel runtime failed";
  145. }
  146. }
  147. void GPUSession::Optimize(const std::shared_ptr<KernelGraph> &kernel_graph) {
  148. MS_EXCEPTION_IF_NULL(kernel_graph);
  149. auto optimizer = std::make_shared<opt::GraphOptimizer>();
  150. auto pm = std::make_shared<opt::PassManager>();
  151. #ifdef ENABLE_GPU_INFER
  152. pm->AddPass(std::make_shared<opt::GraphConverter>());
  153. #endif
  154. pm->AddPass(std::make_shared<opt::MatMulBiasAddFusion>());
  155. pm->AddPass(std::make_shared<opt::AdamWeightDecayFusion>());
  156. pm->AddPass(std::make_shared<opt::AdamFusion>());
  157. pm->AddPass(std::make_shared<opt::AllToAllFusion>());
  158. pm->AddPass(std::make_shared<opt::ApplyMomentumWeightDecayScaleFusion>());
  159. pm->AddPass(std::make_shared<opt::ApplyMomentumScaleFusion>());
  160. pm->AddPass(std::make_shared<opt::ApplyMomentumWeightDecayFusion>());
  161. if (!graphkernel::GraphKernelFlags::GetInstance().IsEnableGraphKernel()) {
  162. pm->AddPass(std::make_shared<opt::CastAllFusion>("cast_all"));
  163. }
  164. pm->AddPass(std::make_shared<opt::CombineMomentumFusion>("combine_momentum"));
  165. pm->AddPass(std::make_shared<opt::ReplaceMomentumCastFusion>());
  166. pm->AddPass(std::make_shared<opt::ReplaceAddNFusion>());
  167. pm->AddPass(std::make_shared<opt::PrintReduceFusion>("print_reduce"));
  168. pm->AddPass(std::make_shared<opt::BCEWithLogitsLossFusion>());
  169. pm->AddPass(std::make_shared<opt::InsertCastGPU>("insert_cast_gpu"));
  170. optimizer->AddPassManager(pm);
  171. (void)optimizer->Optimize(kernel_graph);
  172. kernel_graph->SetExecOrderByDefault();
  173. }
  174. void GPUSession::HardwareOptimize(const std::shared_ptr<KernelGraph> &kernel_graph) {
  175. MS_EXCEPTION_IF_NULL(kernel_graph);
  176. auto optimizer = std::make_shared<opt::GraphOptimizer>();
  177. auto pm = std::make_shared<opt::PassManager>();
  178. pm->AddPass(std::make_shared<opt::BatchNormReluFusion>());
  179. pm->AddPass(std::make_shared<opt::BatchNormReluGradFusion>());
  180. pm->AddPass(std::make_shared<opt::BatchNormAddReluFusion>());
  181. pm->AddPass(std::make_shared<opt::PostBatchNormAddReluFusion>());
  182. pm->AddPass(std::make_shared<opt::BatchNormAddReluGradFusion>());
  183. pm->AddPass(std::make_shared<opt::InsertFormatTransformOp>());
  184. pm->AddPass(std::make_shared<opt::RemoveFormatTransformPair>());
  185. pm->AddPass(std::make_shared<opt::RemoveRedundantFormatTransform>());
  186. // Remove node only used by UpdateState, in order to ensure the correct execution sequence in CudnnInplaceAggregate.
  187. pm->AddPass(std::make_shared<opt::OptimizeUpdateState>());
  188. pm->AddPass(std::make_shared<opt::CudnnInplaceAggregate>());
  189. pm->AddPass(std::make_shared<opt::ReluV2Pass>());
  190. pm->AddPass(std::make_shared<opt::AddReluV2Fusion>());
  191. pm->AddPass(std::make_shared<opt::AddReluGradV2Fusion>());
  192. pm->AddPass(std::make_shared<opt::AllReduceFusion>());
  193. pm->AddPass(std::make_shared<opt::AdjustDependForParallelOptimizerRecomputeAllGatherFusion>(
  194. "adjust_depend_for_parallel_optimizer_recompute_all_gather_fusion"));
  195. pm->AddPass(std::make_shared<opt::AllGatherFusion>());
  196. pm->AddPass(std::make_shared<opt::ConcatOutputsForAllGather>());
  197. pm->AddPass(std::make_shared<opt::GetitemTuple>());
  198. pm->AddPass(std::make_shared<opt::ReducePrecisionFusion>("reduce_precision"));
  199. optimizer->AddPassManager(pm);
  200. (void)optimizer->Optimize(kernel_graph);
  201. kernel_graph->SetExecOrderByDefault();
  202. }
  203. void GPUSession::RunOpOptimize(const std::shared_ptr<KernelGraph> &kernel_graph) {
  204. MS_EXCEPTION_IF_NULL(kernel_graph);
  205. auto optimizer = std::make_shared<opt::GraphOptimizer>();
  206. auto pm = std::make_shared<opt::PassManager>();
  207. pm->AddPass(std::make_shared<opt::BCEWithLogitsLossFusion>());
  208. pm->AddPass(std::make_shared<opt::InsertCastGPU>("insert_cast_gpu"));
  209. optimizer->AddPassManager(pm);
  210. (void)optimizer->Optimize(kernel_graph);
  211. kernel_graph->SetExecOrderByDefault();
  212. }
  213. void GPUSession::RunOpHardwareOptimize(const std::shared_ptr<KernelGraph> &kernel_graph) {
  214. MS_EXCEPTION_IF_NULL(kernel_graph);
  215. auto optimizer = std::make_shared<opt::GraphOptimizer>();
  216. auto pm = std::make_shared<opt::PassManager>();
  217. pm->AddPass(std::make_shared<opt::ReducePrecisionFusion>("reduce_precision"));
  218. optimizer->AddPassManager(pm);
  219. (void)optimizer->Optimize(kernel_graph);
  220. kernel_graph->SetExecOrderByDefault();
  221. }
  222. void GPUSession::GraphKernelOptimize(const std::shared_ptr<KernelGraph> &kernel_graph) {
  223. if (!graphkernel::GraphKernelFlags::GetInstance().IsEnableGraphKernel()) {
  224. return;
  225. }
  226. graphkernel::GraphKernelOptimize(kernel_graph);
  227. kernel_graph->SetExecOrderByDefault();
  228. }
  229. void GPUSession::AssignStream(const std::shared_ptr<KernelGraph> &kernel_graph) {
  230. MS_EXCEPTION_IF_NULL(kernel_graph);
  231. device::gpu::AssignGpuStream(kernel_graph);
  232. }
  233. void GPUSession::BuildKernel(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  234. auto kernels = kernel_graph->execution_order();
  235. device::gpu::CreateGPUKernel(kernels);
  236. }
  237. void GPUSession::AllocateMemory(const KernelGraph *kernel_graph) const {
  238. MS_EXCEPTION_IF_NULL(kernel_graph);
  239. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  240. MS_EXCEPTION_IF_NULL(runtime_instance);
  241. runtime_instance->AssignMemory(*kernel_graph);
  242. }
  243. void GPUSession::RunOpAllocateMemory(const std::vector<tensor::TensorPtr> &input_tensors,
  244. const KernelGraph *kernel_graph) const {
  245. MS_EXCEPTION_IF_NULL(kernel_graph);
  246. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  247. MS_EXCEPTION_IF_NULL(runtime_instance);
  248. runtime_instance->RunOpAssignMemory(input_tensors, *kernel_graph);
  249. }
  250. void GPUSession::RunOpGenKernelEvent(const KernelGraph *graph) const {
  251. MS_EXCEPTION_IF_NULL(graph);
  252. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  253. MS_EXCEPTION_IF_NULL(runtime_instance);
  254. runtime_instance->GenKernelEvents(*graph);
  255. }
  256. void GPUSession::RunOpClearMemory(const KernelGraph *kernel_graph) const {
  257. MS_EXCEPTION_IF_NULL(kernel_graph);
  258. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  259. MS_EXCEPTION_IF_NULL(runtime_instance);
  260. runtime_instance->RunOpClearMemory(*kernel_graph);
  261. }
  262. namespace {
  263. constexpr auto kAssignInputSize = 3;
  264. constexpr auto kAssignUpdateIndex = 1;
  265. bool UpdatedByAssign(const KernelGraphPtr &kernel_graph, const AnfNodePtr &node) {
  266. MS_EXCEPTION_IF_NULL(kernel_graph);
  267. auto manager = kernel_graph->manager();
  268. if (manager == nullptr) {
  269. return false;
  270. }
  271. auto &node_users = manager->node_users();
  272. auto iter = node_users.find(node);
  273. if (iter == node_users.end()) {
  274. return false;
  275. }
  276. auto &users = iter->second;
  277. return std::any_of(users.begin(), users.end(), [](const std::pair<AnfNodePtr, int64_t> &user) {
  278. MS_EXCEPTION_IF_NULL(user.first);
  279. auto output_cnode = user.first->cast<CNodePtr>();
  280. return output_cnode != nullptr && IsPrimitiveCNode(output_cnode, prim::kPrimAssign) &&
  281. user.second == kAssignUpdateIndex && output_cnode->inputs().size() > kAssignInputSize;
  282. });
  283. }
  284. size_t UpdateGraphInputAbstract(const AnfNodePtr input_node, const tensor::TensorPtr tensor) {
  285. MS_EXCEPTION_IF_NULL(input_node);
  286. MS_EXCEPTION_IF_NULL(tensor);
  287. size_t size = LongToSize(tensor->data().nbytes());
  288. if (!input_node->isa<Parameter>()) {
  289. return size;
  290. }
  291. auto input_param = input_node->cast<ParameterPtr>();
  292. if (input_param != nullptr && input_param->has_dynamic_shape()) {
  293. auto tensor_shape = tensor->shape();
  294. std::vector<size_t> shape_tmp;
  295. (void)std::transform(tensor_shape.begin(), tensor_shape.end(), std::back_inserter(shape_tmp), IntToSize);
  296. AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(input_node, 0)}, {shape_tmp},
  297. input_node.get());
  298. size = abstract::ShapeSize(shape_tmp) * abstract::TypeIdSize(tensor->data_type());
  299. }
  300. return size;
  301. }
  302. bool CheckIfNeedSync(const tensor::TensorPtr &tensor, const DeviceAddressPtr &device_address,
  303. const ParameterPtr &pk_node) {
  304. MS_EXCEPTION_IF_NULL(tensor);
  305. MS_EXCEPTION_IF_NULL(pk_node);
  306. auto tensor_address = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address());
  307. bool need_sync = false;
  308. auto ms_context = MsContext::GetInstance();
  309. MS_EXCEPTION_IF_NULL(ms_context);
  310. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER)) {
  311. if (tensor_address == nullptr || tensor_address != device_address) {
  312. need_sync = true;
  313. }
  314. } else if (tensor->NeedSyncHostToDevice() || tensor_address == nullptr) {
  315. need_sync = true;
  316. } else if (tensor_address != device_address) {
  317. if (tensor_address->DeviceType() == device_address->DeviceType()) {
  318. AnfAlgo::SetOutputAddr(tensor_address, 0, pk_node.get());
  319. } else {
  320. need_sync = true;
  321. }
  322. }
  323. return need_sync;
  324. }
  325. } // namespace
  326. void GPUSession::LoadInputData(const std::shared_ptr<KernelGraph> &kernel_graph,
  327. const std::vector<tensor::TensorPtr> &inputs_const) const {
  328. std::vector<tensor::TensorPtr> inputs(inputs_const);
  329. MS_EXCEPTION_IF_NULL(kernel_graph);
  330. auto &input_nodes = kernel_graph->input_nodes();
  331. auto ms_context = MsContext::GetInstance();
  332. MS_EXCEPTION_IF_NULL(ms_context);
  333. if (inputs.size() != input_nodes.size()) {
  334. MS_LOG(EXCEPTION) << "Tensor input:" << inputs.size() << " is not equal graph inputs:" << input_nodes.size();
  335. }
  336. for (size_t i = 0; i < inputs.size(); ++i) {
  337. auto tensor = inputs[i];
  338. MS_EXCEPTION_IF_NULL(tensor);
  339. auto input_node = input_nodes[i];
  340. MS_EXCEPTION_IF_NULL(input_node);
  341. if (input_node->isa<Parameter>() && AnfAlgo::OutputAddrExist(input_node, 0)) {
  342. #if ENABLE_CPU && ENABLE_GPU
  343. const std::string &param_name = input_node->fullname_with_scope();
  344. if (ps::ps_cache_instance.IsHashTable(param_name)) {
  345. continue;
  346. }
  347. #endif
  348. auto pk_node = input_node->cast<ParameterPtr>();
  349. auto device_address = AnfAlgo::GetMutableOutputAddr(pk_node, 0);
  350. MS_EXCEPTION_IF_NULL(device_address);
  351. bool need_sync = CheckIfNeedSync(tensor, device_address, pk_node);
  352. if (need_sync) {
  353. if (AnfAlgo::IsParameterWeight(pk_node) || UpdatedByAssign(kernel_graph, input_node) ||
  354. ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode) {
  355. tensor->set_device_address(device_address);
  356. }
  357. auto size = UpdateGraphInputAbstract(input_node, tensor);
  358. if (!device_address->SyncHostToDevice(trans::GetRuntimePaddingShape(pk_node, 0), size, tensor->data_type(),
  359. tensor->data_c())) {
  360. MS_LOG(EXCEPTION) << "SyncHostToDevice failed.";
  361. }
  362. if (kernel_graph->IsUpdatedParameter(pk_node)) {
  363. tensor->SetIsUpdateByDevice();
  364. }
  365. }
  366. }
  367. tensor->set_sync_status(kNoNeedSync);
  368. }
  369. }
  370. GraphId GPUSession::CompileGraphImpl(const AnfNodePtrList &lst, const AnfNodePtrList &outputs) {
  371. // Construct graph, if successfully, graph_sum_ + 1
  372. auto graph = ConstructKernelGraph(lst, outputs);
  373. MS_EXCEPTION_IF_NULL(graph);
  374. return CompileGraphImpl(graph);
  375. }
  376. GraphId GPUSession::CompileGraphImpl(NotNull<FuncGraphPtr> func_graph) {
  377. std::vector<KernelGraphPtr> all_graphs;
  378. auto root_graph = ConstructKernelGraph(func_graph, &all_graphs);
  379. MS_EXCEPTION_IF_NULL(root_graph);
  380. if (all_graphs.size() != 1) {
  381. MS_LOG(EXCEPTION) << "Gpu backend does not support multi-graph schedule, graph num is " << all_graphs.size();
  382. }
  383. // Insert maketuple graph output in case of multi-outputs.
  384. // The ConvertTupleOutputToMaketuple pass will insert TupleGetItem.
  385. AnfAlgo::InsertMakeTupleForOutput(NOT_NULL(root_graph));
  386. opt::BackendCommonOptimization(root_graph);
  387. return CompileGraphImpl(root_graph);
  388. }
  389. GraphId GPUSession::CompileGraphImpl(const KernelGraphPtr &graph) {
  390. MS_EXCEPTION_IF_NULL(graph);
  391. // Prepare ms context info for dump .pb graph
  392. auto context_ptr = MsContext::GetInstance();
  393. MS_EXCEPTION_IF_NULL(context_ptr);
  394. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  395. MS_EXCEPTION_IF_NULL(runtime_instance);
  396. #ifndef ENABLE_SECURITY
  397. auto &json_parser = DumpJsonParser::GetInstance();
  398. json_parser.Parse();
  399. #endif
  400. #ifdef ENABLE_DUMP_IR
  401. bool save_graphs = context_ptr->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG);
  402. // Dump .pb graph before graph optimization
  403. if (save_graphs) {
  404. DumpIRProto(graph, "before_opt_" + std::to_string(graph->graph_id()));
  405. }
  406. #endif
  407. // Graph optimization irrelevant to device data format
  408. Optimize(graph);
  409. // Select kernel build info
  410. SelectKernel(graph);
  411. // Graph optimization relevant to device data format
  412. HardwareOptimize(graph);
  413. // Run final optimization
  414. FinalOptimize(graph);
  415. // Graph kernel fusion optimization
  416. GraphKernelOptimize(graph);
  417. // Start gpu kernel runtime
  418. StartKernelRT();
  419. #if ENABLE_CPU && ENABLE_GPU
  420. InitPsWorker(graph);
  421. #endif
  422. // Assign CUDA streams
  423. AssignStream(graph);
  424. #ifdef ENABLE_DUMP_IR
  425. // Dump .pb graph before remove nop nodes
  426. if (save_graphs) {
  427. DumpIRProto(graph, "before_removeNop_" + std::to_string(graph->graph_id()));
  428. }
  429. #endif
  430. opt::AddDynamicShapeAttrPass(graph);
  431. const bool pynative_mode = context_ptr->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode;
  432. // Hide NopOp from execution graph in graph mode
  433. if (!pynative_mode) {
  434. opt::HideNopNode(graph.get());
  435. }
  436. // Build kernel if node is cnode
  437. BuildKernel(graph);
  438. #ifdef ENABLE_DUMP_IR
  439. std::string name = "graph_build";
  440. DumpGraphParams dump_params = {true, static_cast<int>(kWholeStack)};
  441. (void)mindspore::RDR::RecordAnfGraph(SubModuleId::SM_SESSION, name, graph, dump_params, ".ir,.pb");
  442. auto &kernels = graph->execution_order();
  443. std::string exec_order_name = "graph_exec_order." + std::to_string(graph->graph_id());
  444. (void)mindspore::RDR::RecordGraphExecOrder(SubModuleId::SM_SESSION, exec_order_name, kernels);
  445. #endif
  446. #ifndef ENABLE_SECURITY
  447. // Get summary nodes.
  448. SetSummaryNodes(graph.get());
  449. #endif
  450. // Dump .pb graph after graph optimization
  451. #ifdef ENABLE_DUMP_IR
  452. if (save_graphs) {
  453. DumpIRProto(graph, "after_opt_" + std::to_string(graph->graph_id()));
  454. }
  455. #endif
  456. #ifndef ENABLE_SECURITY
  457. if (json_parser.e2e_dump_enabled()) {
  458. graph->set_root_graph_id(graph->graph_id());
  459. std::string final_graph = "trace_code_graph_" + std::to_string(graph->graph_id());
  460. std::string root_dir = json_parser.path() + "/rank_" + std::to_string(rank_id_);
  461. std::string target_dir = root_dir + "/graphs";
  462. std::string ir_file_path = target_dir + "/" + "ms_output_" + final_graph + ".ir";
  463. DumpIRProtoWithSrcInfo(graph, final_graph, target_dir, kDebugWholeStack);
  464. DumpIR("trace_code_graph", graph, true, kWholeStack, ir_file_path);
  465. DumpGraphExeOrder("ms_execution_order_graph_" + std::to_string(graph->graph_id()) + ".csv", root_dir,
  466. graph->execution_order());
  467. }
  468. #endif
  469. // Set graph manager.
  470. MS_EXCEPTION_IF_NULL(context_);
  471. FuncGraphManagerPtr manager = MakeManager({graph});
  472. context_->AddManager(manager);
  473. if (manager) {
  474. manager->AddFuncGraph(graph);
  475. graph->set_manager(manager);
  476. }
  477. InitAllBucket(graph);
  478. // Alloc memory in graph mode, including static memory and dynamic memory
  479. if (!pynative_mode) {
  480. AllocateMemory(graph.get());
  481. }
  482. DumpGraph(graph);
  483. #ifdef ENABLE_DEBUGGER
  484. if (debugger_ && debugger_->DebuggerBackendEnabled()) {
  485. debugger_->LoadGraphs(graph);
  486. }
  487. #endif
  488. MS_LOG(INFO) << "CompileGraph graph_id: " << graph->graph_id();
  489. return graph->graph_id();
  490. }
  491. void GPUSession::PreExecuteGraph(const std::shared_ptr<KernelGraph> &kernel_graph,
  492. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  493. #ifdef ENABLE_DEBUGGER
  494. if (debugger_) {
  495. debugger_->PreExecute(kernel_graph);
  496. }
  497. DumpSetup(kernel_graph);
  498. #endif
  499. #if ENABLE_CPU && ENABLE_GPU
  500. // Initialize parameter server
  501. InitPSParamAndOptim(kernel_graph, inputs);
  502. #endif
  503. }
  504. void GPUSession::PostExecuteGraph(const std::shared_ptr<KernelGraph> &kernel_graph,
  505. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  506. // Summary
  507. auto context_ptr = MsContext::GetInstance();
  508. MS_EXCEPTION_IF_NULL(context_ptr);
  509. #ifndef ENABLE_SECURITY
  510. if (context_ptr->get_param<bool>(MS_CTX_ENABLE_GPU_SUMMARY)) {
  511. Summary(kernel_graph.get());
  512. }
  513. #endif
  514. #ifdef ENABLE_DEBUGGER
  515. if (debugger_ && debugger_->DebuggerBackendEnabled()) {
  516. debugger_->LoadParametersAndConst(kernel_graph);
  517. }
  518. // debug used for dump
  519. if (debugger_ && debugger_->CheckDebuggerDumpEnabled()) {
  520. Dump(kernel_graph);
  521. }
  522. if (debugger_) {
  523. debugger_->PostExecute();
  524. }
  525. #endif
  526. }
  527. void GPUSession::ExecuteGraph(const std::shared_ptr<KernelGraph> &kernel_graph) {
  528. int kernel_num = kernel_graph->execution_order().size();
  529. int64_t loopsize = (kernel_num > 1) ? ConfigManager::GetInstance().gpu_loopsink_size() : 1;
  530. for (int64_t i = 0; i < loopsize; i++) {
  531. #if ENABLE_CPU && ENABLE_GPU
  532. std::string channel_name;
  533. if (ps::PsDataPrefetch::GetInstance().cache_enable() && IsGetNextGraph(kernel_graph, &channel_name)) {
  534. ps::ps_cache_instance.IncreaseGraphStep(channel_name);
  535. }
  536. #endif
  537. Execute(kernel_graph);
  538. }
  539. }
  540. void GPUSession::UpdateOutputTensors(const VectorRef *outputs,
  541. const std::map<tensor::TensorPtr, session::KernelWithIndex> &tensor_to_node,
  542. std::map<DeviceAddressPtr, DeviceAddressPtr> *new_to_old_device_address) {
  543. MS_EXCEPTION_IF_NULL(outputs);
  544. for (const auto &item : *outputs) {
  545. if (utils::isa<VectorRefPtr>(item)) {
  546. const auto &vector_ref = utils::cast<VectorRef>(item);
  547. UpdateOutputTensors(&vector_ref, tensor_to_node, new_to_old_device_address);
  548. } else if (utils::isa<tensor::TensorPtr>(item)) {
  549. const auto &tensor = utils::cast<tensor::TensorPtr>(item);
  550. MS_EXCEPTION_IF_NULL(tensor);
  551. const auto &iter = tensor_to_node.find(tensor);
  552. if (iter != tensor_to_node.end()) {
  553. const auto &node = iter->second.first;
  554. const auto &output_index = iter->second.second;
  555. MS_EXCEPTION_IF_NULL(node);
  556. // When the parameter does not have a user in the graph and is used as an output, the device address is null,
  557. // and there is no need to set the device address for tensor.
  558. if (!AnfAlgo::OutputAddrExist(node, output_index, true)) {
  559. continue;
  560. }
  561. auto address = AnfAlgo::GetMutableOutputAddr(node, output_index);
  562. // The outputs may have the same tensor, so need skip when the tensor has been set to device address.
  563. if ((address == nullptr) || (address->GetPtr() == nullptr)) {
  564. // If the device address in the node is invalid, you need to find out whether there is a corresponding
  565. // device address in the new to old device address map to check whether the device address in the node
  566. // has been replaced with a new one.
  567. if ((*new_to_old_device_address).find(address) != (*new_to_old_device_address).end()) {
  568. address = (*new_to_old_device_address)[address];
  569. } else {
  570. continue;
  571. }
  572. }
  573. tensor->set_device_address(address);
  574. // When the device address of graph cnode output is set in tensor, the graph output need be set new device
  575. // address, to avoid that the device address context of tensor be rewritten in the next step or next loop.
  576. // But one time memory application scenarios need to be skipped, because the memory is not allocated next step:
  577. // 1. Non cnode 2. Communication kernel.
  578. bool ps_mode = false;
  579. #if ((defined ENABLE_CPU) && (!defined _WIN32))
  580. ps_mode = ps::PSContext::instance()->is_ps_mode();
  581. #endif
  582. if (node->isa<CNode>() && !AnfAlgo::IsCommunicationOp(node) && !ps_mode) {
  583. auto new_address = std::make_shared<device::gpu::GPUDeviceAddress>(nullptr, address->GetSize());
  584. AnfAlgo::SetOutputAddr(new_address, output_index, node.get());
  585. (*new_to_old_device_address)[new_address] = address;
  586. if (graphkernel::GraphKernelFlags::GetInstance().IsEnableGraphKernel()) {
  587. auto runtime_instance =
  588. device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  589. MS_EXCEPTION_IF_NULL(runtime_instance);
  590. auto gpu_runtime_instance = dynamic_cast<device::gpu::GPUKernelRuntime *>(runtime_instance);
  591. gpu_runtime_instance->SetAddrInvalid(address);
  592. }
  593. }
  594. if (AnfAlgo::IsDynamicShape(node)) {
  595. const auto &updated_shape = AnfAlgo::GetOutputInferShape(node, output_index);
  596. ShapeVector int_shape;
  597. std::transform(updated_shape.begin(), updated_shape.end(), std::back_inserter(int_shape), SizeToInt);
  598. tensor->set_shape(int_shape);
  599. }
  600. }
  601. if (tensor->NeedSyncDeviceToHostImmediately()) {
  602. tensor->data_sync(false);
  603. tensor->set_device_address(nullptr);
  604. tensor->set_sync_status(kNeedSyncHostToDevice);
  605. }
  606. }
  607. }
  608. }
  609. void GPUSession::Execute(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  610. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  611. MS_EXCEPTION_IF_NULL(runtime_instance);
  612. if (!runtime_instance->Run(*kernel_graph, false)) {
  613. MS_LOG(EXCEPTION) << "GPU execute graph failed!";
  614. }
  615. }
  616. KernelGraphPtr GPUSession::BuildOpImpl(const OpRunInfo &op_run_info, const GraphInfo &graph_info,
  617. const std::vector<tensor::TensorPtr> &input_tensors,
  618. const std::vector<int64_t> &tensors_mask) {
  619. // Check if the graph cache exists.
  620. auto it = run_op_graphs_.find(graph_info);
  621. if (it != run_op_graphs_.end() && kOpCacheBlackList.find(op_run_info.op_name) == kOpCacheBlackList.end()) {
  622. return it->second;
  623. }
  624. // Prepare the graph
  625. const auto &kernel_graph = ConstructSingleOpGraph(op_run_info, input_tensors, tensors_mask);
  626. MS_EXCEPTION_IF_NULL(kernel_graph);
  627. RunOpOptimize(kernel_graph);
  628. SelectKernel(kernel_graph);
  629. RunOpHardwareOptimize(kernel_graph);
  630. StartKernelRT();
  631. RunOpHideNopNode(kernel_graph);
  632. BuildKernel(kernel_graph);
  633. auto enable_op_graph_cache = MsContext::GetInstance()->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_OP_GRAPH_CACHE);
  634. if (enable_op_graph_cache) {
  635. run_op_graphs_[graph_info] = kernel_graph;
  636. }
  637. return kernel_graph;
  638. }
  639. void GPUSession::RunOpImplOrigin(const GraphInfo &graph_info, OpRunInfo *op_run_info,
  640. std::vector<tensor::TensorPtr> *input_tensors, VectorRef *outputs,
  641. const std::vector<int64_t> &tensors_mask) {
  642. RunOpImpl(graph_info, op_run_info, input_tensors, outputs, tensors_mask);
  643. }
  644. void GPUSession::RunOpImpl(const GraphInfo &graph_info, OpRunInfo *op_run_info,
  645. std::vector<tensor::TensorPtr> *input_tensors, VectorRef *outputs,
  646. const std::vector<int64_t> &tensors_mask) {
  647. MS_EXCEPTION_IF_NULL(input_tensors);
  648. MS_EXCEPTION_IF_NULL(op_run_info);
  649. ProcessInputTensorsForHeterogeneous("GPU", *input_tensors);
  650. const auto &kernel_graph = BuildOpImpl(*op_run_info, graph_info, *input_tensors, tensors_mask);
  651. EraseValueNodeTensor(tensors_mask, input_tensors);
  652. // wait for allreduce
  653. for (auto &tensor : *input_tensors) {
  654. MS_EXCEPTION_IF_NULL(tensor);
  655. if (tensor->NeedWaitDevice()) {
  656. tensor->WaitDevice();
  657. }
  658. }
  659. // run op
  660. MS_EXCEPTION_IF_NULL(kernel_graph);
  661. RunOpRemoveNopNode(kernel_graph);
  662. RunOpAllocateMemory(*input_tensors, kernel_graph.get());
  663. RunOpGenKernelEvent(kernel_graph.get());
  664. // Execute the computation
  665. LoadInputData(kernel_graph, *input_tensors);
  666. Execute(kernel_graph);
  667. // Fetch outputs
  668. std::map<tensor::TensorPtr, session::KernelWithIndex> tensor_to_node;
  669. UpdateOutputs(kernel_graph, outputs, *input_tensors, &tensor_to_node);
  670. // update output abstract of dynamic op to op_run_info
  671. if (op_run_info->is_dynamic_shape) {
  672. UpdateOutputAbstract(kernel_graph, op_run_info);
  673. }
  674. RunOpClearMemory(kernel_graph.get());
  675. if (kOpCacheBlackList.find(op_run_info->op_name) != kOpCacheBlackList.end()) {
  676. run_op_graphs_.erase(graph_info);
  677. }
  678. }
  679. #ifdef ENABLE_DEBUGGER
  680. void GPUSession::DumpSetup(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  681. MS_LOG(INFO) << "Start!";
  682. MS_EXCEPTION_IF_NULL(kernel_graph);
  683. E2eDump::DumpSetup(kernel_graph.get());
  684. MS_LOG(INFO) << "Finish!";
  685. }
  686. void GPUSession::Dump(const std::shared_ptr<KernelGraph> &kernel_graph) const {
  687. if (debugger_->DebuggerBackendEnabled()) {
  688. MS_EXCEPTION_IF_NULL(kernel_graph);
  689. E2eDump::DumpRunIter(kernel_graph, rank_id_);
  690. E2eDump::DumpData(kernel_graph.get(), rank_id_, debugger_.get());
  691. } else {
  692. DumpJsonParser::GetInstance().UpdateDumpIter();
  693. }
  694. }
  695. bool GPUSession::DumpDataEnabledIteration() const {
  696. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  697. MS_EXCEPTION_IF_NULL(runtime_instance);
  698. return runtime_instance->DumpDataEnabledIteration();
  699. }
  700. #endif
  701. void GPUSession::SyncStream() const {
  702. auto runtime_instance = device::KernelRuntimeManager::Instance().GetSingleKernelRuntime(kGPUDevice, device_id_);
  703. MS_EXCEPTION_IF_NULL(runtime_instance);
  704. auto ret = runtime_instance->SyncStream();
  705. if (!ret) {
  706. MS_LOG(EXCEPTION) << "Sync stream error!";
  707. }
  708. }
  709. std::shared_ptr<device::Bucket> GPUSession::CreateBucket(uint32_t bucket_id, uint32_t bucket_size) {
  710. auto bucket = std::make_shared<device::gpu::GPUBucket>(bucket_id, bucket_size);
  711. auto kernel_runtime = device::KernelRuntimeManager::Instance().GetCurrentKernelRuntime();
  712. MS_EXCEPTION_IF_NULL(kernel_runtime);
  713. auto compute_stream = kernel_runtime->compute_stream();
  714. auto communication_stream = kernel_runtime->communication_stream();
  715. MS_EXCEPTION_IF_NULL(compute_stream);
  716. MS_EXCEPTION_IF_NULL(communication_stream);
  717. MS_EXCEPTION_IF_NULL(bucket);
  718. bucket->Init({compute_stream}, {communication_stream});
  719. return bucket;
  720. }
  721. } // namespace gpu
  722. } // namespace session
  723. } // namespace mindspore