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.

max_recursion_limit.py 2.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import platform
  10. import resource
  11. import sys
  12. import threading
  13. class AlternativeRecursionLimit:
  14. r"""A reentrant context manager for setting global recursion limits.
  15. """
  16. def __init__(self, new_py_limit):
  17. self.new_py_limit = new_py_limit
  18. self.count = 0
  19. self.lock = threading.Lock()
  20. self.orig_py_limit = 0
  21. self.orig_rlim_stack_soft = 0
  22. self.orig_rlim_stack_hard = 0
  23. def __enter__(self):
  24. with self.lock:
  25. if self.count == 0:
  26. self.orig_py_limit = sys.getrecursionlimit()
  27. (
  28. self.orig_rlim_stack_soft,
  29. self.orig_rlim_stack_hard,
  30. ) = resource.getrlimit(resource.RLIMIT_STACK)
  31. # FIXME: https://bugs.python.org/issue34602, python3 release version
  32. # on Macos always have this issue, not all user install python3 from src
  33. try:
  34. resource.setrlimit(
  35. resource.RLIMIT_STACK,
  36. (self.orig_rlim_stack_hard, self.orig_rlim_stack_hard),
  37. )
  38. except ValueError as exc:
  39. if platform.system() != "Darwin":
  40. raise exc
  41. # increase recursion limit
  42. sys.setrecursionlimit(self.new_py_limit)
  43. self.count += 1
  44. def __exit__(self, type, value, traceback):
  45. with self.lock:
  46. self.count -= 1
  47. if self.count == 0:
  48. sys.setrecursionlimit(self.orig_py_limit)
  49. try:
  50. resource.setrlimit(
  51. resource.RLIMIT_STACK,
  52. (self.orig_rlim_stack_soft, self.orig_rlim_stack_hard),
  53. )
  54. except ValueError as exc:
  55. if platform.system() != "Darwin":
  56. raise exc
  57. _max_recursion_limit_context_manager = AlternativeRecursionLimit(2 ** 31 - 1)
  58. def max_recursion_limit():
  59. r"""Sets recursion limit to the max possible value
  60. """
  61. return _max_recursion_limit_context_manager

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