Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Import: scan installed distributions once while transformers and TRL import (#16189)
Daniel Hana5f1381d6275
diff --git a/scripts/risky_loaders_baseline.json b/scripts/risky_loaders_baseline.jsonindex 8c92d5ff956..004d287fd24 100644--- a/scripts/risky_loaders_baseline.json+++ b/scripts/risky_loaders_baseline.json@@ -306,6 +306,14 @@"count": 1,"reason": "Probes fixed kernel package names (causal_conv1d, mamba_ssm, flash_attn) after installing them."},+ {+ "file": "studio/backend/core/training/worker.py",+ "rule": "dynamic-import",+ "sink": "spec_from_file_location",+ "digest": "18d25a0356adb1dd",+ "count": 1,+ "reason": "Loads _import_metadata_cache.py, a fixed file name, from the installed unsloth package directory (find_spec of the literal 'unsloth'); stdlib only, nothing from a model repo."+ },{"file": "studio/backend/core/training/worker.py","rule": "trust-remote-code",diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex a1f2d4f179b..ac9e09d0ede 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -2112,6 +2112,38 @@ def _rebind_in_already_imported_modules(*, attr_name: str, old_obj: Any, new_obj_TVM_FFI_BROKEN_VERSIONS = ("0.1.10", "0.1.11")+def _install_metadata_scan_cache() -> Any:+ """Share one packages_distributions() scan between transformers and TRL (unsloth's own window+ opens after this worker's first transformers import). Loaded by path: the package would run+ unsloth's whole init. None when the helper is missing (older unsloth) or fails."""+ try:+ spec = importlib.util.find_spec("unsloth")+ for root in list(getattr(spec, "submodule_search_locations", None) or ()):+ path = os.path.join(root, "_import_metadata_cache.py")+ if not os.path.isfile(path):+ continue+ helper_spec = importlib.util.spec_from_file_location(+ "_unsloth_studio_import_metadata_cache", path+ )+ helper = importlib.util.module_from_spec(helper_spec)+ helper_spec.loader.exec_module(helper)+ token = helper.install()+ return None if token is None else (helper, token)+ except Exception:+ pass+ return None+++def _uninstall_metadata_scan_cache(installed: Any) -> None:+ if installed is None:+ return+ helper, token = installed+ try:+ helper.uninstall(token)+ except Exception:+ pass++def _guard_fla_tilelang() -> None:"""Default FLA_TILELANG to 0 on ROCm torch and on an apache-tvm-ffi that faults on sm_100."""try:@@ -3982,6 +4014,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->"true" if sys.platform in ("win32", "darwin") else "false")os.environ["PYTHONWARNINGS"] = "ignore" # before imports+ # Until unsloth is imported below; transformers is first imported well before that.+ metadata_scan_cache = _install_metadata_scan_cache()from utils.security.hub_data_files import install as guard_hub_data_filesfrom utils.security.dataset_media import allow_dataset_repos, install as guard_dataset_media@@ -4659,6 +4693,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->})return+ finally:+ _uninstall_metadata_scan_cache(metadata_scan_cache)if config.get("offload_layers"):from utils.models.diffusion_lm import diffusion_lm_profile_for_modeldiff --git a/studio/backend/tests/test_worker_metadata_scan_cache.py b/studio/backend/tests/test_worker_metadata_scan_cache.pynew file mode 100644index 00000000000..33589005fb3--- /dev/null+++ b/studio/backend/tests/test_worker_metadata_scan_cache.py@@ -0,0 +1,159 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The training worker shares one packages_distributions() scan between transformers and TRL."""++import ast+import json+import os+import shutil+import subprocess+import sys+import textwrap+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parents[1]+_WORKER = _BACKEND / "core" / "training" / "worker.py"+_HELPER = _BACKEND.parents[1] / "unsloth" / "_import_metadata_cache.py"++pytestmark = pytest.mark.skipif(+ sys.version_info < (3, 10), reason = "importlib.metadata.packages_distributions needs Python 3.10"+)+++def _function_source(name):+ tree = ast.parse(_WORKER.read_text(encoding = "utf-8"))+ for node in tree.body:+ if isinstance(node, ast.FunctionDef) and node.name == name:+ return node+ raise AssertionError(f"{name} not found in worker.py")+++_CHILD = textwrap.dedent(+ """+ import ast, importlib.metadata as md, importlib.util, json, os, sys, types+ worker = os.environ["R12_WORKER"]+ tree = ast.parse(open(worker, encoding = "utf-8").read())+ funcs = [n for n in tree.body if isinstance(n, ast.FunctionDef)+ and n.name in ("_install_metadata_scan_cache", "_uninstall_metadata_scan_cache")]+ module = ast.Module(body = funcs, type_ignores = [])+ ns = {"importlib": importlib, "os": os, "Any": object}+ exec(compile(module, worker, "exec"), ns)+ real = md.packages_distributions+ calls = []+ def scan():+ calls.append(1)+ return real()+ md.packages_distributions = scan+ installed = ns["_install_metadata_scan_cache"]()+ wrapped = md.packages_distributions is not scan+ a = md.packages_distributions(); b = md.packages_distributions()+ ns["_uninstall_metadata_scan_cache"](installed)+ print("R12 " + json.dumps({+ "installed": installed is not None, "wrapped": wrapped, "scans": len(calls), "equal": a == b,+ "restored": md.packages_distributions is scan,+ "unsloth_imported": any(m == "unsloth" or m.startswith("unsloth.") for m in sys.modules),+ }))+ """+)+++def _run_child(package_root):+ env = dict(os.environ, R12_WORKER = str(_WORKER))+ env["PYTHONPATH"] = str(package_root)+ result = subprocess.run(+ [sys.executable, "-c", _CHILD],+ env = env,+ cwd = str(package_root),+ capture_output = True,+ text = True,+ timeout = 300,+ )+ lines = [line for line in result.stdout.splitlines() if line.startswith("R12 ")]+ assert lines, (result.returncode, result.stderr[-3000:])+ return json.loads(lines[-1][4:])+++def test_loads_the_helper_by_path_without_importing_unsloth(tmp_path):+ package = tmp_path / "unsloth"+ package.mkdir()+ # An __init__ that would fail loudly if the worker imported the package.+ (package / "__init__.py").write_text(+ "raise RuntimeError('unsloth/__init__.py must not run here')\n"+ )+ shutil.copy(_HELPER, package / "_import_metadata_cache.py")+ report = _run_child(tmp_path)+ assert report == {+ "installed": True,+ "wrapped": True,+ "scans": 1,+ "equal": True,+ "restored": True,+ "unsloth_imported": False,+ }+++def test_older_unsloth_without_the_helper_is_left_alone(tmp_path):+ package = tmp_path / "unsloth"+ package.mkdir()+ (package / "__init__.py").write_text("raise RuntimeError('must not run')\n")+ report = _run_child(tmp_path)+ assert report == {+ "installed": False,+ "wrapped": False,+ "scans": 2,+ "equal": True,+ "restored": True,+ "unsloth_imported": False,+ }+++def test_installed_before_any_ml_import_and_removed_after_unsloth():+ func = _function_source("run_training_process")+ lines = _WORKER.read_text(encoding = "utf-8").splitlines()+ body = lines[func.lineno - 1 : func.end_lineno]+ install = next(i for i, l in enumerate(body) if "_install_metadata_scan_cache()" in l)+ for line in body[:install]:+ if line.strip().startswith("#"):+ continue+ assert (+ "transformers" not in line and "import torch" not in line and "unsloth" not in line+ ), line+ # Nothing before the install calls a helper that imports transformers.+ for helper in ("_install_fast_path_hooks(", "_model_load_security_error("):+ hits = [i for i, l in enumerate(body) if helper in l]+ assert all(i > install for i in hits), helper++ tries = [n for n in ast.walk(func) if isinstance(n, ast.Try)]+ owner = [+ t+ for t in tries+ if any(+ isinstance(n, ast.ImportFrom) and n.module == "core.training.trainer"+ for s in t.body+ for n in ast.walk(s)+ )+ ]+ assert owner, "no try imports core.training.trainer"+ finals = [ast.unparse(s) for s in owner[0].finalbody]+ assert any("_uninstall_metadata_scan_cache(metadata_scan_cache)" in f for f in finals), finals+++def test_a_failing_lookup_returns_none(monkeypatch):+ import importlib.util++ func = _function_source("_install_metadata_scan_cache")+ ns = {"importlib": importlib, "os": os, "Any": object}+ exec(compile(ast.Module(body = [func], type_ignores = []), str(_WORKER), "exec"), ns)++ def boom(name):+ raise ValueError(name)++ monkeypatch.setattr(importlib.util, "find_spec", boom)+ import importlib.metadata as md++ before = md.packages_distributions+ assert ns["_install_metadata_scan_cache"]() is None+ assert md.packages_distributions is beforediff --git a/tests/test_import_metadata_cache.py b/tests/test_import_metadata_cache.pynew file mode 100644index 00000000000..f40b87ce317--- /dev/null+++ b/tests/test_import_metadata_cache.py@@ -0,0 +1,439 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+"""`import unsloth` scans the installed distributions once, not once per library that asks."""++import ast+import importlib.metadata as metadata+import importlib.util+import os+import pathlib+import subprocess+import sys+import textwrap+import threading+import time++import pytest++_UNSLOTH = pathlib.Path(__file__).resolve().parents[1] / "unsloth"+_REPO = _UNSLOTH.parent++pytestmark = pytest.mark.skipif(+ not hasattr(metadata, "packages_distributions"),+ reason = "importlib.metadata.packages_distributions needs Python 3.10",+)+++def _load(name = "_unsloth_import_metadata_cache_under_test"):+ spec = importlib.util.spec_from_file_location(name, _UNSLOTH / "_import_metadata_cache.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def cache_module():+ original = metadata.packages_distributions+ module = _load()+ try:+ yield module+ finally:+ metadata.packages_distributions = original+++def counted(monkeypatch):+ """The real scan, counted; installed before the cache so the cache wraps it."""+ real = metadata.packages_distributions+ calls = []++ def scan():+ calls.append(1)+ return real()++ monkeypatch.setattr(metadata, "packages_distributions", scan)+ return calls+++def _write_dist(site, name, top_level):+ dist_info = site / f"{name}-1.0.dist-info"+ dist_info.mkdir()+ (dist_info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: 1.0\n")+ (dist_info / "top_level.txt").write_text(top_level + "\n")+++def _bump_mtime(path):+ # Some filesystems keep coarse mtimes; force a visible change.+ stat = os.stat(path)+ os.utime(path, ns = (stat.st_atime_ns, stat.st_mtime_ns + 2_000_000_000))+++def test_repeat_call_reuses_the_scan_and_matches_it(cache_module, counted):+ token = cache_module.install()+ first = metadata.packages_distributions()+ second = metadata.packages_distributions()+ assert len(counted) == 1+ cache_module.uninstall(token)+ reference = metadata.packages_distributions()+ assert first == second == reference+ assert list(first) == list(second) == list(reference) # key order too+++def test_callers_get_independent_copies(cache_module, counted):+ cache_module.install()+ first = metadata.packages_distributions()+ key = next(iter(first))+ first[key].append("mutated")+ first["__unsloth_injected__"] = ["x"]+ second = metadata.packages_distributions()+ assert "mutated" not in second[key]+ assert "__unsloth_injected__" not in second+ assert len(counted) == 1+++def test_new_distribution_on_sys_path_is_seen(cache_module, counted, tmp_path, monkeypatch):+ site = tmp_path / "site"+ site.mkdir()+ monkeypatch.syspath_prepend(str(site))+ cache_module.install()+ assert "unsloth_cache_probe_pkg" not in metadata.packages_distributions()+ _write_dist(site, "unsloth-cache-probe", "unsloth_cache_probe_pkg")+ _bump_mtime(site)+ after = metadata.packages_distributions()+ assert after["unsloth_cache_probe_pkg"] == ["unsloth-cache-probe"]+ assert len(counted) == 2+++def test_removed_distribution_is_dropped(cache_module, counted, tmp_path, monkeypatch):+ site = tmp_path / "site"+ site.mkdir()+ _write_dist(site, "unsloth-cache-gone", "unsloth_cache_gone_pkg")+ monkeypatch.syspath_prepend(str(site))+ cache_module.install()+ assert "unsloth_cache_gone_pkg" in metadata.packages_distributions()+ for child in (site / "unsloth-cache-gone-1.0.dist-info").iterdir():+ child.unlink()+ (site / "unsloth-cache-gone-1.0.dist-info").rmdir()+ _bump_mtime(site)+ assert "unsloth_cache_gone_pkg" not in metadata.packages_distributions()+ assert len(counted) == 2+++def test_sys_path_change_rescans(cache_module, counted, tmp_path, monkeypatch):+ site = tmp_path / "site"+ site.mkdir()+ _write_dist(site, "unsloth-cache-late", "unsloth_cache_late_pkg")+ cache_module.install()+ assert "unsloth_cache_late_pkg" not in metadata.packages_distributions()+ monkeypatch.syspath_prepend(str(site))+ assert metadata.packages_distributions()["unsloth_cache_late_pkg"] == ["unsloth-cache-late"]+ assert len(counted) == 2+++def test_new_distribution_finder_rescans(cache_module, counted, monkeypatch):+ class Finder:+ def find_spec(self, *args, **kwargs):+ return None++ def find_distributions(self, context = None):+ return iter(())++ cache_module.install()+ metadata.packages_distributions()+ monkeypatch.setattr(sys, "meta_path", sys.meta_path + [Finder()])+ metadata.packages_distributions()+ assert len(counted) == 2+++def test_a_plain_import_hook_does_not_rescan(cache_module, counted, monkeypatch):+ # unsloth_zoo adds a modeling-module finder between the transformers and TRL scans.+ class ImportOnly:+ def find_spec(self, *args, **kwargs):+ return None++ cache_module.install()+ metadata.packages_distributions()+ monkeypatch.setattr(sys, "meta_path", [ImportOnly()] + sys.meta_path)+ metadata.packages_distributions()+ assert len(counted) == 1+++def test_uninstall_restores_and_forgets(cache_module, counted):+ before = metadata.packages_distributions+ token = cache_module.install()+ assert metadata.packages_distributions is token+ metadata.packages_distributions()+ cache_module.uninstall(token)+ assert metadata.packages_distributions is before+ assert token._unsloth_metadata_cache[0] is None+ cache_module.uninstall(None) # a failed install is a no-op+++def test_uninstall_leaves_a_later_wrapper_in_place(cache_module, counted):+ token = cache_module.install()++ def outer():+ return token()++ metadata.packages_distributions = outer+ cache_module.uninstall(token)+ assert metadata.packages_distributions is outer+ metadata.packages_distributions()+ metadata.packages_distributions()+ assert len(counted) == 2+++def test_a_reference_kept_past_the_window_reaches_the_original(cache_module, counted):+ token = cache_module.install()+ bound = metadata.packages_distributions # e.g. `from importlib.metadata import ...` meanwhile+ bound()+ cache_module.uninstall(token)+ bound()+ bound()+ assert len(counted) == 3+ assert token._unsloth_metadata_cache[0] is None+++def _fake_owner(monkeypatch, name = "_unsloth_metadata_owner_under_test"):+ import types++ owner = types.ModuleType(name)+ monkeypatch.setitem(sys.modules, name, owner)+ return owner+++def test_a_failed_import_does_not_leave_the_wrapper(cache_module, counted, monkeypatch):+ # `import unsloth` raised midway: uninstall never ran and the module left sys.modules.+ real = metadata.packages_distributions+ owner = _fake_owner(monkeypatch)+ token = cache_module.install(owner)+ metadata.packages_distributions()+ metadata.packages_distributions()+ assert len(counted) == 1+ del sys.modules[owner.__name__]+ assert metadata.packages_distributions is token+ metadata.packages_distributions() # the first call after the failure restores the original+ assert metadata.packages_distributions is real+ assert len(counted) == 2+ token() # a kept reference passes through+ assert len(counted) == 3+++def test_retrying_a_failed_import_does_not_stack(cache_module, counted, monkeypatch):+ real = metadata.packages_distributions+ first = _fake_owner(monkeypatch)+ cache_module.install(first)+ del sys.modules[first.__name__] # failed, nobody called the wrapper since+ second = _fake_owner(monkeypatch)+ token = cache_module.install(second)+ assert token.__wrapped__ is real+ metadata.packages_distributions()+ metadata.packages_distributions()+ assert len(counted) == 1+ cache_module.uninstall(token)+ assert metadata.packages_distributions is real+++def test_inner_failure_inside_an_outer_window(cache_module, counted, monkeypatch):+ # Studio's worker window is open; unsloth's import inside it raises; the worker's finally runs.+ real = metadata.packages_distributions+ outer = cache_module.install()+ inner_module = _load("_unsloth_import_metadata_cache_inner_fail")+ owner = _fake_owner(monkeypatch)+ inner = inner_module.install(owner)+ assert inner.__wrapped__ is outer+ del sys.modules[owner.__name__]+ cache_module.uninstall(outer) # inner is still on top: left in place+ assert metadata.packages_distributions is inner+ metadata.packages_distributions() # inner closes, finds outer closed too, unwraps both+ assert metadata.packages_distributions is real+ assert len(counted) == 1+++def test_nested_scopes_share_the_outer_scan(cache_module, counted):+ outer = cache_module.install()+ metadata.packages_distributions() # transformers+ inner_module = _load("_unsloth_import_metadata_cache_inner")+ inner = inner_module.install()+ metadata.packages_distributions() # TRL, during import unsloth+ inner_module.uninstall(inner)+ assert metadata.packages_distributions is outer+ cache_module.uninstall(outer)+ assert len(counted) == 1+++def test_concurrent_callers_agree(cache_module, counted):+ cache_module.install()+ reference = metadata.packages_distributions()+ results, errors = [], []++ def worker():+ try:+ for _ in range(5):+ results.append(metadata.packages_distributions())+ except Exception as exc: # pragma: no cover+ errors.append(exc)++ threads = [threading.Thread(target = worker) for _ in range(8)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ assert not errors+ assert all(result == reference for result in results)+ assert len(counted) == 1+++def test_unreadable_entries_do_not_break_it(cache_module, counted, monkeypatch):+ monkeypatch.setattr(+ sys, "path", sys.path + [os.path.join(os.sep, "nonexistent-unsloth-dir"), ""]+ )+ cache_module.install()+ assert metadata.packages_distributions() == metadata.packages_distributions()+ assert len(counted) == 1+++def test_helper_is_stdlib_only():+ tree = ast.parse((_UNSLOTH / "_import_metadata_cache.py").read_text())+ imported = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ imported.update(alias.name.split(".")[0] for alias in node.names)+ elif isinstance(node, ast.ImportFrom):+ assert node.level == 0, "Studio loads this file by path: no relative imports"+ imported.add(node.module.split(".")[0])+ assert imported <= set(sys.stdlib_module_names)+++def test_init_installs_first_and_removes_last():+ source = (_UNSLOTH / "__init__.py").read_text()+ tree = ast.parse(source)+ calls = [+ node.func.id+ for node in ast.walk(tree)+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)+ ]+ assert "_install_metadata_cache" in calls and "_uninstall_metadata_cache" in calls+ lines = source.splitlines()+ install = next(i for i, l in enumerate(lines) if "_install_metadata_cache(sys.modules" in l)+ uninstall = next(i for i, l in enumerate(lines) if "_uninstall_metadata_cache(" in l)+ first_import = next(+ i+ for i, l in enumerate(lines)+ if l.startswith(("from .", "import "))+ and "_import_gc" not in l+ and "_import_metadata_cache" not in l+ and not l.startswith("import os")+ )+ assert install < first_import, "must be in place before transformers / TRL can be imported"+ assert uninstall > len(lines) - 20, "must stay in place for the whole import"+++_COUNT_SCRIPT = textwrap.dedent(+ """+ import importlib.metadata as md, json, sys+ real = md.packages_distributions+ calls = []+ def scan():+ calls.append(1)+ return real()+ md.packages_distributions = scan+ import unsloth+ restored = md.packages_distributions is scan+ import importlib.util+ print("R12COUNT " + json.dumps({"scans": len(calls), "restored": restored,+ "trl": "trl" in sys.modules, "transformers": "transformers" in sys.modules}))+ """+)+++_FAILED_IMPORT_SCRIPT = textwrap.dedent(+ """+ import importlib.metadata as md, json, sys+ real = md.packages_distributions+ sys.modules["unsloth_zoo"] = None # any failure partway through unsloth/__init__.py+ try:+ import unsloth+ failed = False+ except ImportError:+ failed = True+ md.packages_distributions()+ print("R12FAIL " + json.dumps({"failed": failed, "restored": md.packages_distributions is real}))+ """+)+++def test_import_unsloth_that_raises_gives_the_function_back():+ env = dict(os.environ, PYTHONWARNINGS = "ignore", UNSLOTH_DISABLE_AUTO_UPDATES = "1")+ env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(_REPO), env.get("PYTHONPATH")]))+ result = subprocess.run(+ [sys.executable, "-c", _FAILED_IMPORT_SCRIPT],+ env = env,+ cwd = str(_REPO),+ capture_output = True,+ text = True,+ timeout = 900,+ )+ lines = [l for l in result.stdout.splitlines() if l.startswith("R12FAIL ")]+ assert lines, (result.returncode, result.stderr[-4000:])+ import json++ report = json.loads(lines[-1].split(" ", 1)[1])+ assert report == {"failed": True, "restored": True}, report+++def _scan_callers_at_import():+ """How many of transformers / TRL call packages_distributions() at import (versions differ)."""+ found = 0+ for name in ("transformers.utils.import_utils", "trl.import_utils"):+ try:+ spec = importlib.util.find_spec(name)+ except (ImportError, ValueError):+ continue+ if spec is None or not spec.origin or not os.path.isfile(spec.origin):+ continue+ with open(spec.origin, encoding = "utf-8") as fh:+ for line in fh:+ if not line[:1].isspace() and "packages_distributions()" in line:+ found += 1+ break+ return found+++def _has_accelerator():+ try:+ import torch+ return bool(+ torch.cuda.is_available() or (hasattr(torch, "xpu") and torch.xpu.is_available())+ )+ except Exception:+ return False+++def test_import_unsloth_scans_distributions_at_most_once():+ if _scan_callers_at_import() < 2:+ pytest.skip(+ reason = "transformers < 5 / TRL < 1 do not call packages_distributions() at import"+ )+ env = dict(os.environ, PYTHONWARNINGS = "ignore", UNSLOTH_DISABLE_AUTO_UPDATES = "1")+ # tests/conftest.py sets this for in-process tests; a GPU-less child still imports through the CPU path.+ if not _has_accelerator():+ env.pop("UNSLOTH_DISABLE_CPU_FALLBACK", None)+ env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(_REPO), env.get("PYTHONPATH")]))+ started = time.time()+ result = subprocess.run(+ [sys.executable, "-c", _COUNT_SCRIPT],+ env = env,+ cwd = str(_REPO),+ capture_output = True,+ text = True,+ timeout = 900,+ )+ lines = [l for l in result.stdout.splitlines() if l.startswith("R12COUNT ")]+ assert lines, (result.returncode, result.stderr[-4000:], time.time() - started)+ import json++ report = json.loads(lines[-1].split(" ", 1)[1])+ assert report["transformers"] and report["trl"], report+ assert report["scans"] == 1, report+ assert report["restored"], report # the caller's function is back after the importdiff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex 3354d3c9edc..2ecd3563594 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -17,6 +17,12 @@ from ._import_gc import raise_gc_threshold as _raise_gc_threshold_raise_gc_threshold(sys.modules.get(__name__))del _raise_gc_threshold+# transformers and TRL both scan every installed distribution at import: share one scan until the end of this file.+from ._import_metadata_cache import install as _install_metadata_cache++_metadata_cache_token = _install_metadata_cache(sys.modules.get(__name__))+del _install_metadata_cache+os.environ["UNSLOTH_IS_PRESENT"] = "1"# Opt into ROCm AOTriton kernels torch still gates as experimental; setdefault keeps an explicit "0".@@ -1770,6 +1776,11 @@ try:except Exception:pass+from ._import_metadata_cache import uninstall as _uninstall_metadata_cache++_uninstall_metadata_cache(_metadata_cache_token)+del _uninstall_metadata_cache, _metadata_cache_token+from ._import_gc import restore_gc_threshold as _restore_gc_threshold_restore_gc_threshold()diff --git a/unsloth/_import_metadata_cache.py b/unsloth/_import_metadata_cache.pynew file mode 100644index 00000000000..524821704e9--- /dev/null+++ b/unsloth/_import_metadata_cache.py@@ -0,0 +1,114 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Reuse `importlib.metadata.packages_distributions()` while `import unsloth` runs.++transformers >= 5 and TRL >= 1 both scan every distribution at import. A repeat call returns a copy+of the first result while sys.path, each entry's mtime and the distribution finders are unchanged:+the same mtimes key importlib.metadata's own FastPath.lookup cache, so installs are still seen.+Stdlib only: Studio loads this file by path, without running unsloth/__init__.py.+"""++import importlib.metadata as _metadata+import os+import sys+import threading++__all__ = ["install", "uninstall"]++_lock = threading.Lock()+++def _fingerprint():+ entries = []+ for entry in list(sys.path):+ root = entry+ try:+ if not entry:+ # "" is the current directory, which can change between two calls.+ root = os.getcwd()+ mtime = os.stat(root).st_mtime_ns+ except (OSError, TypeError, ValueError):+ mtime = None+ entries.append((entry, root, mtime))+ finders = tuple(+ id(finder)+ for finder in list(sys.meta_path)+ if getattr(finder, "find_distributions", None) is not None+ )+ return (tuple(entries), finders)+++def _copy(mapping):+ return {name: list(dists) for name, dists in mapping.items()}+++def _live(scope):+ if not scope["open"]:+ return False+ owner = scope["owner"]+ # A failed import drops its module from sys.modules; uninstall never ran.+ return owner is None or sys.modules.get(scope["name"]) is owner+++def _close(wrapper):+ wrapper._unsloth_metadata_scope["open"] = False+ wrapper._unsloth_metadata_cache[0] = None+ if getattr(_metadata, "packages_distributions", None) is wrapper:+ restored = wrapper.__wrapped__+ _metadata.packages_distributions = restored+ # An outer window that closed while this one was on top.+ scope = getattr(restored, "_unsloth_metadata_scope", None)+ if scope is not None and not _live(scope):+ _close(restored)+++def install(owner = None):+ """Returns a token for `uninstall`, else None. If `owner`'s import raises, the wrapper closes itself."""+ with _lock:+ original = getattr(_metadata, "packages_distributions", None)+ # Left by an earlier import that raised: never stack on it.+ scope = getattr(original, "_unsloth_metadata_scope", None)+ if scope is not None and not _live(scope):+ _close(original)+ original = getattr(_metadata, "packages_distributions", None)+ if original is None:+ return None+ cache = [None]+ scope = {+ "open": True,+ "owner": owner,+ "name": getattr(owner, "__name__", None),+ }++ def packages_distributions():+ if not _live(scope):+ with _lock:+ _close(packages_distributions)+ return original()+ key = _fingerprint()+ with _lock:+ hit = cache[0]+ if hit is not None and hit[0] == key:+ return _copy(hit[1])+ result = original()+ # Keyed on the state before the call: a change while it ran misses next time.+ with _lock:+ if scope["open"]:+ cache[0] = (key, _copy(result))+ return result++ packages_distributions.__wrapped__ = original+ packages_distributions.__doc__ = getattr(original, "__doc__", None)+ packages_distributions._unsloth_metadata_cache = cache+ packages_distributions._unsloth_metadata_scope = scope+ _metadata.packages_distributions = packages_distributions+ return packages_distributions+++def uninstall(token):+ """Restore the original unless something wrapped it since; the wrapper stops caching either way."""+ if token is None:+ return+ with _lock:+ _close(token)