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: serve /v1/completions from MLX models (#13796)
Long Yixing3de513d3a032
diff --git a/studio/backend/core/inference/grammar_constraint.py b/studio/backend/core/inference/grammar_constraint.pyindex cb80f09092a..6637fee4741 100644--- a/studio/backend/core/inference/grammar_constraint.py+++ b/studio/backend/core/inference/grammar_constraint.py@@ -188,6 +188,33 @@ def _require_schema_object(schema, message: str) -> dict:return schema+def grammar_from_json_schema(schema: dict) -> str:+ if not LLGUIDANCE_AVAILABLE:+ raise ResponseFormatError(MISSING_ENGINE_MESSAGE)+ return _cached_grammar(_canonical_schema_json(schema), prelude_close = None)+++def grammar_from_gbnf(gbnf: str) -> str:+ """A llama.cpp GBNF grammar as an llguidance one."""+ if not LLGUIDANCE_AVAILABLE:+ raise ResponseFormatError(MISSING_ENGINE_MESSAGE)+ digest = hashlib.sha256(gbnf.encode("utf-8")).hexdigest()+ return _memoized(f"{LLGUIDANCE_VERSION}:gbnf:{digest}", lambda: _compile_gbnf(gbnf))+++def _compile_gbnf(gbnf: str) -> str:+ from llguidance.gbnf_to_lark import gbnf_to_lark++ try:+ grammar = _llg.LLMatcher.grammar_from_lark(gbnf_to_lark(gbnf))+ except Exception as exc:+ raise ResponseFormatError(f"invalid grammar: {exc}") from exc+ error = _llg.LLMatcher.validate_grammar(grammar)+ if error:+ raise ResponseFormatError(f"invalid grammar: {error}")+ return grammar++def _reserved_token_text(tokenizer, token_id: int) -> str:try:return str(_unwrap_hf_tokenizer(tokenizer).convert_ids_to_tokens(int(token_id)))@@ -370,12 +397,16 @@ def _canonical_schema_json(schema: dict) -> str:def _cached_grammar(schema_json: str, *, prelude_close: Optional[str]) -> str:digest = hashlib.sha256(schema_json.encode("utf-8")).hexdigest()key = f"{LLGUIDANCE_VERSION}:{prelude_close or ''}:" f"{_PRELUDE_MAX_TOKENS}:{digest}"+ return _memoized(key, lambda: _compile_grammar(schema_json, prelude_close))+++def _memoized(key: str, build) -> str:with _CACHE_LOCK:cached = _GRAMMAR_CACHE.get(key)if cached is not None:_GRAMMAR_CACHE.move_to_end(key)return cached- grammar = _compile_grammar(schema_json, prelude_close)+ grammar = build()with _CACHE_LOCK:_GRAMMAR_CACHE[key] = grammarcached_bytes = sum(len(value) for value in _GRAMMAR_CACHE.values())diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 2c60049151d..08e0a04e3e7 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -3100,18 +3100,26 @@ def _make_seeded_mlx_sampler(return _sampler-def _make_mlx_presence_penalty_processor(penalty: float):+def _penalized_tokens(tokens, state, window):+ """The tokens a penalty scores: the whole completion, or with ``window`` the last ``window``+ tokens of prompt and completion, as llama-server's ``repeat_last_n`` scores them."""+ if window is not None:+ return tokens[-window:]+ if state["prompt_len"] is None:+ # First call is prompt-only; latch its length.+ state["prompt_len"] = int(tokens.shape[0])+ return tokens[:0]+ return tokens[state["prompt_len"] :]+++def _make_mlx_presence_penalty_processor(penalty: float, window = None):"""Presence penalty as an mlx_lm/mlx_vlm logits processor, matching the safetensors path.generate_step calls processors as ``fn(tokens, logits)`` with ``tokens`` the full runningsequence; the first call is prompt-only, so latch that length and penalize only after it."""state = {"prompt_len": None}def _processor(tokens, logits):- if state["prompt_len"] is None:- # First call is prompt-only; latch its length.- state["prompt_len"] = int(tokens.shape[0])- return logits- generated = tokens[state["prompt_len"] :]+ generated = _penalized_tokens(tokens, state, window)if generated.size == 0:return logitsimport mlx.core as mx@@ -3152,7 +3160,7 @@ def _row_logits_processors(processors):return [_shown(processor) for processor in processors]-def _make_mlx_frequency_penalty_processor(penalty: float):+def _make_mlx_frequency_penalty_processor(penalty: float, window = None):"""Frequency penalty as an mlx_lm/mlx_vlm logits processor. Identical to the presence processorexcept the scatter *accumulates*, so a token repeated N times in the completion is charged Nx penalty. It counts occurrences and scales once, in float32: accumulating the penalty itself@@ -3161,10 +3169,7 @@ def _make_mlx_frequency_penalty_processor(penalty: float):state = {"prompt_len": None}def _processor(tokens, logits):- if state["prompt_len"] is None:- state["prompt_len"] = int(tokens.shape[0])- return logits- generated = tokens[state["prompt_len"] :]+ generated = _penalized_tokens(tokens, state, window)if generated.size == 0:return logitsimport mlx.core as mx@@ -3243,6 +3248,34 @@ def _build_grammar_constraint(return constraint+def _raw_prompt_constraint(grammar, tokenizer):+ if grammar is None:+ return None+ from core.inference.grammar_constraint import GrammarConstraint++ # Raw replies decode with skip_special_tokens, so a special id spelling a literal would vanish.+ return GrammarConstraint(grammar, tokenizer, strips_special_tokens = True)+++def _with_prompt_history(processor, prompt, window):+ """*processor* also scoring the prompt tokens the runtime withholds: mlx_lm and mlx_vlm hand+ processors only what is left of the prompt after prefill and prompt-cache reuse."""+ import mlx.core as mx++ head = None++ def _processor(tokens, logits):+ nonlocal head+ if head is None:+ seen = int(tokens.shape[0])+ head = mx.array(list(prompt)[: max(len(prompt) - seen, 0)][-window:], dtype = mx.int32)+ return processor(mx.concatenate([head, tokens.astype(mx.int32)]), logits)++ # Still a function of the token history alone, so a speculative draft keeps running.+ _processor.history_only = getattr(processor, "history_only", False)+ return _processor++def _mlx_sampling_processors(*,repetition_penalty = None,@@ -3250,29 +3283,46 @@ def _mlx_sampling_processors(frequency_penalty: float = 0.0,logit_bias = None,grammar_constraint = None,+ penalty_window = None,+ penalty_prompt = None,):"""Logits processors for the sampling knobs, or ``None`` when all are inert. Bias runs beforethe penalties, matching llama-server's sampler order. mlx_lm supplies only the repetitionpenalty here: its presence and frequency processors window the last 20 tokens *including theprompt*, while the penalties below score the whole completion and exclude it, so using them- would make the same request sample differently depending on the backend."""+ would make the same request sample differently depending on the backend. ``penalty_window``+ is llama-server's ``repeat_last_n``: one window for all three penalties, ``0`` disabling them.+ ``penalty_prompt`` is the full prompt, so the window reaches the part the runtime withholds."""processors = []if grammar_constraint is not None:from core.inference.grammar_constraint import make_grammar_logits_processorprocessors.append(make_grammar_logits_processor(grammar_constraint))if logit_bias:processors.append(_make_mlx_logit_bias_processor(logit_bias))+ if penalty_window == 0:+ return processors or None+ penalties = []if repetition_penalty is not None and float(repetition_penalty) not in (0.0, 1.0):from mlx_lm.sample_utils import make_logits_processors- repetition = make_logits_processors(repetition_penalty = float(repetition_penalty))+ window = {} if penalty_window is None else {"repetition_context_size": penalty_window}+ repetition = make_logits_processors(repetition_penalty = float(repetition_penalty), **window)for processor in repetition:processor.history_only = True- processors.extend(repetition)+ penalties.extend(repetition)if presence_penalty:- processors.append(_make_mlx_presence_penalty_processor(float(presence_penalty)))+ penalties.append(+ _make_mlx_presence_penalty_processor(float(presence_penalty), penalty_window)+ )if frequency_penalty:- processors.append(_make_mlx_frequency_penalty_processor(float(frequency_penalty)))+ penalties.append(+ _make_mlx_frequency_penalty_processor(float(frequency_penalty), penalty_window)+ )+ if penalty_window is not None and penalty_prompt:+ penalties = [+ _with_prompt_history(penalty, penalty_prompt, penalty_window) for penalty in penalties+ ]+ processors.extend(penalties)return processors or None@@ -3493,7 +3543,7 @@ def _request_batch_gap(request):return "a reply carries a video clip"if request.get("tools") or request.get("tool_protocol_active"):return "a reply runs the tool protocol"- if request.get("response_format") is not None:+ if request.get("response_format") is not None or request.get("grammar") is not None:return "a reply is constrained to a response format"return None@@ -3594,6 +3644,8 @@ def _row_kwargs(request):frequency_penalty = request.get("frequency_penalty", 0.0),logit_bias = request.get("logit_bias"),stop = request.get("stop"),+ prompt_ids = request.get("prompt_ids"),+ penalty_window = request.get("penalty_window"),)@@ -3962,7 +4014,7 @@ class _VisionBatchSession:try:row_number = self.stream.add(GenerationRequest(- prompt = backend._vlm_batch_prompt(plan.prompt),+ **backend._vlm_batch_prompt(plan.prompt),image = plan.images[0] if plan.images else None,max_tokens = plan.max_tokens,sampling = SamplingParams(**plan.sampling),@@ -4320,7 +4372,7 @@ class MLXInferenceBackend:if history is None:return prompt, None, None, None, 0try:- tokens = self._encode_prompt(prompt)+ tokens = list(prompt) if isinstance(prompt, list) else self._encode_prompt(prompt)if not tokens:return prompt, None, None, None, 0key = f"{self.active_model_name}|{adapter_state!r}"@@ -4360,6 +4412,8 @@ class MLXInferenceBackend:videos = None,cap = None,):+ if prompt_tokens is None and isinstance(prompt, list):+ prompt_tokens = promptbudget = getattr(self, "_kv_context_budget", None)if not budget:# No budget: size from the placeholder count as before, never preparing the media.@@ -5452,6 +5506,93 @@ class MLXInferenceBackend:)yield from stream+ def _vocab_size(self):+ """The model's token-id range, as llama-server's ``n_vocab`` bounds a prompt's ids."""+ config = getattr(self._model, "config", None)+ for owner in (+ getattr(self._model, "args", None),+ getattr(config, "text_config", None),+ config,+ ):+ size = getattr(owner, "vocab_size", None)+ if isinstance(size, int) and size > 0:+ return size+ return len(getattr(self._tokenizer, "_tokenizer", self._tokenizer))++ def resolve_completion_prompt(self, prompt) -> dict:+ """Token ids and echo text for one llama-server completion prompt, tokenized as its+ ``tokenize_mixed`` does: specials parsed, only a leading string gets BOS."""+ if self._model is None:+ raise RuntimeError("No model loaded")+ if isinstance(prompt, dict):+ prompt = prompt.get("prompt_string")+ pieces = [prompt] if isinstance(prompt, str) else prompt+ if not isinstance(pieces, list):+ raise ValueError("Invalid prompt.")+ vocab = self._vocab_size()+ ids, text, run = [], [], []+ for index, piece in enumerate(pieces + [""]):+ if isinstance(piece, int) and not isinstance(piece, bool):+ if not 0 <= piece < vocab:+ raise ValueError("Prompt contains invalid tokens.")+ run.append(piece)+ continue+ if not isinstance(piece, str):+ raise ValueError("Invalid prompt.")+ if run:+ text.append(+ self._tokenizer.decode(+ run, skip_special_tokens = False, clean_up_tokenization_spaces = False+ )+ )+ ids.extend(run)+ run = []+ if index < len(pieces):+ ids.extend(self._tokenizer.encode(piece, add_special_tokens = index == 0))+ text.append(piece)+ if not ids:+ raise ValueError("The prompt is empty.")+ return {"ids": ids, "text": "".join(text), "n_vocab": vocab}++ def generate_completion(+ self,+ prompt_ids,+ temperature = 0.7,+ top_p = 0.9,+ top_k = 40,+ min_p = 0.0,+ max_new_tokens = 256,+ repetition_penalty = 1.0,+ cancel_event = None,+ presence_penalty = 0.0,+ seed = None,+ frequency_penalty = 0.0,+ logit_bias = None,+ stop = None,+ penalty_window = None,+ grammar = None,+ ) -> Generator[str, None, None]:+ """Cumulative text sampled after ``prompt_ids`` with no chat template.+ ``penalty_window`` is llama-server's ``repeat_last_n``."""+ if self._model is None:+ raise RuntimeError("No model loaded")+ self.last_generation_stats = None+ sampling = dict(+ presence_penalty = presence_penalty,+ seed = seed,+ frequency_penalty = frequency_penalty,+ logit_bias = logit_bias,+ stop = stop,+ prompt_ids = list(prompt_ids),+ penalty_window = penalty_window,+ grammar = grammar,+ )+ args = (temperature, top_p, top_k, min_p, max_new_tokens, repetition_penalty, cancel_event)+ if self._is_vlm:+ yield from self._generate_vlm(None, None, *args, **sampling)+ else:+ yield from self._generate_text(None, *args, **sampling)+def _mark_stopped(self):"""Record that a text sequence ended the turn, not the runtime."""if isinstance(self.last_generation_stats, dict):@@ -5482,51 +5623,60 @@ class MLXInferenceBackend:stop = None,response_format = None,reasoning_is_extracted = False,+ prompt_ids = None,+ penalty_window = None,+ grammar = None,):from mlx_lm import stream_generatefrom mlx_lm.sample_utils import make_sampler- render_result = self._render_text_prompt(- messages,- tools = tools,- enable_thinking = enable_thinking,- reasoning_effort = reasoning_effort,- preserve_thinking = preserve_thinking,- continue_final_message = continue_final_message,- )- prompt = render_result.prompt- reasoning_channel_markers = render_result.reasoning_channel_markers+ if prompt_ids is not None:+ # A raw completion prompt: no template, so no prefill or reasoning channel.+ prompt, reasoning_channel_markers, think_prefix = list(prompt_ids), None, ""+ preserve_native_channels = False+ constraint = _raw_prompt_constraint(grammar, self._tokenizer)+ else:+ render_result = self._render_text_prompt(+ messages,+ tools = tools,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ continue_final_message = continue_final_message,+ )+ prompt = render_result.prompt+ reasoning_channel_markers = render_result.reasoning_channel_markers++ preserve_native_channels = reasoning_channel_markers is not None+ # An open <think> prefilled by the template lives in the prompt, not the generated tokens; re-emit it so the+ # frontend renders the block.+ # Matches native_token_decoder below: when it runs </think> survives, so re-emit the opener.+ think_close_survives = (+ bool(tools) or tool_protocol_active or reasoning_channel_markers is not None+ ) and decoder_preserves_token(+ self._tokenizer, "</think>", reasoning_control_tokens(reasoning_channel_markers)+ )+ think_prefix = _think_prefix(+ prompt,+ getattr(self._tokenizer, "all_special_tokens", None),+ messages,+ continue_final_message,+ preserves_think_close = think_close_survives,+ )+ constraint = _build_grammar_constraint(+ response_format,+ self._tokenizer,+ prompt,+ reasoning_markers = reasoning_channel_markers,+ reasoning_is_extracted = reasoning_is_extracted,+ # Must match the prefill's answer, or a closer it re-emits would be refused.+ reply_keeps_special_tokens = preserve_native_channels or think_close_survives,+ )+ if constraint is not None and not constraint.allows_reasoning:+ think_prefix = ""+ preserve_native_channels = False# Not the request flag: a later tool-loop pass keeps it but renders an ordinary post-tool prompt._resumed_partial = bool(continue_final_message and trailing_assistant_text(messages))-- preserve_native_channels = reasoning_channel_markers is not None- # An open <think> prefilled by the template lives in the prompt, not the generated tokens; re-emit it so the- # frontend renders the block.- # Matches native_token_decoder below: when it runs </think> survives, so re-emit the opener.- think_close_survives = (- bool(tools) or tool_protocol_active or reasoning_channel_markers is not None- ) and decoder_preserves_token(- self._tokenizer, "</think>", reasoning_control_tokens(reasoning_channel_markers)- )- think_prefix = _think_prefix(- prompt,- getattr(self._tokenizer, "all_special_tokens", None),- messages,- continue_final_message,- preserves_think_close = think_close_survives,- )- constraint = _build_grammar_constraint(- response_format,- self._tokenizer,- prompt,- reasoning_markers = reasoning_channel_markers,- reasoning_is_extracted = reasoning_is_extracted,- # Must match the prefill's answer, or a closer it re-emits would be refused.- reply_keeps_special_tokens = preserve_native_channels or think_close_survives,- )- if constraint is not None and not constraint.allows_reasoning:- think_prefix = ""- preserve_native_channels = Falseif seed is None:sampler = make_sampler(temp = temperature,@@ -5549,6 +5699,8 @@ class MLXInferenceBackend:frequency_penalty = frequency_penalty,logit_bias = logit_bias,grammar_constraint = constraint,+ penalty_window = penalty_window,+ penalty_prompt = prompt_ids,)native_token_decoder = (@@ -5690,10 +5842,11 @@ class MLXInferenceBackend:sampled = self._tokenizer.decode(token_ids,skip_special_tokens = True,- # Cleanup would rewrite " ." inside a grammar-approved string.+ # Cleanup would rewrite " ." inside a grammar-approved string,+ # and llama-server returns a raw completion's pieces as is.**({"clean_up_tokenization_spaces": False}- if constraint is not None+ if constraint is not None or prompt_ids is not Noneelse {}),)@@ -5796,33 +5949,39 @@ class MLXInferenceBackend:logit_bias = None,stop = None,tool_protocol_active = None,+ prompt_ids = None,+ penalty_window = None,) -> "_TextRowPlan":from mlx_lm.sample_utils import make_sampler- render_result = self._render_text_prompt(- messages,- tools = tools,- enable_thinking = enable_thinking,- reasoning_effort = reasoning_effort,- preserve_thinking = preserve_thinking,- continue_final_message = continue_final_message,- )- prompt = render_result.prompt- reasoning_channel_markers = render_result.reasoning_channel_markers- _resumed_partial = bool(continue_final_message and trailing_assistant_text(messages))+ if prompt_ids is not None:+ prompt, reasoning_channel_markers, think_prefix = list(prompt_ids), None, ""+ _resumed_partial = False+ else:+ render_result = self._render_text_prompt(+ messages,+ tools = tools,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ continue_final_message = continue_final_message,+ )+ prompt = render_result.prompt+ reasoning_channel_markers = render_result.reasoning_channel_markers+ _resumed_partial = bool(continue_final_message and trailing_assistant_text(messages))- think_prefix = _think_prefix(- prompt,- getattr(self._tokenizer, "all_special_tokens", None),- messages,- continue_final_message,- preserves_think_close = (- bool(tools) or tool_protocol_active or reasoning_channel_markers is not None+ think_prefix = _think_prefix(+ prompt,+ getattr(self._tokenizer, "all_special_tokens", None),+ messages,+ continue_final_message,+ preserves_think_close = (+ bool(tools) or tool_protocol_active or reasoning_channel_markers is not None+ )+ and decoder_preserves_token(+ self._tokenizer, "</think>", reasoning_control_tokens(reasoning_channel_markers)+ ),)- and decoder_preserves_token(- self._tokenizer, "</think>", reasoning_control_tokens(reasoning_channel_markers)- ),- )if seed is None:sampler = make_sampler(temp = temperature,@@ -5844,6 +6003,8 @@ class MLXInferenceBackend:presence_penalty = presence_penalty,frequency_penalty = frequency_penalty,logit_bias = logit_bias,+ penalty_window = penalty_window,+ penalty_prompt = prompt_ids,)normalizer = (@@ -5863,7 +6024,11 @@ class MLXInferenceBackend:decode = (Noneif normalizer is not None- else lambda ids: self._tokenizer.decode(ids, skip_special_tokens = True)+ else lambda ids: self._tokenizer.decode(+ ids,+ skip_special_tokens = True,+ **({"clean_up_tokenization_spaces": False} if prompt_ids is not None else {}),+ )),)return _TextRowPlan(@@ -5874,7 +6039,9 @@ class MLXInferenceBackend:sampler = sampler,processors = logits_processors,max_tokens = (- self._unset_generation_budget(prompt) if max_new_tokens is None else max_new_tokens+ self._unset_generation_budget(prompt, prompt_ids)+ if max_new_tokens is None+ else max_new_tokens),)@@ -6037,8 +6204,10 @@ class MLXInferenceBackend:def _plan_vlm_request(self, request) -> "_VLMRowPlan":image = request.get("image")messages = request.get("messages") or []- conversation = self._conversation_to_render(- messages, request.get("system_prompt", ""), image+ conversation = (+ []+ if request.get("prompt_ids") is not None+ else self._conversation_to_render(messages, request.get("system_prompt", ""), image))return self._plan_vlm_row(conversation, image, **_row_kwargs(request))@@ -6063,24 +6232,29 @@ class MLXInferenceBackend:frequency_penalty = 0.0,logit_bias = None,stop = None,+ prompt_ids = None,+ penalty_window = None,) -> "_VLMRowPlan":images = [image] if image is not None else None- prompt, chat_target, markers = self._render_vlm_prompt(- messages,- images,- tools = tools,- enable_thinking = enable_thinking,- reasoning_effort = reasoning_effort,- preserve_thinking = preserve_thinking,- continue_final_message = continue_final_message,- )+ if prompt_ids is not None:+ prompt, markers, think_prefix = list(prompt_ids), None, ""+ else:+ prompt, chat_target, markers = self._render_vlm_prompt(+ messages,+ images,+ tools = tools,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ continue_final_message = continue_final_message,+ )- think_prefix = _think_prefix(- prompt,- getattr(chat_target, "all_special_tokens", None),- messages,- continue_final_message,- )+ think_prefix = _think_prefix(+ prompt,+ getattr(chat_target, "all_special_tokens", None),+ messages,+ continue_final_message,+ )normalizer = (make_reasoning_normalizer(markers,@@ -6101,6 +6275,7 @@ class MLXInferenceBackend:max_new_tokens = self._generation_limit(prompt,max_new_tokens,+ prompt_ids,images = images,cap = UNSET_GENERATION_BUDGET if images else None,)@@ -6125,6 +6300,8 @@ class MLXInferenceBackend:presence_penalty = presence_penalty,frequency_penalty = frequency_penalty,logit_bias = logit_bias,+ penalty_window = penalty_window,+ penalty_prompt = prompt_ids,)if processors:# Never the repetition_penalty shortcut: mlx-vlm would build that processor@@ -6175,38 +6352,43 @@ class MLXInferenceBackend:video = None,response_format = None,reasoning_is_extracted = False,+ prompt_ids = None,+ penalty_window = None,+ grammar = None,):from mlx_vlm import stream_generate as vlm_stream- images = list(images) if images else None- prompt, chat_target, vlm_reasoning_markers = self._render_vlm_prompt(- messages,- images,- videos = [video] if video is not None else None,- tools = tools,- enable_thinking = enable_thinking,- reasoning_effort = reasoning_effort,- preserve_thinking = preserve_thinking,- continue_final_message = continue_final_message,- )-from core.inference.chat_template_helpers import detect_think_prefill- # Detected once: the decoder keeps the delimiters the normalizer below consumes.- prefill = _think_prefix(- prompt,- getattr(chat_target, "all_special_tokens", None),- messages,- continue_final_message,- # The same activation the decoder below uses: in unrestricted mode ``tools`` is- # empty while the protocol is live, so ``bool(tools)`` said the closer would be- # stripped, the opener was suppressed, and the stream ran on to an orphan- # ``</think>``. Mirrors the text path.- preserves_think_close = (- bool(tools) or tool_protocol_active or vlm_reasoning_markers is not None+ images = list(images) if images else None+ if prompt_ids is not None:+ prompt, chat_target, vlm_reasoning_markers, prefill = "", None, None, ""+ else:+ prompt, chat_target, vlm_reasoning_markers = self._render_vlm_prompt(+ messages,+ images,+ videos = [video] if video is not None else None,+ tools = tools,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ continue_final_message = continue_final_message,+ )+ # Detected once: the decoder keeps the delimiters the normalizer below consumes.+ prefill = _think_prefix(+ prompt,+ getattr(chat_target, "all_special_tokens", None),+ messages,+ continue_final_message,+ # The same activation the decoder below uses: in unrestricted mode ``tools`` is+ # empty while the protocol is live, so ``bool(tools)`` said the closer would be+ # stripped, the opener was suppressed, and the stream ran on to an orphan+ # ``</think>``. Mirrors the text path.+ preserves_think_close = (+ bool(tools) or tool_protocol_active or vlm_reasoning_markers is not None+ )+ and decoder_preserves_token(self._tokenizer, "</think>"),)- and decoder_preserves_token(self._tokenizer, "</think>"),- )vlm_continued = bool(continue_final_message and trailing_assistant_text(messages))# Matched on the sampled text, for the reason _generate_text gives.sequences = _mlx_stop_sequences(stop)@@ -6221,6 +6403,7 @@ class MLXInferenceBackend:max_new_tokens = self._generation_limit(prompt,max_new_tokens,+ prompt_ids,images = images,videos = [counted_clip] if counted_clip is not None else None,cap = UNSET_GENERATION_BUDGET if images or video is not None else None,@@ -6259,14 +6442,18 @@ class MLXInferenceBackend:0.0,1.0,)- constraint = _build_grammar_constraint(- response_format,- chat_target,- prompt,- reasoning_markers = vlm_reasoning_markers,- tools = tools,- reasoning_is_extracted = reasoning_is_extracted,- reply_keeps_special_tokens = True,+ constraint = (+ _raw_prompt_constraint(grammar, self._tokenizer)+ if prompt_ids is not None+ else _build_grammar_constraint(+ response_format,+ chat_target,+ prompt,+ reasoning_markers = vlm_reasoning_markers,+ tools = tools,+ reasoning_is_extracted = reasoning_is_extracted,+ reply_keeps_special_tokens = True,+ ))document_only = constraint is not None and not constraint.allows_reasoningif document_only:@@ -6289,6 +6476,7 @@ class MLXInferenceBackend:or logit_biasor constraint is not Noneor (_rep_active and draft is not None)+ or penalty_window is not None):# These need custom processors: pass the full list (repetition + the rest) instead of the# repetition_penalty shortcut so all apply.@@ -6298,6 +6486,8 @@ class MLXInferenceBackend:frequency_penalty = frequency_penalty,logit_bias = logit_bias,grammar_constraint = constraint,+ penalty_window = penalty_window,+ penalty_prompt = prompt_ids,)elif _rep_active:vlm_kwargs["repetition_penalty"] = float(repetition_penalty)@@ -6337,11 +6527,15 @@ class MLXInferenceBackend:else None)- if not self._reads_vision_input():+ if prompt_ids is not None:+ import mlx.core as mx+ vlm_kwargs["input_ids"] = mx.array([list(prompt_ids)])+ # As the text path and llama-server: control tokens are not reply text.+ vlm_kwargs["skip_special_tokens"] = True+ elif not self._reads_vision_input():# mlx-vlm adds special tokens by family, doubling a BOS the template already emitted.import mlx.core as mxvlm_kwargs["input_ids"] = mx.array([self._encode_prompt(prompt)])-session = self._vlm_prompt_cache_session(_adapter_state, images, prompt, has_video = video is not None)@@ -6441,11 +6635,37 @@ class MLXInferenceBackend:))) as responses:+ raw_ids = [] if prompt_ids is not None else Nonefor response in responses:final_response = response- if vlm_streamed_text is not None:+ raw_id = (+ getattr(response, "token", None) if raw_ids is not None else None+ )+ filled = getattr(response, "generation_tokens", None)+ if raw_id is not None and (+ filled is None or int(filled) == len(raw_ids) + 1+ ):+ # The streaming detokenizer trims the first leading space; decode the ids.+ raw_ids.append(int(raw_id))+ decoded = self._tokenizer.decode(+ raw_ids,+ skip_special_tokens = True,+ clean_up_tokenization_spaces = False,+ ).rstrip("\ufffd")+ token_text = (+ decoded[len(sampled) :] if decoded.startswith(sampled) else ""+ )+ elif (+ raw_ids is not None+ and filled is not None+ and int(filled) <= len(raw_ids)+ ):+ token_text = ""+ elif vlm_streamed_text is not None:token_text = vlm_streamed_text.feed(response)else:+ # A block naming several ids (a denoised step): the runtime's text stands.+ raw_ids = Nonetoken_text = (response.text if hasattr(response, "text") else str(response))@@ -6519,7 +6739,7 @@ class MLXInferenceBackend:else (draft.draft_n, draft.draft_n_accepted),)- if document_only:+ if document_only or prompt_ids is not None:# The normalizer would rewrite marker text inside the document.yield from _stream_vlm_snapshots()else:@@ -6635,6 +6855,9 @@ class MLXInferenceBackend:gap = _row_processor_gap(engine, requests)if gap is not None:return gap+ if any(request.get("prompt_ids") is not None for request in requests):+ # The batch detokenizer keeps control tokens and trims the first leading space.+ return "a raw prompt on a vision model decodes on its own"if not getattr(self._model, "_is_vlm_model", False):return "this model was not loaded as a vision model"return None@@ -6696,6 +6919,8 @@ class MLXInferenceBackend:session.close()def _vlm_batch_prompt(self, prompt):+ if isinstance(prompt, list):+ return {"prompt_token_ids": prompt}from unsloth_zoo.mlx.generate import vlm_batch_adds_special_tokensbos = getattr(self._tokenizer, "bos_token", None)@@ -6706,8 +6931,8 @@ class MLXInferenceBackend:and vlm_batch_adds_special_tokens(self._model, self._processor)):# The single path encodes a text load's prompt itself, keeping only the template's BOS.- return prompt[len(bos) :]- return prompt+ return {"prompt": prompt[len(bos) :]}+ return {"prompt": prompt}def _generate_vlm_batch(self,@@ -6728,7 +6953,7 @@ class MLXInferenceBackend:plans = [self._plan_vlm_request(request) for request in requests]batch = [GenerationRequest(- prompt = self._vlm_batch_prompt(plan.prompt),+ **self._vlm_batch_prompt(plan.prompt),image = plan.images[0] if plan.images else None,max_tokens = plan.max_tokens,sampling = SamplingParams(**plan.sampling),@@ -6823,7 +7048,7 @@ class MLXInferenceBackend:def _batch_prompt_row(self, prompt, adapter_state):rest, cache, key, tokens, cached_n = self._prepare_prompt_cache(prompt, adapter_state)if cache is None or tokens is None:- tokens = self._encode_prompt(prompt)+ tokens = list(prompt) if isinstance(prompt, list) else self._encode_prompt(prompt)rest, cached_n, key = tokens, 0, Nonecache = self._make_row_cache()return list(tokens[:cached_n]), list(rest), cache, key, list(tokens)diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 287b706cb7c..ccf9ec705c9 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -1448,6 +1448,9 @@ class InferenceOrchestrator:response_format: Optional[dict] = None,reasoning_is_extracted: bool = False,diffusion_frames: bool = False,+ prompt_ids: Optional[list] = None,+ penalty_window: Optional[int] = None,+ grammar: Optional[str] = None,) -> dict:"""Build the 'generate' command shared by the locked and dispatched paths."""cmd = {@@ -1496,6 +1499,12 @@ class InferenceOrchestrator:cmd["tool_protocol_active"] = tool_protocol_activeif diffusion_frames and not rows:cmd["diffusion_frames"] = True+ if prompt_ids is not None:+ cmd["prompt_ids"] = list(prompt_ids)+ if penalty_window is not None:+ cmd["penalty_window"] = penalty_window+ if grammar is not None:+ cmd["grammar"] = grammarreturn cmddef _consume_token_stream(@@ -1744,6 +1753,9 @@ class InferenceOrchestrator:response_format: Optional[dict] = None,reasoning_is_extracted: bool = False,diffusion_frames: bool = False,+ prompt_ids: Optional[list] = None,+ penalty_window: Optional[int] = None,+ grammar: Optional[str] = None,) -> Generator[Any, None, None]:"""Dispatched generation, sending the command without holding _gen_lock. Uses a per-requestmailbox for tokens so two compare-mode requests can be queued at once. The subprocess@@ -1801,6 +1813,9 @@ class InferenceOrchestrator:rows = rows,video_b64 = video,diffusion_frames = diffusion_frames,+ prompt_ids = prompt_ids,+ penalty_window = penalty_window,+ grammar = grammar,)mailbox = _WorkerMailbox(self._proc)@@ -2769,26 +2784,9 @@ class InferenceOrchestrator:"preserve_thinking": preserve_thinking,})- deadline = time.monotonic() + timeout- resp = None- while time.monotonic() < deadline:- candidate = read_one(timeout = min(1.0, deadline - time.monotonic()))- if candidate is None:- if not self._ensure_subprocess_alive():- # A count takes no part in the claim bookkeeping.- raise RuntimeError(- self._subprocess_crash_message(- "count", with_worker_output = self._owns_worker(None)- )- )- continue- # _direct_reader already drops a reply whose mailbox is gone; this is the backstop.- if (- candidate.get("type") == "count_tokens_response"- and candidate.get("request_id") == request_id- ):- resp = candidate- break+ resp = self._await_reply(+ read_one, request_id, "count_tokens_response", "count", timeout+ )if resp is None:raise RuntimeError("Timed out counting tokens")finally:@@ -2987,6 +2985,117 @@ class InferenceOrchestrator:logger.warning("Could not preflight the context window: %s", exc)return unchanged+ def _await_reply(+ self,+ read_one,+ request_id,+ reply_type,+ crash_context,+ timeout,+ cancelled = None,+ ):+ """The worker's *reply_type* answer to *request_id*, or None once *timeout* passes+ or *cancelled* returns true."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if cancelled is not None and cancelled():+ return None+ candidate = read_one(timeout = min(1.0, deadline - time.monotonic()))+ if candidate is None:+ if not self._ensure_subprocess_alive():+ # A query takes no part in the claim bookkeeping.+ raise RuntimeError(+ self._subprocess_crash_message(+ crash_context, with_worker_output = self._owns_worker(None)+ )+ )+ continue+ # _direct_reader already drops a reply whose mailbox is gone; this is the backstop.+ if candidate.get("type") == reply_type and candidate.get("request_id") == request_id:+ return candidate+ return None++ def resolve_completion_prompt(+ self,+ prompt,+ timeout: float = 30.0,+ cancel_event = None,+ ) -> dict:+ """``ids`` and echo ``text`` for one raw completion prompt; ValueError if invalid,+ InterruptedError once *cancel_event* is set while it waits."""++ def cancelled():+ return cancel_event is not None and cancel_event.is_set()++ # Polled, so a Stop or disconnect while queued behind a generation ends the wait.+ while not self._gen_lock.acquire(timeout = 0.1):+ if cancelled():+ raise InterruptedError("Request cancelled.")+ try:+ if self._unload_pending or not self.active_model_name:+ raise RuntimeError("No active model")+ request_id = str(uuid.uuid4())+ read_one, _drain, release_mailbox = self._direct_reader(request_id)+ try:+ self._send_cmd(+ {"type": "resolve_prompt", "request_id": request_id, "prompt": prompt}+ )+ resp = None+ while resp is None:+ resp = self._await_reply(+ read_one,+ request_id,+ "resolve_prompt_response",+ "prompt resolution",+ timeout,+ cancelled,+ )+ # A dispatched generation the worker runs alone answers first, however long.+ if self._replies_in_flight() <= 1 or cancelled():+ break+ finally:+ release_mailbox()+ finally:+ self._gen_lock.release()+ if resp is None and cancelled():+ raise InterruptedError("Request cancelled.")+ if resp is None:+ raise RuntimeError("Timed out resolving the prompt")+ if resp.get("error"):+ raise (ValueError if resp.get("invalid") else RuntimeError)(resp["error"])+ return {"ids": list(resp["ids"]), "text": resp["text"], "n_vocab": resp.get("n_vocab")}++ def generate_completion(+ self,+ prompt_ids: list,+ cancel_event = None,+ stats_holder: Optional[dict] = None,+ **sampling,+ ) -> Generator[str, None, None]:+ """Cumulative text sampled after ``prompt_ids`` with no chat template."""+ yield from self._generate_inner(+ prompt_ids = prompt_ids,+ cancel_event = cancel_event,+ stats_holder = stats_holder,+ **sampling,+ )++ def generate_completion_batch(+ self,+ rows: list,+ cancel_event = None,+ stats_holder: Optional[dict] = None,+ **sampling,+ ) -> Generator[Any, None, None]:+ """Several raw-prompt rows in one command, reported as :meth:`generate_chat_batch`."""+ yield from self._generate_inner(+ messages = [],+ rows = rows,+ cancel_event = cancel_event,+ stats_holder = stats_holder,+ **sampling,+ )+def generate_chat_response(self,messages: list,@@ -3432,6 +3541,9 @@ class InferenceOrchestrator:response_format: Optional[dict] = None,reasoning_is_extracted: bool = False,diffusion_frames: bool = False,+ prompt_ids: Optional[list] = None,+ penalty_window: Optional[int] = None,+ grammar: Optional[str] = None,) -> Generator[Any, None, None]:"""Inner generation logic: sends the command to the subprocess and yields tokens. Serializedby _gen_lock (one generation at a time) so concurrent readers don't consume each other's@@ -3495,6 +3607,9 @@ class InferenceOrchestrator:response_format = response_format,reasoning_is_extracted = reasoning_is_extracted,diffusion_frames = diffusion_frames,+ prompt_ids = prompt_ids,+ penalty_window = penalty_window,+ grammar = grammar,)return@@ -3537,6 +3652,9 @@ class InferenceOrchestrator:rows = rows,video_b64 = video,diffusion_frames = diffusion_frames,+ prompt_ids = prompt_ids,+ penalty_window = penalty_window,+ grammar = grammar,)read_one, drain, release_mailbox = self._direct_reader(request_id, cancel_event)diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 0efc5b0c8d9..56b5cd67bdb 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -1138,6 +1138,10 @@ def _generation_kwargs(backend, cmd: dict, cancel_event) -> dict:if not _backend_declares(backend, "video"):raise RuntimeError("The loaded backend does not read video.")gen_kwargs["video"] = cmd["video_base64"]+ # Only a raw completion carries these; its batch rows are planned from them.+ for raw in ("prompt_ids", "penalty_window", "grammar"):+ if raw in cmd:+ gen_kwargs[raw] = cmd[raw]return gen_kwargs@@ -1161,7 +1165,9 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:gen_kwargs = _generation_kwargs(backend, cmd, cancel_event)use_adapter = cmd.get("use_adapter")- if use_adapter is not None:+ if "prompt_ids" in cmd:+ generator = _completion_generator(backend, cmd, cancel_event)+ elif use_adapter is not None:generator = backend.generate_with_adapter_control(use_adapter = use_adapter,**gen_kwargs,@@ -1210,6 +1216,50 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:backend.diffusion_frame_sink = None+_COMPLETION_OPTIONS = (+ "seed",+ "frequency_penalty",+ "logit_bias",+ "stop",+ "penalty_window",+ "grammar",+)+++def _completion_generator(backend, cmd: dict, cancel_event):+ """A raw-prompt completion, which only a backend with ``generate_completion`` serves."""+ if not callable(getattr(backend, "generate_completion", None)):+ raise RuntimeError("The loaded backend does not serve raw-prompt completions.")+ return backend.generate_completion(+ cmd["prompt_ids"],+ temperature = cmd.get("temperature", 0.7),+ top_p = cmd.get("top_p", 0.9),+ top_k = cmd.get("top_k", 40),+ min_p = cmd.get("min_p", 0.0),+ max_new_tokens = cmd.get("max_new_tokens", 256),+ repetition_penalty = cmd.get("repetition_penalty", 1.0),+ presence_penalty = cmd.get("presence_penalty", 0.0),+ cancel_event = cancel_event,+ **{key: cmd[key] for key in _COMPLETION_OPTIONS if key in cmd},+ )+++def _handle_resolve_prompt(backend, cmd: dict, resp_queue: Any) -> None:+ """Resolve a raw completion prompt to token ids with the loaded tokenizer."""+ reply = {"type": "resolve_prompt_response", "request_id": cmd.get("request_id")}+ resolve = getattr(backend, "resolve_completion_prompt", None)+ if not callable(resolve):+ reply["error"] = "The loaded backend does not serve raw-prompt completions."+ else:+ try:+ reply.update(resolve(cmd.get("prompt")))+ except ValueError as exc:+ reply["error"], reply["invalid"] = str(exc), True+ except Exception as exc:+ reply["error"] = str(exc)+ _send_response(resp_queue, reply)++def _handle_count_tokens(backend, cmd: dict, resp_queue: Any) -> None:"""Count prompt tokens for the loaded model and reply with the total."""try:@@ -1273,13 +1323,17 @@ def _rows_apart(backend, requests, cancel_event, stats: list):"""A declined batch served reply by reply, as the batch's own (row, snapshot) events."""for row, request in enumerate(requests):if not cancel_event.is_set():- generator = backend.generate_chat_response(- **{- name: value- for name, value in request.items()- if _backend_declares(backend, name)- },- cancel_event = cancel_event,+ generator = (+ _completion_generator(backend, request, cancel_event)+ if "prompt_ids" in request+ else backend.generate_chat_response(+ **{+ name: value+ for name, value in request.items()+ if _backend_declares(backend, name)+ },+ cancel_event = cancel_event,+ ))try:for cumulative_text in generator:@@ -2243,6 +2297,8 @@ def run_inference_process(_decline_count_tokens(cmd, resp_queue, "A generation is in progress.")else:_handle_count_tokens(backend, cmd, resp_queue)+ elif cmd_type == "resolve_prompt":+ _handle_resolve_prompt(backend, cmd, resp_queue)elif cmd_type == "share_object":_handle_share_object(backend, cmd, resp_queue)elif cmd_type == "load":@@ -2510,6 +2566,9 @@ def run_inference_process(elif cmd_type == "count_tokens":_decline_count_tokens(cmd, resp_queue)+ elif cmd_type == "resolve_prompt":+ _handle_resolve_prompt(backend, cmd, resp_queue)+elif cmd_type == "share_object":_handle_share_object(backend, cmd, resp_queue)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex e5ee4443579..97021f0d0b5 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -11200,12 +11200,15 @@ async def _maybe_auto_switch_model(require_audio_input: bool = False,require_video: bool = False,gguf_only: bool = False,+ gguf_only_reason: Optional[str] = None,+ audio_cpp_ok: bool = True,audio_preflight: Optional[dict] = None,image_preflight: Optional[dict] = None,require_speech: bool = False,require_audio_workflow: Optional[str] = None,speech_budget: Optional[dict] = None,tool_images_only: bool = False,+ gguf_target_check: Optional[Callable[[], None]] = None,) -> None:"""Load a downloaded local model named by an OpenAI request when auto-switch is on.@@ -11228,8 +11231,9 @@ async def _maybe_auto_switch_model(token. ``modality_label`` names the inputs attached, so therejection does not report a modality the request never carried. ``gguf_only``marks an endpoint that reads llama.cpp alone, where loading a non-GGUF model- would unload the resident one and leave the handler with nothing to serve.- ``audio_preflight`` carries an audio upload whose format-dependent+ would unload the resident one and leave the handler with nothing to serve;+ ``gguf_only_reason`` replaces its refusal message when the request, not the+ endpoint, is what only llama.cpp can serve. ``audio_preflight`` carries an audio upload whose format-dependentchecks only the resolved target can decide; see:func:`_preflight_audio_for_switch`. ``image_preflight`` does the same fornon-GGUF image count and byte validation. ``require_audio_workflow`` refuses a target that@@ -11334,7 +11338,7 @@ async def _maybe_auto_switch_model(a resident non-GGUF model reaches the handler's own error instead, since noswap is pending to refuse."""- message = (+ message = gguf_only_reason or (f"This endpoint serves GGUF models only, and '{requested_model}' is not one. ""Use /v1/chat/completions for this model.")@@ -11595,6 +11599,12 @@ async def _maybe_auto_switch_model(# llama.cpp alone, so the swap would strand them with nothing to serve.if gguf_only and not target_is_gguf and resolved is not None:_refuse_non_gguf_endpoint()+ # A raw-prompt endpoint opened to MLX still has nothing an audio.cpp model can serve.+ if not audio_cpp_ok and looks_like_audio_cpp(target_id) and resolved is not None:+ _refuse_non_gguf_endpoint()+ # Raises for a request only a non-GGUF target serves, before any GGUF load or reload.+ if gguf_target_check is not None and target_is_gguf:+ gguf_target_check()# An image/audio request naming a different text-only target would load it# here and only 400 below, evicting the working model. Reject before the# swap. Only the resolver branch (an explicit new target); the reload-stash@@ -11960,6 +11970,9 @@ async def _auto_switch_from_request_body(current_subject: str,*,gguf_only: bool = False,+ gguf_only_reason: Optional[str] = None,+ gguf_target_check: Optional[Callable[[], None]] = None,+ audio_cpp_ok: bool = True,):"""Run auto-switch from a raw-body endpoint's ``model`` without changing itspre-feature status codes: a malformed/non-dict body yields no model (so an@@ -11977,12 +11990,18 @@ async def _auto_switch_from_request_body(model = body.get("model") or _RELOAD_ONLY_MODELelse:model = None- # Serves the GGUF-only /v1/completions and /v1/embeddings routes, which still 503 "No- # GGUF model loaded" after this returns. Don't claim here (claim_resident=False); the- # caller claims only once it confirms a GGUF is loaded, so that 503 can't strand a- # preview-owned non-GGUF model as Unsloth-owned.+ # Serves /v1/completions and /v1/embeddings, which still 503 "No GGUF model loaded"+ # after this returns when nothing loaded can serve them. Don't claim here+ # (claim_resident=False), so that 503 can't strand a preview-owned model as Unsloth-owned.await _maybe_auto_switch_model(- model, request, current_subject, claim_resident = False, gguf_only = gguf_only+ model,+ request,+ current_subject,+ claim_resident = False,+ gguf_only = gguf_only,+ gguf_only_reason = gguf_only_reason,+ gguf_target_check = gguf_target_check,+ audio_cpp_ok = audio_cpp_ok,)return body@@ -37556,43 +37575,658 @@ def _completions_prompt_present(body: dict) -> bool:return prompt is not None-def _raise_ignored_completions_params(body: dict) -> None:- if body.get("echo"):+def _raise_ignored_completions_params(body: dict, echo: bool = True) -> None:+ # llama-server ignores echo; an MLX model serves it, so its caller passes ``echo = False``.+ if echo and body.get("echo"):_raise_unsupported_openai_parameter("echo", "echo is not supported for completions.")if body.get("suffix"):_raise_unsupported_openai_parameter("suffix", "suffix is not supported for completions.")- if body.get("best_of") not in (None, 1, body.get("n")):+ if body.get("best_of") not in (None, 1, _llama_value(body, "n_cmpl")):_raise_unsupported_openai_parameter("best_of", "best_of is not supported for completions.")+def _is_token_id(value) -> bool:+ return isinstance(value, int) and not isinstance(value, bool)+++def _completion_prompts(prompt) -> Optional[list]:+ """The prompts in a /v1/completions ``prompt``, split as llama-server's+ ``tokenize_input_prompts`` splits it, or None for a shape it rejects. A list holding+ any token id is one prompt; any other list is one prompt per element."""+ if isinstance(prompt, (str, dict)) or (+ isinstance(prompt, list) and any(_is_token_id(p) for p in prompt)+ ):+ prompts = [prompt]+ elif isinstance(prompt, list):+ prompts = prompt+ else:+ return None+ for one in prompts:+ pieces = one.get("prompt_string") if isinstance(one, dict) else one+ if not isinstance(pieces, str) and not (+ isinstance(pieces, list) and all(isinstance(p, str) or _is_token_id(p) for p in pieces)+ ):+ return None+ return prompts+++def _llama_field(body: dict, name: str, default):+ value = body.get(name)+ return default if value is None else value+++def _llama_dry_off(body: dict) -> bool:+ return (+ _llama_field(body, "dry_multiplier", 0.0) == 0+ or _llama_field(body, "dry_penalty_last_n", 64) == 0+ )+++def _llama_grammar_off(body: dict) -> bool:+ # llama-server converts json_schema only while the body has no "grammar" key at all.+ if "grammar" not in body:+ return body.get("json_schema") is None+ return not (isinstance(body["grammar"], str) and body["grammar"])+++_LLAMA_DEFAULT_SAMPLERS = (+ ["penalties", "dry", "top_n_sigma", "top_k", "typ_p", "top_p", "min_p", "xtc", "temperature"],+ "edskypmxt",+)++# /v1/completions fields that change the text or the response shape and that MLX cannot+# reproduce, each with the test for the value that leaves it off: llama-server's own+# (tools/server/server-schema.cpp) plus OpenAI's. A field llama-server reads only while another+# is on is off with it.+_MLX_COMPLETION_FIELDS_OFF = {+ "logprobs": lambda v, b: v == 0,+ "n_probs": lambda v, b: v == 0,+ # best_of equal to the choice count asks for no hidden candidates; llama-server ignores it.+ "best_of": lambda v, b: v in (1, _llama_value(b, "n_cmpl")),+ "suffix": lambda v, b: v == "",+ # A lazy grammar waits for a trigger; this one constrains from the first token.+ "grammar_lazy": lambda v, b: v is False or _llama_grammar_off(b),+ "timings_per_token": lambda v, b: v is False,+ "return_tokens": lambda v, b: v is False,+ "return_progress": lambda v, b: v is False,+ "verbose": lambda v, b: v is False,+ "response_fields": lambda v, b: v == [],+ "lora": lambda v, b: v == [],+ # A raw reply decodes without special tokens, so none can be kept.+ "preserved_tokens": lambda v, b: v == [],+ "n_indent": lambda v, b: v == 0,+ "t_max_predict_ms": lambda v, b: v <= 0,+ "ignore_eos": lambda v, b: v is False,+ "min_keep": lambda v, b: v == 0,+ "samplers": lambda v, b: v in _LLAMA_DEFAULT_SAMPLERS,+ "typical_p": lambda v, b: v >= 1,+ "top_n_sigma": lambda v, b: v <= 0,+ # llama-server's XTC keeps one qualifying candidate chosen by an unspecified sort order.+ "xtc_probability": lambda v, b: v <= 0 or _llama_field(b, "xtc_threshold", 0.1) > 0.5,+ "xtc_threshold": lambda v, b: v > 0.5 or _llama_field(b, "xtc_probability", 0.0) <= 0,+ "dynatemp_range": lambda v, b: v <= 0,+ "dynatemp_exponent": lambda v, b: _llama_field(b, "dynatemp_range", 0.0) <= 0,+ "mirostat": lambda v, b: v <= 0,+ "mirostat_tau": lambda v, b: _llama_field(b, "mirostat", 0) <= 0,+ "mirostat_eta": lambda v, b: _llama_field(b, "mirostat", 0) <= 0,+ "dry_multiplier": lambda v, b: _llama_dry_off(b),+ "dry_base": lambda v, b: _llama_dry_off(b),+ "dry_allowed_length": lambda v, b: _llama_dry_off(b),+ "dry_penalty_last_n": lambda v, b: _llama_dry_off(b),+ "dry_sequence_breakers": lambda v, b: _llama_dry_off(b),+ "adaptive_target": lambda v, b: v < 0,+ "adaptive_decay": lambda v, b: _llama_field(b, "adaptive_target", -1.0) < 0,+ "reasoning_budget_tokens": lambda v, b: v == -1,+}++# n_cmpl's upper bound is llama-server's slot count there; here it is chat's cap on n.+_LLAMA_HARD_LIMITS = {+ "n_predict": (-1, 2**31 - 1),+ "n_cmpl": (1, 128),+ "repeat_last_n": (0, 2**31 - 1),+}+++# llama-server reads only the first non-null name of each group.+_LLAMA_ALIASES = (+ ("n_predict", "max_completion_tokens", "max_tokens"),+ ("n_cmpl", "n"),+ ("n_probs", "logprobs"),+)+++def _llama_read_fields(body: dict) -> dict:+ """*body* without the aliases llama-server passes over."""+ fields = dict(body)+ for names in _LLAMA_ALIASES:+ for name in [n for n in names if body.get(n) is not None][1:]:+ del fields[name]+ return fields+++def _llama_value(body: dict, name: str):+ """*name*, or the alias of it llama-server reads."""+ names = next((group for group in _LLAMA_ALIASES if group[0] == name), (name,))+ return next((body[n] for n in names if body.get(n) is not None), None)+++# llama-server's defaults for the fields no pin or per-model recommendation sets, so an MLX+# model samples a request as the GGUF route's llama-server would.+_LLAMA_SAMPLING_DEFAULTS = {+ "temperature": 0.8,+ "top_p": 0.95,+ "top_k": 40,+ "min_p": 0.05,+ "repetition_penalty": 1.0,+ "presence_penalty": 0.0,+}+++def _llama_logit_bias(raw) -> Optional[dict]:+ """llama-server's ``logit_bias`` (an object or ``[token, bias]`` pairs; ``false`` bans the+ token) as ``{token id: bias}``. Raises ValueError for a token given as text, which needs+ the tokenizer."""+ if isinstance(raw, dict):+ pairs = list(raw.items())+ elif isinstance(raw, list):+ pairs = [p for p in raw if isinstance(p, list) and len(p) == 2]+ else:+ return None+ bias = {}+ for token, value in pairs:+ if isinstance(token, str) and token.lstrip("-").isdigit() and isinstance(raw, dict):+ token = int(token)+ if not _is_token_id(token):+ raise ValueError("logit_bias tokens given as text are not supported for MLX models.")+ if value is False:+ bias[token] = float("-inf")+ elif isinstance(value, (int, float)) and not isinstance(value, bool):+ bias[token] = bias.get(token, 0.0) + float(value)+ return bias or None+++def _mlx_completion_grammar(body: dict) -> Optional[str]:+ """The llguidance grammar constraining a /v1/completions body, read in llama-server's+ precedence, with ``response_format`` (which llama-server ignores here) honored last.+ Raises ResponseFormatError for one that does not compile."""+ from core.inference.grammar_constraint import (+ ResponseFormatError,+ constraint_spec_from_response_format,+ grammar_from_gbnf,+ grammar_from_json_schema,+ )++ if "grammar" in body:+ gbnf = body["grammar"]+ if gbnf is not None and not isinstance(gbnf, str):+ raise ResponseFormatError("'grammar' must be a GBNF string.")+ return grammar_from_gbnf(gbnf) if gbnf else None+ schema = body.get("json_schema")+ if schema is not None:+ if not isinstance(schema, dict):+ raise ResponseFormatError("'json_schema' must be a JSON Schema object.")+ # llama.cpp reads an empty schema as any object, llguidance as any value.+ return grammar_from_json_schema(schema or {"type": "object"})+ spec = constraint_spec_from_response_format(body.get("response_format"))+ return spec.grammar if spec is not None else None+++def _mlx_completions_refusal(body: dict) -> Optional[str]:+ """Why an MLX model cannot serve this /v1/completions body as llama-server would, or None."""+ prompts = _completion_prompts(body.get("prompt"))+ if not prompts:+ return (+ "'prompt' must be a string, a list of strings and token ids, a "+ '{"prompt_string": ...} object, or an array of those.'+ )+ if any(isinstance(p, dict) and p.get("multimodal_data") for p in prompts):+ return "'multimodal_data' is not supported for MLX models; send images to /v1/chat/completions."+ fields = _llama_read_fields(body)+ for name, off in _MLX_COMPLETION_FIELDS_OFF.items():+ value = fields.get(name)+ try:+ neutral = value is None or bool(off(value, fields))+ except (TypeError, ValueError):+ neutral = False+ if not neutral:+ return f"'{name}' is not supported for MLX models."+ for name, (low, high) in _LLAMA_HARD_LIMITS.items():+ value = _llama_value(body, name)+ if value is not None and not (_is_token_id(value) and low <= value <= high):+ return (+ f"Field '{name}': Value must be between {low} <= value <= {high}, but got {value}"+ )+ if body.get("stream") is True and len(prompts) * (_llama_value(body, "n_cmpl") or 1) > 1:+ return "Streaming more than one completion is not supported for MLX models."+ try:+ _llama_logit_bias(body.get("logit_bias"))+ _mlx_completion_grammar(body)+ except ValueError as exc:+ return str(exc)+ return None+++def _active_mlx_backend():+ """The orchestrator while it holds an MLX model, else None."""+ backend = _peek_inference_backend()+ name = getattr(backend, "active_model_name", None)+ models = getattr(backend, "models", None)+ if name and isinstance(models, dict) and models.get(name, {}).get("is_mlx"):+ return backend+ return None+++def _mlx_completion_sampling(body: dict, model_id) -> dict:+ """``generate_completion`` knobs for a /v1/completions body, read as llama-server reads+ them: its field names and aliases, its clamps, and its defaults for anything unset."""+ from utils.inference.inference_config import resolve_effective_sampling, SAMPLING_FIELD_NAMES++ explicit = {f: body.get(_COMPLETIONS_SAMPLING_BODY_KEY.get(f, f)) for f in SAMPLING_FIELD_NAMES}+ sampling = {+ **_LLAMA_SAMPLING_DEFAULTS,+ **resolve_effective_sampling(model_id, explicit, fill_defaults = False),+ }+ seed = body.get("seed")+ top_p = min(max(float(sampling["top_p"]), 0.0), 1.0)+ return dict(+ temperature = max(0.0, float(sampling["temperature"])),+ top_p = top_p,+ # llama-server's top-p keeps its one minimum candidate at p = 0; MLX reads 0 as off.+ top_k = 1 if top_p == 0 else max(0, int(sampling["top_k"])),+ min_p = min(max(float(sampling["min_p"]), 0.0), 1.0),+ repetition_penalty = float(sampling["repetition_penalty"]),+ presence_penalty = float(sampling["presence_penalty"]),+ frequency_penalty = float(_llama_field(body, "frequency_penalty", 0.0)),+ # llama-server draws a random seed for LLAMA_DEFAULT_SEED (0xFFFFFFFF, e.g. -1).+ seed = None if seed is None or (int(seed) & 0xFFFFFFFF) == 0xFFFFFFFF else int(seed),+ logit_bias = _llama_logit_bias(body.get("logit_bias")),+ stop = _normalize_stop_sequences(body.get("stop")),+ penalty_window = _llama_field(body, "repeat_last_n", 64),+ grammar = _mlx_completion_grammar(body),+ )+++def _mlx_completion_error(failure, message: str, body: dict) -> tuple:+ """A failed MLX completion's status and OpenAI error body, typed as chat types them."""+ if isinstance(failure, context_refusal.ContextBudgetExceeded):+ code, param = "context_length_exceeded", "prompt"+ else:+ code, param = "unsupported_parameter", _refused_parameter(failure)+ if param == "response_format":+ # Name the field the grammar came from, in _mlx_completion_grammar's precedence.+ if "grammar" in body:+ param = "grammar"+ elif body.get("json_schema") is not None:+ param = "json_schema"+ if param is None:+ return 500, {"error": {"message": message, "type": "server_error"}}+ return 400, openai_error_body(message, status = 400, code = code, param = param)+++def _text_completion_chunk(completion_id, created, model_name, text, finish_reason) -> dict:+ return {+ "id": completion_id,+ "object": "text_completion",+ "created": created,+ "model": model_name,+ "choices": [{"text": text, "index": 0, "logprobs": None, "finish_reason": finish_reason}],+ }+++async def _mlx_completions(request, current_subject, backend, body: dict, refusal):+ """Serve /v1/completions from the resident MLX model: one prompt, untemplated."""+ if refusal:+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(refusal, status = 400, code = "unsupported_parameter"),+ )+ n_predict = _llama_value(body, "n_predict")+ budget = None if n_predict == -1 else n_predict+ n = _llama_value(body, "n_cmpl") or 1+ stream_options = body.get("stream_options")+ include_usage = isinstance(stream_options, dict) and stream_options.get("include_usage") is True+ try:+ model_name = _orchestrator_public_model_id(backend) or backend.active_model_name+ sampling = _mlx_completion_sampling(body, model_name)+ except (TypeError, ValueError) as exc:+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(f"Invalid sampling parameter: {exc}", status = 400),+ )+ completion_id = f"cmpl-{uuid.uuid4().hex}"+ cancel_event = threading.Event()+ # Resolving waits behind a running generation, so the request is cancellable from here on.+ tracker = _TrackedCancel(cancel_event, completion_id, model = model_name, kind = "completions")+ tracker.__enter__()+ watcher = asyncio.create_task(_await_disconnect_then_cancel(request, cancel_event))+ try:+ # Every prompt first (an invalid one is a 400), tracked until a cancel ends the thread.+ resolved = await _run_blocking_generation(+ lambda: [+ backend.resolve_completion_prompt(prompt, cancel_event = cancel_event)+ for prompt in _completion_prompts(body["prompt"])+ ],+ cancel_event,+ name = "openai-completions-prompt",+ )+ except BaseException as exc:+ tracker.__exit__(None, None, None)+ if isinstance(exc, InterruptedError):+ raise HTTPException(status_code = 499, detail = "Request cancelled.")+ if not isinstance(exc, ValueError):+ raise+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(str(exc), status = 400, param = "prompt"),+ )+ finally:+ await _stop_local_disconnect_cancel_watcher(watcher)+ n_vocab = resolved[0].get("n_vocab")+ if n_vocab and sampling["top_k"] >= n_vocab:+ # llama-server keeps every candidate here; mlx_lm's apply_top_k raises instead.+ sampling["top_k"] = 0+ echo = body.get("echo") is True+ created = int(time.time())+ stats_holder: dict = {}+ monitor_id = api_monitor.start(+ endpoint = request.url.path,+ via_api_key = _request_used_api_key(request),+ method = request.method,+ model = model_name,+ prompt = resolved[0]["text"]+ if len(resolved) == 1+ else "\n\n".join(f"Prompt {i + 1}:\n{r['text']}" for i, r in enumerate(resolved)),+ context_length = _monitor_context_length(),+ subject = current_subject,+ )++ def generate(prompt_ids, choice = 0):+ return backend.generate_completion(+ prompt_ids,+ cancel_event = cancel_event,+ stats_holder = stats_holder,+ max_new_tokens = budget,+ **{**sampling, "seed": _choice_seed(sampling["seed"], choice)},+ )++ def choice_end(prompt_ids, stats):+ if budget == 0:+ reason = "length"+ elif cancel_event.is_set():+ reason = "stop"+ else:+ reason = _stats_finish_reason(stats, token_budget = budget)+ usage = (stats or {}).get("usage") or {+ "prompt_tokens": len(prompt_ids),+ "completion_tokens": 0,+ "total_tokens": len(prompt_ids),+ }+ return reason, usage++ if body.get("stream") is True:+ prompt_ids = resolved[0]["ids"]++ def sse(obj) -> str:+ return f"data: {json.dumps(obj)}\n\n"++ async def stream_chunks():+ gen = None+ next_task = None+ watcher = asyncio.create_task(_await_disconnect_then_cancel(request, cancel_event))+ try:+ from core.inference.llama_keepwarm import mark_current_response_failed++ if echo:+ yield sse(+ _text_completion_chunk(+ completion_id, created, model_name, resolved[0]["text"], None+ )+ )+ _DONE = object()+ gen = generate(prompt_ids) if budget != 0 else iter(())+ prev = ""+ while True:+ if cancel_event.is_set():+ break+ next_task = asyncio.create_task(asyncio.to_thread(next, gen, _DONE))+ while not (+ await asyncio.wait(+ {next_task}, timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S+ )+ )[0]:+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ cumulative, next_task = next_task.result(), None+ if cumulative is _DONE:+ break+ if isinstance(cumulative, GenStreamError):+ backend.reset_generation_state(cancel_event)+ message = _friendly_gen_stream_error(cumulative)+ api_monitor.fail(monitor_id, message)+ yield _openai_stream_error_sse(+ _mlx_completion_error(cumulative, message, body)[1]+ )+ return+ delta, prev = cumulative[len(prev) :], cumulative+ if delta:+ api_monitor.append_reply(monitor_id, delta)+ yield sse(+ _text_completion_chunk(completion_id, created, model_name, delta, None)+ )+ if cancel_event.is_set():+ backend.reset_generation_state(cancel_event)+ mark_current_response_failed()+ stats = stats_holder.pop("stats", None)+ reason, usage = choice_end(prompt_ids, stats)+ api_monitor.set_perf(monitor_id, stop_reason = reason)+ _monitor_usage(monitor_id, usage, timings = (stats or {}).get("timings"))+ yield sse(_text_completion_chunk(completion_id, created, model_name, "", reason))+ if include_usage:+ yield sse(+ {+ **_text_completion_chunk(completion_id, created, model_name, "", None),+ "choices": [],+ "usage": usage,+ }+ )+ api_monitor.finish(+ monitor_id, "cancelled" if cancel_event.is_set() else "completed"+ )+ yield "data: [DONE]\n\n"+ except asyncio.CancelledError:+ cancel_event.set()+ backend.reset_generation_state(cancel_event)+ api_monitor.finish(monitor_id, "cancelled")+ raise+ except Exception as exc:+ backend.reset_generation_state(cancel_event)+ logger.error("MLX completions stream error: %s", exc, exc_info = True)+ message = _friendly_error(exc)+ api_monitor.fail(monitor_id, message)+ yield _openai_stream_error_sse(_mlx_completion_error(exc, message, body)[1])+ finally:+ await _stop_local_disconnect_cancel_watcher(watcher)+ await _drain_pending_worker(next_task, cancel_event)+ if gen is not None and hasattr(gen, "close"):+ try:+ await asyncio.to_thread(gen.close)+ except (RuntimeError, ValueError):+ pass+ tracker.__exit__(None, None, None)++ async def unstarted_cleanup():+ api_monitor.finish(monitor_id, "cancelled")+ tracker.__exit__(None, None, None)++ return _sse_streaming_response(stream_chunks(), unstarted_cleanup = unstarted_cleanup)++ # llama-server's order: each prompt's n choices in turn, choice j seeded as chat seeds it.+ rows = [+ {"prompt_ids": resolved[i // n]["ids"], "seed": _choice_seed(sampling["seed"], i % n)}+ for i in range(len(resolved) * n)+ ]++ def drain_rows(chunk):+ texts, batch_stats = [""] * len(chunk), {}+ if len(rows) == 1:+ events = (+ text if isinstance(text, GenStreamError) else (0, text)+ for text in generate(chunk[0]["prompt_ids"])+ )+ else:+ events = backend.generate_completion_batch(+ chunk,+ cancel_event = cancel_event,+ stats_holder = batch_stats,+ max_new_tokens = budget,+ **{k: v for k, v in sampling.items() if k != "seed"},+ )+ for event in events:+ if isinstance(event, GenStreamError):+ return event+ row, text = event+ if text is not None:+ texts[row] = text+ reported = (+ [stats_holder.pop("stats", None)] if len(rows) == 1 else batch_stats.get("stats") or []+ )+ return [+ (text, reported[row] if row < len(reported) else None) for row, text in enumerate(texts)+ ]++ def drain():+ """At most chat's n cap per batch, so many prompts cannot exhaust memory."""+ produced, width = [], _LLAMA_HARD_LIMITS["n_cmpl"][1]+ for start in range(0, len(rows), width):+ chunk = rows[start : start + width]+ if cancel_event.is_set() and produced:+ produced += [("", None)] * len(chunk)+ continue+ result = drain_rows(chunk)+ if isinstance(result, GenStreamError):+ return result+ produced += result+ return produced++ choices, replies, stats = [], [], None+ prompt_tokens = completion_tokens = 0+ cached_tokens: Optional[int] = None+ failure = None+ watcher = asyncio.create_task(_await_disconnect_then_cancel(request, cancel_event))+ try:+ produced = (+ [("", None)] * len(rows)+ if budget == 0 or cancel_event.is_set()+ else await _run_blocking_generation(drain, cancel_event, name = "openai-completions")+ )+ if isinstance(produced, GenStreamError):+ failure, produced = produced, []+ for index, (text, stats) in enumerate(produced):+ prompt_index, choice = divmod(index, n)+ reason, usage = choice_end(resolved[prompt_index]["ids"], stats)+ if not choice:+ prompt_tokens += usage["prompt_tokens"]+ cached = cached_prompt_tokens(usage)+ if cached is not None:+ cached_tokens = (cached_tokens or 0) + cached+ completion_tokens += usage["completion_tokens"]+ prefix = resolved[prompt_index]["text"] if echo else ""+ choices.append(+ {"text": prefix + text, "index": index, "logprobs": None, "finish_reason": reason}+ )+ replies.append(text)+ except asyncio.CancelledError:+ backend.reset_generation_state(cancel_event)+ api_monitor.finish(monitor_id, "cancelled")+ raise+ except Exception as exc:+ failure = exc+ finally:+ await _stop_local_disconnect_cancel_watcher(watcher)+ tracker.__exit__(None, None, None)+ if failure is not None:+ backend.reset_generation_state(cancel_event)+ message = (+ _friendly_gen_stream_error(failure)+ if isinstance(failure, GenStreamError)+ else _friendly_error(failure)+ )+ api_monitor.fail(monitor_id, message)+ status, error = _mlx_completion_error(failure, message, body)+ raise HTTPException(status_code = status, detail = message if status == 500 else error)+ usage = {+ "prompt_tokens": prompt_tokens,+ "completion_tokens": completion_tokens,+ "total_tokens": prompt_tokens + completion_tokens,+ }+ if cached_tokens is not None:+ usage["prompt_tokens_details"] = {"cached_tokens": cached_tokens}+ single = len(choices) == 1+ api_monitor.set_reply(+ monitor_id,+ replies[0]+ if single+ else "\n\n".join(f"Choice {i + 1}:\n{r}" for i, r in enumerate(replies)),+ )+ # One choice's reason and timings would misdescribe several.+ if single:+ api_monitor.set_perf(monitor_id, stop_reason = choices[0]["finish_reason"])+ _monitor_usage(monitor_id, usage, timings = (stats or {}).get("timings") if single else None)+ if cancel_event.is_set():+ from core.inference.llama_keepwarm import mark_current_response_failed+ mark_current_response_failed()+ api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")+ return {+ **_text_completion_chunk(completion_id, created, model_name, "", None),+ "choices": choices,+ "usage": usage,+ }++@router.post("/completions")@account_access.gpu_busy_routeasync def openai_completions(request: Request, current_subject: str = Depends(get_current_subject)):"""OpenAI-compatible text completions endpoint (non-chat).- Proxies to the running llama-server's ``/v1/completions``. Only available- when a GGUF model is loaded.+ Proxies to the running llama-server's ``/v1/completions`` when a GGUF model is+ loaded, and serves an MLX model in process."""+ from utils.hardware import DeviceType, get_device++ try:+ _pre = await request.json()+ except (json.JSONDecodeError, ValueError):+ _pre = _UNPARSEABLE_BODY+ _mlx_device = await asyncio.to_thread(get_device) == DeviceType.MLX+ # MLX hosts only; grammar compiles off the event loop, as chat's does.+ _mlx_refusal = (+ await asyncio.get_running_loop().run_in_executor(+ _SCHEMA_VALIDATION_EXECUTOR, _mlx_completions_refusal, _pre+ )+ if _mlx_device and isinstance(_pre, dict)+ else None+ )+# Reject a request with no prompt before any automatic load so an invalid request never# swaps or reloads the resident model (as chat/embeddings already validate before# switching). Gate on every automatic-load trigger, and on a preview-owned slot the switch# helper would claim even with both features off.if _should_validate_before_switch():- try:- _pre = await request.json()- except (json.JSONDecodeError, ValueError):- _pre = _UNPARSEABLE_BODYif isinstance(_pre, dict):_pre_prompt = _pre.get("prompt")- if _pre_prompt is not None and not isinstance(_pre_prompt, (str, list, tuple)):- # An object/number prompt is a deterministic client error (only a- # string or array is valid); reject it before the switch so a bad- # shape can't load a GGUF only to be rejected by llama-server after.- raise HTTPException(status_code = 400, detail = "'prompt' must be a string or array.")+ if _pre_prompt is not None and not (+ isinstance(_pre_prompt, (str, list, tuple))+ or (isinstance(_pre_prompt, dict) and "prompt_string" in _pre_prompt)+ ):+ # Any other prompt is a deterministic client error; reject it before the+ # switch so a bad shape can't load a model only to be rejected after.+ raise HTTPException(+ status_code = 400,+ detail = "'prompt' must be a string, an array or a {\"prompt_string\": ...} object.",+ )if not _completions_prompt_present(_pre):raise HTTPException(status_code = 400, detail = "'prompt' is required for completions.")- _raise_ignored_completions_params(_pre)+ _raise_ignored_completions_params(_pre, echo = not _mlx_device)elif _pre is not _UNPARSEABLE_BODY:# A valid JSON body that is not an object (e.g. [] or null) is rejected below as# "Request body must be a JSON object"; reject it here, before the switch, so the@@ -37600,10 +38234,22 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge# that never runs.raise HTTPException(status_code = 400, detail = "Request body must be a JSON object")- # Opt-in: load the requested local GGUF before the loaded-state check.- body = await _auto_switch_from_request_body(request, current_subject, gguf_only = True)+ # Opt-in: load the requested local model before the loaded-state check. Only an MLX model+ # serves a raw prompt in process, and only a request it can serve as llama-server would.+ body = await _auto_switch_from_request_body(+ request,+ current_subject,+ gguf_only = _mlx_refusal is not None or not _mlx_device,+ gguf_only_reason = _mlx_refusal,+ # echo, which the check above left to the target: a GGUF one refuses it unloaded.+ gguf_target_check = (+ (lambda: _raise_ignored_completions_params(_pre)) if isinstance(_pre, dict) else None+ ),+ audio_cpp_ok = False,+ )llama_backend = get_llama_cpp_backend()- if not llama_backend.is_loaded:+ mlx_backend = None if llama_backend.is_loaded else _active_mlx_backend()+ if not llama_backend.is_loaded and mlx_backend is None:_status, _detail = await _no_model_loaded_error("No GGUF model loaded. Load a GGUF model first.",_raw_body_model(body),@@ -37617,6 +38263,11 @@ async def openai_completions(request: Request, current_subject: str = Depends(gebody = await request.json()if not isinstance(body, dict):raise HTTPException(status_code = 400, detail = "Request body must be a JSON object")+ if mlx_backend is not None:+ refusal = await asyncio.get_running_loop().run_in_executor(+ _SCHEMA_VALIDATION_EXECUTOR, _mlx_completions_refusal, body+ )+ return await _mlx_completions(request, current_subject, mlx_backend, body, refusal)_raise_ignored_completions_params(body)# GGUF is loaded and the body is valid. The middleware claims the slot on a successfuldiff --git a/studio/backend/tests/test_mlx_completions_apple.py b/studio/backend/tests/test_mlx_completions_apple.pynew file mode 100644index 00000000000..deb9359bce1--- /dev/null+++ b/studio/backend/tests/test_mlx_completions_apple.py@@ -0,0 +1,116 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Real MLX raw-prompt completion (/v1/completions), on Apple Silicon only."""++from __future__ import annotations++import platform+import sys++import pytest++pytestmark = [+ pytest.mark.skipif(+ sys.platform != "darwin" or platform.machine() != "arm64",+ reason = "MLX runs on Apple Silicon only",+ ),+ pytest.mark.allow_network,+]++_TINY = "mlx-community/SmolLM-135M-Instruct-4bit"+_PROMPT = "The capital of France is"+++def backend():+ pytest.importorskip("mlx_lm")+ pytest.importorskip("unsloth_zoo.mlx.loader")+ from core.inference.mlx_inference import MLXInferenceBackend+ from utils.models.model_config import ModelConfig++ backend = MLXInferenceBackend()+ assert backend.load_model(ModelConfig.from_identifier(_TINY), max_seq_length = 512)+ return backend+++def _greedy(backend, ids, **kw):+ text = ""+ for text in backend.generate_completion(+ ids, temperature = 0.0, top_p = 1.0, top_k = 0, min_p = 0.0, max_new_tokens = 8, **kw+ ):+ pass+ return text+++def test_raw_prompt_matches_a_direct_untemplated_mlx_lm_run(backend):+ from mlx_lm import stream_generate++ resolved = backend.resolve_completion_prompt(_PROMPT)+ assert resolved["ids"] == backend._tokenizer.encode(_PROMPT, add_special_tokens = True)+ assert resolved["text"] == _PROMPT++ # Decoded from the ids: mlx_lm's streaming detokenizer trims the first piece's leading+ # space, which a raw continuation (and llama-server) keeps.+ tokens = [+ r.token+ for r in stream_generate(+ backend._model, backend._tokenizer, prompt = resolved["ids"], max_tokens = 8+ )+ ]+ direct = backend._tokenizer.decode(+ tokens, skip_special_tokens = True, clean_up_tokenization_spaces = False+ )+ assert direct.strip()+ assert _greedy(backend, resolved["ids"]) == direct+ # Token ids resolve to themselves and decode as the same greedy text.+ assert backend.resolve_completion_prompt(resolved["ids"])["ids"] == resolved["ids"]+++def test_raw_prompt_grammar_constrains_the_completion(backend):+ pytest.importorskip("llguidance")+ from core.inference.grammar_constraint import grammar_from_gbnf++ text = _greedy(+ backend,+ backend.resolve_completion_prompt("Answer yes or no:")["ids"],+ grammar = grammar_from_gbnf('root ::= " yes" | " no"'),+ )+ assert text in (" yes", " no")+++def test_raw_prompt_rejects_out_of_vocabulary_ids(backend):+ with pytest.raises(ValueError):+ backend.resolve_completion_prompt([10**9])+++def test_raw_vision_prompt_matches_the_decoded_sampled_ids():+ pytest.importorskip("mlx_vlm")+ pytest.importorskip("unsloth_zoo.mlx.loader")+ import mlx.core as mx+ from mlx_vlm import stream_generate++ from core.inference.mlx_inference import MLXInferenceBackend+ from utils.models.model_config import ModelConfig++ backend = MLXInferenceBackend()+ assert backend.load_model(+ ModelConfig.from_identifier("mlx-community/Qwen3.5-0.8B-4bit"), max_seq_length = 512+ )+ if not backend._is_vlm:+ pytest.skip("loaded as a text model")+ ids = backend.resolve_completion_prompt(_PROMPT)["ids"]+ # Keyed by count: the closing summary repeats the last token.+ by_count = {+ r.generation_tokens: int(r.token)+ for r in stream_generate(+ backend._model, backend._processor, "", None, input_ids = mx.array([ids]), max_tokens = 8+ )+ if r.token is not None+ }+ tokens = [by_count[n] for n in sorted(by_count)]+ # Leading space included: the runtime's own text trims it, a raw continuation keeps it.+ direct = backend._tokenizer.decode(+ tokens, skip_special_tokens = True, clean_up_tokenization_spaces = False+ )+ assert direct.strip() and _greedy(backend, ids) == directdiff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 0c4f6944f98..c305b0be4d9 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -2380,6 +2380,7 @@ def _install_fake_text_stack(self,ids,skip_special_tokens = False,+ clean_up_tokenization_spaces = True,):return "".join(str(i) for i in ids)@@ -2449,6 +2450,210 @@ def test_mlx_text_tracks_tokens_on_the_native_reasoning_path(monkeypatch):assert captured[1]["prompt"] == [9]+def test_mlx_completion_prompt_skips_the_template_and_reuses_the_prompt_cache(monkeypatch):+ _install_fake_prompt_cache_api(monkeypatch)+ captured = []+ token_map = {"P1": [1, 2, 3], "generated": [7, 8]}+ backend = _install_fake_text_stack(monkeypatch, token_map, captured)+ _run_turn(backend, "P1")++ monkeypatch.setattr(backend, "_render_text_prompt", lambda *_a, **_k: pytest.fail("templated"))+ seen = {}+ monkeypatch.setattr(+ "core.inference.mlx_inference._mlx_sampling_processors", lambda **kw: seen.update(kw)+ )+ monkeypatch.setattr("core.inference.grammar_constraint.GrammarConstraint", _RawConstraint)+ ids = [1, 2, 3, 7, 8, 9]+ out = list(backend.generate_completion(ids, max_new_tokens = 4, penalty_window = 4, grammar = "G"))++ assert captured[1]["prompt"] == [9]+ assert out[-1] == "78" and backend.last_generation_stats["timings"]["cache_n"] == 5+ assert seen["penalty_prompt"] == [1, 2, 3, 7, 8, 9] and seen["penalty_window"] == 4+ assert seen["grammar_constraint"].built == ("G", backend._tokenizer)+ # The reply decodes with skip_special_tokens, so the grammar must not spell text with them.+ assert seen["grammar_constraint"].options == {"strips_special_tokens": True}+ # Unconstrained too: llama-server returns the pieces without whitespace cleanup.+ cleanups, decode = [], type(backend._tokenizer).decode+ monkeypatch.setattr(+ type(backend._tokenizer),+ "decode",+ lambda tok, ids, **kw: cleanups.append(kw.get("clean_up_tokenization_spaces"))+ or decode(tok, ids, **kw),+ )+ list(backend.generate_completion(ids, max_new_tokens = 4))+ assert cleanups and set(cleanups) == {False}+++def _RawConstraint(grammar, tokenizer, **kw):+ noop = lambda *_a: None+ return SimpleNamespace(+ built = (grammar, tokenizer),+ options = kw,+ allows_reasoning = False,+ decoded_dropping = noop,+ stops_on = noop,+ )+++def test_mlx_vlm_completion_prompt_runs_untemplated_from_its_ids(monkeypatch):+ from core.inference import mlx_inference++ seen = {}+ mlx_vlm = types.ModuleType("mlx_vlm")+ mlx_vlm.stream_generate = lambda *a, **kw: seen.update(args = a, kwargs = kw) or iter(+ [SimpleNamespace(text = "ok", prompt_tokens = 3, generation_tokens = 1)]+ )+ monkeypatch.setitem(sys.modules, "mlx_vlm", mlx_vlm)+ _install_fake_mlx(monkeypatch)+ sys.modules["mlx.core"].array = lambda rows: rows+ monkeypatch.setattr(+ mlx_inference, "_temporary_mlx_adapter_state", lambda *_a: contextlib.nullcontext()+ )+ backend = mlx_inference.MLXInferenceBackend()+ backend._model, backend._is_vlm = SimpleNamespace(), True+ backend._tokenizer = backend._processor = SimpleNamespace()+ monkeypatch.setattr(backend, "_render_vlm_prompt", lambda *_a, **_k: pytest.fail("templated"))+ monkeypatch.setattr(backend, "_vlm_prompt_cache_session", lambda *a, **_k: seen.update(cache = a))+ monkeypatch.setattr(mlx_inference, "_mlx_sampling_processors", lambda **kw: seen.update(kw))+ monkeypatch.setattr("core.inference.grammar_constraint.GrammarConstraint", _RawConstraint)++ assert list(backend.generate_completion([5, 6], max_new_tokens = 2, grammar = "G")) == ["ok"]+ assert seen["args"][2:] == ("", None) and seen["kwargs"]["input_ids"] == [[5, 6]]+ assert seen["kwargs"]["skip_special_tokens"] is True+ assert seen["penalty_prompt"] == [5, 6]+ assert seen["grammar_constraint"].built == ("G", backend._tokenizer)+ assert seen["cache"] == (None, None, "")++ # With sampled ids the reply is decoded from them: the runtime's text trims the first+ # piece's leading space and keeps control tokens, which a raw continuation must not.+ pieces = {7: " Paris", 8: "<|im_start|>", 9: "!"}+ backend._tokenizer = SimpleNamespace(+ decode = lambda ids, skip_special_tokens, clean_up_tokenization_spaces: "".join(+ pieces[i] for i in ids if not (skip_special_tokens and i == 8)+ )+ )+ responses = [+ SimpleNamespace(text = text, token = token, generation_tokens = n, prompt_tokens = 2)+ for n, (token, text) in enumerate([(7, "Paris"), (8, "<|im_start|>"), (9, "!")], 1)+ ]+ mlx_vlm.stream_generate = lambda *a, **kw: iter(responses)+ assert list(backend.generate_completion([5, 6], max_new_tokens = 3))[-1] == " Paris!"+++def test_a_raw_vision_prompt_decodes_on_its_own_even_when_zoo_could_batch_it(monkeypatch):+ from core.inference import mlx_inference++ engine = types.ModuleType("unsloth_zoo.mlx.generate")+ engine.VLM_TOKEN_ID_PROMPTS = True+ package = types.ModuleType("unsloth_zoo.mlx")+ package.generate = engine+ monkeypatch.setitem(sys.modules, "unsloth_zoo", types.ModuleType("unsloth_zoo"))+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx", package)+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.generate", engine)+ sys.modules["unsloth_zoo"].mlx = package+ monkeypatch.setattr(mlx_inference, "_batched_vision_engine_gap", lambda _e: None)+ monkeypatch.setattr(mlx_inference, "_row_processor_gap", lambda _e, _r: None)+ backend = mlx_inference.MLXInferenceBackend()+ backend._model = SimpleNamespace(_is_vlm_model = True)+ assert backend._vlm_batch_unavailable_reason([{}, {}]) is None+ assert backend._vlm_batch_unavailable_reason([{"prompt_ids": [1]}, {"prompt_ids": [2]}])+++def test_mlx_batch_rows_plan_a_raw_completion_prompt_untemplated(monkeypatch):+ from core.inference import mlx_inference++ backend = _install_fake_text_stack(monkeypatch, {"generated": [7]}, [])+ monkeypatch.setattr(backend, "_render_text_prompt", lambda *_a, **_k: pytest.fail("templated"))+ seen = {}+ monkeypatch.setattr(mlx_inference, "_mlx_sampling_processors", lambda **kw: seen.update(kw))+ row = mlx_inference._row_kwargs({"prompt_ids": [1, 2, 3], "penalty_window": 2})+ plan = backend._plan_text_row([], **row)+ assert (plan.prompt, plan.think_prefix, seen["penalty_prompt"], seen["penalty_window"]) == (+ [1, 2, 3],+ "",+ [1, 2, 3],+ 2,+ )+ backend._make_row_cache = lambda: None+ assert backend._batch_prompt_row(plan.prompt, None)[1] == [1, 2, 3]+ kwargs = []+ monkeypatch.setattr(type(backend._tokenizer), "decode", lambda _t, _i, **kw: kwargs.append(kw))+ plan.stream._decode([7])+ assert kwargs[-1]["clean_up_tokenization_spaces"] is False+ monkeypatch.setattr(backend, "_render_vlm_prompt", lambda *_a, **_k: pytest.fail("templated"))+ monkeypatch.setattr(+ backend, "_generation_limit", lambda prompt, limit, ids, **_k: (prompt, ids)+ )+ vision = backend._plan_vlm_request({"prompt_ids": [4, 5], "messages": []})+ assert (vision.prompt, vision.max_tokens) == ([4, 5], ([4, 5], [4, 5]))+ assert backend._vlm_batch_prompt([4, 5]) == {"prompt_token_ids": [4, 5]}+ assert mlx_inference._request_batch_gap({"grammar": "G"})+++_COMPLETION_TOK = SimpleNamespace(+ encode = lambda text, add_special_tokens: [100] * add_special_tokens + [ord(c) for c in text],+ decode = lambda ids, skip_special_tokens, clean_up_tokenization_spaces = True: "".join(+ chr(i % 256) for i in ids+ ).replace(" .", "." if clean_up_tokenization_spaces else " ."),+)+++ "prompt, ids, text",+ [+ ("ab", [100, 97, 98], "ab"),+ # Only a leading string gets the tokenizer's special tokens.+ ([5, "ab"], [5, 97, 98], "\x05ab"),+ (["ab", 5, 6, "c"], [100, 97, 98, 5, 6, 99], "ab\x05\x06c"),+ ({"prompt_string": [5, "a"]}, [5, 97], "\x05a"),+ ([199], [199], "\xc7"),+ ([97, 32, 46], [97, 32, 46], "a ."),+ ([200], ValueError, None),+ ([-1], ValueError, None),+ ([], ValueError, None),+ ([True], ValueError, None),+ ],+)+def test_mlx_completion_prompt_resolves_as_llama_server_tokenizes_it(prompt, ids, text):+ from core.inference.mlx_inference import MLXInferenceBackend++ backend = MLXInferenceBackend()+ backend._model = SimpleNamespace(args = SimpleNamespace(vocab_size = 200))+ backend._tokenizer = _COMPLETION_TOK+ if ids is ValueError:+ with pytest.raises(ValueError):+ backend.resolve_completion_prompt(prompt)+ else:+ assert backend.resolve_completion_prompt(prompt) == {+ "ids": ids,+ "text": text,+ "n_vocab": 200,+ }+++def test_mlx_penalty_window_scores_the_last_tokens_of_prompt_and_completion():+ mx = pytest.importorskip("mlx.core")+ from core.inference import mlx_inference++ presence = mlx_inference._make_mlx_presence_penalty_processor(1.0, window = 2)+ frequency = mlx_inference._make_mlx_frequency_penalty_processor(1.0, window = 3)+ z = mx.zeros((1, 5))+ # The prompt's own tail counts from the first step; tokens past the window do not.+ assert mx.array_equal(presence(mx.array([1, 2, 3]), z)[0], mx.array([0, 0, -1, -1, 0]))+ assert mx.array_equal(frequency(mx.array([1, 3, 3, 3]), z)[0], mx.array([0, 0, 0, -3, 0]))+ off = dict(repetition_penalty = 1.3, presence_penalty = 1.0, frequency_penalty = 1.0)+ assert mlx_inference._mlx_sampling_processors(penalty_window = 0, **off) is None+ # Prefill and prompt-cache reuse hand processors only the prompt's last token at first.+ make = lambda: mlx_inference._mlx_sampling_processors(+ presence_penalty = 1.0, penalty_window = 3, penalty_prompt = [0, 1, 2, 3]+ )[0]+ tail, whole = make(), make()+ assert tail.history_only+ assert mx.array_equal(tail(mx.array([3]), z)[0], mx.array([0, -1, -1, -1, 0]))+ assert mx.array_equal(tail(mx.array([3, 4]), z)[0], mx.array([0, 0, -1, -1, -1]))+ assert mx.array_equal(whole(mx.array([0, 1, 2, 3]), z)[0], mx.array([0, -1, -1, -1, 0]))++def test_mlx_presence_penalty_latches_the_first_decode_step():mx = pytest.importorskip("mlx.core")import numpy as npdiff --git a/studio/backend/tests/test_mlx_resident_batch.py b/studio/backend/tests/test_mlx_resident_batch.pyindex 0a7055d8bc6..6a89df1c63b 100644--- a/studio/backend/tests/test_mlx_resident_batch.py+++ b/studio/backend/tests/test_mlx_resident_batch.py@@ -161,6 +161,23 @@ def test_replies_a_command_asked_for_together_are_addressed_and_counted_by_row()assert resp.sent[-1]["stats"] is None+def test_raw_completion_rows_join_the_batch_and_decode_alone_through_the_completion_path():+ batch, _ = _batch()+ cmd = _cmd(+ rows = [{"prompt_ids": [5], "seed": 1}, {"prompt_ids": [6], "seed": 2}],+ penalty_window = 3,+ parallel_slots = 2,+ )+ assert batch.unavailable_reason(cmd) is None and batch.admit(cmd, None)+ assert [(r["prompt_ids"], r["penalty_window"]) for _, r in batch.session.admitted] == [+ ([5], 3),+ ([6], 3),+ ]+ backend = SimpleNamespace(generate_completion = lambda ids, **kw: iter([f"{ids} {kw['seed']}"]))+ apart = worker._rows_apart(backend, [{"prompt_ids": [5], "seed": 1}], threading.Event(), [None])+ assert list(apart) == [(0, "[5] 1"), (0, None)]++IDLE = object()diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 38c6e83bc15..52ebc57bfb6 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -4544,6 +4544,7 @@ def test_completions_rejects_ignored_params_without_switch(monkeypatch, extra, p{"echo": False, "suffix": "", "best_of": 1},{"echo": None, "suffix": None, "best_of": None},{"best_of": 2, "n": 2},+ {"best_of": 2, "n_cmpl": 2},],)def test_completions_default_ignored_params_still_proxy(monkeypatch, extra):@@ -12367,3 +12368,62 @@ def test_tensor_split_requires_matching_gpu_ids_at_the_settings_boundary(ids):settings_route.ModelOverridePayload(model_id = "org/split-GGUF", gpu_ids = ids, tensor_split = [3, 1])++[email protected]("reload", [False, True], ids = ["switch", "idle reload"])+def test_completions_echo_to_a_gguf_target_is_refused_before_it_loads_on_mlx(monkeypatch, reload):+ from utils import hardware++ monkeypatch.setattr(hardware, "get_device", lambda: hardware.DeviceType.MLX)+ if reload:+ _, rec = _wired(monkeypatch, _FakeBackend(None), None, enabled = False)+ _stash(monkeypatch)+ else:+ _, rec = _wired(monkeypatch, _FakeBackend("org/A-GGUF"), ("/p/B", "Q8_0", "org/B-GGUF"))+ body = {"model": "org/B-GGUF", "prompt": "hi", "echo": True}+ with pytest.raises(HTTPException) as exc:+ asyncio.run(inference_route.openai_completions(_json_body_request(body), "tester"))+ assert exc.value.detail["error"]["param"] == "echo" and rec.calls == []+++def test_completions_switch_admits_an_mlx_target_only_for_what_it_serves(monkeypatch):+ from utils import hardware++ seen = []++ async def _switch(_request, _subject, **kw):+ seen.append(kw)+ raise RuntimeError("stop")++ monkeypatch.setattr(inference_route, "_should_validate_before_switch", lambda: True)+ monkeypatch.setattr(inference_route, "_auto_switch_from_request_body", _switch)+ for device, body in (+ (hardware.DeviceType.MLX, {"prompt": {"prompt_string": "p"}}),+ (hardware.DeviceType.MLX, {"prompt": "p", "echo": True}),+ (hardware.DeviceType.MLX, {"prompt": "p", "typical_p": 0.5}),+ (hardware.DeviceType.CUDA, {"prompt": "p"}),+ (hardware.DeviceType.CUDA, {"prompt": "p", "typical_p": 0.5}),+ ):+ monkeypatch.setattr(hardware, "get_device", lambda: device)+ with pytest.raises(RuntimeError):+ asyncio.run(inference_route.openai_completions(_json_body_request(body), "tester"))+ assert [(kw["gguf_only"], kw["gguf_only_reason"]) for kw in seen] == [+ (False, None),+ (False, None),+ (True, "'typical_p' is not supported for MLX models."),+ (True, None),+ # A GGUF-only host keeps the GGUF refusal: no MLX reason, no grammar compiled.+ (True, None),+ ]+++def test_completions_on_mlx_refuses_an_audio_cpp_target_before_it_loads(monkeypatch):+ from utils import hardware++ monkeypatch.setattr(hardware, "get_device", lambda: hardware.DeviceType.MLX)+ target = "audio-cpp/audio.cpp-gguf/HTDemucs-6stems-GGUF"+ _, rec = _wired(monkeypatch, _FakeBackend("org/A-GGUF"), (target, None, target))+ body = {"model": target, "prompt": "hello"}+ with pytest.raises(HTTPException) as exc:+ asyncio.run(inference_route.openai_completions(_json_body_request(body), "tester"))+ assert exc.value.status_code == 400 and rec.calls == []diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex 5cc22ed749b..badf3936e30 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -85,6 +85,8 @@ from routes.inference import (openai_embeddings,openai_chat_completions,)+import routes.inference as inf_mod+from state import active_generationsfrom state.tool_policy import reset_tool_policy, set_tool_policy# 1x1 PNGs that Pillow can actually decode, for the paths that reach the decoder.@@ -11739,3 +11741,299 @@ def test_admission_prices_replay_against_what_generation_really_sends():f"reserved {image_parts} image embeddings for a request that sends "f"{mcp_images.MAX_TOTAL_MODEL_IMAGES + 1}")+++class _MLXCompletionBackend:+ active_model_name = "mlx/m"++ def resolve_completion_prompt(+ self,+ prompt,+ cancel_event = None,+ ):+ if prompt == "stopped":+ cancel_event.set()+ raise InterruptedError("Request cancelled.")+ if prompt == [999]:+ raise ValueError("Prompt contains invalid tokens.")+ if prompt == "queued":+ active_generations.cancel_all() # e.g. a model swap while behind another generation+ ids = [1, 2] * len(prompt) if isinstance(prompt, str) else [1, 2]+ return {"ids": ids, "text": prompt if isinstance(prompt, str) else "P", "n_vocab": 50}++ def generate_completion(self, prompt_ids, cancel_event, stats_holder, **kw):+ self.call, self.runs = (+ (prompt_ids, kw),+ [*getattr(self, "runs", []), (prompt_ids, kw["seed"])],+ )+ if kw["stop"] == ["cancel"]:+ cancel_event.set()+ if kw["stop"] == ["budget"]:+ from core.inference.context_refusal import ContextBudgetExceeded+ raise ContextBudgetExceeded(9, 4)+ if kw["stop"] == ["refused"]:+ from core.inference.orchestrator import GenStreamError+ yield GenStreamError("No grammar here.", public = True, openai_param = "response_format")+ return+ yield from ("a", "ab" + ("" if kw["seed"] is None else str(kw["seed"])))+ n = len(prompt_ids)+ usage = {"prompt_tokens": n, "completion_tokens": n, "total_tokens": 2 * n}+ usage["prompt_tokens_details"] = {"cached_tokens": n - 1}+ stats_holder["stats"] = {"usage": usage, "finish_reason": "length" if n == 2 else "stop"}++ def generate_completion_batch(self, rows, cancel_event, stats_holder, **kw):+ self.batches = [*getattr(self, "batches", []), len(rows)]+ stats_holder["stats"] = [{} for _ in rows]+ for row, spec in enumerate(rows):+ for text in self.generate_completion(+ spec["prompt_ids"],+ cancel_event,+ stats_holder["stats"][row],+ **kw,+ seed = spec["seed"],+ ):+ yield row, text+ stats_holder["stats"][row] = stats_holder["stats"][row]["stats"]++ def reset_generation_state(self, _event):+ pass+++def _run_mlx_completion(monkeypatch, body):+ class Request:+ state = SimpleNamespace()+ url = SimpleNamespace(path = "/v1/completions")+ method = "POST"++ async def json(self):+ return body++ async def is_disconnected(self):+ return False++ async def _switch(request, *_a, **_k):+ return await request.json()++ from utils.hardware import DeviceType++ backend = _MLXCompletionBackend()+ monkeypatch.setattr("utils.hardware.get_device", lambda: DeviceType.MLX)+ # No per-model recommendation, so llama-server's own defaults show.+ monkeypatch.setattr("utils.inference.inference_config._recommended_sampling", lambda _m: {})+ monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))+ monkeypatch.setattr(inf_mod, "_auto_switch_from_request_body", _switch)+ monkeypatch.setattr(inf_mod, "_active_mlx_backend", lambda: backend)+ _pin_loaded_backend(monkeypatch, is_loaded = False)++ async def _run():+ out = await openai_completions(Request(), current_subject = "test")+ if not hasattr(out, "body_iterator"):+ return out+ lines = [ln[6:] async for chunk in out.body_iterator for ln in chunk.split("\n")]+ return [ln if ln == "[DONE]" else json.loads(ln) for ln in lines if ln]++ return backend, asyncio.run(_run())+++def test_mlx_completion_reads_the_body_as_llama_server_does(monkeypatch):+ body = {"prompt": "P", "echo": True, "n_predict": 5, "max_tokens": 9, "repeat_last_n": 3}+ body.update(repeat_penalty = 1.2, seed = -1, top_k = -3, temperature = -1, stop = "x")+ threads, refusal = [], inf_mod._mlx_completions_refusal+ record = lambda b: threads.append(threading.current_thread().name) or refusal(b) # noqa: E731+ monkeypatch.setattr(inf_mod, "_mlx_completions_refusal", record)+ backend, out = _run_mlx_completion(monkeypatch, {**body, "logit_bias": [[7, False], [8, 2]]})+ # A client grammar compiles here, so it stays off the event loop.+ assert threads and all(t.startswith("inference-response-format") for t in threads)+ assert out["object"] == "text_completion" and out["id"].startswith("cmpl-")+ assert out["choices"] == [dict(text = "Pab", index = 0, logprobs = None, finish_reason = "length")]+ assert out["usage"]["total_tokens"] == 4 and backend.call[0] == [1, 2]+ kw = backend.call[1]+ read = [kw[k] for k in ("max_new_tokens", "penalty_window", "stop", "seed")]+ assert read == [5, 3, ["x"], None]+ # llama-server's defaults, clamps and random-seed sentinel.+ sampled = [kw[k] for k in ("temperature", "top_k", "min_p", "repetition_penalty")]+ assert sampled == [0.0, 0, 0.05, 1.2] and kw["logit_bias"] == {7: float("-inf"), 8: 2.0}+ greedy, _ = _run_mlx_completion(monkeypatch, {"prompt": "P", "top_p": 0, "top_k": 0})+ assert greedy.call[1]["top_k"] == 1+ # top_k at or past the vocabulary keeps every candidate, as on llama-server.+ for top_k, sent in ((10**6, 0), (50, 0), (49, 49)):+ wide, _ = _run_mlx_completion(monkeypatch, {"prompt": "P", "top_k": top_k})+ assert wide.call[1]["top_k"] == sent+ assert inf_mod.api_monitor.snapshot()[0]["reply_preview"] == "ab"+ for alias in ("n_predict", "max_completion_tokens"):+ unset, _ = _run_mlx_completion(monkeypatch, {"prompt": "P", alias: -1, "max_tokens": 9})+ assert unset.call[1]["max_new_tokens"] is None and unset.call[1]["penalty_window"] == 64+ none, out = _run_mlx_completion(monkeypatch, {"prompt": "P", "n_predict": 0})+ assert not hasattr(none, "call") and out["choices"][0]["finish_reason"] == "length"+ unmarked = [None, None]+ monkeypatch.setattr("core.inference.llama_keepwarm.mark_current_response_failed", unmarked.pop)+ _run_mlx_completion(monkeypatch, {"prompt": "P", "stop": "cancel"})+ assert unmarked == [None] and inf_mod.api_monitor.snapshot()[0]["status"] == "cancelled"+ queued, _ = _run_mlx_completion(monkeypatch, {"prompt": "queued"})+ assert not hasattr(queued, "call") and unmarked == []+ assert inf_mod.api_monitor.snapshot()[0]["status"] == "cancelled"+ with pytest.raises(HTTPException) as exc:+ _run_mlx_completion(monkeypatch, {"prompt": [999]})+ assert exc.value.status_code == 400 and active_generations.count() == 0+ # Stopped while queued behind another generation: the wait ends, nothing generates.+ with pytest.raises(HTTPException) as exc:+ _run_mlx_completion(monkeypatch, {"prompt": "stopped"})+ assert exc.value.status_code == 499 and active_generations.count() == 0+++def test_mlx_completion_streams_text_completion_chunks(monkeypatch):+ stream, usage = {"prompt": "P", "stream": True}, {"include_usage": True}+ _, chunks = _run_mlx_completion(monkeypatch, {**stream, "echo": True, "stream_options": usage})+ assert [c["choices"][0]["text"] for c in chunks[:4]] == ["P", "a", "b", ""]+ assert chunks[3]["choices"][0]["finish_reason"] == "length"+ assert chunks[4]["choices"] == [] and chunks[4]["usage"]["completion_tokens"] == 2+ assert chunks[5:] == ["[DONE]"]+ _, plain = _run_mlx_completion(monkeypatch, {**stream, "stream_options": True})+ assert len(plain) == 4 and "usage" not in plain[2]+ # A client gone before the body starts still closes the monitor entry and the tracker.+ monkeypatch.setattr(inf_mod, "_sse_streaming_response", lambda _, **k: k["unstarted_cleanup"])+ _, cleanup = _run_mlx_completion(monkeypatch, stream)+ asyncio.run(cleanup())+ assert inf_mod.api_monitor.snapshot()[0]["status"] == "cancelled"+ assert active_generations.count() == 0+++def test_mlx_completion_fans_out_prompts_and_n_in_llama_server_order(monkeypatch):+ body = {"prompt": ["a", "bb"], "n": 2, "seed": 7, "echo": True}+ backend, out = _run_mlx_completion(monkeypatch, body)+ got = [(c["index"], c["text"], c["finish_reason"]) for c in out["choices"]]+ texts = ["aab7", "aab8", "bbab7", "bbab8"]+ assert got == [(i, t, "length" if i < 2 else "stop") for i, t in enumerate(texts)]+ assert backend.runs == [([1, 2], 7), ([1, 2], 8), ([1, 2] * 2, 7), ([1, 2] * 2, 8)]+ assert backend.batches == [4], "every choice in one command"+ # Cached prompt tokens count once per prompt, as its prompt tokens do.+ cached = {"prompt_tokens_details": {"cached_tokens": 4}}+ assert out["usage"] == {+ "prompt_tokens": 6,+ "completion_tokens": 12,+ "total_tokens": 18,+ **cached,+ }+ assert "Choice 4:\nab8" in inf_mod.api_monitor.snapshot()[0]["reply_preview"]+ # Cancelled mid-batch: every choice decoding with it answers as stopped.+ _, out = _run_mlx_completion(monkeypatch, {**body, "stop": "cancel"})+ assert [(c["text"], c["finish_reason"]) for c in out["choices"]] == [(t, "stop") for t in texts]+ # No batch is wider than chat's cap on n, however many prompts there are.+ monkeypatch.setitem(inf_mod._LLAMA_HARD_LIMITS, "n_cmpl", (1, 3))+ backend, out = _run_mlx_completion(monkeypatch, body)+ assert backend.batches == [3, 1] and [c["text"] for c in out["choices"]] == texts+++ "stop, code", [("budget", "context_length_exceeded"), ("refused", "unsupported_parameter")]+)+def test_mlx_completion_refusals_are_client_errors_as_in_chat(monkeypatch, stop, code):+ monkeypatch.setattr(inf_mod, "_mlx_completion_grammar", lambda body: body.get("grammar"))+ with pytest.raises(HTTPException) as err:+ _run_mlx_completion(monkeypatch, {"prompt": "P", "stop": stop, "grammar": 'root ::= "a"'})+ assert err.value.status_code == 400 and err.value.detail["error"]["code"] == code+ # A runtime grammar refusal names the field the request sent.+ assert err.value.detail["error"]["param"] == ("prompt" if stop == "budget" else "grammar")+ _, lines = _run_mlx_completion(monkeypatch, {"prompt": "P", "stop": stop, "stream": True})+ assert [line["error"]["code"] for line in lines if "error" in line] == [code]+++# llama-server's /v1/completions fields at b11160 (tools/server/server-schema.cpp) that MLX+# serves, or ignores because they change neither the text nor the response shape.+_LLAMA_SERVED = (+ "stream stream_options n_predict max_tokens max_completion_tokens top_k top_p min_p "+ "temperature repeat_last_n repeat_penalty frequency_penalty presence_penalty seed "+ "logit_bias stop echo n n_cmpl grammar json_schema response_format"+)+_LLAMA_IGNORED = (+ "cache_prompt sse_ping_interval n_keep n_discard n_cache_reuse backend_sampling "+ "post_sampling_probs grammar_triggers chat_format "+ "reasoning_format generation_prompt parse_tool_calls chat_parser continue_final_message "+ "reasoning_control reasoning_budget_start_tag reasoning_budget_end_tags "+ "reasoning_budget_end_tag reasoning_budget_message"+)+# The rest change the text or the shape with no MLX equivalent: a value MLX refuses, and the one+# that turns the field off.+_LLAMA_UNSERVED = json.loads(+ '{"logprobs": [2, 0], "n_probs": [1, 0], "best_of": [2, 1], "suffix": ["x", ""],'+ ' "timings_per_token": [true, false], "return_tokens": [true, false],'+ ' "return_progress": [true, false], "verbose": [true, false], "response_fields": [["id"], []], "lora":'+ ' [[{"id": 0, "scale": 1}], []], "n_indent": [2, 0], "t_max_predict_ms": [100, -1], "ignore_eos":'+ ' [true, false], "min_keep": [2, 0], "samplers": ["kt", "edskypmxt"], "typical_p": [0.5, 1.0],'+ ' "top_n_sigma": [1.0, -1.0], "xtc_probability": [0.5, 0.0], "dynatemp_range": [0.5, 0.0],'+ ' "mirostat": [2, 0], "dry_multiplier": [0.8, 0.0], "adaptive_target": [0.5, -1.0],'+ ' "reasoning_budget_tokens": [0, -1], "preserved_tokens": [["<|im_start|>"], []]}'+)+# Read by llama-server only while the field named with it is on.+_LLAMA_DEPENDENT = json.loads(+ '{"xtc_threshold": "xtc_probability", "dynatemp_exponent": "dynatemp_range", "mirostat_tau":'+ ' "mirostat", "mirostat_eta": "mirostat", "dry_base": "dry_multiplier", "dry_allowed_length":'+ ' "dry_multiplier", "dry_penalty_last_n": "dry_multiplier", "dry_sequence_breakers":'+ ' "dry_multiplier", "adaptive_decay": "adaptive_target", "grammar_lazy": "grammar"}'+)+++def test_mlx_completion_grammar_follows_llama_server_precedence(monkeypatch):+ pytest.importorskip("llguidance.mlx")+ from core.inference.grammar_constraint import grammar_from_gbnf, grammar_from_json_schema+ from routes.inference import _mlx_completion_grammar as grammar++ yes, array = 'root ::= "yes"', {"type": "json_schema", "json_schema": {"schema": {}}}+ assert grammar({"grammar": "", "json_schema": {}, "response_format": array}) is None+ object_ = grammar_from_json_schema({"type": "object"})+ assert grammar({"json_schema": {}, "response_format": array}) == object_+ assert grammar({"response_format": array}) == grammar_from_json_schema({})+ run, _ = _run_mlx_completion(monkeypatch, {"prompt": "P", "grammar": yes, "json_schema": {}})+ assert run.call[1]["grammar"] == grammar_from_gbnf(yes)+ # A client grammar is held only within the shared cache's byte budget.+ from collections import OrderedDict+ import core.inference.grammar_constraint as gc++ for budget, held in ((gc._GRAMMAR_CACHE_MAX_BYTES, 1), (0, 0)):+ monkeypatch.setattr(gc, "_GRAMMAR_CACHE", OrderedDict())+ monkeypatch.setattr(gc, "_GRAMMAR_CACHE_MAX_BYTES", budget)+ grammar_from_gbnf(yes)+ assert len(gc._GRAMMAR_CACHE) == held+++def test_mlx_completion_refuses_only_what_mlx_cannot_reproduce(monkeypatch):+ from routes.inference import _MLX_COMPLETION_FIELDS_OFF, _mlx_completions_refusal as refusal++ for is_mlx in (True, False):+ held = SimpleNamespace(active_model_name = "m", models = {"m": {"is_mlx": is_mlx}})+ monkeypatch.setattr(inf_mod, "_peek_inference_backend", lambda: held)+ assert (inf_mod._active_mlx_backend() is held) is is_mlx++ assert set(_MLX_COMPLETION_FIELDS_OFF) == set(_LLAMA_UNSERVED) | set(_LLAMA_DEPENDENT)+ assert not set((_LLAMA_SERVED + " " + _LLAMA_IGNORED).split()) & set(_MLX_COMPLETION_FIELDS_OFF)+ for name, (on, off) in _LLAMA_UNSERVED.items():+ assert f"'{name}'" in refusal({"prompt": "p", name: on})+ assert refusal({"prompt": "p", name: off}) is None+ for name, enabler in _LLAMA_DEPENDENT.items():+ on = _LLAMA_UNSERVED.get(enabler, ['root ::= "x"'])[0]+ assert refusal({"prompt": "p", name: 0.3}) is None+ assert refusal({"prompt": "p", name: 0.3, enabler: on})+ assert refusal({"prompt": "p", "xtc_probability": 0.5, "xtc_threshold": 0.6}) is None+ assert refusal({"prompt": "p", "dry_multiplier": 0.8, "dry_penalty_last_n": 0}) is None+ assert refusal({"prompt": "p", "n_cmpl": 1, "n": 2, "n_probs": 0, "logprobs": 5}) is None+ assert refusal({"prompt": "p", "n": 2, "best_of": 2}) is None+ assert refusal({"prompt": "p", "grammar": None, "json_schema": {}}) is None+ for prompt in ([1, "a"], ["a", 1], [[1, 2]], {"prompt_string": [1, "a"]}):+ assert refusal({"prompt": prompt, "n_predict": -1, "repeat_last_n": 0}) is None+ for bad in (+ {"prompt": ["a", "b"], "stream": True},+ {"prompt": "p", "n": 2, "stream": True},+ {"prompt": "p", "n": 0},+ {"prompt": "p", "n_cmpl": 129, "n": 1},+ {"prompt": ["a", {"prompt_string": "a", "multimodal_data": ["x"]}]},+ {"prompt": [1, 1.5]},+ {"prompt": "p", "typical_p": "x"},+ {"prompt": [True]},+ {"prompt": {}},+ {"prompt": []},+ {"prompt": "p", "max_tokens": -2, "n_predict": None},+ {"prompt": "p", "repeat_last_n": -1},+ {"prompt": "p", "logit_bias": {"hi": 1}},+ {"prompt": "p", "grammar": "root ::= nowhere"},+ ):+ assert refusal(bad), baddiff --git a/studio/backend/tests/test_presence_penalty.py b/studio/backend/tests/test_presence_penalty.pyindex 52aa4e79619..d479603cd31 100644--- a/studio/backend/tests/test_presence_penalty.py+++ b/studio/backend/tests/test_presence_penalty.py@@ -9,6 +9,7 @@ over route -> orchestrator cmd -> worker gen_kwargs."""import threading+from types import SimpleNamespaceimport pytestimport torch@@ -472,3 +473,93 @@ def test_both_orchestrator_entry_points_forward_the_clip_into_the_command():with pytest.raises(_Built):list(o.generate_with_adapter_control(use_adapter = True, messages = turn, video = "AAAA"))assert [kw["video_b64"] for kw in built] == ["AAAA", "AAAA"]+++def test_a_raw_completion_prompt_crosses_the_worker_only_to_a_backend_that_serves_it():+ from core.inference.orchestrator import InferenceOrchestrator+ from core.inference.worker import _handle_generate, _handle_resolve_prompt, _ResidentBatch++ class _Queue(list):+ put = list.append++ class _Built(Exception):+ pass++ o = InferenceOrchestrator.__new__(InferenceOrchestrator)+ o._gen_lock, o._unload_pending, o.active_model_name = threading.Lock(), False, "m"+ o._ensure_subprocess_alive = lambda: True+ o._stop_ledger, o.models = SimpleNamespace(read_by_worker = lambda: True), {}+ built = []+ real_build = o._build_generate_cmd+ o._build_generate_cmd = lambda *a, **kw: built.append(real_build(*a, **kw)) or (+ _ for _ in ()+ ).throw(_Built())+ with pytest.raises(_Built):+ list(o.generate_completion([5, 6], max_new_tokens = 3, penalty_window = 0, grammar = "G"))+ cmd = built[0]+ assert (cmd["messages"], cmd["prompt_ids"], cmd["penalty_window"]) == ([], [5, 6], 0)+ assert cmd["grammar"] == "G"+ with pytest.raises(_Built):+ list(o.generate_completion_batch([{"prompt_ids": [5]}], penalty_window = 1))+ assert (built[1]["messages"], built[1]["rows"], built[1]["penalty_window"]) == (+ [],+ [{"prompt_ids": [5]}],+ 1,+ )++ class _MLX:+ last_generation_stats = None++ def generate_completion(self, prompt_ids, **kwargs):+ self.received = (prompt_ids, kwargs)+ return iter(["x"])++ def resolve_completion_prompt(self, prompt):+ raise ValueError("Prompt contains invalid tokens.")++ chat = SimpleNamespace(last_generation_stats = None) # no raw-prompt capability+ mlx, queue = _MLX(), _Queue()+ _handle_generate(mlx, cmd, queue, threading.Event())+ assert mlx.received[0] == [5, 6] and mlx.received[1]["penalty_window"] == 0+ assert mlx.received[1]["grammar"] == "G"+ assert [item["type"] for item in queue] == ["token", "gen_done"]+ queue.clear()+ _handle_generate(chat, cmd, queue, threading.Event())+ assert [item["type"] for item in queue] == ["gen_error"]+ assert "raw-prompt completions" in queue[0]["error"]+ for backend, invalid in ((mlx, True), (chat, None)):+ queue.clear()+ _handle_resolve_prompt(backend, {"request_id": "r", "prompt": [10**9]}, queue)+ assert queue[0]["error"] and queue[0].get("invalid") is invalid+++def test_a_raw_prompt_queued_behind_a_generation_stops_waiting_on_cancel():+ import time++ from core.inference.orchestrator import InferenceOrchestrator++ orch = InferenceOrchestrator.__new__(InferenceOrchestrator)+ orch._gen_lock = threading.Lock()+ orch._gen_lock.acquire() # a running generation holds it+ cancel = threading.Event()+ threading.Timer(0.2, cancel.set).start()+ started = time.monotonic()+ with pytest.raises(InterruptedError):+ orch.resolve_completion_prompt("p", cancel_event = cancel)+ assert time.monotonic() - started < 2+++def test_a_raw_prompt_reply_wait_stops_on_cancel():+ import time++ from core.inference.orchestrator import InferenceOrchestrator++ orch = InferenceOrchestrator.__new__(InferenceOrchestrator)+ orch._ensure_subprocess_alive = lambda: True+ cancel = threading.Event()+ threading.Timer(0.2, cancel.set).start()+ started = time.monotonic()+ reply = orch._await_reply(+ lambda timeout: time.sleep(timeout) or None, "r", "t", "c", 30.0, cancel.is_set+ )+ assert reply is None and time.monotonic() - started < 3