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
Studio: Neural Engine Prefill toggle for MLX models (#15954)
Long Yixing70750d9a0457
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 2ee53103b4e..1c9d7cadcdb 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -1065,6 +1065,44 @@ def _int8_prefill_status(requested, model):return status+def _ane_prefill_zoo():+ """unsloth_zoo's MLX inference module when it can run Neural Engine prefill, else None."""+ try:+ zoo = importlib.import_module("unsloth_zoo.mlx.inference")+ if "ane_prefill" in inspect.signature(zoo.ane_prefill_mlp).parameters:+ return zoo+ except Exception:+ pass+ return None+++def _ane_prefill_status(requested, model):+ """Whether a load runs Neural Engine prefill: asked for, and the loaded model can use it here. Read again after+ the warm-up, whose first prepare settles which layers attach."""+ status = {"requested": bool(requested), "active": False, "reason": "", "scope": None}+ if not requested:+ return status+ zoo = _ane_prefill_zoo()+ if zoo is None:+ status["reason"] = "unsupported_zoo"+ return status+ try:+ verdict = zoo.ane_prefill_available(model)+ except Exception as exc:+ if is_metal_queue_dead(exc):+ raise+ logger.warning("MLX Neural Engine prefill check failed: %s", exc)+ status["reason"] = "probe_failed"+ return status+ status["reason"] = verdict.reason+ if verdict.available:+ status["active"] = True+ status["scope"] = zoo.ane_prefill_mlp+ else:+ logger.info("MLX Neural Engine prefill not applied: %s", verdict.reason)+ return status++_MLX_OFFLOAD_PARTS = (("ple", "PLE tables"), ("experts", "quantized routed experts"))@@ -1309,6 +1347,37 @@ def mlx_int8_prefill_checkpoint_status(model_dir) -> tuple[bool, str]:return answer+_ane_prefill_checkpoint_cache: dict = {}+_ane_prefill_checkpoint_lock = threading.Lock()+++def mlx_ane_prefill_checkpoint_status(model_dir) -> tuple[bool, str]:+ """(available, reason) of Neural Engine prefill for a downloaded MLX checkpoint, without loading it."""+ check = getattr(_ane_prefill_zoo(), "ane_prefill_checkpoint_available", None)+ if check is None:+ return False, "unsupported_zoo"+ try:+ from core.inference.mlx_memory import _checkpoint_fingerprint+ key = (os.path.realpath(model_dir), _checkpoint_fingerprint(model_dir))+ except Exception:+ key = None+ with _ane_prefill_checkpoint_lock:+ if key in _ane_prefill_checkpoint_cache:+ return _ane_prefill_checkpoint_cache[key]+ try:+ verdict = check(model_dir)+ answer = (bool(verdict.available), verdict.reason)+ except Exception as exc:+ logger.debug("MLX Neural Engine prefill checkpoint check failed for %s: %s", model_dir, exc)+ return False, "probe_failed"+ if key is not None and answer[1] != "probe_failed":+ with _ane_prefill_checkpoint_lock:+ _ane_prefill_checkpoint_cache[key] = answer+ while len(_ane_prefill_checkpoint_cache) > 32:+ _ane_prefill_checkpoint_cache.pop(next(iter(_ane_prefill_checkpoint_cache)))+ return answer++def _vlm_generation_context():import mlx.core as mxfrom mlx_vlm.generate import generation_stream@@ -4292,7 +4361,7 @@ class _TextBatchSession:self._held.enter_context(_temporary_mlx_adapter_state(backend._model, adapter_state))- self._held.enter_context(backend._int8_prefill_scope())+ self._held.enter_context(backend._prefill_decision_scopes())self._held.enter_context(backend._generation_scopes("batch"))self.generator = BatchGenerator(backend._model,@@ -4631,7 +4700,7 @@ class _VisionBatchSession:self._held.enter_context(_temporary_mlx_adapter_state(backend._model, adapter_state))- self._held.enter_context(backend._int8_prefill_scope())+ self._held.enter_context(backend._prefill_decision_scopes())self._speculative = getattr(backend, "_speculative_draft", None)self._decodes_ids = _vision_batch_reports_ids(engine, self._speculative)self.stream = BatchStream(@@ -4859,6 +4928,7 @@ class MLXInferenceBackend:# Load-time knobs read by all generation paths; bound early so a failed load still leaves dicts.self._kv_quant = _kv_quant_status(None, None, False)self._int8_prefill = _int8_prefill_status(False, None)+ self._ane_prefill = _ane_prefill_status(False, None)self._kv_cache_window = Noneself._kv_context_budget = Noneself._served_context = None@@ -4945,6 +5015,7 @@ class MLXInferenceBackend:bool(getattr(self, "_turboquant", False)),self._kv_cache_window,bool(self._int8_prefill.get("active")),+ bool(self._ane_prefill.get("active")),self._prefill_step,self._resume_load_args,)@@ -5260,20 +5331,25 @@ class MLXInferenceBackend:max_new_tokens = max(1, min(int(max_new_tokens), int(budget) - len(prompt_tokens)))return max_new_tokens- def _int8_prefill_scope(self):- """Outermost scope of a generation, which every Zoo scope nested in it inherits. Pinned- off when inactive, so Zoo's full-precision NAX routes still run and no scope reads the Int8- Prefill env."""- scope = (getattr(self, "_int8_prefill", None) or {}).get("scope")- if scope is not None:- return scope(self._model, True)- if _int8_prefill_zoo() is None:- return nullcontext()- return _mlx_optional_fusion("nax_quantized_linear", self._model, False)+ def _prefill_decision_scopes(self):+ """Outermost scopes of a generation, whose Int8 and Neural Engine Prefill decisions every Zoo+ scope nested in them inherits. Each is pinned off when inactive, so Zoo's full-precision NAX+ routes still run and no scope reads either env switch."""+ with ExitStack() as stack: # a scope that fails to enter unwinds the ones before it+ for status, zoo, name in (+ (getattr(self, "_int8_prefill", None), _int8_prefill_zoo, "nax_quantized_linear"),+ (getattr(self, "_ane_prefill", None), _ane_prefill_zoo, "ane_prefill_mlp"),+ ):+ scope = (status or {}).get("scope")+ if scope is not None:+ stack.enter_context(scope(self._model, True))+ elif zoo() is not None:+ stack.enter_context(_mlx_optional_fusion(name, self._model, False))+ return stack.pop_all()def _generation_scopes(self, *call):"""Zoo's scopes for a generation of this load, under its Int8 Prefill decision. Nested in- _int8_prefill_scope, which stays outermost."""+ _prefill_decision_scopes, which stays outermost."""active = (getattr(self, "_int8_prefill", None) or {}).get("active", False)return _mlx_inference_scopes(self._model, call, active)@@ -5542,6 +5618,7 @@ class MLXInferenceBackend:kv_quant = None,chat_template_override = None,int8_prefill = False,+ ane_prefill = False,speculative_type = None,spec_draft_n_max = None,spec_draft_model = None,@@ -5939,6 +6016,7 @@ class MLXInferenceBackend:self._kv_quant["eligibility"],)self._int8_prefill = _int8_prefill_status(int8_prefill, self._model)+ self._ane_prefill = _ane_prefill_status(ane_prefill, self._model)# Captured before install so the shipped template is kept, from the render target, not the nested tokenizer, which would overwrite the processor templatenative_source = _native_template_source(self._tokenizer, self._processor)@@ -6026,6 +6104,9 @@ class MLXInferenceBackend:"mlx_int8_prefill": self._int8_prefill["active"],"mlx_int8_prefill_requested": self._int8_prefill["requested"],"mlx_int8_prefill_reason": self._int8_prefill["reason"],+ "mlx_ane_prefill": self._ane_prefill["active"],+ "mlx_ane_prefill_requested": self._ane_prefill["requested"],+ "mlx_ane_prefill_reason": self._ane_prefill["reason"],"mlx_offload": _offload,"chat_template_override_requested": self._template_override["requested"],"chat_template_override_reason": self._template_override["reason"],@@ -6043,8 +6124,14 @@ class MLXInferenceBackend:self._model_fusion.enter_context(_mlx_optional_fusion("fused_moe_gate_up", model))# Every rank of a distributed load must run each forward together.if not is_distributed:- with mlx_rng_preserved(), self._int8_prefill_scope():+ with mlx_rng_preserved(), self._prefill_decision_scopes():_mlx_warm_inference(model, self._int8_prefill["active"])+ if self._ane_prefill["active"]:+ self._ane_prefill = _ane_prefill_status(True, model)+ self.models[model_name].update(+ mlx_ane_prefill = self._ane_prefill["active"],+ mlx_ane_prefill_reason = self._ane_prefill["reason"],+ )logger.info("Model %s loaded successfully", model_name)return True@@ -6141,6 +6228,14 @@ class MLXInferenceBackend:import gcself._model_fusion.close()+ if self._ane_prefill["active"] and self._model is not None:+ # The Neural Engine worker can hold its last request's program past the model; a failed release must not+ # stop the unload.+ try:+ _ane_prefill_zoo().release_ane_prefill(self._model)+ except Exception as exc:+ logger.warning("MLX Neural Engine prefill release failed: %s", exc)+ self._ane_prefill = _ane_prefill_status(False, None)if model_name in self.models:del self.models[model_name]self._speculative_draft = None@@ -6689,7 +6784,7 @@ class MLXInferenceBackend:with (self._generation_lock,_temporary_mlx_adapter_state(self._model, _adapter_state),- self._int8_prefill_scope(),+ self._prefill_decision_scopes(),self._generation_scopes(),):input_embeddings = None@@ -7641,7 +7736,7 @@ class MLXInferenceBackend:with (self._generation_lock,_temporary_mlx_adapter_state(self._model, _adapter_state),- self._int8_prefill_scope(),+ self._prefill_decision_scopes(),ExitStack() as generation_scope,session_scope,):@@ -8065,7 +8160,7 @@ class MLXInferenceBackend:with (self._generation_lock,_temporary_mlx_adapter_state(self._model, _adapter_state),- self._int8_prefill_scope(),+ self._prefill_decision_scopes(),ExitStack() as clips,):batch = [@@ -8267,7 +8362,7 @@ class MLXInferenceBackend:with (self._generation_lock,_temporary_mlx_adapter_state(self._model, use_adapter),- self._int8_prefill_scope(),+ self._prefill_decision_scopes(),ExitStack() as generation_scope,):# As on the image path: the tower gets the headroom, under the lock.diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 964abfd0c15..933cb7b384c 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -274,6 +274,9 @@ _MLX_RUNTIME_MIRROR_FIELDS = ("mlx_int8_prefill","mlx_int8_prefill_requested","mlx_int8_prefill_reason",+ "mlx_ane_prefill",+ "mlx_ane_prefill_requested",+ "mlx_ane_prefill_reason","mlx_offload","chat_template_override_requested","chat_template_override_reason",@@ -2005,6 +2008,7 @@ class InferenceOrchestrator:mlx_distributed: bool = False,mlx_kv_quant: Optional[str] = None,mlx_int8_prefill: bool = False,+ mlx_ane_prefill: bool = False,mlx_offload: tuple = (None, None),speculative_type: Optional[str] = None,spec_draft_n_max: Optional[int] = None,@@ -2083,6 +2087,7 @@ class InferenceOrchestrator:else None,"mlx_kv_quant": mlx_kv_quant,"mlx_int8_prefill": bool(mlx_int8_prefill),+ "mlx_ane_prefill": bool(mlx_ane_prefill),"mlx_offload": tuple(mlx_offload),"speculative_type": speculative_type,"spec_draft_n_max": spec_draft_n_max,diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex f15e63cbba6..326ac963020 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -777,6 +777,7 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:load_kwargs["distributed_group"] = config.get("_mlx_distributed_group")load_kwargs["kv_quant"] = config.get("mlx_kv_quant")load_kwargs["int8_prefill"] = bool(config.get("mlx_int8_prefill"))+ load_kwargs["ane_prefill"] = bool(config.get("mlx_ane_prefill"))load_kwargs["offload"] = tuple(config.get("mlx_offload") or (None, None))load_kwargs["speculative_type"] = config.get("speculative_type")load_kwargs["spec_draft_n_max"] = config.get("spec_draft_n_max")@@ -885,6 +886,9 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:"mlx_int8_prefill","mlx_int8_prefill_requested","mlx_int8_prefill_reason",+ "mlx_ane_prefill",+ "mlx_ane_prefill_requested",+ "mlx_ane_prefill_reason","mlx_offload","chat_template_override_requested","chat_template_override_reason",diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 817220e68ac..de476c68dd6 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -215,6 +215,15 @@ class LoadRequest(BaseModel):"reason otherwise."),)+ mlx_ane_prefill: bool = Field(+ False,+ description = (+ "Experimental, MLX only: run part of each MLP on the Apple Neural Engine alongside the "+ "GPU for faster prompt processing. Lossy: the Neural Engine uses int8 weights, so "+ "outputs change slightly. Applied only when the model supports it and the split is "+ "measured faster here; the status reports the reason otherwise."+ ),+ )mlx_ple_offload: MlxOffload = Field(None,description = (@@ -1181,6 +1190,27 @@ class Int8PrefillAvailabilityResponse(BaseModel):)+class AnePrefillAvailabilityRequest(BaseModel):+ """A model whose run settings may offer MLX Neural Engine prefill."""++ model_path: str = Field(..., description = "Model identifier or local path")+ hf_token: Optional[str] = Field(None, description = "Token for gated repositories")++ _resolve_the_handle = field_validator("model_path")(resolve_inventory_handle)+++class AnePrefillAvailabilityResponse(BaseModel):+ """Whether a load of this model could run MLX Neural Engine prefill, judged from its downloaded files."""++ available: bool+ reason: Optional[str] = Field(+ None,+ description = "Cause when available is false: 'not_downloaded', 'unsupported_model', "+ "'unsupported_zoo', 'probe_failed', or unsloth_zoo's own reason ('no_neural_engine', "+ "'no_eligible_mlps').",+ )++class MlxDraftersRequest(BaseModel):model_path: str = Field(..., description = "Model identifier or local path of the target")@@ -1832,6 +1862,17 @@ class _InferenceRuntimeFields(BaseModel):description = "Why requested int8 prefill is not active, as unsloth_zoo reports it ""(for example nax_unavailable or no_eligible_projections)",)+ mlx_ane_prefill: Optional[bool] = Field(+ None, description = "Whether MLX Neural Engine prefill is active for the loaded model"+ )+ mlx_ane_prefill_requested: Optional[bool] = Field(+ None, description = "Whether the load asked for MLX Neural Engine prefill"+ )+ mlx_ane_prefill_reason: Optional[str] = Field(+ None,+ description = "Why requested Neural Engine prefill is not active, as unsloth_zoo reports it "+ "(for example no_neural_engine, no_eligible_mlps, no_gain, not_enough_memory or released)",+ )mlx_offload: Optional[MlxOffloadStatus] = Field(None, description = "MLX: weights read from disk")chat_template: Optional[str] = Field(None,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 41cd37ecec5..5c740591c2e 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3464,6 +3464,8 @@ from models.inference import (EstimateMemoryResponse,Int8PrefillAvailabilityRequest,Int8PrefillAvailabilityResponse,+ AnePrefillAvailabilityRequest,+ AnePrefillAvailabilityResponse,MlxDraftersRequest,MlxDraftersResponse,TransformersUpgradeInfo,@@ -8088,6 +8090,9 @@ def _llama_runtime_fields(llama_backend: LlamaCppBackend) -> dict:mlx_int8_prefill = None,mlx_int8_prefill_requested = None,mlx_int8_prefill_reason = None,+ mlx_ane_prefill = None,+ mlx_ane_prefill_requested = None,+ mlx_ane_prefill_reason = None,mlx_offload = None,mlx_context_budget = None,spec_draft_model = None,@@ -16988,6 +16993,8 @@ def _mlx_runtime_settings_match(backend, request) -> bool:== (request.chat_template_override or None)and bool(entry.get("mlx_int8_prefill_requested"))== bool(getattr(request, "mlx_int8_prefill", False))+ and bool(entry.get("mlx_ane_prefill_requested"))+ == bool(getattr(request, "mlx_ane_prefill", False))and all(normalize_mlx_offload(((entry.get("mlx_offload") or {}).get(part) or {}).get("requested")@@ -18743,6 +18750,9 @@ async def _load_model_impl(mlx_int8_prefill = _model_info.get("mlx_int8_prefill"),mlx_int8_prefill_requested = _model_info.get("mlx_int8_prefill_requested"),mlx_int8_prefill_reason = _model_info.get("mlx_int8_prefill_reason"),+ mlx_ane_prefill = _model_info.get("mlx_ane_prefill"),+ mlx_ane_prefill_requested = _model_info.get("mlx_ane_prefill_requested"),+ mlx_ane_prefill_reason = _model_info.get("mlx_ane_prefill_reason"),mlx_offload = _model_info.get("mlx_offload"),memory_warning = _mlx_offload_warning(_model_info),# Requested, as /status reports it: a null override would read@@ -19413,6 +19423,7 @@ async def _load_model_impl(subject = current_subject,mlx_kv_quant = request.mlx_kv_quant,mlx_int8_prefill = request.mlx_int8_prefill,+ mlx_ane_prefill = request.mlx_ane_prefill,mlx_offload = (request.mlx_ple_offload, request.mlx_expert_offload),speculative_type = request.speculative_type,spec_draft_n_max = request.spec_draft_n_max,@@ -19608,6 +19619,9 @@ async def _load_model_impl(mlx_int8_prefill = _model_info.get("mlx_int8_prefill"),mlx_int8_prefill_requested = _model_info.get("mlx_int8_prefill_requested"),mlx_int8_prefill_reason = _model_info.get("mlx_int8_prefill_reason"),+ mlx_ane_prefill = _model_info.get("mlx_ane_prefill"),+ mlx_ane_prefill_requested = _model_info.get("mlx_ane_prefill_requested"),+ mlx_ane_prefill_reason = _model_info.get("mlx_ane_prefill_reason"),mlx_offload = _model_info.get("mlx_offload"),memory_warning = _mlx_offload_warning(_model_info),# Requested, as /status reports it: a null override would read as@@ -20771,23 +20785,20 @@ def _cached_estimate_config(return config[email protected]("/int8-prefill-availability", response_model = Int8PrefillAvailabilityResponse)-async def int8_prefill_availability(- request: Int8PrefillAvailabilityRequest, current_subject: str = Depends(get_current_subject)-):- """Whether MLX int8 prefill would apply to this model, judged from its downloaded checkpoint- without loading it. The first answer on a new macOS or MLX version builds the kernels once."""+async def _mlx_prefill_option_availability(request, response, checkpoint_status):+ """`response` for an MLX prefill option that `checkpoint_status(model_dir)` judges from the+ downloaded checkpoint, without loading it."""if account_access.managed_account():await asyncio.to_thread(account_access.require_model_access, request.model_path)if is_ollama_manifest_ref(request.model_path):- return Int8PrefillAvailabilityResponse(available = False, reason = "unsupported_model")+ return response(available = False, reason = "unsupported_model")- def _check() -> Int8PrefillAvailabilityResponse:+ def _check():if not _mlx_estimate_available():- return Int8PrefillAvailabilityResponse(available = False, reason = "unsupported_model")+ return response(available = False, reason = "unsupported_model")config = _cached_estimate_config(request.model_path, None, request.hf_token, False)if config is _ESTIMATE_NOT_ON_DISK:- return Int8PrefillAvailabilityResponse(available = False, reason = "not_downloaded")+ return response(available = False, reason = "not_downloaded")from core.inference.native_audio import is_native_audio_modelif (@@ -20796,18 +20807,40 @@ async def int8_prefill_availability(or getattr(config, "is_lora", False)or is_native_audio_model(request.model_path)):- return Int8PrefillAvailabilityResponse(available = False, reason = "unsupported_model")+ return response(available = False, reason = "unsupported_model")model_dir = _local_mlx_model_dir(config)if not model_dir:- return Int8PrefillAvailabilityResponse(available = False, reason = "not_downloaded")- from core.inference.mlx_inference import mlx_int8_prefill_checkpoint_status-- available, reason = mlx_int8_prefill_checkpoint_status(model_dir)- return Int8PrefillAvailabilityResponse(available = available, reason = reason or None)+ return response(available = False, reason = "not_downloaded")+ available, reason = checkpoint_status(model_dir)+ return response(available = available, reason = reason or None)return await asyncio.to_thread(_check)[email protected]("/int8-prefill-availability", response_model = Int8PrefillAvailabilityResponse)+async def int8_prefill_availability(+ request: Int8PrefillAvailabilityRequest, current_subject: str = Depends(get_current_subject)+):+ """Whether MLX int8 prefill would apply to this model, judged from its downloaded checkpoint+ without loading it. The first answer on a new macOS or MLX version builds the kernels once."""+ from core.inference.mlx_inference import mlx_int8_prefill_checkpoint_status+ return await _mlx_prefill_option_availability(+ request, Int8PrefillAvailabilityResponse, mlx_int8_prefill_checkpoint_status+ )++[email protected]("/ane-prefill-availability", response_model = AnePrefillAvailabilityResponse)+async def ane_prefill_availability(+ request: AnePrefillAvailabilityRequest, current_subject: str = Depends(get_current_subject)+):+ """Whether MLX Neural Engine prefill could apply to this model, judged from its downloaded+ checkpoint without loading it; calibration and free memory still decide at load."""+ from core.inference.mlx_inference import mlx_ane_prefill_checkpoint_status+ return await _mlx_prefill_option_availability(+ request, AnePrefillAvailabilityResponse, mlx_ane_prefill_checkpoint_status+ )++@router.post("/estimate-memory", response_model = EstimateMemoryResponse)async def estimate_memory(request: EstimateMemoryRequest,@@ -22137,6 +22170,9 @@ async def _slot_status(current_subject: str):mlx_int8_prefill = model_info.get("mlx_int8_prefill"),mlx_int8_prefill_requested = model_info.get("mlx_int8_prefill_requested"),mlx_int8_prefill_reason = model_info.get("mlx_int8_prefill_reason"),+ mlx_ane_prefill = model_info.get("mlx_ane_prefill"),+ mlx_ane_prefill_requested = model_info.get("mlx_ane_prefill_requested"),+ mlx_ane_prefill_reason = model_info.get("mlx_ane_prefill_reason"),mlx_offload = model_info.get("mlx_offload"),memory_warning = _mlx_offload_warning(model_info),chat_template_override = model_info.get("chat_template_override_requested"),diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex e993ce2b234..34e16f1c548 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -1060,6 +1060,7 @@ class ModelOverridePayload(BaseModel):tensor_parallel: bool = Falsedisable_vision: bool = Falsemlx_int8_prefill: bool = False+ mlx_ane_prefill: bool = False# Auto (null or "auto") is stored as absence; omitted keeps the stored value.mlx_ple_offload: Optional[Union[Literal["auto", "off"], float]] = Nonemlx_expert_offload: Optional[Union[Literal["auto", "off"], float]] = None@@ -2688,6 +2689,7 @@ def update_openai_auto_switch_override(not payload.tensor_paralleland not payload.disable_visionand not payload.mlx_int8_prefill+ and not payload.mlx_ane_prefilland payload.load_in_4bit# null clears just that knob, so naming one is not a forget.and not {"mlx_ple_offload", "mlx_expert_offload"} & payload.model_fields_set@@ -2695,7 +2697,13 @@ def update_openai_auto_switch_override(key: valuefor key, value in saved_fields.items()if key- not in ("tensor_parallel", "disable_vision", "mlx_int8_prefill", "load_in_4bit")+ not in (+ "tensor_parallel",+ "disable_vision",+ "mlx_int8_prefill",+ "mlx_ane_prefill",+ "load_in_4bit",+ )})if requested_extra_args is None and not is_removal:@@ -2919,6 +2927,7 @@ def update_openai_auto_switch_override(tensor_parallel = payload.tensor_parallel,disable_vision = payload.disable_vision,mlx_int8_prefill = payload.mlx_int8_prefill,+ mlx_ane_prefill = payload.mlx_ane_prefill,load_in_4bit = payload.load_in_4bit,chat_template_override = payload.chat_template_override,gpu_memory_mode = payload.gpu_memory_mode,diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex a13dd3baa0f..bc90145555c 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -1198,6 +1198,9 @@ class TestLoadHubDownloadExclusion:"mlx_int8_prefill","mlx_int8_prefill_requested","mlx_int8_prefill_reason",+ "mlx_ane_prefill",+ "mlx_ane_prefill_requested",+ "mlx_ane_prefill_reason","mlx_offload","mlx_context_budget","spec_draft_model",diff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.pyindex 7dbec10a12e..afe487ec2de 100644--- a/studio/backend/tests/test_memory_estimate.py+++ b/studio/backend/tests/test_memory_estimate.py@@ -1600,33 +1600,50 @@ class TestEstimateMemoryRoute:assert resp.n_ctx == 4096-class TestInt8PrefillAvailabilityRoute:+class TestPrefillOptionAvailabilityRoute:@pytest.mark.parametrize(- "downloaded,takes_int8,answer",+ "option,scope,takes",+ [+ ("int8", "nax_quantized_linear", lambda m, int8_prefill = None: m),+ ("ane", "ane_prefill_mlp", lambda m, ane_prefill = None: m),+ ],+ )+ @pytest.mark.parametrize(+ "downloaded,takes_option,answer",[(True, True, (True, None)),(False, True, (False, "not_downloaded")),(True, False, (False, "unsupported_zoo")),],)- def test_the_answer(self, monkeypatch, tmp_path, downloaded, takes_int8, answer):+ def test_the_answer(+ self, monkeypatch, tmp_path, option, scope, takes, downloaded, takes_option, answer+ ):from core.inference import mlx_inference- from models.inference import Int8PrefillAvailabilityRequest+ import models.inference as modelsasked = []zoo = _types.ModuleType("unsloth_zoo.mlx.inference")- zoo.nax_quantized_linear = (lambda m, int8_prefill = None: m) if takes_int8 else len+ setattr(zoo, scope, takes if takes_option else len)verdict = SimpleNamespace(available = True, reason = "")- zoo.int8_prefill_checkpoint_available = lambda path: asked.append(path) or verdict+ setattr(+ zoo,+ f"{option}_prefill_checkpoint_available",+ lambda path: asked.append(path) or verdict,+ )monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.inference", zoo)- monkeypatch.setattr(mlx_inference, "_int8_prefill_checkpoint_cache", {})+ monkeypatch.setattr(mlx_inference, f"_{option}_prefill_checkpoint_cache", {})model_dir = str(tmp_path) if downloaded else NoneTestEstimateMemoryRoute._mlx_target(monkeypatch, model_dir)- request = Int8PrefillAvailabilityRequest(model_path = "org/model")- resp = asyncio.run(ri.int8_prefill_availability(request, current_subject = "test"))+ request = getattr(models, f"{option.capitalize()}PrefillAvailabilityRequest")(+ model_path = "org/model"+ )+ route = getattr(ri, f"{option}_prefill_availability")+ resp = asyncio.run(route(request, current_subject = "test"))assert (resp.available, resp.reason) == answerif answer[0]:- assert mlx_inference.mlx_int8_prefill_checkpoint_status(model_dir) == (True, "")+ status = getattr(mlx_inference, f"mlx_{option}_prefill_checkpoint_status")+ assert status(model_dir) == (True, "")assert asked == ([model_dir] if answer[0] else [])diff --git a/studio/backend/tests/test_mlx_completions_apple.py b/studio/backend/tests/test_mlx_completions_apple.pyindex a863c0b7ae6..b055ac2a24e 100644--- a/studio/backend/tests/test_mlx_completions_apple.py+++ b/studio/backend/tests/test_mlx_completions_apple.py@@ -121,7 +121,7 @@ def _direct_logprobs(backend, ids):scopes Studio decodes in: the logits llama-server reads ``n_probs`` from."""from mlx_lm import stream_generate- with backend._int8_prefill_scope(), backend._generation_scopes():+ with backend._prefill_decision_scopes(), backend._generation_scopes():(first,) = list(stream_generate(backend._model, backend._tokenizer, prompt = ids, max_tokens = 1))diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 7a4f9924d6b..7610c7a7f71 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -62,6 +62,7 @@ def _stub_inference_scopes(module):call = None,*,int8_prefill = None,+ ane_prefill = None,on_error = None,_modules = None,):@@ -73,7 +74,13 @@ def _stub_inference_scopes(module):continueif opt_in and opt_in[0] and os.environ.get(opt_in[0]) != "1":continue- args = (int8_prefill,) if name == "nax_quantized_linear" else ()+ args = (+ (int8_prefill,)+ if name == "nax_quantized_linear"+ else (ane_prefill,)+ if name == "ane_prefill_mlp"+ else ()+ )try:stack.enter_context(getattr(module, name)(model, *args))except Exception as error:@@ -304,7 +311,9 @@ def test_mlx_fusion_failure_at_load_still_loads_the_model(monkeypatch, mlx_moe):assert backend.unload_model("fake/text")[email protected]("outcome", ["warmed", "int8", "failed", "dead_queue", "distributed"])+ "outcome", ["warmed", "int8", "ane", "failed", "dead_queue", "distributed"]+)def test_a_load_warms_zoo_scopes_under_its_int8_decision(monkeypatch, mlx_moe, outcome):from core.inference import mlx_inference@@ -355,6 +364,16 @@ def test_a_load_warms_zoo_scopes_under_its_int8_decision(monkeypatch, mlx_moe, oif outcome == "int8":status = {"requested": True, "active": True, "reason": "", "scope": int8}monkeypatch.setattr(mlx_inference, "_int8_prefill_status", lambda *_: status)+ if outcome == "ane":+ # Calibration in the warm-up's first prepare rejects the split the static check allowed.+ ane = lambda model, on: (events.append(("ane", on)), contextlib.nullcontext())[1]+ reads = iter(+ [+ {"requested": True, "active": True, "reason": "", "scope": ane},+ {"requested": True, "active": False, "reason": "no_gain", "scope": None},+ ]+ )+ monkeypatch.setattr(mlx_inference, "_ane_prefill_status", lambda *_: next(reads))config = SimpleNamespace(identifier = "fake/text", is_vision = False, is_lora = False)group = SimpleNamespace(size = lambda: 2, rank = lambda: 0)kwargs = (@@ -370,9 +389,20 @@ def test_a_load_warms_zoo_scopes_under_its_int8_decision(monkeypatch, mlx_moe, owarmed = ([]if outcome == "distributed"- else ["rng", ("int8", active), ("warm", True, active), "/int8", "/rng"]+ else [+ "rng",+ ("int8", active),+ *[("ane", True)] * (outcome == "ane"),+ ("warm", True, active),+ "/int8",+ "/rng",+ ])assert events == ["gate_up", *warmed]+ if outcome == "ane":+ entry = backend.models["fake/text"]+ assert (entry["mlx_ane_prefill"], entry["mlx_ane_prefill_reason"]) == (False, "no_gain")+ assert not backend._ane_prefill["active"]assert any("MLX warm-up failed" in warning for warning in warnings) == (outcome == "failed")@@ -5686,10 +5716,86 @@ def test_int8_prefill_is_the_outermost_scope_of_generation_pinned_off_when_inactmlx_inference_patches.nax_quantized_linear = brokenif not active: # an inactive load never asked for the scope, so its failure costs no request- with backend._int8_prefill_scope():+ with backend._prefill_decision_scopes():pass[email protected]("requested,available", [(True, True), (True, False), (False, True)])+def test_ane_prefill_is_pinned_inside_int8_released_on_unload_and_reloads_on_change(+ monkeypatch, mlx_inference_patches, requested, available+):+ from core.inference import mlx_inference+ from models.inference import LoadRequest+ from routes.inference import _mlx_runtime_settings_match++ _install_fake_mlx(monkeypatch)++ events = _int8_zoo(mlx_inference_patches)++ @contextmanager+ def ane_prefill_mlp(model, ane_prefill = None):+ events.append(("ane", ane_prefill))+ yield+ events.append(("ane_exit", ane_prefill))++ mlx_inference_patches.ane_prefill_mlp = ane_prefill_mlp+ verdict = SimpleNamespace(available = available, reason = "" if available else "no_gain")+ mlx_inference_patches.ane_prefill_available = lambda m: verdict+ mlx_inference_patches.release_ane_prefill = lambda m: events.append(("release", None))+ active = requested and available+ backend = mlx_inference.MLXInferenceBackend()+ backend._model, backend.models["m"] = object(), {}+ backend._ane_prefill = mlx_inference._ane_prefill_status(requested, backend._model)+ assert backend._ane_prefill["reason"] == ("no_gain" if requested and not available else "")+ with backend._prefill_decision_scopes():+ pass+ backend.unload_model("m")+ assert events == [+ ("int8", False),+ ("ane", active),+ ("ane_exit", active),+ ("int8_exit", False),+ ] + ([("release", None)] if active else [])+ if active:+ # A release that raises still finishes the unload.+ def broken_release(model):+ raise RuntimeError("ane")++ mlx_inference_patches.release_ane_prefill = broken_release+ backend._model, backend.models["m"] = object(), {}+ backend._ane_prefill = mlx_inference._ane_prefill_status(True, backend._model)+ backend.unload_model("m")+ assert backend._model is None and not backend._ane_prefill["active"]+ entry = {"mlx_kv_quant_requested": "auto", "mlx_ane_prefill_requested": requested}+ load = lambda on: LoadRequest(model = "m", model_path = "m", mlx_ane_prefill = on)+ be = SimpleNamespace(active_model_name = "m", models = {"m": entry})+ assert _mlx_runtime_settings_match(be, load(requested))+ assert not _mlx_runtime_settings_match(be, load(not requested))++ @contextmanager+ def int8(model, int8_prefill = None):+ events.append(("int8", int8_prefill))+ try:+ yield+ finally:+ events.append(("int8_exit", int8_prefill))++ @contextmanager+ def dead(model, on):+ raise RuntimeError("[METAL] Command buffer execution failed")+ yield++ events.clear()+ mlx_inference_patches.nax_quantized_linear = int8+ backend._ane_prefill = {"scope": dead}+ try:+ backend._prefill_decision_scopes()+ except RuntimeError: # unwound before the error leaves, not when its traceback is collected+ assert events == [("int8", False), ("int8_exit", False)]+ else:+ pytest.fail("the Neural Engine scope's error was swallowed")++def test_a_batch_session_holds_int8_prefill_for_its_whole_life(monkeypatch, mlx_inference_patches):from core.inference import mlx_inferencediff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 9cf5b9c7838..da5cefb72d0 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -9105,15 +9105,16 @@ def test_mlx_kv_quant_survives_the_whole_override_projection():assert LoadRequest(model_path = "unsloth/A", **kwargs).mlx_kv_quant == "tq-4"-def test_mlx_int8_prefill_is_stored_only_when_on_and_reaches_the_load(monkeypatch):[email protected]("knob", ["mlx_int8_prefill", "mlx_ane_prefill"])+def test_mlx_prefill_options_are_stored_only_when_on_and_reach_the_load(monkeypatch, knob):_mock_override_store(monkeypatch)- assert settings.normalize_model_override({"mlx_int8_prefill": False}) == {}- _put("org/m", mlx_int8_prefill = True)+ assert settings.normalize_model_override({knob: False}) == {}+ _put("org/m", **{knob: True})stored = settings.get_model_overrides()["org/m"]- assert stored == {"mlx_int8_prefill": True}+ assert stored == {knob: True}kwargs = settings.model_override_load_kwargs(stored, is_gguf = False)- assert LoadRequest(model_path = "org/m", **kwargs).mlx_int8_prefill is True- _put("org/m", mlx_int8_prefill = False)+ assert getattr(LoadRequest(model_path = "org/m", **kwargs), knob) is True+ _put("org/m", **{knob: False})assert "org/m" not in settings.get_model_overrides()diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex df814af31e9..9591afaca15 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -550,6 +550,9 @@ def normalize_model_override(if _coerce_bool(payload.get("mlx_int8_prefill")):entry["mlx_int8_prefill"] = True+ if _coerce_bool(payload.get("mlx_ane_prefill")):+ entry["mlx_ane_prefill"] = True+for key in ("mlx_ple_offload", "mlx_expert_offload"):value = payload.get(key)if value == "off" or (@@ -702,6 +705,7 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> di("disable_vision", "disable_vision"),("chat_template_override", "chat_template_override"),("mlx_int8_prefill", "mlx_int8_prefill"),+ ("mlx_ane_prefill", "mlx_ane_prefill"),("mlx_ple_offload", "mlx_ple_offload"),("mlx_expert_offload", "mlx_expert_offload"),):diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 86e13866e00..9db85dc085f 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -2726,6 +2726,8 @@ const VISIBLE_MODEL_RUNTIME_KEYS = ["mlxKvQuantNote","mlxInt8Prefill","loadedMlxInt8PrefillRequested",+ "mlxAnePrefill",+ "loadedMlxAnePrefillRequested","mlxPleOffload","mlxExpertOffload","loadedMlxPleOffloadRequested",@@ -3700,6 +3702,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{cache_type_kv: config.kvCacheDtype,mlx_kv_quant: config.mlxKvQuant ?? null,mlx_int8_prefill: config.mlxInt8Prefill ?? false,+ mlx_ane_prefill: config.mlxAnePrefill ?? false,mlx_ple_offload: config.mlxPleOffload ?? null,mlx_expert_offload: config.mlxExpertOffload ?? null,speculative_type: effectiveSpeculativeType,diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex 39674ea07b0..4a3ae6fdecc 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -1971,6 +1971,9 @@ export function useChatModelRuntime() {const previousMlxInt8Prefill = rollbackConfig? (rollbackConfig.mlxInt8Prefill ?? false): useChatRuntimeStore.getState().mlxInt8Prefill;+ const previousMlxAnePrefill = rollbackConfig+ ? (rollbackConfig.mlxAnePrefill ?? false)+ : useChatRuntimeStore.getState().mlxAnePrefill;const previousMlxPleOffload = rollbackConfig? (rollbackConfig.mlxPleOffload ?? null): useChatRuntimeStore.getState().mlxPleOffload;@@ -2062,6 +2065,9 @@ export function useChatModelRuntime() {let loadMlxInt8Prefill = pendingLoadConfig? (pendingLoadConfig.mlxInt8Prefill ?? false): stateBeforeUnload.mlxInt8Prefill;+ let loadMlxAnePrefill = pendingLoadConfig+ ? (pendingLoadConfig.mlxAnePrefill ?? false)+ : stateBeforeUnload.mlxAnePrefill;let loadMlxPleOffload = pendingLoadConfig? (pendingLoadConfig.mlxPleOffload ?? null): stateBeforeUnload.mlxPleOffload;@@ -2235,6 +2241,7 @@ export function useChatModelRuntime() {loadKvCacheDtype = pendingLoadConfig?.kvCacheDtype ?? null;loadMlxKvQuant = pendingLoadConfig?.mlxKvQuant ?? null;loadMlxInt8Prefill = pendingLoadConfig?.mlxInt8Prefill ?? false;+ loadMlxAnePrefill = pendingLoadConfig?.mlxAnePrefill ?? false;loadMlxPleOffload = pendingLoadConfig?.mlxPleOffload ?? null;loadMlxExpertOffload = pendingLoadConfig?.mlxExpertOffload ?? null;loadChatTemplateOverride =@@ -2338,6 +2345,7 @@ export function useChatModelRuntime() {cache_type_kv: loadKvCacheDtype,mlx_kv_quant: loadMlxKvQuant ?? null,mlx_int8_prefill: loadMlxInt8Prefill,+ mlx_ane_prefill: loadMlxAnePrefill,mlx_ple_offload: loadMlxPleOffload,mlx_expert_offload: loadMlxExpertOffload,speculative_type: loadSpeculativeType,@@ -2920,6 +2928,7 @@ export function useChatModelRuntime() {cache_type_kv: rollbackState.loadedKvCacheDtype,mlx_kv_quant: rollbackState.loadedMlxKvQuantRequested,mlx_int8_prefill: rollbackState.loadedMlxInt8PrefillRequested,+ mlx_ane_prefill: rollbackState.loadedMlxAnePrefillRequested,mlx_ple_offload: rollbackState.loadedMlxPleOffloadRequested,mlx_expert_offload: rollbackState.loadedMlxExpertOffloadRequested,speculative_type:@@ -3017,6 +3026,7 @@ export function useChatModelRuntime() {...mlxRuntimeStateFrom(rollbackResponse),mlxKvQuant: previousMlxKvQuant,mlxInt8Prefill: previousMlxInt8Prefill,+ mlxAnePrefill: previousMlxAnePrefill,mlxPleOffload: previousMlxPleOffload,mlxExpertOffload: previousMlxExpertOffload,loadedChatTemplateOverride:diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex 5bb1e192c3f..61133fcb410 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -229,6 +229,7 @@ export function applyActiveModelStatusToStore(const currentSpecType = normalizeSpeculativeType(status.speculative_type);const incomingMlxKvQuant = normalizeMlxKvQuant(status.mlx_kv_quant_requested);const incomingMlxInt8Prefill = status.mlx_int8_prefill_requested === true;+ const incomingMlxAnePrefill = status.mlx_ane_prefill_requested === true;const incomingMlxOffload = mlxOffloadStateFrom(status);const prevState = useChatRuntimeStore.getState();// A pin is one model's; clamp the chat's own level once the model is actually resident.@@ -541,6 +542,7 @@ export function applyActiveModelStatusToStore(status.chat_template_override_reason ?? null,mlxKvQuantNote: status.mlx_kv_quant_note ?? null,loadedMlxInt8PrefillRequested: incomingMlxInt8Prefill,+ loadedMlxAnePrefillRequested: incomingMlxAnePrefill,...incomingMlxOffload,...((hydratingExistingModel ||(prevState.mlxPleOffload ?? null) ===@@ -562,6 +564,11 @@ export function applyActiveModelStatusToStore(prevState.loadedMlxInt8PrefillRequested) && {mlxInt8Prefill: incomingMlxInt8Prefill,}),+ ...((hydratingExistingModel ||+ prevState.mlxAnePrefill ===+ prevState.loadedMlxAnePrefillRequested) && {+ mlxAnePrefill: incomingMlxAnePrefill,+ }),}: {loadedMlxKvQuantRequested: null,@@ -569,6 +576,7 @@ export function applyActiveModelStatusToStore(chatTemplateOverrideReason: null,mlxKvQuantNote: null,loadedMlxInt8PrefillRequested: false,+ loadedMlxAnePrefillRequested: false,...incomingMlxOffload,})),// Baseline only, never the control: the echo is the RESOLVED count and would pin a blankdiff --git a/studio/frontend/src/features/chat/lib/mlx-runtime-state.ts b/studio/frontend/src/features/chat/lib/mlx-runtime-state.tsindex 19e7f48eaa9..208245e9d43 100644--- a/studio/frontend/src/features/chat/lib/mlx-runtime-state.ts+++ b/studio/frontend/src/features/chat/lib/mlx-runtime-state.ts@@ -17,6 +17,7 @@ type MlxRuntimeResponse = Pick<| "chat_template_override_reason"| "mlx_kv_quant_note"| "mlx_int8_prefill_requested"+ | "mlx_ane_prefill_requested"| "mlx_offload">;@@ -58,7 +59,9 @@ export function mlxRuntimeStateFrom(resp: MlxRuntimeResponse): {chatTemplateOverrideReason: string | null;mlxKvQuantNote: string | null;mlxInt8Prefill?: boolean;+ mlxAnePrefill?: boolean;loadedMlxInt8PrefillRequested: boolean;+ loadedMlxAnePrefillRequested: boolean;mlxPleOffload?: MlxOffload;mlxExpertOffload?: MlxOffload;} & ReturnType<typeof mlxOffloadStateFrom> {@@ -70,6 +73,7 @@ export function mlxRuntimeStateFrom(resp: MlxRuntimeResponse): {chatTemplateOverrideReason: null,mlxKvQuantNote: null,loadedMlxInt8PrefillRequested: false,+ loadedMlxAnePrefillRequested: false,...offload,};}@@ -82,6 +86,8 @@ export function mlxRuntimeStateFrom(resp: MlxRuntimeResponse): {mlxKvQuantNote: resp.mlx_kv_quant_note ?? null,mlxInt8Prefill: resp.mlx_int8_prefill_requested === true,loadedMlxInt8PrefillRequested: resp.mlx_int8_prefill_requested === true,+ mlxAnePrefill: resp.mlx_ane_prefill_requested === true,+ loadedMlxAnePrefillRequested: resp.mlx_ane_prefill_requested === true,mlxPleOffload: offload.loadedMlxPleOffloadRequested,mlxExpertOffload: offload.loadedMlxExpertOffloadRequested,...offload,diff --git a/studio/frontend/src/features/chat/lib/resident-config-match.ts b/studio/frontend/src/features/chat/lib/resident-config-match.tsindex bfa2377d982..f803fb9c191 100644--- a/studio/frontend/src/features/chat/lib/resident-config-match.ts+++ b/studio/frontend/src/features/chat/lib/resident-config-match.ts@@ -36,6 +36,7 @@ type ResidentRuntime = Pick<| "cache_type_kv"| "mlx_kv_quant_requested"| "mlx_int8_prefill_requested"+ | "mlx_ane_prefill_requested"| "mlx_offload"| "speculative_type"| "spec_draft_n_max"@@ -239,6 +240,12 @@ const SETTING_CHECKS: SettingCheck[] = [agrees: (c, s) =>Boolean(c.mlxInt8Prefill) === (s.mlx_int8_prefill_requested === true),},+ {+ mlxComparable: true,+ pinned: () => true,+ agrees: (c, s) =>+ Boolean(c.mlxAnePrefill) === (s.mlx_ane_prefill_requested === true),+ },{// The request, not the applied fraction: Auto stays Auto whatever it picked.mlxComparable: true,diff --git a/studio/frontend/src/features/chat/presets/preset-load-config.ts b/studio/frontend/src/features/chat/presets/preset-load-config.tsindex cce486aa62a..b774b9d5b03 100644--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts@@ -332,6 +332,7 @@ export function applyPresetLoadConfig(config?: PresetLoadConfig | null): void {chatTemplateOverride: null,// Not carried by presets: enabling it always goes through its confirmation.mlxInt8Prefill: store.mlxInt8Prefill,+ mlxAnePrefill: store.mlxAnePrefill,mlxPleOffload: store.mlxPleOffload,mlxExpertOffload: store.mlxExpertOffload,gpuMemoryMode: config.gpuMemoryMode,diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 0fc949de1b8..d3a9d2d627f 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -1800,6 +1800,7 @@ export function SharedComposer({cache_type_kv: ownConfig.kvCacheDtype ?? null,mlx_kv_quant: ownConfig.mlxKvQuant ?? null,mlx_int8_prefill: ownConfig.mlxInt8Prefill ?? false,+ mlx_ane_prefill: ownConfig.mlxAnePrefill ?? false,mlx_ple_offload: ownConfig.mlxPleOffload ?? null,mlx_expert_offload: ownConfig.mlxExpertOffload ?? null,speculative_type: effectiveSpeculativeType,diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 418993b55dc..48ee03cd906 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -2482,6 +2482,8 @@ type ChatRuntimeStore = {mlxKvQuantNote: string | null;mlxInt8Prefill: boolean;loadedMlxInt8PrefillRequested: boolean;+ mlxAnePrefill: boolean;+ loadedMlxAnePrefillRequested: boolean;/** MLX offload knobs as chosen (null = Auto), as the resident load asked for them, the* fraction it applied (null = none), and why a request was not applied. */mlxPleOffload: MlxOffload;@@ -4268,6 +4270,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({mlxKvQuantNote: null,mlxInt8Prefill: false,loadedMlxInt8PrefillRequested: false,+ mlxAnePrefill: false,+ loadedMlxAnePrefillRequested: false,mlxPleOffload: null,mlxExpertOffload: null,loadedMlxPleOffloadRequested: null,@@ -5203,6 +5207,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({mlxKvQuantNote: null,mlxInt8Prefill: false,loadedMlxInt8PrefillRequested: false,+ mlxAnePrefill: false,+ loadedMlxAnePrefillRequested: false,mlxPleOffload: null,mlxExpertOffload: null,loadedMlxPleOffloadRequested: null,diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 178e05ee94b..6fd78fa5ad3 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -88,6 +88,7 @@ export interface LoadModelRequest {cache_type_kv?: string | null;mlx_kv_quant?: string | null;mlx_int8_prefill?: boolean;+ mlx_ane_prefill?: boolean;/** MLX only: share of the PLE tables / routed experts read from disk, "off", or null for Auto. */mlx_ple_offload?: "off" | number | null;mlx_expert_offload?: "off" | number | null;@@ -268,6 +269,9 @@ export interface LoadModelResponse {mlx_int8_prefill?: boolean | null;mlx_int8_prefill_requested?: boolean | null;mlx_int8_prefill_reason?: string | null;+ mlx_ane_prefill?: boolean | null;+ mlx_ane_prefill_requested?: boolean | null;+ mlx_ane_prefill_reason?: string | null;mlx_offload?: MlxOffloadReport | null;chat_template?: string | null;speculative_type?: string | null;@@ -404,6 +408,9 @@ export interface InferenceStatusResponse {mlx_int8_prefill?: boolean | null;mlx_int8_prefill_requested?: boolean | null;mlx_int8_prefill_reason?: string | null;+ mlx_ane_prefill?: boolean | null;+ mlx_ane_prefill_requested?: boolean | null;+ mlx_ane_prefill_reason?: string | null;mlx_offload?: MlxOffloadReport | null;chat_template_override?: string | null;speculative_type?: string | null;diff --git a/studio/frontend/src/features/model-picker/api/int8-prefill.ts b/studio/frontend/src/features/model-picker/api/int8-prefill.tsindex 8954c3ad465..ffea2b45f39 100644--- a/studio/frontend/src/features/model-picker/api/int8-prefill.ts+++ b/studio/frontend/src/features/model-picker/api/int8-prefill.ts@@ -3,13 +3,16 @@import { authFetch } from "@/features/auth";+export type PrefillOption = "int8" | "ane";+/** Failure only hides the setting: a stored choice is kept and the load-time check guards it. */-export async function fetchInt8PrefillAvailable(+export async function fetchPrefillOptionAvailable(+ option: PrefillOption,modelPath: string,hfToken: string | null,signal?: AbortSignal,): Promise<boolean> {- const response = await authFetch("/api/inference/int8-prefill-availability", {+ const response = await authFetch(`/api/inference/${option}-prefill-availability`, {method: "POST",headers: { "Content-Type": "application/json" },signal,diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.tsindex 9ae3bfc3d66..bb1280c113c 100644--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts@@ -42,6 +42,7 @@ export interface ApiModelOverride {mlx_kv_bits?: number;// biome-ignore lint/style/useNamingConvention: API schemamlx_int8_prefill?: boolean;+ mlx_ane_prefill?: boolean;// biome-ignore lint/style/useNamingConvention: API schemamlx_ple_offload?: "off" | number | null;// biome-ignore lint/style/useNamingConvention: API schema@@ -357,6 +358,7 @@ export function fromApiOverride(tensorParallel: override.tensor_parallel ?? local.tensorParallel,disableVision: override.disable_vision ?? local.disableVision,mlxInt8Prefill: override.mlx_int8_prefill ?? local.mlxInt8Prefill,+ mlxAnePrefill: override.mlx_ane_prefill ?? local.mlxAnePrefill,mlxPleOffload: override.mlx_ple_offload ?? local.mlxPleOffload,mlxExpertOffload: override.mlx_expert_offload ?? local.mlxExpertOffload,loadIn4bit: override.load_in_4bit ?? local.loadIn4bit,@@ -457,6 +459,9 @@ export function toApiOverride(config: PerModelConfig | null): ApiModelOverride {if (config.mlxInt8Prefill) {payload.mlx_int8_prefill = true;}+ if (config.mlxAnePrefill) {+ payload.mlx_ane_prefill = true;+ }if (config.loadIn4bit === false) {payload.load_in_4bit = false;}diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex 7bde66f36e2..1ee33461367 100644--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx@@ -148,7 +148,7 @@ import {selectResidentEstimateSettings,} from "../model-config/resident-memory-request";import { useMemoryEstimate } from "../hooks/use-memory-estimate";-import { useInt8PrefillAvailable } from "../hooks/use-int8-prefill-available";+import { usePrefillOptionAvailable } from "../hooks/use-int8-prefill-available";import {fetchLoadModelOverride,fromApiOverride,@@ -1606,6 +1606,8 @@ function MlxAdvancedSettings({servedByMlx,int8PrefillAvailable,onInt8PrefillChange,+ anePrefillAvailable,+ onAnePrefillChange,offloadable,offloadDecided,offloadNotes,@@ -1620,6 +1622,8 @@ function MlxAdvancedSettings({servedByMlx: boolean;int8PrefillAvailable: boolean;onInt8PrefillChange: (checked: boolean) => void;+ anePrefillAvailable: boolean;+ onAnePrefillChange: (checked: boolean) => void;offloadable: readonly MlxOffloadablePart[];offloadDecided: Record<MlxOffloadablePart, number | null> | null;offloadNotes: Record<MlxOffloadablePart, string | null>;@@ -1691,6 +1695,26 @@ function MlxAdvancedSettings({/></div>)}+ {servedByMlx && (anePrefillAvailable || config.mlxAnePrefill) && (+ <div className={ROW_CLASS}>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className={LABEL_CLASS}>Neural Engine Prefill</span>+ <span className="shrink-0 rounded-md bg-[rgb(0_0_0_/_calc(0.04*var(--contrast-wash-gain,1)))] px-1.5 py-0.5 text-ui-10 font-medium uppercase tracking-wide text-muted-foreground dark:bg-muted">+ Exp+ </span>+ <InfoHint>+ Reads long prompts faster by running part of each layer on the+ Neural Engine beside the GPU. Answers can change slightly. Loading+ takes longer the first time while it measures this Mac.+ </InfoHint>+ </div>+ <Switch+ className="panel-switch shrink-0"+ checked={config.mlxAnePrefill ?? false}+ onCheckedChange={onAnePrefillChange}+ />+ </div>+ )}{servedByMlx && (<MlxSpeculativeRowsconfig={config}@@ -2664,14 +2688,23 @@ export function ModelConfigPage({platformDeviceType,platformChatOnlyReason,);- const int8PrefillAvailable = useInt8PrefillAvailable(+ const prefillOptionPath =servedByMlx &&- !(target.meta.nativePathToken ?? (isActiveModel ? activeNativePathToken : null))+ !(target.meta.nativePathToken ?? (isActiveModel ? activeNativePathToken : null))? target.id- : null,+ : null;+ const int8PrefillAvailable = usePrefillOptionAvailable(+ "int8",+ prefillOptionPath,+ hfToken || null,+ );+ const anePrefillAvailable = usePrefillOptionAvailable(+ "ane",+ prefillOptionPath,hfToken || null,);const [int8PrefillConfirmOpen, setInt8PrefillConfirmOpen] = useState(false);+ const [anePrefillConfirmOpen, setAnePrefillConfirmOpen] = useState(false);// Read live: the sidebar copy stays mounted while collapsed.const advancedPreference = useSyncExternalStore(subscribeAdvancedSettingsOpen,@@ -2695,6 +2728,9 @@ export function ModelConfigPage({const [initialMlxInt8Prefill] = useState(() => configState.mlxInt8Prefill ?? false,);+ const [initialMlxAnePrefill] = useState(+ () => configState.mlxAnePrefill ?? false,+ );const [initialMlxOffload] = useState(() => configState.mlxPleOffload != null || configState.mlxExpertOffload != null,);@@ -2702,6 +2738,7 @@ export function ModelConfigPage({// and a width that starts applying then has to surface.const autoOpenForMlxKvQuant = servedByMlx && initialMlxKvQuant != null;const autoOpenForMlxInt8Prefill = servedByMlx && initialMlxInt8Prefill;+ const autoOpenForMlxAnePrefill = servedByMlx && initialMlxAnePrefill;const autoOpenForMlxOffload = servedByMlx && initialMlxOffload;// Opened to change one field: show its section for this visit, leaving the saved switch alone.const [revealForFocus, setRevealForFocus] = useState(focusField != null);@@ -2711,6 +2748,7 @@ export function ModelConfigPage({(autoOpenAdvanced ||autoOpenForMlxKvQuant ||autoOpenForMlxInt8Prefill ||+ autoOpenForMlxAnePrefill ||autoOpenForMlxOffload));const toggleAdvanced = (open: boolean) => {setRevealForFocus(false);@@ -4266,6 +4304,12 @@ export function ModelConfigPage({? setInt8PrefillConfirmOpen(true): update({ mlxInt8Prefill: false })}+ anePrefillAvailable={anePrefillAvailable}+ onAnePrefillChange={(checked) =>+ checked+ ? setAnePrefillConfirmOpen(true)+ : update({ mlxAnePrefill: false })+ }offloadable={memoryEstimate.estimate?.mlxOffloadable ?? []}offloadDecided={mlxOffloadDecidedNow}offloadNotes={mlxOffloadNotes}@@ -4461,6 +4505,34 @@ export function ModelConfigPage({</AlertDialogFooter></AlertDialogContent></AlertDialog>+ <AlertDialog+ open={anePrefillConfirmOpen}+ onOpenChange={setAnePrefillConfirmOpen}+ >+ <AlertDialogContent size="sm">+ <AlertDialogHeader>+ <AlertDialogTitle>Turn on Neural Engine Prefill?</AlertDialogTitle>+ <AlertDialogDescription>+ Long prompts are read faster, but the model's answers will+ change slightly. The first load on this Mac takes longer while it+ measures whether this helps; when it does not, the model runs as+ before. You can turn it off at any time.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ update({ mlxAnePrefill: true });+ setAnePrefillConfirmOpen(false);+ }}+ >+ Turn on+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog><AlertDialogopen={pendingDelete !== null}onOpenChange={(open) => {diff --git a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.tsindex d44e8841856..8446e3a3dc0 100644--- a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts+++ b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts@@ -41,6 +41,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {const kvCacheDtype = useChatRuntimeStore((s) => s.kvCacheDtype);const mlxKvQuant = useChatRuntimeStore((s) => s.mlxKvQuant);const mlxInt8Prefill = useChatRuntimeStore((s) => s.mlxInt8Prefill);+ const mlxAnePrefill = useChatRuntimeStore((s) => s.mlxAnePrefill);const mlxPleOffload = useChatRuntimeStore((s) => s.mlxPleOffload);const mlxExpertOffload = useChatRuntimeStore((s) => s.mlxExpertOffload);const speculativeType = useChatRuntimeStore((s) => s.speculativeType);@@ -101,6 +102,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {// Null off MLX, or the model compares unequal to its own defaults.const effectiveMlxKvQuant = isMlx ? (mlxKvQuant ?? null) : null;const effectiveMlxInt8Prefill = isMlx && mlxInt8Prefill;+ const effectiveMlxAnePrefill = isMlx && mlxAnePrefill;const effectiveMlxPleOffload = isMlx ? (mlxPleOffload ?? null) : null;const effectiveMlxExpertOffload = isMlx ? (mlxExpertOffload ?? null) : null;@@ -118,6 +120,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {kvCacheDtype: kvCacheDtype ?? null,mlxKvQuant: effectiveMlxKvQuant,mlxInt8Prefill: effectiveMlxInt8Prefill,+ mlxAnePrefill: effectiveMlxAnePrefill,mlxPleOffload: effectiveMlxPleOffload,mlxExpertOffload: effectiveMlxExpertOffload,speculativeType: speculativeType ?? "auto",@@ -177,6 +180,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {kvCacheDtype,effectiveMlxKvQuant,effectiveMlxInt8Prefill,+ effectiveMlxAnePrefill,effectiveMlxPleOffload,effectiveMlxExpertOffload,speculativeType,diff --git a/studio/frontend/src/features/model-picker/hooks/use-int8-prefill-available.ts b/studio/frontend/src/features/model-picker/hooks/use-int8-prefill-available.tsindex 0aef36c88f2..d54c1a4e616 100644--- a/studio/frontend/src/features/model-picker/hooks/use-int8-prefill-available.ts+++ b/studio/frontend/src/features/model-picker/hooks/use-int8-prefill-available.ts@@ -2,13 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { useEffect, useState } from "react";-import { fetchInt8PrefillAvailable } from "../api/int8-prefill";+import { fetchPrefillOptionAvailable, type PrefillOption } from "../api/int8-prefill";-export function useInt8PrefillAvailable(+export function usePrefillOptionAvailable(+ option: PrefillOption,modelPath: string | null,hfToken: string | null,): boolean {- const key = modelPath == null ? null : `${modelPath}\n${hfToken ?? ""}`;+ const key = modelPath == null ? null : `${option}\n${modelPath}\n${hfToken ?? ""}`;const [answer, setAnswer] = useState<{key: string;available: boolean;@@ -18,7 +19,7 @@ export function useInt8PrefillAvailable(return;}const controller = new AbortController();- fetchInt8PrefillAvailable(modelPath, hfToken, controller.signal)+ fetchPrefillOptionAvailable(option, modelPath, hfToken, controller.signal).then((available) => {if (!controller.signal.aborted) {setAnswer({ key, available });@@ -30,6 +31,6 @@ export function useInt8PrefillAvailable(}});return () => controller.abort();- }, [key, modelPath, hfToken]);+ }, [key, option, modelPath, hfToken]);return answer != null && answer.key === key && answer.available;}diff --git a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.tsindex 3831b0fbbb3..bd8f22768da 100644--- a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts@@ -76,6 +76,7 @@ export function applyPerModelConfigToRuntime(customContextLength: config.customContextLength ?? null,mlxKvQuant: config.mlxKvQuant ?? null,mlxInt8Prefill: config.mlxInt8Prefill ?? false,+ mlxAnePrefill: config.mlxAnePrefill ?? false,mlxPleOffload: config.mlxPleOffload ?? null,mlxExpertOffload: config.mlxExpertOffload ?? null,kvCacheDtype: config.kvCacheDtype ?? null,@@ -151,6 +152,7 @@ export function currentRuntimePerModelConfig(kvCacheDtype: s.kvCacheDtype ?? null,mlxKvQuant: s.mlxKvQuant ?? null,mlxInt8Prefill: s.mlxInt8Prefill ?? false,+ mlxAnePrefill: s.mlxAnePrefill ?? false,mlxPleOffload: s.mlxPleOffload ?? null,mlxExpertOffload: s.mlxExpertOffload ?? null,speculativeType: normalizeSpeculativeType(s.speculativeType),@@ -209,6 +211,7 @@ export function perModelConfigsEqual((a.kvCacheDtype ?? null) === (b.kvCacheDtype ?? null) &&(a.mlxKvQuant ?? null) === (b.mlxKvQuant ?? null) &&Boolean(a.mlxInt8Prefill) === Boolean(b.mlxInt8Prefill) &&+ Boolean(a.mlxAnePrefill) === Boolean(b.mlxAnePrefill) &&(a.mlxPleOffload ?? null) === (b.mlxPleOffload ?? null) &&(a.mlxExpertOffload ?? null) === (b.mlxExpertOffload ?? null) &&speculative(a.speculativeType) === speculative(b.speculativeType) &&diff --git a/studio/frontend/src/features/model-picker/model-config/config-signature.ts b/studio/frontend/src/features/model-picker/model-config/config-signature.tsindex 402e8da2a7c..b5bf0f59fa4 100644--- a/studio/frontend/src/features/model-picker/model-config/config-signature.ts+++ b/studio/frontend/src/features/model-picker/model-config/config-signature.ts@@ -55,6 +55,7 @@ export function loadedConfigSignature(config.kvCacheDtype ?? "",config.mlxKvQuant ?? "",config.mlxInt8Prefill ? "1" : "0",+ config.mlxAnePrefill ? "1" : "0",config.mlxPleOffload ?? "",config.mlxExpertOffload ?? "",config.speculativeType ?? "",diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.tsindex cea77813fdd..4717faeccbe 100644--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts@@ -35,6 +35,7 @@ export interface PerModelConfig {kvCacheDtype: string | null;mlxKvQuant?: MlxKvQuant | null;mlxInt8Prefill?: boolean;+ mlxAnePrefill?: boolean;/** MLX only: share of the PLE tables / routed experts read from disk, "off", or null for Auto. */mlxPleOffload?: MlxOffload;mlxExpertOffload?: MlxOffload;@@ -84,6 +85,7 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {kvCacheDtype: null,mlxKvQuant: null,mlxInt8Prefill: false,+ mlxAnePrefill: false,mlxPleOffload: null,mlxExpertOffload: null,speculativeType: null,@@ -407,9 +409,10 @@ const LEGACY_MIGRATION_FLAG = "unsloth_model_configs_migrated";// would normalize the unknown field straight back out of the record.// v2 added nBatch/nUbatch, v3 llamaExtraArgs, v4 disableVision, v5 the llama-server tuning group// (loadMode / specDraftCacheDtype / ctxCheckpoints / cacheRam), v6 the reasoning budget pair,-// v7 mlxKvQuant, v9 mlxInt8Prefill, v10 the per-GPU split, v11 the MLX drafter, v12 the MLX offload pair. v8 is skipped: nightly builds stamped it for the reverted custom+// v7 mlxKvQuant, v9 mlxInt8Prefill, v10 the per-GPU split, v11 the MLX drafter, v12 the MLX offload pair, v13 mlxAnePrefill. v8 is skipped: nightly builds stamped it for the reverted custom// llama.cpp config (#12725), so a v8 client must not claim to understand an int8 prefill record.-const STORAGE_SCHEMA_VERSION = 12;+const STORAGE_SCHEMA_VERSION = 13;+const PRE_MLX_ANE_PREFILL_SCHEMA_VERSION = 12;const PRE_MLX_OFFLOAD_SCHEMA_VERSION = 11;const PRE_MLX_DRAFTER_SCHEMA_VERSION = 10;const PRE_TENSOR_SPLIT_SCHEMA_VERSION = 9;@@ -457,6 +460,7 @@ const STORED_CONFIG_FIELDS = new Set(["kvCacheDtype","mlxKvQuant","mlxInt8Prefill",+ "mlxAnePrefill","mlxPleOffload","mlxExpertOffload","loadIn4bit",@@ -1081,6 +1085,7 @@ function normalizeV1(partial: RawConfig): PerModelConfig {maxSeqLength: normalizeMaxSeqLength(partial.maxSeqLength),mlxKvQuant: normalizeMlxKvQuant(partial.mlxKvQuant, partial.mlxKvBits),mlxInt8Prefill: partial.mlxInt8Prefill === true,+ mlxAnePrefill: partial.mlxAnePrefill === true,mlxPleOffload: normalizeMlxOffload(partial.mlxPleOffload),mlxExpertOffload: normalizeMlxOffload(partial.mlxExpertOffload),kvCacheDtype:@@ -1167,9 +1172,12 @@ function storedSchemaVersion(normalized: PerModelConfig): number {const mode = normalized.speculativeType;// A kept Auto and the MLX-only modes are values an older client folds back to unset.const mlxMode = mode === "auto" || (MLX_ONLY_SPEC_TYPES as readonly string[]).includes(mode ?? "");- if (normalized.mlxPleOffload != null || normalized.mlxExpertOffload != null) {+ if (normalized.mlxAnePrefill) {return STORAGE_SCHEMA_VERSION;}+ if (normalized.mlxPleOffload != null || normalized.mlxExpertOffload != null) {+ return PRE_MLX_ANE_PREFILL_SCHEMA_VERSION;+ }if (normalized.specDraftModel != null || mlxMode) {return PRE_MLX_OFFLOAD_SCHEMA_VERSION;}@@ -1361,6 +1369,7 @@ export function isDefaultConfig(config: PerModelConfig): boolean {(config.kvCacheDtype ?? null) === DEFAULT_PER_MODEL_CONFIG.kvCacheDtype &&(config.mlxKvQuant ?? null) === DEFAULT_PER_MODEL_CONFIG.mlxKvQuant &&!config.mlxInt8Prefill &&+ !config.mlxAnePrefill &&config.mlxPleOffload == null &&config.mlxExpertOffload == null &&config.speculativeType === DEFAULT_PER_MODEL_CONFIG.speculativeType &&diff --git a/studio/frontend/src/features/model-picker/sharing/fields.ts b/studio/frontend/src/features/model-picker/sharing/fields.tsindex 4372896caa9..2ca9bcdb091 100644--- a/studio/frontend/src/features/model-picker/sharing/fields.ts+++ b/studio/frontend/src/features/model-picker/sharing/fields.ts@@ -47,6 +47,7 @@ export type SharedConfigKey = Exclude<| "maxSeqLength"| "mlxKvQuant"| "mlxInt8Prefill"+ | "mlxAnePrefill"| "mlxPleOffload"| "mlxExpertOffload"| "engine"diff --git a/studio/frontend/tests/hydration-clears-stale-local-record.test.ts b/studio/frontend/tests/hydration-clears-stale-local-record.test.tsindex 5d6cbb50580..c3429ad08e3 100644--- a/studio/frontend/tests/hydration-clears-stale-local-record.test.ts+++ b/studio/frontend/tests/hydration-clears-stale-local-record.test.ts@@ -30,13 +30,18 @@ const {const MODEL = "unsloth/Model-GGUF";const VARIANT = "q4_k_m";-test("int8 prefill reaches the server row only when on", () => {- const on = { ...DEFAULT_PER_MODEL_CONFIG, mlxInt8Prefill: true };- assert.equal(toApiOverride(on).mlx_int8_prefill, true);- assert.equal("mlx_int8_prefill" in toApiOverride(DEFAULT_PER_MODEL_CONFIG), false);- assert.equal(fromApiOverride({ mlx_int8_prefill: true }).mlxInt8Prefill, true);- assert.equal(fromApiOverride({}, on).mlxInt8Prefill, true);-});+for (const [key, wire] of [+ ["mlxInt8Prefill", "mlx_int8_prefill"],+ ["mlxAnePrefill", "mlx_ane_prefill"],+] as const) {+ test(`${key} reaches the server row only when on`, () => {+ const on = { ...DEFAULT_PER_MODEL_CONFIG, [key]: true };+ assert.equal(toApiOverride(on)[wire], true);+ assert.equal(wire in toApiOverride(DEFAULT_PER_MODEL_CONFIG), false);+ assert.equal(fromApiOverride({ [wire]: true })[key], true);+ assert.equal(fromApiOverride({}, on)[key], true);+ });+}test("MLX offload is always sent, null clearing to Auto, and hydrates from the row else the local value", () => {const set = { ...DEFAULT_PER_MODEL_CONFIG, mlxPleOffload: 0.5, mlxExpertOffload: "off" as const };diff --git a/studio/frontend/tests/mlx-context-pin-record-compat.test.ts b/studio/frontend/tests/mlx-context-pin-record-compat.test.tsindex 96dc28c44c5..55b0e6508c2 100644--- a/studio/frontend/tests/mlx-context-pin-record-compat.test.ts+++ b/studio/frontend/tests/mlx-context-pin-record-compat.test.ts@@ -189,8 +189,8 @@ const ROWS: Row[] = ["and reads normally.",},{- name: "version 13 (genuinely future)",- raw: { version: 13, customContextLength: 32768 },+ name: "version 14 (genuinely future)",+ raw: { version: 14, customContextLength: 32768 },normalizedPin: null,rawPin: 32768,isDefault: true,@@ -339,6 +339,10 @@ test("both pin shapes are stamped version 1, so neither is distinguishable by ve);assert.equal(stage({ version: 13, customContextLength: 32768 }).remembered,+ true,+ );+ assert.equal(+ stage({ version: 14, customContextLength: 32768 }).remembered,false,);});@@ -374,6 +378,15 @@ test("MLX offload keeps off or a fraction in (0, 1], and only a set one stamps vassert.deepEqual([config.mlxPleOffload, config.mlxExpertOffload], [0.75, "off"]);});+test("Neural Engine prefill defaults off, and only an enabled one stamps v13", () => {+ assert.equal(normalizePerModelConfig({ version: 12 }).mlxAnePrefill, false);+ assert.equal(normalizePerModelConfig({ mlxAnePrefill: "true" }).mlxAnePrefill, false);+ assert.equal(isDefaultConfig({ ...DEFAULT_PER_MODEL_CONFIG, mlxAnePrefill: true }), false);+ assert.equal(stampedVersion({ mlxAnePrefill: false, mlxPleOffload: 0.25 }), 12);+ assert.equal(stampedVersion({ mlxAnePrefill: true, mlxPleOffload: 0.25 }), 13);+ assert.equal(stage({ mlxAnePrefill: true }).config.mlxAnePrefill, true);+});+/** Old config page, non-GGUF: the number reads maxSeqLength; customContextLength only sets atDefault. */function oldClientConfigPage(diff --git a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.tsindex 6fcdc318fdf..bdfbc91e751 100644--- a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts+++ b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts@@ -254,6 +254,12 @@ const FIELDS: FieldCase[] = [same: true,different: false,},+ {+ key: "mlxAnePrefill",+ statusKey: "mlx_ane_prefill_requested",+ same: true,+ different: false,+ },{ key: "mlxPleOffload", statusKey: "mlx_offload", same: 0.5, different: "off", wrap: offloadRequest("ple") },{key: "mlxExpertOffload",diff --git a/studio/frontend/tests/same-model-reload-load-settings.test.ts b/studio/frontend/tests/same-model-reload-load-settings.test.tsindex 246a8b229a5..dd2acd2f57f 100644--- a/studio/frontend/tests/same-model-reload-load-settings.test.ts+++ b/studio/frontend/tests/same-model-reload-load-settings.test.ts@@ -62,6 +62,7 @@ function mlxStatus(over: Record<string, unknown>) {mlx_kv_quant_note: null,chat_template_override_reason: null,mlx_int8_prefill_requested: false,+ mlx_ane_prefill_requested: false,...over,};}@@ -98,13 +99,14 @@ test("a same-model GGUF reload elsewhere moves every clean control and baseline"test("a same-model MLX reload elsewhere moves the KV width, int8 prefill and verdict", () => {useChatRuntimeStore.setState({ activeGgufVariant: null });- hydrate(mlxStatus({}), MLX);+ hydrate(mlxStatus({ mlx_ane_prefill_requested: true }), MLX);reload(mlxStatus({mlx_kv_quant_requested: "8",mlx_kv_quant_reason: "Quantized KV cache to 8 bits",mlx_kv_quant_note: "from token 256",mlx_int8_prefill_requested: true,+ mlx_ane_prefill_requested: false,mlx_offload: {ple: { applied: 0.5, requested: "auto", reason: null },experts: { applied: null, requested: 0.25, reason: "no_quantized_experts" },@@ -120,6 +122,8 @@ test("a same-model MLX reload elsewhere moves the KV width, int8 prefill and verassert.equal(s.mlxKvQuantNote, "from token 256");assert.equal(s.mlxInt8Prefill, true);assert.equal(s.loadedMlxInt8PrefillRequested, true);+ assert.equal(s.mlxAnePrefill, false);+ assert.equal(s.loadedMlxAnePrefillRequested, false);assert.deepEqual([s.mlxPleOffload, s.loadedMlxPleOffload, s.mlxExpertOffload, s.loadedMlxExpertOffload, s.mlxExpertOffloadReason],[null, 0.5, 0.25, null, "no_quantized_experts"],@@ -158,13 +162,20 @@ test("a same-model MLX reload keeps a value this tab staged but advances the basassert.equal(s.loadedMlxKvQuantRequested, null);});-test("a steady MLX poll leaves a staged value alone", () => {- useChatRuntimeStore.setState({ activeGgufVariant: null });- hydrate(mlxStatus({ mlx_kv_quant_requested: "8" }), MLX);- useChatRuntimeStore.setState({ mlxKvQuant: "4", mlxInt8Prefill: true });- reload(mlxStatus({ mlx_kv_quant_requested: "8" }), MLX);- const s = useChatRuntimeStore.getState();- assert.equal(s.mlxKvQuant, "4");- assert.equal(s.mlxInt8Prefill, true);- assert.equal(s.loadedMlxKvQuantRequested, "8");-});+for (const staged of ["int8", "ane"] as const) {+ test(`a steady MLX poll leaves a staged ${staged} value alone while the other follows the server`, () => {+ useChatRuntimeStore.setState({ activeGgufVariant: null });+ hydrate(mlxStatus({ mlx_kv_quant_requested: "8" }), MLX);+ useChatRuntimeStore.setState({ mlxKvQuant: "4", [staged === "int8" ? "mlxInt8Prefill" : "mlxAnePrefill"]: true });+ const other = staged === "int8" ? "mlx_ane_prefill_requested" : "mlx_int8_prefill_requested";+ reload(mlxStatus({ mlx_kv_quant_requested: "8", [other]: true }), MLX);+ const s = useChatRuntimeStore.getState();+ assert.equal(s.mlxKvQuant, "4");+ assert.deepEqual([s.mlxInt8Prefill, s.mlxAnePrefill], [true, true]);+ assert.deepEqual(+ [s.loadedMlxInt8PrefillRequested, s.loadedMlxAnePrefillRequested],+ staged === "int8" ? [false, true] : [true, false],+ );+ assert.equal(s.loadedMlxKvQuantRequested, "8");+ });+}diff --git a/studio/frontend/tests/server-tuning-settings.test.ts b/studio/frontend/tests/server-tuning-settings.test.tsindex 5c8ab0a7d25..89a36bbced1 100644--- a/studio/frontend/tests/server-tuning-settings.test.ts+++ b/studio/frontend/tests/server-tuning-settings.test.ts@@ -102,8 +102,9 @@ test("the four take part in the editor's identity", () => {test("a record only claims the new schema version when it carries one", () => {// toStoredConfig stamps the oldest version that understands every field present.const source = readSrc("features/model-picker/model-config/per-model-config.ts");- assert.match(source, /const STORAGE_SCHEMA_VERSION = 12;\nconst PRE_MLX_OFFLOAD_SCHEMA_VERSION = 11;\nconst PRE_MLX_DRAFTER_SCHEMA_VERSION = 10;/);- assert.match(source, /mlxExpertOffload != null\)\s*\{\s*return STORAGE_SCHEMA_VERSION;/);+ assert.match(source, /const STORAGE_SCHEMA_VERSION = 13;\nconst PRE_MLX_ANE_PREFILL_SCHEMA_VERSION = 12;\nconst PRE_MLX_OFFLOAD_SCHEMA_VERSION = 11;\nconst PRE_MLX_DRAFTER_SCHEMA_VERSION = 10;/);+ assert.match(source, /mlxAnePrefill\)\s*\{\s*return STORAGE_SCHEMA_VERSION;/);+ assert.match(source, /mlxExpertOffload != null\)\s*\{\s*return PRE_MLX_ANE_PREFILL_SCHEMA_VERSION;/);assert.match(source, /specDraftModel != null \|\| mlxMode\)\s*\{\s*return PRE_MLX_OFFLOAD_SCHEMA_VERSION;/);assert.match(source, /tensorSplit != null\)\s*\{\s*return PRE_MLX_DRAFTER_SCHEMA_VERSION;/);assert.match(source, /const PRE_TENSOR_SPLIT_SCHEMA_VERSION = 9;/);