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