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

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