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.

utils.py 4.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import os
  2. import sys
  3. import __main__
  4. from functools import wraps
  5. from inspect import ismethod
  6. from copy import deepcopy
  7. from io import StringIO
  8. import time
  9. import numpy as np
  10. from fastNLP.core.utils.utils import get_class_that_defined_method
  11. from fastNLP.envs.env import FASTNLP_GLOBAL_RANK
  12. from fastNLP.core.drivers.utils import distributed_open_proc
  13. from fastNLP.core.log import logger
  14. def recover_logger(fn):
  15. @wraps(fn)
  16. def wrapper(*args, **kwargs):
  17. # 保存logger的状态
  18. handlers = [handler for handler in logger.handlers]
  19. level = logger.level
  20. res = fn(*args, **kwargs)
  21. logger.handlers = handlers
  22. logger.setLevel(level)
  23. return res
  24. return wrapper
  25. def magic_argv_env_context(fn):
  26. @wraps(fn)
  27. def wrapper(*args, **kwargs):
  28. command = deepcopy(sys.argv)
  29. env = deepcopy(os.environ.copy())
  30. used_args = []
  31. for each_arg in sys.argv[1:]:
  32. if "test" not in each_arg:
  33. used_args.append(each_arg)
  34. pytest_current_test = os.environ.get('PYTEST_CURRENT_TEST')
  35. try:
  36. l_index = pytest_current_test.index("[")
  37. r_index = pytest_current_test.index("]")
  38. subtest = pytest_current_test[l_index: r_index + 1]
  39. except:
  40. subtest = ""
  41. if not ismethod(fn) and get_class_that_defined_method(fn) is None:
  42. sys.argv = [sys.argv[0], f"{os.path.abspath(sys.modules[fn.__module__].__file__)}::{fn.__name__}{subtest}"] + used_args
  43. else:
  44. sys.argv = [sys.argv[0], f"{os.path.abspath(sys.modules[fn.__module__].__file__)}::{get_class_that_defined_method(fn).__name__}::{fn.__name__}{subtest}"] + used_args
  45. res = fn(*args, **kwargs)
  46. sys.argv = deepcopy(command)
  47. os.environ = env
  48. return res
  49. return wrapper
  50. class Capturing(list):
  51. # 用来捕获当前环境中的stdout和stderr,会将其中stderr的输出拼接在stdout的输出后面
  52. """
  53. 使用例子
  54. with Capturing() as output:
  55. do_something
  56. assert 'xxx' in output[0]
  57. """
  58. def __init__(self, no_del=False):
  59. # 如果no_del为True,则不会删除_stringio,和_stringioerr
  60. super().__init__()
  61. self.no_del = no_del
  62. def __enter__(self):
  63. self._stdout = sys.stdout
  64. self._stderr = sys.stderr
  65. sys.stdout = self._stringio = StringIO()
  66. sys.stderr = self._stringioerr = StringIO()
  67. return self
  68. def __exit__(self, *args):
  69. self.append(self._stringio.getvalue() + self._stringioerr.getvalue())
  70. if not self.no_del:
  71. del self._stringio, self._stringioerr # free up some memory
  72. sys.stdout = self._stdout
  73. sys.stderr = self._stderr
  74. def re_run_current_cmd_for_torch(num_procs, output_from_new_proc='ignore'):
  75. # Script called as `python a/b/c.py`
  76. if int(os.environ.get('LOCAL_RANK', '0')) == 0:
  77. if __main__.__spec__ is None: # pragma: no-cover
  78. # pull out the commands used to run the script and resolve the abs file path
  79. command = sys.argv
  80. command[0] = os.path.abspath(command[0])
  81. # use the same python interpreter and actually running
  82. command = [sys.executable] + command
  83. # Script called as `python -m a.b.c`
  84. else:
  85. command = [sys.executable, "-m", __main__.__spec__._name] + sys.argv[1:]
  86. for rank in range(1, num_procs+1):
  87. env_copy = os.environ.copy()
  88. env_copy["LOCAL_RANK"] = f"{rank}"
  89. env_copy['WOLRD_SIZE'] = f'{num_procs+1}'
  90. env_copy['RANK'] = f'{rank}'
  91. # 如果是多机,一定需要用户自己拉起,因此我们自己使用 open_subprocesses 开启的进程的 FASTNLP_GLOBAL_RANK 一定是 LOCAL_RANK;
  92. env_copy[FASTNLP_GLOBAL_RANK] = str(rank)
  93. proc = distributed_open_proc(output_from_new_proc, command, env_copy, None)
  94. delay = np.random.uniform(1, 5, 1)[0]
  95. time.sleep(delay)