diff --git a/CHANGELOG.md b/CHANGELOG.md index 7963027..ae89cc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ under Unreleased and move into a version section at release time. ## Unreleased +### Fixed + +- Enabling the `huggingface` hub no longer imports unused transformers model + modules. To find references to `hf_hub_download` and `snapshot_download`, + the hub tracker looked up the name on every loaded module, and transformers' + lazy modules import code on lookup. With transformers loaded this imported + about 140 extra modules, took about 0.15 s and logged about 430 "failed to + patch" debug lines. The tracker now reads each module's namespace instead. + ## 0.3.0 - 2026-10-21 ### Added diff --git a/tests/test_hubs.py b/tests/test_hubs.py index fff52d9..c1c4c37 100644 --- a/tests/test_hubs.py +++ b/tests/test_hubs.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import sys import types from unittest.mock import patch @@ -188,3 +189,35 @@ def test_hf_tracker_drain_returns_and_clears_buffer(monkeypatch): assert result[0]["repo_id"] == "test/model" # Buffer should be cleared assert tracker.drain() == [] + + +class _LazyModule(types.ModuleType): + """Imports on attribute access, like transformers' lazy modules.""" + + def __init__(self, name: str) -> None: + super().__init__(name) + self.lookups: list[str] = [] + + def __getattr__(self, name: str): + self.lookups.append(name) + raise ModuleNotFoundError("No module named 'torchvision'") + + +def test_patch_symbol_references_skips_lazy_attribute_lookup(monkeypatch): + def original(): + pass + + def replacement(): + pass + + eager = types.ModuleType("eager_mod") + eager.hf_hub_download = original + lazy = _LazyModule("lazy_mod") + monkeypatch.setitem(sys.modules, "eager_mod", eager) + monkeypatch.setitem(sys.modules, "lazy_mod", lazy) + + count = hf_mod._patch_symbol_references("hf_hub_download", original, replacement) + + assert count >= 1 + assert eager.hf_hub_download is replacement + assert lazy.lookups == [] diff --git a/wildedge/hubs/huggingface.py b/wildedge/hubs/huggingface.py index 9e72b37..d531ecc 100644 --- a/wildedge/hubs/huggingface.py +++ b/wildedge/hubs/huggingface.py @@ -72,7 +72,16 @@ def _patch_symbol_references(symbol: str, original: object, replacement: object) patched_count = 0 for mod in list(sys.modules.values()): try: - if getattr(mod, symbol, None) is original: + # Read the module dict, not getattr: lazy modules (transformers) + # import submodules on attribute access. A name a lazy module has + # not loaded yet cannot hold a reference to the original. The lazy + # huggingface_hub package resolves names from its submodules on + # each access, so patching those covers `from huggingface_hub import`. + namespace = vars(mod) + except TypeError: + continue + try: + if namespace.get(symbol) is original: setattr(mod, symbol, replacement) patched_count += 1 except Exception as exc: