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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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-2020 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 FunctionHooker;
  17. template <typename TRet, typename... TArgs>
  18. class FunctionHooker<TRet(TArgs...)> {
  19. public:
  20. using FunctionType = thin_function<TRet(TArgs&&...)>;
  21. //Type of hooks. Hook should accept a real function as argument
  22. //and invoke it on an appropriate time
  23. using HookType = thin_function<TRet(FunctionType, TArgs&&...)>;
  24. explicit FunctionHooker(FunctionType* fptr) : m_fptr{fptr} {
  25. m_backup = {nullptr, [](FunctionType*){}};
  26. }
  27. public:
  28. FunctionHooker& apply_hook(HookType&& hook) {
  29. if (!m_backup) {
  30. FunctionType* backup = new FunctionType(*m_fptr);
  31. //Restore hooked function, would be invoked when destructed
  32. std::function<void(FunctionType*)> restorer =
  33. [fptr = m_fptr](FunctionType* bkp) -> void {
  34. *fptr = *bkp;
  35. delete bkp;
  36. };
  37. m_backup = decltype(m_backup)(backup, restorer);
  38. }
  39. //Replace with hooked version
  40. *m_fptr = [func = *m_fptr, hook](TArgs&&... args) -> TRet {
  41. return hook(func, std::forward<TArgs>(args)...);
  42. };
  43. //Convinent for chain call
  44. return *this;
  45. }
  46. private:
  47. FunctionType* m_fptr;
  48. std::unique_ptr<FunctionType, std::function<void(FunctionType*)>> m_backup;
  49. };
  50. //Helps to deduce template args
  51. template <typename TRet, typename... TArgs>
  52. FunctionHooker(thin_function<TRet(TArgs...)>* f)
  53. ->FunctionHooker<TRet(TArgs...)>;
  54. template<typename TSignature>
  55. auto make_shared_hook(thin_function<TSignature>* fptr){
  56. return std::make_shared<FunctionHooker<TSignature>>(fptr);
  57. }
  58. } // namespace imperative
  59. } // namespace mgb

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