Skip to content

Commit f8fb9b3

Browse files
committed
test: clean hf dynamic modules before test setup
1 parent 0c44833 commit f8fb9b3

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

tests/conftest.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import importlib
2+
import os
3+
import sys
4+
from pathlib import Path
5+
6+
from huggingface_hub import constants
7+
8+
9+
_HF_DYNAMIC_MODULE_PREFIX = "transformers_modules"
10+
_HF_PATCH_MODULES_CACHE_PREFIX = "modules_cache"
11+
12+
13+
def _is_hf_dynamic_module_root(path: str) -> bool:
14+
path_obj = Path(path)
15+
hf_home = Path(constants.HF_HOME)
16+
return path_obj.parent == hf_home and (
17+
path_obj.name == "modules" or path_obj.name.startswith(_HF_PATCH_MODULES_CACHE_PREFIX)
18+
)
19+
20+
21+
def _cleanup_hf_dynamic_modules() -> None:
22+
for module_name in tuple(sys.modules):
23+
if module_name == _HF_DYNAMIC_MODULE_PREFIX or module_name.startswith(f"{_HF_DYNAMIC_MODULE_PREFIX}."):
24+
sys.modules.pop(module_name, None)
25+
26+
removed_paths = [path for path in sys.path if _is_hf_dynamic_module_root(path)]
27+
sys.path[:] = [path for path in sys.path if not _is_hf_dynamic_module_root(path)]
28+
for path in removed_paths:
29+
sys.path_importer_cache.pop(path, None)
30+
31+
if _is_hf_dynamic_module_root(os.environ.get("HF_MODULES_CACHE", "")):
32+
os.environ.pop("HF_MODULES_CACHE", None)
33+
34+
default_modules_cache = os.path.join(constants.HF_HOME, "modules")
35+
for module_name in ("transformers.utils.hub", "transformers.utils", "transformers.dynamic_module_utils"):
36+
module = sys.modules.get(module_name)
37+
if module is not None and hasattr(module, "HF_MODULES_CACHE"):
38+
module.HF_MODULES_CACHE = default_modules_cache
39+
40+
importlib.invalidate_caches()
41+
42+
43+
def pytest_runtest_setup(item):
44+
_cleanup_hf_dynamic_modules()

0 commit comments

Comments
 (0)