Skip to content

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.

get_model_name: keep the fetched upstream mapper for an hour instead of refetching it on every load (#17490)

Daniel Han20d9ab5e9fd9
diff --git a/tests/conftest.py b/tests/conftest.py
index d681923a8f4..369b8503ca4 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -93,6 +93,14 @@ def _fresh_parallel_layout():
tp_env._reset_env_layout()
[email protected](autouse = True)
+def _fresh_new_mapper_cache():
+ """Reset loader_utils' process-wide mapper cache; never imports unsloth."""
+ loader_utils = sys.modules.get("unsloth.models.loader_utils")
+ if loader_utils is not None and hasattr(loader_utils, "_NEW_MAPPER_CACHE"):
+ loader_utils._NEW_MAPPER_CACHE["entry"] = None
+
+
@pytest.hookimpl(trylast = True)
def pytest_collection_modifyitems(config, items):
"""After xdist tags grouped tests; see tests/_shared/xdist_group_check.py."""
diff --git a/tests/python/test_load_probe_memo.py b/tests/python/test_load_probe_memo.py
index 6c92c7ed7d8..6ba355654ad 100644
--- a/tests/python/test_load_probe_memo.py
+++ b/tests/python/test_load_probe_memo.py
@@ -105,7 +105,19 @@ def test_delegated_load_probes_config_and_adapter_once(tmp_path, monkeypatch):
assert resolved == [path, path]
-def test_mapper_fetched_once_per_load(monkeypatch):
+def _fresh_mapper_cache(monkeypatch, clock):
+ monkeypatch.setattr(loader_utils, "_NEW_MAPPER_CACHE", {"entry": None})
+ monkeypatch.setattr(loader_utils, "_time_monotonic", lambda: clock[0])
+ monkeypatch.setattr(loader_utils, "_env_says_offline", lambda: False)
+
+
+def _two_lookups():
+ return [loader_utils.get_model_name("org/unmapped-model", load_in_4bit = False) for _ in range(2)]
+
+
+def test_mapper_fetched_once_across_loads_until_it_ages_out(monkeypatch):
+ clock = [1000.0]
+ _fresh_mapper_cache(monkeypatch, clock)
fetches = []
def _fetch():
@@ -113,28 +125,44 @@ def test_mapper_fetched_once_per_load(monkeypatch):
return ({"org/old": "org/old"}, {}, {}, {}, {})
monkeypatch.setattr(loader_utils, "_get_new_mapper", _fetch)
- monkeypatch.setattr(loader_utils, "_env_says_offline", lambda: False)
-
- def _two_lookups():
- return [
- loader_utils.get_model_name("org/unmapped-model", load_in_4bit = False) for _ in range(2)
- ]
assert _two_lookups() == ["org/unmapped-model"] * 2
- assert len(fetches) == 2
-
- fetches.clear()
assert loader_utils._load_probe_memo_scope(_two_lookups)() == ["org/unmapped-model"] * 2
assert len(fetches) == 1
- fetches.clear()
+ clock[0] += loader_utils._NEW_MAPPER_TTL_S
+ _two_lookups()
+ assert len(fetches) == 2
+
+
+def test_failed_mapper_fetch_is_retried_after_a_short_pause(monkeypatch):
+ clock = [1000.0]
+ _fresh_mapper_cache(monkeypatch, clock)
+ fetches = []
monkeypatch.setattr(
loader_utils, "_get_new_mapper", lambda: fetches.append(1) or ({}, {}, {}, {}, {})
)
+
loader_utils._load_probe_memo_scope(_two_lookups)()
+ _two_lookups()
+ assert len(fetches) == 1
+
+ clock[0] += loader_utils._NEW_MAPPER_RETRY_S
+ _two_lookups()
assert len(fetches) == 2
+def test_cached_mapper_tables_are_copies(monkeypatch):
+ clock = [1000.0]
+ _fresh_mapper_cache(monkeypatch, clock)
+ monkeypatch.setattr(
+ loader_utils, "_get_new_mapper", lambda: ({"org/old": "org/old"}, {}, {}, {}, {})
+ )
+ first = loader_utils._new_mapper_tables()
+ first[0]["org/injected"] = "x"
+ assert "org/injected" not in loader_utils._new_mapper_tables()[0]
+
+
def test_probe_memo_copies_reraises_and_skips_network_errors():
calls = []
diff --git a/tests/python/test_new_mapper_cache_fork.py b/tests/python/test_new_mapper_cache_fork.py
new file mode 100644
index 00000000000..dd740fc23b4
--- /dev/null
+++ b/tests/python/test_new_mapper_cache_fork.py
@@ -0,0 +1,51 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+import os
+import threading
+import time
+
+import pytest
+
+from unsloth.models import loader_utils
+
+
[email protected](not hasattr(os, "fork"), reason = "needs os.fork")
+def test_a_fork_during_a_mapper_fetch_does_not_deadlock_the_child(monkeypatch):
+ """A worker forked while another thread is fetching the upstream mapper must still resolve names."""
+ started, release = threading.Event(), threading.Event()
+
+ def _slow_fetch():
+ started.set()
+ release.wait(30)
+ return ({}, {}, {}, {}, {})
+
+ monkeypatch.setattr(loader_utils, "_get_new_mapper", _slow_fetch)
+ monkeypatch.setattr(loader_utils, "_env_says_offline", lambda: False)
+ fetcher = threading.Thread(
+ target = loader_utils.get_model_name, args = ("org/parent-model",), daemon = True
+ )
+ fetcher.start()
+ assert started.wait(10)
+ pid = os.fork()
+ if pid == 0:
+ try:
+ loader_utils._get_new_mapper = lambda: ({}, {}, {}, {}, {})
+ loader_utils.get_model_name("org/child-model", load_in_4bit = False)
+ finally:
+ os._exit(0)
+ try:
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ done, status = os.waitpid(pid, os.WNOHANG)
+ if done:
+ assert os.waitstatus_to_exitcode(status) == 0
+ break
+ time.sleep(0.05)
+ else:
+ os.kill(pid, 9)
+ os.waitpid(pid, 0)
+ pytest.fail("the forked child hung on the mapper lock")
+ finally:
+ release.set()
+ fetcher.join(10)
diff --git a/tests/test_new_mapper_fetched_fp8.py b/tests/test_new_mapper_fetched_fp8.py
index 9e821d8f560..0b597172cce 100644
--- a/tests/test_new_mapper_fetched_fp8.py
+++ b/tests/test_new_mapper_fetched_fp8.py
@@ -147,6 +147,10 @@ def _load_resolver(installed_source):
"build_mappers": build_mappers,
"_MAPPER_HELPERS": _loader_utils_globals()["_MAPPER_HELPERS"],
"_LOAD_PROBE_MEMO": _loader_utils_globals()["_LOAD_PROBE_MEMO"],
+ "_NEW_MAPPER_CACHE": {"entry": None},
+ "_NEW_MAPPER_TTL_S": _loader_utils_globals()["_NEW_MAPPER_TTL_S"],
+ "_NEW_MAPPER_RETRY_S": _loader_utils_globals()["_NEW_MAPPER_RETRY_S"],
+ "_time_monotonic": _loader_utils_globals()["_time_monotonic"],
"SUPPORTS_FOURBIT": True,
"transformers_version": Version("4.57.6"),
"Version": Version,
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index dfcf9b18a36..99fe4be74cc 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -23,6 +23,7 @@ import contextlib
import contextvars
import copy
import threading as _threading
+from time import monotonic as _time_monotonic
import functools
import inspect
from typing import Union
@@ -1819,11 +1820,27 @@ def _load_probe_memo_scope(fn):
return _wrapper
+# Failed fetches retry after a short pause, not per load: a firewall would cost each load the timeout.
+_NEW_MAPPER_TTL_S = 3600.0
+_NEW_MAPPER_RETRY_S = 300.0
+_NEW_MAPPER_CACHE = {"entry": None} # (tables, fetched_at): one slot, never a torn pair
+
+
def _new_mapper_tables():
memo = _LOAD_PROBE_MEMO.get()
if memo is not None and "new_mapper" in memo:
return tuple(dict(table) for table in memo["new_mapper"])
- tables = _get_new_mapper()
+ entry = _NEW_MAPPER_CACHE["entry"]
+ tables = None
+ if entry is not None:
+ cached, at = entry
+ age = _time_monotonic() - at
+ if 0 <= age < (_NEW_MAPPER_TTL_S if any(cached) else _NEW_MAPPER_RETRY_S):
+ tables = tuple(dict(table) for table in cached)
+ if tables is None:
+ # No lock around the fetch: a fork while another thread is fetching must not leave the child waiting.
+ tables = _get_new_mapper()
+ _NEW_MAPPER_CACHE["entry"] = (tuple(dict(table) for table in tables), _time_monotonic())
if memo is not None and any(tables):
memo["new_mapper"] = tuple(dict(table) for table in tables)
return tables