1 /** 2 * Copyright 2019 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 17 #ifndef MINDSPORE_CCSRC_RUNTIME_DEVICE_KERNEL_RUNTIME_MANAGER_H_ 18 #define MINDSPORE_CCSRC_RUNTIME_DEVICE_KERNEL_RUNTIME_MANAGER_H_ 19 #include <map> 20 #include <memory> 21 #include <string> 22 #include <functional> 23 #include <utility> 24 #include <mutex> 25 #include <unordered_set> 26 #include <vector> 27 #include "utils/ms_utils.h" 28 #include "runtime/device/kernel_runtime.h" 29 #include "include/backend/visible.h" 30 31 namespace mindspore { 32 namespace device { 33 using KernelRuntimeCreator = std::function<std::shared_ptr<KernelRuntime>()>; 34 35 class BACKEND_EXPORT KernelRuntimeManager { 36 public: 37 static KernelRuntimeManager &Instance(); 38 void Register(const std::string &device_name, KernelRuntimeCreator &&runtime_creator) const; 39 void Clear(); 40 KernelRuntime *GetKernelRuntime(const std::string &device_name, uint32_t device_id); 41 KernelRuntime *GetCurrentKernelRuntime(); 42 KernelRuntime *GetSingleKernelRuntime(const std::string &device_name, uint32_t device_id); 43 void ReleaseKernelRuntime(const std::string &device_name, uint32_t device_id); 44 void ClearRuntimeResource(); 45 void ClearGraphResource(uint32_t graph_id); 46 void WaitTaskFinishOnDevice() const; 47 48 private: 49 KernelRuntimeManager() = default; 50 ~KernelRuntimeManager() = default; 51 DISABLE_COPY_AND_ASSIGN(KernelRuntimeManager); 52 std::string GetDeviceKey(const std::string &device_name, uint32_t device_id) const; 53 inline static std::map<std::string, std::shared_ptr<KernelRuntime> > runtime_map_; 54 inline static std::map<std::string, KernelRuntimeCreator> runtime_creators_; 55 std::mutex lock_; 56 }; 57 58 class KernelRuntimeRegistrar { 59 public: KernelRuntimeRegistrar(const std::string & device_name,KernelRuntimeCreator && runtime_creator)60 KernelRuntimeRegistrar(const std::string &device_name, KernelRuntimeCreator &&runtime_creator) { 61 KernelRuntimeManager::Instance().Register(device_name, std::move(runtime_creator)); 62 } 63 ~KernelRuntimeRegistrar() = default; 64 }; 65 66 #define MS_REG_KERNEL_RUNTIME(DEVICE_NAME, RUNTIME_CLASS) \ 67 static const KernelRuntimeRegistrar g_kernel_runtime_##DEVICE_NAME##_reg( \ 68 DEVICE_NAME, []() { return std::make_shared<RUNTIME_CLASS>(); }); 69 } // namespace device 70 } // namespace mindspore 71 #endif // MINDSPORE_CCSRC_RUNTIME_DEVICE_KERNEL_RUNTIME_MANAGER_H_ 72