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
fix(studio): make room for the MLX drafter in the auto offload plan (#15342)
Long Yixing6322f7bca80a
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 38f4ac3c5ce..ca076fd9642 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -1087,12 +1087,13 @@ def mlx_resolve_offload(retains_history: bool,kv_bits = None,vision = None,+ drafter = None,) -> tuple:"""The ``(ple, expert)`` fractions a load of *model_dir* reads from disk (None for off), fromknobs as ``normalize_mlx_offload`` gives them: an ``"auto"`` knob decided by unsloth_zoo's 50/50rule on this load's pricing, and off where that cannot be planned; any other knob as given;then the planned prefill step for experts on disk, else None. ``vision=True`` prices the- mlx-vlm route a speculative text load takes."""+ mlx-vlm route a speculative text load takes; ``drafter``, a ``(path, builtin)`` to make room for."""fixed = tuple(None if knob == "auto" else knob for knob in knobs) + (None,)if "auto" not in knobs or not model_dir:return fixed@@ -1118,6 +1119,7 @@ def mlx_resolve_offload(kv_bits = kv_bits,load_in_4bit = load_in_4bit,vision = vision,+ drafter = drafter,)except Exception as exc:logger.info("MLX auto offload not planned for %s: %s", model_dir, exc)@@ -1125,6 +1127,53 @@ def mlx_resolve_offload(return fixed if plan is None else plan+# Most of each offloadable part an auto drafter may add to disk (break-even was ~5 points on sampled decode, #15342).+MLX_AUTO_DRAFTER_ROOM = 0.04+++def mlx_resolve_drafter_offload(model_dir, knobs, drafter, *, auto: bool, **priced) -> tuple:+ """``(plan, baseline)``: ``mlx_resolve_offload``'s plan with room made for *drafter*, and for an *auto*+ drafter the target-only plan its costless check measures against. An explicit drafter keeps its room+ unless it is priced not to fit there; an auto drafter gets room only when no part puts more than+ ``MLX_AUTO_DRAFTER_ROOM`` more of itself on disk and it then fits costlessly; otherwise, the target-only plan."""+ if not drafter:+ return mlx_resolve_offload(model_dir, knobs, **priced), None+ from types import SimpleNamespace++ def fits(plan, **kwargs):+ return mlx_drafter_fit(+ model_dir,+ mlx_checkpoint_window(model_dir),+ priced["pinned"],+ SimpleNamespace(path = drafter[0], builtin = drafter[1]),+ load_in_4bit = priced["load_in_4bit"],+ **kwargs,+ **mlx_offload_route(plan),+ )[0]++ room = mlx_resolve_offload(model_dir, knobs, drafter = drafter, **priced)+ if not auto:+ # A plan the load would then refuse the drafter on (nothing fits: all on disk, no step) helps nobody.+ if "auto" in knobs and fits(room) is False:+ return mlx_resolve_offload(model_dir, knobs, **priced), None+ return room, None+ alone = mlx_resolve_offload(model_dir, knobs, **priced)+ if room == alone:+ return room, alone+ if all(+ (more or 0) - (less or 0) <= MLX_AUTO_DRAFTER_ROOM+ for more, less in zip(room[:2], alone[:2])+ ) and fits(room, costless = True, baseline = mlx_offload_route(alone)):+ return room, alone+ return alone, alone+++def mlx_offload_route(plan) -> dict:+ """The ``offload`` / ``prefill_chunk`` pricing kwargs of a ``(ple, experts, prefill_step)`` plan, both+ always present so they override a priced route."""+ return {"offload": tuple(plan[:2]) if any(plan[:2]) else None, "prefill_chunk": plan[2]}++def mlx_checkpoint_window(model_dir) -> Optional[int]:from types import SimpleNamespace@@ -2788,6 +2837,11 @@ def _fitted_context(return fitted, verdict+def _fit_rank(outcome, context) -> tuple:+ # An unpriceable baseline outranks every fit, so nothing is costless against it.+ return {"no_fit": 0, "fitted": 1, "fits": 2}.get(outcome, 3), context or 0++def mlx_drafter_fit(model_dir,ceiling,@@ -2798,10 +2852,12 @@ def mlx_drafter_fit(costless = False,offload = None,prefill_chunk = None,+ baseline = None,):"""``(attaches, fitted context or None)`` for *source*'s drafter on an mlx-vlm load of *model_dir*:only a priced fit reserves it, a pinned context must fit whole, and a ``costless`` one must fit- the context the load fits without it. ``attaches`` is None when the fit could not be priced."""+ at least the context the load fits without it, on the *baseline* route (``mlx_offload_route``)+ when the offload made room for it. ``attaches`` is None when the fit could not be priced."""budget = mlx_memory_budget(retains_history = mlx_vlm_snapshot_store_available())ceiling = pinned or ceilingif budget is None or not ceiling or not model_dir:@@ -2823,7 +2879,7 @@ def mlx_drafter_fit(outcome, fitted = fit(drafter = (source.path, source.builtin))if outcome == "unsizable":return None, fitted- if costless and (outcome, fitted) != fit():+ if costless and _fit_rank(outcome, fitted) < _fit_rank(*fit(**(baseline or {}))):return False, fittedexcept Exception as exc:logger.info("MLX drafter %s not priced: %s", source.path, exc)@@ -5312,20 +5368,36 @@ class MLXInferenceBackend:# Auto is planned only where the load is priced: not distributed, an adapter or an explicit dtype.def offload_request():- return _mlx_offload_request(- knobs,- None- if is_distributed or is_lora or dtype is not None- else functools.partial(- mlx_resolve_offload,- pinned = _positive_int(max_seq_length),- load_in_4bit = load_in_4bit,- retains_history = not use_vlm or mlx_vlm_snapshot_store_available(),- kv_bits = None if self._turboquant else _normalize_mlx_kv_bits(kv_bits),- vision = True if speculates and not is_vision else None,- ),+ if is_distributed or is_lora or dtype is not None:+ return _mlx_offload_request(knobs, None)+ priced = dict(+ pinned = _positive_int(max_seq_length),+ load_in_4bit = load_in_4bit,+ retains_history = not use_vlm or mlx_vlm_snapshot_store_available(),+ kv_bits = None if self._turboquant else _normalize_mlx_kv_bits(kv_bits),+ vision = True if speculates and not is_vision else None,)+ def plan(model_dir, wanted):+ drafter = speculates and mlx_speculative.offload_drafter(+ spec_mode,+ spec_draft_model,+ model_dir = model_dir,+ target_name = model_name,+ allowed = spec_drafters_allowed,+ )+ chosen, alone = mlx_resolve_drafter_offload(+ model_dir, wanted, drafter or None, auto = spec_mode == "auto", **priced+ )+ # A repeat call sees the fractions and plans no step: keep the first baseline.+ if "auto" in wanted:+ offload_baseline.update(route = alone and mlx_offload_route(alone))+ return chosen++ return _mlx_offload_request(knobs, plan)++ offload_baseline = {"route": None}+offload = offload_request()load_kwargs.update(offload["kwargs"])@@ -5459,6 +5531,7 @@ class MLXInferenceBackend:source,load_in_4bit = load_in_4bit,costless = spec_mode == "auto",+ baseline = offload_baseline["route"],**_offloaded,)diff --git a/studio/backend/core/inference/mlx_memory.py b/studio/backend/core/inference/mlx_memory.pyindex 6661d033e42..049dee429a2 100644--- a/studio/backend/core/inference/mlx_memory.py+++ b/studio/backend/core/inference/mlx_memory.py@@ -1513,12 +1513,17 @@ def mlx_offload_plan(prefill_chunk: Optional[int] = None,load_in_4bit: bool = False,vision: Optional[bool] = None,+ drafter: Optional[tuple] = None,) -> Optional[tuple]:"""The ``(ple, experts, prefill_step)`` unsloth_zoo's 50/50 rule takes for this load, priced- as Studio prices it; a knob not ``"auto"`` and a pinned ``context`` are kept. When nothing fits,- everything offloadable goes to disk. None when the load cannot be planned."""+ as Studio prices it, with ``drafter`` when given; a knob not ``"auto"`` and a pinned ``context``+ are kept. When nothing fits, everything offloadable goes to disk. None when the load cannot be planned."""planner = mlx_offload_planner()- sizing = _size_load(model_dir, kv_bits, prefill_chunk, load_in_4bit, vision)+ sizing = _size_load(model_dir, kv_bits, prefill_chunk, load_in_4bit, vision, drafter)+ if sizing is None and drafter is not None:+ # A drafter that cannot be sized cannot attach either: plan the target as if none was asked for.+ drafter = None+ sizing = _size_load(model_dir, kv_bits, prefill_chunk, load_in_4bit, vision)if planner is None or sizing is None:return Nonewith _on_route(vision):@@ -1527,7 +1532,7 @@ def mlx_offload_plan(def context_cost(tokens, step):if step not in sized:- sized[step] = _size_load(model_dir, kv_bits, step, load_in_4bit, vision)+ sized[step] = _size_load(model_dir, kv_bits, step, load_in_4bit, vision, drafter)priced = sized[step] and _priced_at(sized[step], tokens)if priced is None:raise ValueError(f"cannot price {tokens} tokens")diff --git a/studio/backend/core/inference/mlx_speculative.py b/studio/backend/core/inference/mlx_speculative.pyindex 994894a8bde..669eb760f31 100644--- a/studio/backend/core/inference/mlx_speculative.py+++ b/studio/backend/core/inference/mlx_speculative.py@@ -297,6 +297,13 @@ def resolve_speculation(return SpecResolution(mode, tuple(sources), copies = True, reason = reason)+def offload_drafter(speculative_type, spec_draft_model, **where) -> Optional[tuple]:+ """``(path, builtin)`` of the drafter a load tries first, for an auto offload plan to make room for.+ ``where`` as ``resolve_speculation`` takes it."""+ sources = resolve_speculation(speculative_type, spec_draft_model, **where).sources+ return (sources[0].path, sources[0].builtin) if sources else None++def speculates_on_route(mode: str,vision: bool,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex f3988fbf827..398af25de12 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -14447,13 +14447,16 @@ def _mlx_estimate_fitted_context(config, model_dir: str, load_in_4bit: bool, kv_def _mlx_estimate_offload(- request, config, model_dir: str, load_in_4bit: bool, kv_bits: Optional[int]-) -> tuple[dict, tuple]:- """``({"offload": (ple, experts)} or {}, offloadable parts)`` for an MLX load of *request*,- "auto" decided as the load does, on its route; neither if the load quantizes, which unsloth_zoo+ request, config, model_identifier, model_dir: str, load_in_4bit: bool, kv_bits: Optional[int]+) -> tuple[dict, tuple, Optional[dict]]:+ """``({"offload": (ple, experts)} or {}, offloadable parts, baseline route)`` for an MLX load of+ *request*, "auto" decided as the load does, on its route, with the target-only route an auto+ drafter's costless check measures against; none of them if the load quantizes, which unsloth_zoorefuses."""+ from core.inference import mlx_speculativefrom core.inference.mlx_inference import (- mlx_resolve_offload,+ mlx_offload_route,+ mlx_resolve_drafter_offload,mlx_vlm_snapshot_store_available,normalize_mlx_offload,)@@ -14463,19 +14466,28 @@ def _mlx_estimate_offload(if load_in_4bit and not (checkpoint.get("quantization") or checkpoint.get("quantization_config")):- return {}, ()+ return {}, (), Nonevision = True if _mlx_estimate_speculates(request, model_dir) else Nonetry:parts = mlx_offloadable_parts(model_dir, vision)except Exception as exc:logger.info("MLX offload eligibility unknown for %s: %s", model_dir, exc)parts = ()- offload = mlx_resolve_offload(+ drafter = vision and mlx_speculative.offload_drafter(+ request.speculative_type,+ request.spec_draft_model,+ model_dir = model_dir,+ target_name = model_identifier,+ allowed = _discoverable_drafters(model_identifier),+ )+ offload, alone = mlx_resolve_drafter_offload(model_dir,(normalize_mlx_offload(request.mlx_ple_offload),normalize_mlx_offload(request.mlx_expert_offload),),+ drafter or None,+ auto = mlx_speculative.mlx_spec_mode(request.speculative_type) == "auto",pinned = request.max_seq_length or None,load_in_4bit = load_in_4bit,# As the load: any mlx-vlm route, a speculative text load included, keeps no history without the store.@@ -14488,7 +14500,8 @@ def _mlx_estimate_offload()*offload, step = offloadroute = {"offload": tuple(offload)} if any(offload) else {}- return ({**route, "prefill_chunk": step} if step else route), parts+ route = {**route, "prefill_chunk": step} if step else route+ return route, parts, alone and mlx_offload_route(alone)def _mlx_offload_warning(info: dict) -> Optional[str]:@@ -14531,6 +14544,7 @@ def _mlx_estimate_drafter(ceiling,load_in_4bit: bool,offload_route: Optional[dict] = None,+ baseline: Optional[dict] = None,):"""``((path, builtin), fitted context, speculates)`` of an MLX load of *request*: the drafter itwould attach, chosen as the load chooses it, and whether it speculates at all (so loads through mlx-vlm)."""@@ -14555,6 +14569,7 @@ def _mlx_estimate_drafter(source,load_in_4bit = load_in_4bit,costless = mode == "auto",+ baseline = baseline,**(offload_route or {}),)if attaches:@@ -20480,8 +20495,8 @@ async def estimate_memory(if mlx_kv_bits is not None and mlx_kv_quant_is_refused(model_dir, mlx_kv_bits):mlx_kv_bits = Nonemlx_named_ctx = request.max_seq_length or 0- mlx_offload, mlx_offloadable = _mlx_estimate_offload(- request, config, model_dir, mlx_load_in_4bit, mlx_kv_bits+ mlx_offload, mlx_offloadable, mlx_offload_baseline = _mlx_estimate_offload(+ request, config, model_identifier, model_dir, mlx_load_in_4bit, mlx_kv_bits)mlx_drafter, mlx_fitted_ctx, mlx_speculates = _mlx_estimate_drafter(request,@@ -20490,6 +20505,7 @@ async def estimate_memory(_mlx_estimate_ceiling(model_dir),mlx_load_in_4bit,mlx_offload,+ mlx_offload_baseline,)mlx_route = {**({"vision": True} if mlx_speculates else {}), **mlx_offload}if not mlx_named_ctx and mlx_drafter is None:diff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.pyindex d54443552f0..cc92b9c59bf 100644--- a/studio/backend/tests/test_memory_estimate.py+++ b/studio/backend/tests/test_memory_estimate.py@@ -902,6 +902,35 @@ class TestEstimateMemoryRoute:prefill_chunk = 8192,)assert (asked["offload"], asked["prefill_chunk"]) == ((None, 0.6), 8192)+ seen = []++ def costless(attached, alone):+ monkeypatch.setattr(+ mlx_memory,+ "mlx_fit_outcome",+ lambda d, *, drafter = None, offload = None, prefill_chunk = None, **_: seen.append(+ (bool(drafter), offload, prefill_chunk)+ )+ or (attached if drafter else alone),+ )+ return mlx_inference.mlx_drafter_fit(+ "/m",+ 32768,+ None,+ source,+ load_in_4bit = False,+ costless = True,+ offload = (None, 0.6),+ prefill_chunk = 8192,+ baseline = {"offload": (None, 0.5), "prefill_chunk": 4096},+ )[0]++ assert costless(("fitted", 10240), ("fitted", 8192)) is True+ assert seen == [(True, (None, 0.6), 8192), (False, (None, 0.5), 4096)]+ assert costless(("fits", None), ("fitted", 8192)) is True+ assert costless(("fitted", 9216), ("fitted", 11520)) is False+ assert costless(("fitted", 8192), ("fits", None)) is False+ assert costless(("fits", None), ("unsizable", None)) is Falsedef test_mlx_model_not_on_disk_is_not_downloaded(self, monkeypatch):self._mlx_target(monkeypatch, None)@@ -1123,6 +1152,7 @@ class TestEstimateMemoryRoute:def test_an_mlx_estimate_prices_the_offload_the_load_applies(self, monkeypatch, tmp_path):import core.inference.mlx_inference as mlx_inferenceimport core.inference.mlx_memory as mlx_memory+ import core.inference.mlx_speculative as mlx_speculativeself._mlx_target(monkeypatch, str(tmp_path))seen, four_bit, planned = [], {"on": False}, []@@ -1136,7 +1166,11 @@ class TestEstimateMemoryRoute:mlx_memory,"mlx_offload_plan",lambda d, **kw: planned.append(kw)- or (kw["ple"], 0.6 if kw["experts"] == "auto" else kw["experts"], 8192),+ or (+ kw["ple"],+ (0.62 if kw["drafter"] else 0.6) if kw["experts"] == "auto" else kw["experts"],+ 8192,+ ),)monkeypatch.setattr(mlx_memory,@@ -1159,13 +1193,33 @@ class TestEstimateMemoryRoute:assert seen[-1][1] == 8192assert planned[-1]["vision"] is Nonewith monkeypatch.context() as patch:+ source = mlx_speculative.DrafterSource("mtp", str(tmp_path), True)+ patch.setattr(+ mlx_speculative,+ "resolve_speculation",+ lambda mode, named, **where: mlx_speculative.SpecResolution(mode, (source,)),+ )+ patch.setattr(ri, "_mlx_estimate_speculates", lambda request, model_dir: False)+ estimate(mlx_ple_offload = "off", speculative_type = "mtp")+ assert planned[-1]["drafter"] is None # refused (KV quantization): no room to makepatch.setattr(ri, "_mlx_estimate_speculates", lambda request, model_dir: True)- estimate(mlx_ple_offload = "off")- assert planned[-1]["vision"] is True and len(planned) == 2+ fits = []+ patch.setattr(+ mlx_inference,+ "mlx_drafter_fit",+ lambda *a, **kw: fits.append((kw["offload"], kw.get("baseline"))) or (True, None),+ )+ assert price(mlx_ple_offload = "off") == (None, 0.62)+ assert [p["drafter"] for p in planned[-2:]] == [(str(tmp_path), True), None]+ assert fits[-1] == ((None, 0.62), {"offload": (None, 0.6), "prefill_chunk": 8192})+ estimate(mlx_ple_offload = "off", speculative_type = "mtp")+ assert planned[-1]["drafter"] == (str(tmp_path), True)+ assert fits[-1] == ((None, 0.62), None)+ assert planned[-1]["vision"] is True and len(planned) == 5four_bit["on"] = True # already quantized: nothing for the load to quantize, so it offloadsassert price(mlx_ple_offload = 1.0) == (1.0, 0.6)(tmp_path / "config.json").write_text("{}")- assert price(mlx_ple_offload = 1.0) is None and len(planned) == 3+ assert price(mlx_ple_offload = 1.0) is None and len(planned) == 6off = estimate(mlx_ple_offload = "off", mlx_expert_offload = "off")assert off.mlx_offload.offloadable == []four_bit["on"] = False@@ -3720,23 +3774,34 @@ def test_offload_is_priced_by_what_unsloth_zoos_offload_takes(tmp_path, monkeypadef test_auto_offload_is_planned_on_the_route_the_load_takes(monkeypatch):- routes = []+ routes, costs = [], []decide = lambda inventory, context_cost, **kw: {- "context": context_cost(512, 8192) and 512,+ "context": costs.append(context_cost(512, 8192)) or costs[-1] and 512,"ple": None if inventory["ple"] else 1.0,"experts": 0.5,}- monkeypatch.setattr(mm, "_priced_at", lambda sizing, tokens: SimpleNamespace(total_bytes = 11))+ # A drafter's weights and cache are priced with the context, so a plan making room for one sees them there.+ monkeypatch.setattr(+ mm,+ "_priced_at",+ lambda sizing, tokens: SimpleNamespace(total_bytes = 11 + 5 * bool(sizing.drafter)),+ )monkeypatch.setattr(mm, "mlx_offload_planner", lambda: SimpleNamespace(plan_offload = decide))monkeypatch.setattr(mm, "_snapshot_config", lambda d: {"model_type": "qwen3_moe", "quantization": {"bits": 4}})monkeypatch.setattr(mm, "_checkpoint_fingerprint", lambda d: ())+ drafters = []monkeypatch.setattr(mm,"_size_load",- lambda d, kv, chunk, four, vision = None: routes.append(("sized", vision))- or SimpleNamespace(weights = 10, chunk = 512),+ lambda d, kv, chunk, four, vision = None, drafter = None: routes.append(("sized", vision))+ or drafters.append(drafter)+ or (+ None+ if drafter == ("/unsizable", False)+ else SimpleNamespace(weights = 10, chunk = 512, drafter = drafter)+ ),)monkeypatch.setattr(mm, "_lazy_checkpoint", lambda d, config: mm._builds_on_mlx_vlm(config))found = lambda tree: {@@ -3760,6 +3825,16 @@ def test_auto_offload_is_planned_on_the_route_the_load_takes(monkeypatch):("inventory", True),("sized", True),]+ drafters.clear(), costs.clear()+ mm._clear_sizing_cache()+ mm.mlx_offload_plan("/x", budget_bytes = 1, max_ctx = 512, vision = True, drafter = ("/x", True))+ assert drafters == [("/x", True)] * 2 and costs == [6] # the target alone costs 1+ # One that cannot be sized is skipped by the load too: the target is still planned, alone.+ drafters.clear(), costs.clear()+ mm._clear_sizing_cache()+ unsizable = ("/unsizable", False)+ planned = mm.mlx_offload_plan("/x", budget_bytes = 1, max_ctx = 512, vision = True, drafter = unsizable)+ assert planned == (1.0, 0.5, None) and drafters == [unsizable, None, None] and costs == [1]def test_the_offload_probe_maps_a_text_model_on_the_route_unsloth_zoo_builds_it(monkeypatch):diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 0f8e03b5c37..7f71f3b482b 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -1283,6 +1283,118 @@ def test_auto_offload_is_planned_as_the_load_is_priced(monkeypatch):assert request["prefill_step"] == 8192+def test_an_auto_drafter_gets_offload_room_only_within_the_cap_where_it_then_fits(monkeypatch):+ from core.inference import mlx_inference as mi++ plans, fits, asked = {}, {"on": True}, []+ monkeypatch.setattr(+ mi, "mlx_resolve_offload", lambda d, knobs, drafter = None, **_: plans[bool(drafter)]+ )+ monkeypatch.setattr(mi, "mlx_checkpoint_window", lambda d: 32768)+ monkeypatch.setattr(+ mi,+ "mlx_drafter_fit",+ lambda d, ceiling, pinned, source, **kw: asked.append(+ (ceiling, pinned, source.path, source.builtin, kw)+ )+ or (fits["on"], None),+ )+ resolve = lambda auto, drafter = ("/head", True): mi.mlx_resolve_drafter_offload(+ "/snap", ("auto", "auto"), drafter, auto = auto, pinned = None, load_in_4bit = False+ )+ cases = [ # (with the drafter, without it, the auto plan)+ ((0.5, 0.53, 4096), (0.5, 0.5, 8192), "room"),+ ((None, 0.04, 4096), (None, None, 8192), "room"),+ ((0.5, 0.55, 4096), (0.5, 0.5, 8192), "alone"),+ ((0.55, 0.5, 4096), (0.5, 0.5, 8192), "alone"),+ ((None, 0.05, 4096), (None, None, 8192), "alone"),+ ]+ for room, alone, chosen in cases:+ plans.update({True: room, False: alone})+ assert resolve(True) == ({"room": room, "alone": alone}[chosen], alone)+ assert resolve(False) == (room, None) # an explicit mode's drafter always gets its room+ assert resolve(True, None) == resolve(False, None) == (alone, None)+ # Room only the costless fit would then use: asked on the room plan against the target-only one.+ plans.update({True: (0.5, 0.53, 4096), False: (0.5, 0.5, 8192)})+ asked.clear(), fits.update(on = False)+ assert resolve(True) == ((0.5, 0.5, 8192),) * 2+ assert asked == [+ (+ 32768,+ None,+ "/head",+ True,+ {+ "load_in_4bit": False,+ "costless": True,+ "baseline": {"offload": (0.5, 0.5), "prefill_chunk": 8192},+ "offload": (0.5, 0.53),+ "prefill_chunk": 4096,+ },+ )+ ]+ plans.update({True: (0.5, 0.5, 8192)})+ assert resolve(True) == ((0.5, 0.5, 8192),) * 2 and len(asked) == 1+ # An explicit drafter priced not to fit its room plan keeps the target-only plan, not all-on-disk.+ plans.update({True: (None, 1.0, None), False: (None, 0.78, 8192)})+ asked.clear()+ assert resolve(False) == ((None, 0.78, 8192), None)+ assert asked[-1][4] == {"load_in_4bit": False, "offload": (None, 1.0), "prefill_chunk": None}+ fits.update(on = None) # unpriceable: the load keeps it, so does the plan+ assert resolve(False) == ((None, 1.0, None), None)+++def test_an_auto_load_fits_its_drafter_against_the_target_only_plan(monkeypatch, tmp_path):+ pytest.importorskip("mlx.core")+ from core.inference import mlx_inference as mi+ from core.inference import mlx_memory as mm+ from core.inference import mlx_speculative++ fits = []++ class _Loader:+ @staticmethod+ def from_pretrained(name, **kwargs):+ kwargs["offload"](str(tmp_path)), kwargs["offload"](str(tmp_path)) # as unsloth_zoo may+ model = SimpleNamespace(+ _src_path = str(tmp_path), _unsloth_offload = {"experts": {"on_disk_bytes": 1}}+ )+ return model, SimpleNamespace()++ loader = types.ModuleType("unsloth_zoo.mlx.loader")+ loader.FastMLXModel = _Loader+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.loader", loader)+ monkeypatch.setattr(mm, "mlx_offload_planner", lambda: object())+ monkeypatch.setattr(+ mi,+ "mlx_resolve_offload",+ lambda d, knobs, drafter = None, **_: (+ ((None, 0.52, 4096) if drafter else (None, 0.5, 8192))+ if "auto" in knobs+ else (*knobs, None)+ ),+ )+ monkeypatch.setattr(mi, "_classify_mlx_audio_type", lambda *a, **k: None)+ monkeypatch.setattr(+ mi.MLXInferenceBackend, "_resolve_context_lengths", lambda *a: (8192, 8192, 8192)+ )+ source = mlx_speculative.DrafterSource("mtp", str(tmp_path), True)+ monkeypatch.setattr(mlx_speculative, "speculation_refusal", lambda **_k: None)+ monkeypatch.setattr(+ mlx_speculative,+ "resolve_speculation",+ lambda mode, *_a, **_k: mlx_speculative.SpecResolution(mode, (source,)),+ )+ monkeypatch.setattr(mi, "mlx_drafter_fit", lambda *a, **kw: fits.append(kw) or (True, None))+ config = SimpleNamespace(identifier = "org/moe", is_vision = True, is_lora = False)++ mi.MLXInferenceBackend().load_model(config, max_seq_length = 0)+ assert (fits[-1]["offload"], fits[-1]["prefill_chunk"]) == ((None, 0.52), 4096)+ assert fits[-1]["baseline"] == {"offload": (None, 0.5), "prefill_chunk": 8192}+ mi.MLXInferenceBackend().load_model(config, max_seq_length = 0, speculative_type = "mtp")+ assert fits[-1]["offload"] == (None, 0.52) and fits[-1]["baseline"] is None++@pytest.mark.parametrize("decided_on_mlx_vlm", [False, True])def test_a_load_falling_back_to_mlx_lm_plans_auto_offload_again(monkeypatch, decided_on_mlx_vlm):pytest.importorskip("mlx.core")@@ -1304,7 +1416,7 @@ def test_a_load_falling_back_to_mlx_lm_plans_auto_offload_again(monkeypatch, decreturn SimpleNamespace(config = {}), SimpleNamespace()def resolve(model_dir, knobs, **kw):- plans.append((knobs, kw["vision"]))+ plans.append((knobs, kw["vision"], kw.get("drafter")))# A plan for the mlx-vlm route differs from the one mlx-lm needs, so a reused plan shows.return (None, 0.25, 4096) if kw["vision"] else (None, 1.0, 8192)@@ -1327,7 +1439,10 @@ def test_a_load_falling_back_to_mlx_lm_plans_auto_offload_again(monkeypatch, decconfig = SimpleNamespace(identifier = "org/moe", is_vision = False, is_lora = False)mi.MLXInferenceBackend().load_model(config, speculative_type = "dflash")- assert plans[-1] == (("auto", "auto"), None)+ # The speculative mlx-vlm plan makes room for the drafter; the mlx-lm one, which does not speculate, does not.+ assert plans == [(("auto", "auto"), True, ("/drafter", False))] * decided_on_mlx_vlm + [+ (("auto", "auto"), None, None)+ ]assert applied == [{"ple": None, "experts": 1.0}]diff --git a/studio/backend/tests/test_mlx_speculative.py b/studio/backend/tests/test_mlx_speculative.pyindex 31d0e1eb54d..d1144afa5e2 100644--- a/studio/backend/tests/test_mlx_speculative.py+++ b/studio/backend/tests/test_mlx_speculative.py@@ -95,6 +95,22 @@ def test_auto_takes_every_cached_kind_in_preference_order(cache):assert _resolve("ngram-mod").speculative+def test_an_auto_offload_plan_makes_room_for_a_modes_first_drafter(cache, tmp_path):+ cache({"a/Qwen3.5-4B-DFlash": _DFLASH, "g/Qwen3.5-4B-assistant": _ASSISTANT}, True)+ target = str(tmp_path / "org--Qwen3.5-4B-4bit")+ drafter = lambda mode, named = None: spec.offload_drafter(+ mode, named, model_dir = target, target_name = _TARGET+ )+ assert drafter("mtp") == (target, True) # the head, before the cached assistant+ assert drafter("mtp", "g/Qwen3.5-4B-assistant") == (+ str(tmp_path / "g--Qwen3.5-4B-assistant"),+ False,+ )+ assert drafter("dflash") == (str(tmp_path / "a--Qwen3.5-4B-DFlash"), False)+ assert drafter("auto") == (target, True)+ assert [drafter(mode) for mode in ("off", "ngram", "dspark")] == [None] * 3++def test_cached_drafters_are_matched_by_shape_and_weights_then_marked_by_name(cache, tmp_path):shaped = {**_DFLASH, "hidden_size": 8, "num_target_layers": 4}narrow = {"target_hidden_size": 8, "transformer_layer_config": {"hidden_size": 2}}