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: prefer the self-contained MTP head so llama-server's --fit can measure it (#10342)

Daniel Han353aa33241a8
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index f1fb53faabe..bea65225515 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -3269,6 +3269,11 @@ def _is_published_mtp_drafter_name(path: str) -> bool:
return lower.startswith("mtp-") or stem.endswith("-mtp")
+def _mtp_head_borrows(path: str) -> bool:
+ """Is this the published ``-shared-`` form, which loads only under its target?"""
+ return "-shared-" in Path(path).name.lower()
+
+
def _pick_mtp(candidates: list[str], *, allow_nested: bool = True) -> Optional[str]:
"""The MTP drafter a listing offers, or None. Module level for the same reason
``_pick_dspark`` is: both are handed a live repo listing as well as a snapshot,
@@ -14419,6 +14424,7 @@ class LlamaCppBackend:
label: str,
cancel_event: Optional[threading.Event] = None,
near_path: Optional[str] = None,
+ reuse_snapshot_sibling: bool = True,
outcome: Optional[dict] = None,
on_transient_failure: Optional[Callable[[], None]] = None,
) -> Optional[str]:
@@ -14439,6 +14445,10 @@ class LlamaCppBackend:
show for the download -- and it disagreed with the local scan, which
accepts a split drafter only when every shard is present.
+ ``reuse_snapshot_sibling=False`` is for a caller that already rejected the
+ snapshot copy; without it this repeats the lookup and hands it back. ``near_path``
+ is still passed: it also selects the cache directory the fetch writes into.
+
``on_transient_failure`` fires when the companion was lost to a listing that
never completed or a download that dropped, the one None worth another attempt.
A callback rather than an ``outcome`` key because the DFlash caller loops and
@@ -14459,7 +14469,7 @@ class LlamaCppBackend:
return pick(available)
# Keep companion files in the main GGUF's snapshot.
- if near_path:
+ if near_path and reuse_snapshot_sibling:
cached = _companion_snapshot_sibling(near_path, pick)
if cached:
logger.info("Reusing cached %s: %s", label, cached)
@@ -14748,9 +14758,19 @@ class LlamaCppBackend:
pick = _pick_mtp if allow_nested else _pick_mtp_root_only
+ borrowed_cached: Optional[str] = None
if near_path:
cached = _companion_snapshot_sibling(near_path, pick)
- if cached:
+ if cached and _mtp_head_borrows(cached) and not _hf_env_offline():
+ # --fit cannot measure a borrowing head, so the MTP context OOMs
+ # (unsloth#10322). hf_hub_download reuses this file if nothing is better.
+ logger.info(
+ "Cached MTP drafter borrows the target's embeddings; checking the "
+ "repo for a self-contained head: %s",
+ cached,
+ )
+ borrowed_cached = cached
+ elif cached:
logger.info("Reusing cached MTP drafter: %s", cached)
return cached
@@ -14768,14 +14788,20 @@ class LlamaCppBackend:
logger.info(f"Reusing cached MTP drafter (offline): {cached}")
return cached
- return self._download_companion_gguf(
+ fetched = self._download_companion_gguf(
hf_repo = hf_repo,
hf_token = hf_token,
pick = pick,
label = "MTP drafter",
cancel_event = cancel_event,
near_path = near_path,
+ reuse_snapshot_sibling = borrowed_cached is None,
)
+ if fetched is None and borrowed_cached is not None:
+ # An unmeasurable drafter still drafts; no drafter at all is the bigger loss.
+ logger.info("Keeping the cached borrowing MTP drafter: %s", borrowed_cached)
+ return borrowed_cached
+ return fetched
def _cached_repo_dspark_drafter(
self,
diff --git a/studio/backend/tests/test_kv_cache_estimate_route.py b/studio/backend/tests/test_kv_cache_estimate_route.py
index c4220d81e66..72900603595 100644
--- a/studio/backend/tests/test_kv_cache_estimate_route.py
+++ b/studio/backend/tests/test_kv_cache_estimate_route.py
@@ -277,19 +277,14 @@ class TestDrafterDiscoveryMatchesTheLoader:
got, _ = models_routes._resolve_mtp_drafter(str(main))
assert got == str(q8)
- def test_nested_fallback_prefers_the_shared_head(self, tmp_path):
- """A -shared- head borrows the target's token_embd/output instead of
- carrying its own: 1.35 GB smaller at Q8_0 and no worse, accepting
- identically to the full head (159 of 284) on the shipped prebuilt. Only
- qwen4exp reaches this path, and its MTP graph and the borrow ship in the
- same fork, so a build that can draft one carries the other."""
+ def test_nested_fallback_prefers_the_self_contained_head(self, tmp_path):
snap = self._snapshot(tmp_path)
main = _write_gguf(snap / "model-Q4_K_M.gguf", _MLA_NO_HEAD, arch = "qwen4exp")
- _write_gguf(snap / "MTP" / "mtp-model-Q8_0.gguf", _MLA_NO_HEAD)
- shared = _write_gguf(snap / "MTP" / "mtp-model-shared-Q8_0.gguf", _MLA_NO_HEAD)
+ full = _write_gguf(snap / "MTP" / "mtp-model-Q8_0.gguf", _MLA_NO_HEAD)
+ _write_gguf(snap / "MTP" / "mtp-model-shared-Q8_0.gguf", _MLA_NO_HEAD)
got, _ = models_routes._resolve_mtp_drafter(str(main))
- assert got == str(shared)
+ assert got == str(full)
def test_precision_outranks_the_shared_preference(self, tmp_path):
"""Q8_0 first is the stronger rule: a shared bf16 head is both larger than
diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.py
index 7f0172f5492..edcbbd5d7f7 100644
--- a/studio/backend/tests/test_mtp_drafter_companion.py
+++ b/studio/backend/tests/test_mtp_drafter_companion.py
@@ -689,6 +689,7 @@ def test_download_mtp_prefers_root_over_new_scheme_copies(monkeypatch):
label,
cancel_event = None,
near_path = None,
+ reuse_snapshot_sibling = True,
):
captured["pick"] = pick
return None
@@ -755,6 +756,179 @@ def _seed_snapshot(tmp_path, names):
return snap
+def _hub_snapshot(tmp_path, names):
+ """A snapshot in the layout _snapshot_dir_of recognises: .../snapshots/<rev>/."""
+ snap = tmp_path / "hub" / "models--unsloth--Qwen3.8-Flash-Next-GGUF" / "snapshots" / "abc"
+ for rel in names:
+ f = snap / rel
+ f.parent.mkdir(parents = True, exist_ok = True)
+ f.write_bytes(b"x")
+ return snap
+
+
+def _capture_companion_download(backend):
+ captured = {}
+
+ def _fake(
+ *,
+ hf_repo,
+ hf_token,
+ pick,
+ label,
+ cancel_event = None,
+ near_path = None,
+ reuse_snapshot_sibling = True,
+ ):
+ captured["pick"] = pick
+ captured["near_path"] = near_path
+ captured["reuse_snapshot_sibling"] = reuse_snapshot_sibling
+ return "/downloaded/mtp-Qwen3.8-Flash-Next-Q8_0.gguf"
+
+ backend._download_companion_gguf = _fake
+ return captured
+
+
+def test_download_mtp_refetches_when_the_cache_holds_only_a_shared_head(tmp_path, monkeypatch):
+ import utils.models.gguf_metadata as gm
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
+ snap = _hub_snapshot(
+ tmp_path,
+ ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
+ )
+ b = LlamaCppBackend()
+ captured = _capture_companion_download(b)
+
+ got = b._download_mtp(
+ hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF", near_path = str(snap / "UD-IQ1_S" / "model.gguf")
+ )
+ assert "pick" in captured, "a lone shared head was reused without consulting the repo"
+ assert got == "/downloaded/mtp-Qwen3.8-Flash-Next-Q8_0.gguf"
+
+
+def test_download_mtp_still_reuses_a_cached_self_contained_head(tmp_path, monkeypatch):
+ import utils.models.gguf_metadata as gm
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
+ snap = _hub_snapshot(
+ tmp_path,
+ [
+ "UD-IQ1_S/model.gguf",
+ "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf",
+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0.gguf",
+ ],
+ )
+ b = LlamaCppBackend()
+ captured = _capture_companion_download(b)
+
+ got = b._download_mtp(
+ hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF", near_path = str(snap / "UD-IQ1_S" / "model.gguf")
+ )
+ assert "pick" not in captured
+ assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf"
+
+
+def test_download_mtp_keeps_a_lone_shared_head_offline(tmp_path, monkeypatch):
+ import utils.models.gguf_metadata as gm
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
+ snap = _hub_snapshot(
+ tmp_path,
+ ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
+ )
+ b = LlamaCppBackend()
+ captured = _capture_companion_download(b)
+
+ got = b._download_mtp(
+ hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF", near_path = str(snap / "UD-IQ1_S" / "model.gguf")
+ )
+ assert "pick" not in captured
+ assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"
+
+
+def _stub_hub(
+ monkeypatch,
+ published,
+ *,
+ listing_fails = False,
+):
+ """The live repo without a network, stubbed below the helper's own snapshot lookup."""
+ import huggingface_hub
+
+ import core.inference.llama_cpp as llama_cpp_module
+
+ def _list(repo, token = None):
+ if listing_fails:
+ raise ConnectionError("hub unreachable")
+ return list(published)
+
+ monkeypatch.setattr(huggingface_hub, "list_repo_files", _list)
+ monkeypatch.setattr(llama_cpp_module, "_hub_download_in_flight", lambda repo: False)
+ monkeypatch.setattr(
+ llama_cpp_module,
+ "hf_hub_download_with_xet_fallback",
+ lambda repo, fn, token, cancel_event = None, cache_dir = None: "/downloaded/" + fn,
+ )
+
+
+def test_download_mtp_lists_the_repo_past_the_helpers_own_snapshot_reuse(tmp_path, monkeypatch):
+ """The helper repeats _companion_snapshot_sibling before listing, so the caller's
+ fall-through returned the same borrowing head (unsloth#10322). Uses the real helper."""
+ import utils.models.gguf_metadata as gm
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
+ snap = _hub_snapshot(
+ tmp_path,
+ ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
+ )
+ _stub_hub(
+ monkeypatch,
+ [
+ "UD-IQ1_S/model.gguf",
+ "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf",
+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0.gguf",
+ ],
+ )
+
+ got = LlamaCppBackend()._download_mtp(
+ hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF",
+ near_path = str(snap / "UD-IQ1_S" / "model.gguf"),
+ )
+ assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf", (
+ f"the fall-through handed back {got}; the helper reused the snapshot copy "
+ f"before listing the repo"
+ )
+
+
+def test_download_mtp_keeps_the_borrowing_head_when_the_listing_never_answers(
+ tmp_path, monkeypatch
+):
+ import utils.models.gguf_metadata as gm
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
+ snap = _hub_snapshot(
+ tmp_path,
+ ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
+ )
+ _stub_hub(monkeypatch, [], listing_fails = True)
+
+ got = LlamaCppBackend()._download_mtp(
+ hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF",
+ near_path = str(snap / "UD-IQ1_S" / "model.gguf"),
+ )
+ assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"
+
+
def test_download_mtp_reuses_cached_root_drafter_offline(tmp_path, monkeypatch):
import utils.models.model_config as mc
from core.inference.llama_cpp import LlamaCppBackend
@@ -893,6 +1067,7 @@ def test_download_mtp_online_skips_cache_reuse(tmp_path, monkeypatch):
label,
cancel_event = None,
near_path = None,
+ reuse_snapshot_sibling = True,
):
reached["hit"] = True
return None
@@ -1365,14 +1540,14 @@ def test_detect_mtp_file_skips_incomplete_split_drafter(tmp_path):
def test_detect_mtp_file_ranks_split_drafter_by_total_size(tmp_path):
"""Candidates collapse to shard 1, so a split copy must be summed or it
- outranks a smaller single file."""
+ outranks a smaller single file. Both sides are Q8_0: precision now outranks size."""
weight = tmp_path / "model-Q4_0.gguf"
weight.write_bytes(b"x")
sub = tmp_path / "MTP"
sub.mkdir()
(sub / "mtp-model-Q8_0-00001-of-00002.gguf").write_bytes(b"x" * 90)
(sub / "mtp-model-Q8_0-00002-of-00002.gguf").write_bytes(b"x" * 90)
- smaller = sub / "mtp-model-BF16.gguf"
+ smaller = sub / "mtp-model-Q8_0.gguf"
smaller.write_bytes(b"x" * 100)
assert detect_mtp_file(str(weight)) == str(smaller.resolve())
@@ -1494,8 +1669,8 @@ def test_cached_mtp_lookup_ranks_nested_copies_like_the_download(tmp_path, monke
"""Offline reuse must name the file the online picker names.
Lexical order put mtp-Qwen3.8-Flash-Next-BF16.gguf first, so a cached user got
- the 7.77 GB slowest head while a fresh install downloaded the 2.79 GB shared
- Q8_0 one.
+ the 7.77 GB slowest head while a fresh install downloaded the Q8_0 one. Both
+ pickers now take the self-contained head over the borrowing one (unsloth#10322).
"""
import core.inference.llama_cpp as llama_cpp_module
@@ -1515,7 +1690,7 @@ def test_cached_mtp_lookup_ranks_nested_copies_like_the_download(tmp_path, monke
found = backend._cached_repo_mtp_drafter("unsloth/Qwen3.8-Flash-Next-GGUF")
assert found is not None
- assert Path(found).name == "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf", (
+ assert Path(found).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf", (
f"offline reuse picked {Path(found).name}; the online picker takes "
f"{llama_cpp_module._pick_mtp(published)}"
)
@@ -1540,6 +1715,32 @@ def test_cached_mtp_lookup_rejects_non_drafters_parked_under_mtp(tmp_path, monke
assert backend._cached_repo_mtp_drafter("some/repo") is None
+def test_local_scan_prefers_the_fit_measurable_head_over_the_smaller_shared_one(tmp_path):
+ root = tmp_path / "local"
+ (root / "MTP").mkdir(parents = True)
+ for i in (1, 2, 3):
+ (root / f"Qwen3.8-Flash-Next-UD-IQ1_S-0000{i}-of-00003.gguf").write_bytes(b"x" * 64)
+ (root / "MTP" / "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf").write_bytes(b"x" * 64)
+ (root / "MTP" / "mtp-Qwen3.8-Flash-Next-Q8_0.gguf").write_bytes(b"x" * 128)
+ found = detect_mtp_file(
+ str(root / "Qwen3.8-Flash-Next-UD-IQ1_S-00001-of-00003.gguf"), search_root = str(root)
+ )
+ assert found is not None and Path(found).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf"
+
+
+def test_local_scan_keeps_precision_above_the_borrow_tiebreak(tmp_path):
+ root = tmp_path / "local"
+ (root / "MTP").mkdir(parents = True)
+ for i in (1, 2, 3):
+ (root / f"Qwen3.8-Flash-Next-UD-IQ1_S-0000{i}-of-00003.gguf").write_bytes(b"x" * 64)
+ (root / "MTP" / "mtp-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x" * 512)
+ (root / "MTP" / "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf").write_bytes(b"x" * 64)
+ found = detect_mtp_file(
+ str(root / "Qwen3.8-Flash-Next-UD-IQ1_S-00001-of-00003.gguf"), search_root = str(root)
+ )
+ assert found is not None and Path(found).name == "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"
+
+
def test_a_shared_head_pairs_with_its_target_in_the_local_scan(tmp_path):
"""-shared marks the head's FORM, not its family.
diff --git a/studio/backend/tests/test_native_gguf_companion.py b/studio/backend/tests/test_native_gguf_companion.py
index d5be16beb7c..31e88c45087 100644
--- a/studio/backend/tests/test_native_gguf_companion.py
+++ b/studio/backend/tests/test_native_gguf_companion.py
@@ -398,8 +398,8 @@ def test_status_provenance_survives_deleted_model_directory(tmp_path, monkeypatc
def test_native_load_skips_rejected_mtp_candidate_for_next_one(tmp_path):
- """MTP/ can hold several compatible copies. If the size-preferred one is
- out of the grant, the next must be tried instead of disabling MTP."""
+ """MTP/ can hold several copies: a preferred one out of the grant must not disable
+ MTP. Both are Q8_0 here, since precision now outranks size."""
quant_dir = tmp_path / "Q4_0"
quant_dir.mkdir()
weight = quant_dir / "model.gguf"
@@ -409,10 +409,10 @@ def test_native_load_skips_rejected_mtp_candidate_for_next_one(tmp_path):
companion_dir = tmp_path / "MTP"
companion_dir.mkdir()
try:
- (companion_dir / "mtp-model-Q4_0.gguf").symlink_to(outside)
+ (companion_dir / "mtp-model-Q8_0.gguf").symlink_to(outside)
except OSError as exc:
pytest.skip(f"symlinks unavailable: {exc}")
- larger = companion_dir / "mtp-model-Q8_0.gguf"
+ larger = companion_dir / "mtp-model-Q8_0-00001-of-00001.gguf"
larger.write_bytes(b"d" * 5000)
def _usable(candidate: str) -> bool:
diff --git a/studio/backend/utils/models/drafters/preference.py b/studio/backend/utils/models/drafters/preference.py
index e11080dc69f..490e7a08d0d 100644
--- a/studio/backend/utils/models/drafters/preference.py
+++ b/studio/backend/utils/models/drafters/preference.py
@@ -62,12 +62,11 @@ def mtp_precision_rank(name: str) -> int:
def mtp_preference_key(name: str) -> tuple[int, int, str]:
"""Sort key picking the preferred MTP head by name alone.
- A head borrowing the target's token_embd/output wins the tie: 1.35 GB smaller
- at Q8_0 and no worse, accepting identically (159 of 284) on the shipped
- prebuilt. Only the qwen4exp path reaches a repo publishing both forms, and
- qwen4exp MTP and the borrow ship in one fork, so the borrow always resolves.
+ The self-contained head wins the tie over the borrowing (``-shared-``) form:
+ ``--fit`` budgets a draft by loading it alone, which a borrowing head cannot do,
+ so the MTP context OOMs (unsloth#10322). Worth the 1.35 GB it costs at Q8_0.
"""
- borrows = 0 if "shared" in Path(name).name.lower() else 1
+ borrows = 1 if "shared" in Path(name).name.lower() else 0
return mtp_precision_rank(name), borrows, Path(name).name.lower()
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index f4acafe3fb8..9d914f6cd72 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -1935,27 +1935,24 @@ def detect_mtp_file(
def _launchable(candidate: Path) -> bool:
return _drafter_split_is_complete(candidate)
- def _smallest_first(candidate: Path) -> tuple[int, int, int, str]:
- # Cheapest compatible copy wins. Size first: a fixed precision list ranked unknown quants
- # behind BF16, so a small K-quant lost to a far larger BF16. Precision breaks size ties,
- # name keeps it stable. Split copies collapse to shard 1, so sum across their shards.
- # MTP prefers Q4_0 where DSpark prefers Q8_0, so the order is its own.
+ def _smallest_first(candidate: Path) -> tuple[int, int, int, int, str]:
+ # The same order the hub picker uses (mtp_preference_key), so a snapshot
+ # reopen launches the head the download chose. --fit cannot measure a
+ # borrowing head, so it reserves nothing and the MTP context OOMs
+ # (unsloth#10322); that tiebreak sits after precision so a self-contained
+ # bf16 head never displaces a shared Q8_0 one. Sizes sum across shards.
+ from utils.models.drafters.preference import mtp_precision_rank
+
name = candidate.name.lower()
- if "-q4_0" in name:
- precision = 0
- elif "-q8_0" in name:
- precision = 1
- elif "-bf16" in name or "-f16" in name:
- precision = 2
- else:
- precision = 3
+ borrows = 1 if "-shared-" in name else 0
# Family first, for the same reason as DSpark: both a base-family and a
# release-specific sidecar prefix-match, and only the longer one is
# really this weight's drafter.
return (
_drafter_stem_rank(candidate.name, kind = "mtp"),
+ mtp_precision_rank(name),
+ borrows,
_drafter_total_size(candidate),
- precision,
name,
)