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.

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
  2. import importlib
  3. import importlib.util
  4. import logging
  5. import numpy as np
  6. import os
  7. import random
  8. import sys
  9. from datetime import datetime
  10. import torch
  11. __all__ = ["seed_all_rng"]
  12. def seed_all_rng(seed=None):
  13. """
  14. Set the random seed for the RNG in torch, numpy and python.
  15. Args:
  16. seed (int): if None, will use a strong random seed.
  17. """
  18. if seed is None:
  19. seed = (
  20. os.getpid()
  21. + int(datetime.now().strftime("%S%f"))
  22. + int.from_bytes(os.urandom(2), "big")
  23. )
  24. logger = logging.getLogger(__name__)
  25. logger.info("Using a generated random seed {}".format(seed))
  26. np.random.seed(seed)
  27. torch.set_rng_state(torch.manual_seed(seed).get_state())
  28. random.seed(seed)
  29. # from https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
  30. def _import_file(module_name, file_path, make_importable=False):
  31. spec = importlib.util.spec_from_file_location(module_name, file_path)
  32. module = importlib.util.module_from_spec(spec)
  33. spec.loader.exec_module(module)
  34. if make_importable:
  35. sys.modules[module_name] = module
  36. return module
  37. def _configure_libraries():
  38. """
  39. Configurations for some libraries.
  40. """
  41. # An environment option to disable `import cv2` globally,
  42. # in case it leads to negative performance impact
  43. disable_cv2 = int(os.environ.get("DETECTRON2_DISABLE_CV2", False))
  44. if disable_cv2:
  45. sys.modules["cv2"] = None
  46. else:
  47. # Disable opencl in opencv since its interaction with cuda often has negative effects
  48. # This envvar is supported after OpenCV 3.4.0
  49. os.environ["OPENCV_OPENCL_RUNTIME"] = "disabled"
  50. try:
  51. import cv2
  52. if int(cv2.__version__.split(".")[0]) >= 3:
  53. cv2.ocl.setUseOpenCL(False)
  54. except ImportError:
  55. pass
  56. _ENV_SETUP_DONE = False
  57. def setup_environment():
  58. """Perform environment setup work. The default setup is a no-op, but this
  59. function allows the user to specify a Python source file or a module in
  60. the $DETECTRON2_ENV_MODULE environment variable, that performs
  61. custom setup work that may be necessary to their computing environment.
  62. """
  63. global _ENV_SETUP_DONE
  64. if _ENV_SETUP_DONE:
  65. return
  66. _ENV_SETUP_DONE = True
  67. _configure_libraries()
  68. custom_module_path = os.environ.get("DETECTRON2_ENV_MODULE")
  69. if custom_module_path:
  70. setup_custom_environment(custom_module_path)
  71. else:
  72. # The default setup is a no-op
  73. pass
  74. def setup_custom_environment(custom_module):
  75. """
  76. Load custom environment setup by importing a Python source file or a
  77. module, and run the setup function.
  78. """
  79. if custom_module.endswith(".py"):
  80. module = _import_file("detectron2.utils.env.custom_module", custom_module)
  81. else:
  82. module = importlib.import_module(custom_module)
  83. assert hasattr(module, "setup_environment") and callable(module.setup_environment), (
  84. "Custom environment module defined in {} does not have the "
  85. "required callable attribute 'setup_environment'."
  86. ).format(custom_module)
  87. module.setup_environment()

No Description