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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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 sys
  11. import threading
  12. # Windows do not imp resource package
  13. if platform.system() != "Windows":
  14. import resource
  15. class AlternativeRecursionLimit:
  16. r"""
  17. A reentrant context manager for setting global recursion limits.
  18. """
  19. def __init__(self, new_py_limit):
  20. self.new_py_limit = new_py_limit
  21. self.count = 0
  22. self.lock = threading.Lock()
  23. self.orig_py_limit = 0
  24. self.orig_rlim_stack_soft = 0
  25. self.orig_rlim_stack_hard = 0
  26. def __enter__(self):
  27. with self.lock:
  28. if self.count == 0:
  29. self.orig_py_limit = sys.getrecursionlimit()
  30. if platform.system() != "Windows":
  31. (
  32. self.orig_rlim_stack_soft,
  33. self.orig_rlim_stack_hard,
  34. ) = resource.getrlimit(resource.RLIMIT_STACK)
  35. # FIXME: https://bugs.python.org/issue34602, python3 release version
  36. # on Macos always have this issue, not all user install python3 from src
  37. try:
  38. resource.setrlimit(
  39. resource.RLIMIT_STACK,
  40. (self.orig_rlim_stack_hard, self.orig_rlim_stack_hard),
  41. )
  42. except ValueError as exc:
  43. if platform.system() != "Darwin":
  44. raise exc
  45. # increase recursion limit
  46. sys.setrecursionlimit(self.new_py_limit)
  47. self.count += 1
  48. def __exit__(self, type, value, traceback):
  49. with self.lock:
  50. self.count -= 1
  51. if self.count == 0:
  52. sys.setrecursionlimit(self.orig_py_limit)
  53. if platform.system() != "Windows":
  54. try:
  55. resource.setrlimit(
  56. resource.RLIMIT_STACK,
  57. (self.orig_rlim_stack_soft, self.orig_rlim_stack_hard),
  58. )
  59. except ValueError as exc:
  60. if platform.system() != "Darwin":
  61. raise exc
  62. _max_recursion_limit_context_manager = AlternativeRecursionLimit(2 ** 31 - 1)
  63. def max_recursion_limit():
  64. r"""
  65. Sets recursion limit to the max possible value.
  66. """
  67. return _max_recursion_limit_context_manager

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