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.

Studio: let unsloth_zoo size the download worker instead of overriding it (#7815)

Daniel Han2b979e6c1207
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
index e15e0e55417..70fd8a8d49d 100644
--- a/studio/backend/hub/services/download_lifecycle.py
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -82,6 +82,16 @@ def resolve_auto_use_xet() -> tuple[bool, str]:
return (bool(health.use_xet), str(health.reason))
+def _allow_high_performance() -> bool:
+ """Legacy opt-in, still honoured for installs whose unsloth_zoo cannot size the worker itself."""
+ return os.environ.get("UNSLOTH_XET_ALLOW_HIGH_PERFORMANCE", "").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+ "on",
+ )
+
+
def resolve_transport(use_xet: bool) -> str:
transport = download_registry.TRANSPORT_XET if use_xet else download_registry.TRANSPORT_HTTP
unavailable_reason = download_registry.download_transport_unavailable_reason(transport)
@@ -122,33 +132,23 @@ def spawn_worker(
env["HF_HUB_DISABLE_TELEMETRY"] = "1"
env["HF_HUB_DISABLE_XET"] = "0" if use_xet else "1"
if use_xet:
- # hf_xet sizes its reconstruction buffers from constants (up to 8GB stock, 64GB under
- # high-performance mode), not from the machine. Cap them from this host's RAM and cores
- # BEFORE the worker starts: hf_xet reads its config natively at import, so setting them
- # inside the worker is too late. Anything already in `env` was set by the caller, so leave.
- from utils.hf_xet_fallback import xet_env_overrides
-
- allow_high_perf = os.environ.get(
- "UNSLOTH_XET_ALLOW_HIGH_PERFORMANCE", ""
- ).strip().lower() in (
- "1",
- "true",
- "yes",
- "on",
- )
- if not allow_high_perf:
- # Unconditional, and deliberately not routed through xet_env_overrides(): an older
- # unsloth_zoo has no tuning module (overrides come back empty) and is also the one that
- # sets HF_XET_HIGH_PERFORMANCE=1 at import. `env` is seeded from the parent environment,
- # so that inherited "1" would raise the buffer ceiling to 64GB and void every cap below
- # (xet-core applies the preset AFTER reading the environment). Overwrite, not setdefault.
+ # hf_xet sizes its buffers from constants, not from the machine, and reads its config
+ # natively at import, so the worker's env has to be sized here. unsloth_zoo decides, so
+ # there is one rule and not two: it sizes from RAM/cores/disk and honours a user-set
+ # high-performance flag (standing its own sizing down, since xet-core voids it anyway).
+ # UNSLOTH_XET_FORCE_CAPS=1 bounds the machine regardless. Studio hand-rolled this, and the
+ # copies drifted: on a 2TB host the worker got a 24GB laptop's buffer and ran 3.4x slower.
+ from utils import hf_xet_fallback
+
+ # The worker's own cache, which the sizing measures: this backend's env may still name the
+ # one it started with, since moving the cache in Settings does not rewrite the live process.
+ sized = hf_xet_fallback.apply_xet_env(env, env.get("HF_HUB_CACHE"))
+ if sized is None and not _allow_high_performance():
+ # No tuning module: that unsloth_zoo is also the one setting HF_XET_HIGH_PERFORMANCE=1
+ # at import, and `env` is seeded from the parent, so that inherited "1" would hand the
+ # worker a 64GB ceiling (xet-core applies the preset AFTER reading the environment).
for key in ("HF_XET_HIGH_PERFORMANCE", "HF_XET_HP"):
env[key] = "0"
- for key, value in xet_env_overrides().items():
- if key in ("HF_XET_HIGH_PERFORMANCE", "HF_XET_HP") and not allow_high_perf:
- env[key] = value
- else:
- env.setdefault(key, value)
# No token in Unsloth settings: fall back to the backend's own HF_TOKEN so
# private repos stay downloadable (needed while inkling repos are private).
# Not for a repo an API caller named: that would lend them the owner's identity.
diff --git a/studio/backend/tests/test_hf_xet_fallback.py b/studio/backend/tests/test_hf_xet_fallback.py
index 23c4624aea3..442e420dfc7 100644
--- a/studio/backend/tests/test_hf_xet_fallback.py
+++ b/studio/backend/tests/test_hf_xet_fallback.py
@@ -582,3 +582,95 @@ def test_start_watchdog_passes_everything_to_a_zoo_that_accepts_it(monkeypatch):
shim.start_watchdog(repo_ids = ["a/b"], on_stall = lambda _m: None, connect_timeout = 600.0)
assert seen["connect_timeout"] == 600.0, "a newer zoo lost the kwarg it supports"
+
+
+def test_apply_xet_env_delegates_to_the_zoo(monkeypatch):
+ """One rule, in one place: Studio asks the zoo to size the worker rather than sizing it too."""
+ import types
+
+ import utils.hf_xet_fallback as shim
+
+ seen = {}
+
+ def _apply(env, **kwargs):
+ seen["env"] = env
+ seen["kwargs"] = kwargs
+ env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE"] = "123"
+ return {"HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE": "123"}
+
+ monkeypatch.setattr(
+ shim, "_load_optional", lambda _name: types.SimpleNamespace(apply_xet_env = _apply)
+ )
+ env = {"HF_HUB_DISABLE_XET": "0"}
+ assert shim.apply_xet_env(env) == {"HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE": "123"}
+ assert env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE"] == "123"
+ assert seen["env"] is env, "the worker's own env has to be the one that gets sized"
+ # Short Xet timeouts suit a child our ladder supervises; process-wide they would not.
+ assert seen["kwargs"]["fail_fast"] is True
+
+
+def test_apply_xet_env_returns_none_when_the_zoo_cannot_size(monkeypatch):
+ """None, not {}: an empty write is a legitimate result, so the caller needs the two apart to
+ know whether to fall back to clearing the high-performance flag itself."""
+ import types
+
+ import utils.hf_xet_fallback as shim
+
+ monkeypatch.setattr(shim, "_load_optional", lambda _name: None)
+ assert shim.apply_xet_env({}) is None
+
+ monkeypatch.setattr(shim, "_load_optional", lambda _name: types.SimpleNamespace())
+ assert shim.apply_xet_env({}) is None, "an older zoo without apply_xet_env must read as absent"
+
+ def _boom(env, **kwargs):
+ raise RuntimeError("no")
+
+ monkeypatch.setattr(
+ shim, "_load_optional", lambda _name: types.SimpleNamespace(apply_xet_env = _boom)
+ )
+ assert shim.apply_xet_env({}) is None, "a raising zoo must degrade, not crash the download"
+
+
+def test_a_zoo_that_can_resize_is_asked_for_the_workers_own_cache(monkeypatch):
+ """``env`` is a copy of ours and already carries the zoo's import-time sizing, which its
+ setdefault apply would keep. A zoo that can resize gets the worker's cache instead, so a backend
+ whose cache moved after startup does not size the worker for the volume it left behind. An older
+ zoo, with no resize to call, keeps the previous behaviour."""
+ import types
+
+ import utils.hf_xet_fallback as shim
+
+ seen = {}
+
+ def _resize(env, cache_dir, **kwargs):
+ seen["cache_dir"] = cache_dir
+ env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"] = "1000000000"
+ return {"HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT": "1000000000"}
+
+ def _apply(env, **kwargs):
+ seen["applied"] = True
+ return {}
+
+ monkeypatch.setattr(
+ shim,
+ "_load_optional",
+ lambda _name: types.SimpleNamespace(
+ apply_xet_env = _apply,
+ resize_for_cache_dir = _resize,
+ ),
+ )
+ env = {
+ "HF_HUB_CACHE": "/new/volume/hub",
+ "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT": "64000000000",
+ }
+ written = shim.apply_xet_env(env, env["HF_HUB_CACHE"])
+ assert seen["cache_dir"] == "/new/volume/hub"
+ assert "applied" not in seen, "resizing and applying both would size the worker twice"
+ assert written["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"] == "1000000000"
+ assert env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"] == "1000000000"
+
+ monkeypatch.setattr(
+ shim, "_load_optional", lambda _name: types.SimpleNamespace(apply_xet_env = _apply)
+ )
+ assert shim.apply_xet_env({}, "/new/volume/hub") == {}
+ assert seen["applied"] is True
diff --git a/studio/backend/tests/test_hub_download_transport_auto.py b/studio/backend/tests/test_hub_download_transport_auto.py
index 4b0e8ae2244..cca1d05d2da 100644
--- a/studio/backend/tests/test_hub_download_transport_auto.py
+++ b/studio/backend/tests/test_hub_download_transport_auto.py
@@ -144,19 +144,46 @@ def _tuning_available() -> bool:
not _tuning_available(),
reason = "the installed unsloth_zoo predates hf_xet_tuning, so there are no caps to apply",
)
-def test_xet_worker_gets_ram_caps(monkeypatch):
+def test_xet_worker_is_sized_from_the_machine(monkeypatch):
+ """The budget scales with the host, so pin the invariant rather than a number: what hf_xet can
+ hold (buffer + files * per-file) must fit the limit the same call set."""
env = _spawn_env(monkeypatch, use_xet = True)
limit = int(env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"])
- # Stock hf_xet allows 8GB here (64GB under high-performance mode).
- assert 0 < limit <= 4_000_000_000
+ worst = int(env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE"]) + int(
+ env["HF_XET_DATA_MAX_CONCURRENT_FILE_DOWNLOADS"]
+ ) * int(env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_PERFILE_SIZE"])
+ assert 0 < worst <= limit
assert env["HF_HUB_DISABLE_XET"] == "0"
-def test_high_performance_is_cleared_not_merely_defaulted(monkeypatch):
- """xet-core applies the high-performance preset AFTER reading the environment, so an inherited
- "1" would discard every cap above rather than compete with it. setdefault is not enough."""
- env = _spawn_env(monkeypatch, use_xet = True, parent_env = {"HF_XET_HIGH_PERFORMANCE": "1"})
- assert env["HF_XET_HIGH_PERFORMANCE"] == "0"
+def test_the_zoo_decides_and_studio_does_not_second_guess_it(monkeypatch):
+ """Studio used to force the flag off here. Two copies of one rule drifted, and on a 2TB host the
+ worker ended up with a 24GB laptop's buffer, 3.4x slower than the machine's own setting."""
+ import utils.hf_xet_fallback as shim
+
+ seen = {}
+
+ def _apply(env, cache_dir = None):
+ seen.update(env)
+ seen["cache_dir"] = cache_dir
+ env["HF_XET_SENTINEL"] = "sized-by-the-zoo"
+ return {"HF_XET_SENTINEL": "sized-by-the-zoo"}
+
+ monkeypatch.setattr(shim, "apply_xet_env", _apply)
+ env = _spawn_env(
+ monkeypatch,
+ use_xet = True,
+ parent_env = {
+ "HF_XET_HIGH_PERFORMANCE": "1",
+ "HF_HUB_CACHE": "/moved/volume/hub",
+ },
+ )
+ assert env["HF_XET_SENTINEL"] == "sized-by-the-zoo"
+ # The worker's own env is what gets sized, and the flag is left exactly as the zoo left it.
+ assert seen["HF_HUB_DISABLE_XET"] == "0"
+ # Sized against the cache the worker will write to, not whichever one this process started with.
+ assert seen["cache_dir"] == "/moved/volume/hub"
+ assert env["HF_XET_HIGH_PERFORMANCE"] == "1"
def test_high_performance_is_cleared_even_without_the_tuning_module(monkeypatch):
@@ -165,13 +192,18 @@ def test_high_performance_is_cleared_even_without_the_tuning_module(monkeypatch)
would hand the worker a 64GB buffer ceiling on the installs Studio alone cannot fix."""
import utils.hf_xet_fallback as shim
- monkeypatch.setattr(shim, "xet_env_overrides", lambda *a, **k: {})
+ monkeypatch.setattr(shim, "apply_xet_env", lambda *a, **k: None)
env = _spawn_env(monkeypatch, use_xet = True, parent_env = {"HF_XET_HIGH_PERFORMANCE": "1"})
assert env["HF_XET_HIGH_PERFORMANCE"] == "0"
assert env["HF_XET_HP"] == "0"
-def test_user_can_opt_back_into_high_performance(monkeypatch):
+def test_the_legacy_opt_in_still_works_without_the_tuning_module(monkeypatch):
+ """Newer zoos honour the flag on their own, but this is the escape hatch on installs that
+ cannot, so it has to keep working there."""
+ import utils.hf_xet_fallback as shim
+
+ monkeypatch.setattr(shim, "apply_xet_env", lambda *a, **k: None)
monkeypatch.setenv("UNSLOTH_XET_ALLOW_HIGH_PERFORMANCE", "1")
env = _spawn_env(monkeypatch, use_xet = True, parent_env = {"HF_XET_HIGH_PERFORMANCE": "1"})
assert env["HF_XET_HIGH_PERFORMANCE"] == "1"
@@ -486,3 +518,14 @@ def test_both_loaders_share_one_env_lock():
assert (
"with _load_lock:" in source
), f"{fn.__name__} mutates the GPU-init override outside the shared _load_lock"
+
+
+def test_the_worker_never_gets_the_flag_and_our_caps_together(monkeypatch):
+ """End to end against whichever unsloth_zoo is installed, with nothing stubbed. Which of the
+ two the zoo picks is its call and changes with the version; what must never happen either way
+ is both at once, because xet-core applies the preset after reading the environment, so it
+ voids the limit while still honouring the smaller per-file and concurrency numbers."""
+ env = _spawn_env(monkeypatch, use_xet = True, parent_env = {"HF_XET_HIGH_PERFORMANCE": "1"})
+ flag_on = env.get("HF_XET_HIGH_PERFORMANCE", "0").strip().lower() in ("1", "true", "yes", "on")
+ sized = "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_PERFILE_SIZE" in env
+ assert not (flag_on and sized), f"worst of both: flag on with our sizing still applied ({env})"
diff --git a/studio/backend/utils/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.py
index 863185f60e3..a3fe05ca21f 100644
--- a/studio/backend/utils/hf_xet_fallback.py
+++ b/studio/backend/utils/hf_xet_fallback.py
@@ -215,6 +215,31 @@ def xet_env_overrides() -> "dict[str, str]":
return {}
+def apply_xet_env(env: dict, cache_dir: "Optional[str]" = None) -> "Optional[dict[str, str]]":
+ """Let unsloth_zoo size a download worker's ``HF_XET_*`` in *env*, in place.
+
+ Returns what it wrote, or ``None`` when the installed zoo has no opinion, which is the caller's
+ signal to fall back. ``fail_fast`` suits a supervised child: our Xet -> HTTP ladder acts on the
+ failure, so short Xet timeouts are right here and wrong process-wide.
+
+ *env* is a copy of this process's environment, which already carries the zoo's import-time
+ sizing, and applying is setdefault: on a zoo that can resize we recompute for *cache_dir*
+ instead, so a backend whose cache has since moved does not hand the worker the old volume's
+ numbers. Older zoos keep the previous behaviour."""
+ module = _load_optional("unsloth_zoo.hf_xet_tuning")
+ if module is None or not hasattr(module, "apply_xet_env"):
+ return None
+ try:
+ resize = getattr(module, "resize_for_cache_dir", None)
+ if resize is not None:
+ return dict(resize(env, cache_dir))
+ return dict(module.apply_xet_env(env, fail_fast = True))
+ except Exception as exc: # noqa: BLE001
+ import logging as _logging
+ _logging.getLogger(__name__).debug("apply_xet_env failed: %s", exc)
+ return None
+
+
def child_should_disable_xet(config: dict) -> bool:
"""Single source of truth for the per-worker Xet env flip (mirrors
``unsloth_zoo.hf_xet_fallback.child_should_disable_xet``). Deliberately lightweight: importing or
@@ -450,6 +475,7 @@ __all__ = [
"record_xet_outcome",
"start_watchdog",
"xet_env_overrides",
+ "apply_xet_env",
"xet_health",
"hf_hub_download_with_xet_fallback",
"snapshot_download_with_xet_fallback",