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.

function_hook.h 1.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * \file imperative/src/include/megbrain/imperative/function_hook.h
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #pragma once
  12. #include "megbrain/utils/thin/function.h"
  13. namespace mgb {
  14. namespace imperative {
  15. template <typename TFunction>
  16. class FunctionHook;
  17. template <template <typename> class TFunction, typename TRet, typename... TArgs>
  18. class FunctionHook<TFunction<TRet(TArgs...)>> {
  19. public:
  20. using FunctionType = TFunction<TRet(TArgs...)>;
  21. explicit FunctionHook(FunctionType* fptr) : m_fptr{fptr} {
  22. m_backup = *fptr;
  23. }
  24. public:
  25. template <typename THook, typename=std::enable_if_t<std::is_invocable_r_v<TRet, THook, FunctionType, TArgs...>, void>>
  26. FunctionHook& apply_hook(THook&& hook) {
  27. //Replace with hooked version
  28. *m_fptr = [func = *m_fptr, hook=std::forward<THook>(hook)](TArgs... args) -> TRet {
  29. return hook(func, std::forward<TArgs>(args)...);
  30. };
  31. //Convinent for chain call
  32. return *this;
  33. }
  34. private:
  35. FunctionType* m_fptr;
  36. FunctionType m_backup;
  37. public:
  38. ~FunctionHook() {
  39. *m_fptr = std::move(m_backup);
  40. }
  41. };
  42. template<typename TFunction>
  43. auto make_shared_hook(TFunction* fptr){
  44. return std::make_shared<FunctionHook<TFunction>>(fptr);
  45. }
  46. } // namespace imperative
  47. } // namespace mgb

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台