Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: honor the OpenAI sampling parameters on the MLX backend (#9262)

Long Yixing099865689117
diff --git a/.github/workflows/mlx-ci.yml b/.github/workflows/mlx-ci.yml
index 851073522d7..3552af9c32f 100644
--- a/.github/workflows/mlx-ci.yml
+++ b/.github/workflows/mlx-ci.yml
@@ -92,6 +92,7 @@ on:
# change would burn a slot from the 5-job account-wide macOS cap to run
# nothing related. studio-backend-ci.yml covers both on ubuntu-latest and
# already triggers on them.
+ - 'studio/backend/tests/test_mlx_inference_backend.py'
- 'tests/studio/test_mlx_training_worker_behaviors.py'
- 'tests/studio/run_real_mlx_smoke.py'
- 'tests/studio/mac_capability_verdict_smoke.py'
@@ -111,6 +112,7 @@ on:
- 'studio/backend/core/inference/mlx_inference.py'
- 'studio/backend/main.py'
- 'studio/backend/utils/mlx_repair.py'
+ - 'studio/backend/tests/test_mlx_inference_backend.py'
- 'tests/studio/test_mlx_training_worker_behaviors.py'
- 'tests/studio/run_real_mlx_smoke.py'
- 'tests/studio/mac_capability_verdict_smoke.py'
@@ -322,6 +324,16 @@ jobs:
python -m pytest -v --tb=short \
tests/studio/test_mlx_training_worker_behaviors.py
+ # The inference backend's numerical tests importorskip mlx, so they skip on
+ # studio-backend-ci.yml's ubuntu runner and only ever execute here. Run from
+ # studio/backend: its conftest puts that directory on sys.path.
+ - name: MLX inference backend tests
+ working-directory: studio/backend
+ env:
+ UNSLOTH_COMPILE_DISABLE: '1'
+ run: |
+ python -m pytest -v --tb=short tests/test_mlx_inference_backend.py
+
# Real MLX training + inference smoke test. Trains
# unsloth/gemma-3-270m-it for 7 deterministic LoRA steps
# (batch_size=2, gradient_accumulation_steps=3) on a single
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index b001024bdb2..a313fb64afd 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -2042,7 +2042,11 @@ class ReasoningChannelNormalizer:
return "".join(output)
def finish(self) -> str:
- """Flush a naturally completed stream and close an open think block."""
+ """Flush a stream that ended and close an open think block.
+
+ Ended, not merely finished generating: a stop sequence ends a turn as a stop
+ token does, and the block it cut inside is still owed its close.
+ """
output = self.drain()
if self._in_reasoning:
# Nothing generated: no block at all, rather than a close with no opener.
@@ -2100,8 +2104,12 @@ def normalize_reasoning_snapshots(
tools = None,
prompt: Optional[str] = None,
continued: bool = False,
+ ended = None,
):
- """Normalize a prefix-monotonic cumulative text stream when supported."""
+ """Normalize a prefix-monotonic cumulative text stream when supported.
+
+ ``ended`` is read after the stream: a turn a stop sequence ended still owes
+ its open block a close, even if a cancel landed on the same step."""
markers = markers or detect_reasoning_channel_markers(tokenizer, tools = tools)
if markers is None:
yield from stream
@@ -2122,7 +2130,9 @@ def normalize_reasoning_snapshots(
normalized_output += delta
yield normalized_output
- cancelled = cancel_event is not None and cancel_event.is_set()
+ cancelled = (
+ not (ended is not None and ended()) and cancel_event is not None and cancel_event.is_set()
+ )
tail = normalizer.drain() if cancelled else normalizer.finish()
if tail:
normalized_output += tail
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 36a83b0cc10..bc9d834ce58 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -23409,6 +23409,8 @@ class LlamaCppBackend:
max_tokens: Optional[int] = None,
repetition_penalty: float = 1.0,
presence_penalty: float = 0.0,
+ frequency_penalty: float = 0.0,
+ logit_bias: Optional[dict] = None,
stop: Optional[list[str]] = None,
cancel_event: Optional[threading.Event] = None,
enable_thinking: Optional[bool] = None,
@@ -23457,6 +23459,7 @@ class LlamaCppBackend:
"min_p": min_p,
"repeat_penalty": repetition_penalty,
"presence_penalty": presence_penalty,
+ "frequency_penalty": frequency_penalty,
}
retry_messages = messages
retry_image_b64 = image_b64
@@ -23466,6 +23469,8 @@ class LlamaCppBackend:
if perf_callback is not None:
payload["return_progress"] = True
payload["timings_per_token"] = True
+ if logit_bias:
+ payload["logit_bias"] = logit_bias
# Per-request enable_thinking / reasoning_effort / preserve_thinking
_reasoning_kw = self._request_reasoning_kwargs(
enable_thinking, reasoning_effort, preserve_thinking
@@ -23743,6 +23748,8 @@ class LlamaCppBackend:
max_tokens = retry_max_tokens,
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
stop = stop,
cancel_event = cancel_event,
enable_thinking = enable_thinking,
@@ -23786,6 +23793,8 @@ class LlamaCppBackend:
max_tokens: Optional[int] = None,
repetition_penalty: float = 1.0,
presence_penalty: float = 0.0,
+ frequency_penalty: float = 0.0,
+ logit_bias: Optional[dict] = None,
stop: Optional[list[str]] = None,
cancel_event: Optional[threading.Event] = None,
enable_thinking: Optional[bool] = None,
@@ -24272,11 +24281,14 @@ class LlamaCppBackend:
"min_p": min_p,
"repeat_penalty": repetition_penalty,
"presence_penalty": presence_penalty,
+ "frequency_penalty": frequency_penalty,
}
if perf_callback is not None:
payload["return_progress"] = True
payload["timings_per_token"] = True
+ if logit_bias:
+ payload["logit_bias"] = logit_bias
# As in the passthrough builder: if every name carried markup the catalog is
# now empty, and "tools": [] would still advertise tool use.
if safe_tools:
@@ -25868,7 +25880,10 @@ class LlamaCppBackend:
"min_p": min_p,
"repeat_penalty": repetition_penalty,
"presence_penalty": presence_penalty,
+ "frequency_penalty": frequency_penalty,
}
+ if logit_bias:
+ stream_payload["logit_bias"] = logit_bias
if _reasoning_kw is not None:
stream_payload["chat_template_kwargs"] = _reasoning_kw
stream_payload["max_tokens"] = _final_max_tokens
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 90a73b930d3..75edfc3620f 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -324,14 +324,116 @@ def _vlm_messages_have_tool_history(messages):
)
+def _mlx_config_field(model, name):
+ """Read a config field in either shape a loaded MLX model exposes it in.
+
+ A checkpoint's config is a dict on some models and an object on others, under
+ ``config`` or ``_config`` -- the same spread ``_mlx_vlm_model_config`` walks to
+ find a model_type. A getattr-only read silently misses the dict half.
+ """
+ for cfg in (getattr(model, "config", None), getattr(model, "_config", None)):
+ value = cfg.get(name) if isinstance(cfg, dict) else getattr(cfg, name, None)
+ if value is not None:
+ return value
+ return None
+
+
+def _mlx_stop_token_ids(tokenizer, model = None):
+ """Ids the runtime actually stops on, as a tuple.
+
+ Prefer the stopping criteria mlx_vlm consults, then the model config that
+ seeds them, before the tokenizer attribute: they disagree on some repos
+ (Kimi-VL lists two config ids and a different tokenizer id), and picking the
+ wrong source misreads a real stop as truncation. Each source may be a bare
+ int or a collection.
+ """
+ for source in (
+ getattr(getattr(tokenizer, "stopping_criteria", None), "eos_token_ids", None),
+ _mlx_config_field(model, "eos_token_id"),
+ getattr(tokenizer, "eos_token_ids", None),
+ getattr(tokenizer, "eos_token_id", None),
+ ):
+ if source is None:
+ continue
+ if isinstance(source, (list, tuple, set, frozenset)):
+ # An empty collection falls through too: a source present but unset is
+ # not an answer, and stopping on nothing misreads a real stop as
+ # truncation. A bare id is kept as-is, since 0 is a valid token.
+ if not source:
+ continue
+ return tuple(source)
+ # int() so a numpy scalar cannot raise here, inside a caller's finally.
+ return (int(source),)
+ return ()
+
+
+def _mlx_stop_sequences(stop):
+ """The sequences a request asked to stop on, as a list.
+
+ An empty one is dropped rather than matched: it is found at position 0 of
+ every reply and would end each turn before its first token.
+ """
+ return [x for x in ([stop] if isinstance(stop, str) else stop or []) if x]
+
+
+def _mlx_stop_cut(text: str, stops) -> tuple[int, bool]:
+ """How much of a cumulative reply may be shown, and whether a stop ended it.
+
+ Text that could still grow into a sequence is held back, as llama-server holds
+ it: a client cannot unsee a fragment the next token completes. A trailing
+ replacement character is never matched either, since a decode prints the same
+ character for one the model wrote and for bytes that never finished arriving
+ and neither runtime tells them apart; it is delivered regardless.
+
+ A caller whose decode rewrites as readily as it extends must withhold until the
+ turn ends and apply this cut once.
+ """
+ # An unresolved character is not a character yet, and dropping it can uncover
+ # the start of a sequence.
+ resolved = text.rstrip("\ufffd")
+ cut = len(resolved)
+ for sequence in stops:
+ found = resolved.find(sequence)
+ if found != -1:
+ cut = min(cut, found)
+ if cut < len(resolved):
+ return cut, True
+ held = 0
+ for sequence in stops:
+ for size in range(min(len(sequence) - 1, len(resolved)), held, -1):
+ if resolved.endswith(sequence[:size]):
+ held = size
+ break
+ return len(resolved) - held, False
+
+
+def _mlx_finish_reason(response, stop_ids, generated_n, max_tokens):
+ """Why generation stopped: "length" only when the limit was reached.
+
+ mlx_lm reports it directly. mlx_vlm's result carries no reason, and a count
+ at the limit is ambiguous -- a stop token sampled as the final allowed token
+ looks identical to ordinary exhaustion -- so fall back to the last token's
+ identity, which separates them.
+ """
+ reason = getattr(response, "finish_reason", None)
+ if reason in ("stop", "length"):
+ return reason
+ if generated_n < max_tokens:
+ return "stop"
+ token = getattr(response, "token", None)
+ return "stop" if token is not None and token in tuple(stop_ids) else "length"
+
+
def _build_generation_stats(
prompt_n,
prompt_tps,
gen_n,
gen_tps,
cached_n = 0,
+ finish_reason = None,
):
- """Map mlx stream stats onto the usage/timings shape llama-server emits."""
+ """Map mlx stream stats onto the usage/timings shape llama-server emits,
+ plus the reason generation ended."""
prompt_n = int(prompt_n or 0)
gen_n = int(gen_n or 0)
cached_n = int(cached_n or 0)
@@ -345,6 +447,10 @@ def _build_generation_stats(
"prompt_tokens": total_prompt_n,
"completion_tokens": gen_n,
"total_tokens": total_prompt_n + gen_n,
+ # The reused prefix is inside prompt_tokens, so name it here as
+ # llama-server does. Reporting it only under timings.cache_n leaves a
+ # caller reading the OpenAI field a cached_tokens of 0 on every hit.
+ "prompt_tokens_details": {"cached_tokens": cached_n},
},
"timings": {
"prompt_n": prompt_n,
@@ -357,6 +463,9 @@ def _build_generation_stats(
"predicted_per_second": gen_tps,
"cache_n": cached_n,
},
+ # Latched where generation exits, so a cancel arriving afterwards
+ # cannot rewrite the reason the completion actually ended for.
+ "finish_reason": finish_reason,
}
@@ -1027,6 +1136,63 @@ def _init_mlx_distributed():
return group, rank, world_size
+def _normalize_mlx_seed(seed):
+ """Map any request seed onto ``mx.random.key``'s unsigned domain.
+
+ The seed field is shared with backends that accept values this one cannot:
+ llama-server forwards ``-1`` unchanged, while ``mx.random.key`` raises for
+ negatives and for anything >= 2**64. Reducing modulo 2**64 is total over
+ every Python int, so no schema-valid seed can fail mid-generation.
+ """
+ return int(seed) % (2**64)
+
+
+def _make_seeded_mlx_sampler(
+ seed,
+ *,
+ temp,
+ top_p,
+ min_p,
+ top_k,
+ min_tokens_to_keep = 1,
+):
+ """mlx_lm.make_sampler's chain with a request-scoped key instead of global RNG.
+
+ ``mx.random.seed`` mutates thread-local state that later requests inherit, so
+ an unseeded request following a seeded one would silently become reproducible.
+ A per-request key keeps determinism inside the request that asked for it.
+
+ The filtering stages are mlx_lm's own ``apply_*`` functions rather than
+ reimplementations: supplying a custom sampler suppresses the chain mlx_lm and
+ mlx_vlm would otherwise build, so anything not reused here would be silently
+ dropped from seeded requests only.
+ """
+ import mlx.core as mx
+ from mlx_lm.sample_utils import apply_top_p, apply_min_p, apply_top_k
+
+ if temp == 0:
+ # argmax draws no randomness; seeding it would be meaningless, not wrong.
+ return lambda logprobs: mx.argmax(logprobs, axis = -1)
+
+ stages = []
+ if 0 < top_p < 1.0:
+ stages.append(lambda x: apply_top_p(x, top_p))
+ if min_p != 0.0:
+ stages.append(lambda x: apply_min_p(x, min_p, min_tokens_to_keep))
+ if top_k > 0:
+ stages.append(lambda x: apply_top_k(x, top_k))
+
+ state = {"key": mx.random.key(_normalize_mlx_seed(seed))}
+
+ def _sampler(logprobs):
+ for stage in stages:
+ logprobs = stage(logprobs)
+ state["key"], subkey = mx.random.split(state["key"])
+ return mx.random.categorical(logprobs * (1 / temp), key = subkey)
+
+ return _sampler
+
+
def _make_mlx_presence_penalty_processor(penalty: float):
"""Presence penalty as an mlx_lm/mlx_vlm logits processor, matching the safetensors path.
@@ -1066,6 +1232,91 @@ def _make_mlx_presence_penalty_processor(penalty: float):
return _processor
+def _make_mlx_frequency_penalty_processor(penalty: float):
+ """Frequency penalty as an mlx_lm/mlx_vlm logits processor.
+
+ Identical to the presence processor except the scatter *accumulates*, so a
+ token repeated N times in the completion is charged N × penalty. It counts
+ occurrences and scales once, in float32: accumulating the penalty itself in
+ a float16 logits dtype rounds on every repeat, which drifts by tens of
+ logits over a long run (1000 repeats at 0.3 lands on -274.25, not -300).
+ """
+ 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"] :]
+ if generated.size == 0:
+ return logits
+ import mlx.core as mx
+
+ vocab = logits.shape[-1]
+ valid = (generated >= 0) & (generated < vocab)
+ safe = mx.where(valid, generated, vocab).astype(mx.int32)
+ counts = mx.zeros((vocab + 1,), dtype = mx.float32).at[safe].add(1.0)
+ return logits - (penalty * counts[:vocab]).astype(logits.dtype)
+
+ return _processor
+
+
+def _make_mlx_logit_bias_processor(logit_bias: dict):
+ """Additive logit bias as an mlx_lm/mlx_vlm logits processor.
+
+ mlx_lm's own ``logit_bias`` processor indexes logits with the raw client
+ ids; MLX does no bounds checking, so a bias on an id past the model's logit
+ width is undefined behavior. Route strays to the same discarded scratch
+ slot the penalty processors use.
+ """
+ state = {"safe": None, "values": None, "vocab": None}
+
+ def _processor(tokens, logits):
+ import mlx.core as mx
+
+ vocab = logits.shape[-1]
+ if state["vocab"] != vocab:
+ pairs = [(int(t), float(v)) for t, v in logit_bias.items()]
+ state["safe"] = mx.array(
+ [t if 0 <= t < vocab else vocab for t, _ in pairs], dtype = mx.int32
+ )
+ state["values"] = mx.array([v for _, v in pairs], dtype = mx.float32)
+ state["vocab"] = vocab
+ mask = mx.zeros((vocab + 1,), dtype = mx.float32).at[state["safe"]].add(state["values"])
+ return logits + mask[:vocab].astype(logits.dtype)
+
+ return _processor
+
+
+def _mlx_sampling_processors(
+ *,
+ repetition_penalty = None,
+ presence_penalty: float = 0.0,
+ frequency_penalty: float = 0.0,
+ logit_bias = None,
+):
+ """Logits processors for the sampling knobs, or ``None`` when all are inert.
+
+ Bias runs before the penalties, matching llama-server's sampler order.
+ mlx_lm supplies only the repetition penalty here: its presence and
+ frequency processors window the last 20 tokens *including the prompt*,
+ 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.
+ """
+ processors = []
+ if logit_bias:
+ processors.append(_make_mlx_logit_bias_processor(logit_bias))
+ 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
+ processors.extend(make_logits_processors(repetition_penalty = float(repetition_penalty)))
+ if presence_penalty:
+ processors.append(_make_mlx_presence_penalty_processor(float(presence_penalty)))
+ if frequency_penalty:
+ processors.append(_make_mlx_frequency_penalty_processor(float(frequency_penalty)))
+ return processors or None
+
+
class MLXInferenceBackend:
def __init__(self):
self.models = {}
@@ -1074,7 +1325,8 @@ class MLXInferenceBackend:
self.loaded_local_models = []
self.device = "mlx"
self._generation_lock = threading.Lock()
- # usage/timings of the latest generation, shipped on gen_done.
+ # usage, timings and terminal reason of the latest generation,
+ # shipped on gen_done.
self.last_generation_stats = None
self._model = None
@@ -1506,6 +1758,10 @@ class MLXInferenceBackend:
preserve_thinking = None,
continue_final_message = False,
presence_penalty = 0.0,
+ seed = None,
+ frequency_penalty = 0.0,
+ logit_bias = None,
+ stop = None,
_adapter_state = None,
) -> Generator[str, None, None]:
if self._model is None:
@@ -1552,7 +1808,11 @@ class MLXInferenceBackend:
preserve_thinking = preserve_thinking,
continue_final_message = continue_final_message,
presence_penalty = presence_penalty,
+ seed = seed,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
_adapter_state = _adapter_state,
+ stop = stop,
)
else:
stream = self._generate_text(
@@ -1570,10 +1830,19 @@ class MLXInferenceBackend:
preserve_thinking = preserve_thinking,
continue_final_message = continue_final_message,
presence_penalty = presence_penalty,
+ seed = seed,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
_adapter_state = _adapter_state,
+ stop = stop,
)
yield from stream
+ def _mark_stopped(self):
+ """Record that a text sequence ended the turn, not the runtime."""
+ if isinstance(self.last_generation_stats, dict):
+ self.last_generation_stats["finish_reason"] = "stop"
+
def _generate_text(
self,
messages,
@@ -1591,10 +1860,14 @@ class MLXInferenceBackend:
preserve_thinking = None,
continue_final_message = False,
presence_penalty = 0.0,
+ seed = None,
+ frequency_penalty = 0.0,
+ logit_bias = None,
_adapter_state = None,
+ stop = None,
):
from mlx_lm import stream_generate
- from mlx_lm.sample_utils import make_sampler, make_logits_processors
+ from mlx_lm.sample_utils import make_sampler
from core.inference.chat_template_helpers import (
apply_chat_template_for_generation,
@@ -1645,28 +1918,28 @@ class MLXInferenceBackend:
think_prefix = detect_think_prefill(
prompt, getattr(self._tokenizer, "all_special_tokens", None)
)
- sampler = make_sampler(
- temp = temperature,
- top_p = top_p,
- top_k = int(top_k or 0),
- min_p = float(min_p or 0.0),
- min_tokens_to_keep = 1,
- )
- # Repetition and/or presence penalty processors (GGUF/safetensors parity).
- logits_processors = []
- if repetition_penalty is not None and float(repetition_penalty) not in (
- 0.0,
- 1.0,
- ):
- logits_processors.extend(
- make_logits_processors(
- repetition_penalty = float(repetition_penalty),
- )
+ if seed is None:
+ sampler = make_sampler(
+ temp = temperature,
+ top_p = top_p,
+ top_k = int(top_k or 0),
+ min_p = float(min_p or 0.0),
+ min_tokens_to_keep = 1,
+ )
+ else:
+ sampler = _make_seeded_mlx_sampler(
+ seed,
+ temp = temperature,
+ top_p = top_p,
+ top_k = int(top_k or 0),
+ min_p = float(min_p or 0.0),
)
- if presence_penalty:
- logits_processors.append(_make_mlx_presence_penalty_processor(float(presence_penalty)))
- if not logits_processors:
- logits_processors = None
+ logits_processors = _mlx_sampling_processors(
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
+ )
preserve_native_channels = reasoning_channel_markers is not None
token_ids = []
@@ -1680,6 +1953,13 @@ class MLXInferenceBackend:
if reasoning_channel_markers is not None
else None
)
+ # Sequences match the sampled text, ahead of the prefill this path restores
+ # and the <think> rewriting below: matching delivered text would end turns on
+ # markup the model never wrote, and never find a native marker asked for.
+ sequences = _mlx_stop_sequences(stop)
+ stopped = False
+ sampled = ""
+ released = 0
# MLX consumers diff cumulative snapshots. Keep a prompt-prefilled
# <think> prefix on every native-protocol snapshot just as the normal
# decoding path does below.
@@ -1723,17 +2003,37 @@ class MLXInferenceBackend:
final_response = response
token_ids.append(response.token)
if preserve_native_channels:
- piece = getattr(response, "text", None) or ""
- delta = normalizer.feed(piece)
+ sampled += getattr(response, "text", None) or ""
+ if sequences:
+ cut, stopped = _mlx_stop_cut(sampled, sequences)
+ else:
+ cut = len(sampled)
+ # Cut before normalizing: the markers the normalizer writes are
+ # this layer's own, unmatched for the same reason the prefill is.
+ delta = normalizer.feed(sampled[released:cut])
+ released = cut
if delta:
normalized_output += delta
yield normalized_output
else:
- cumulative = self._tokenizer.decode(
+ # Re-decoding every id rebuilds rather than extends, so an
+ # invalid byte sequence can revise characters already shown.
+ # Predates stop handling and affects plain replies too.
+ sampled = self._tokenizer.decode(
token_ids,
skip_special_tokens = True,
)
- yield think_prefix + cumulative
+ if not sequences:
+ yield think_prefix + sampled
+ else:
+ # Matched every step, delivered once at the end: this
+ # decode revises earlier snapshots, and consumers diff
+ # them by length, so a revised one splices two renderings
+ # into text that can spell the sequence itself. A stream
+ # cannot unsend, so nothing goes out until it settles.
+ cut, stopped = _mlx_stop_cut(sampled, sequences)
+ if stopped:
+ break
if cancel_event and cancel_event.is_set():
break
@@ -1749,7 +2049,8 @@ class MLXInferenceBackend:
logger.error("stream_generate failed:\n%s", traceback.format_exc())
raise
finally:
- # Latch final cumulative stats for the usage/timings chunk.
+ # Latch final stats here, so a cancel arriving later cannot
+ # rewrite the reason the generation actually ended for.
if final_response is not None:
self.last_generation_stats = _build_generation_stats(
getattr(final_response, "prompt_tokens", 0),
@@ -1757,13 +2058,40 @@ class MLXInferenceBackend:
getattr(final_response, "generation_tokens", 0),
getattr(final_response, "generation_tps", 0.0),
cached_n,
+ finish_reason = _mlx_finish_reason(
+ final_response,
+ _mlx_stop_token_ids(self._tokenizer, self._model),
+ getattr(final_response, "generation_tokens", 0),
+ max_new_tokens,
+ ),
)
+ # The turn's settled text: delivered once for the plain path, as the tail for
+ # the native-channel one. Every snapshot was matched as it arrived, so a turn
+ # no sequence ended owes all of its text, held-back partial included.
+ if sequences:
+ if not stopped:
+ cut = len(sampled)
+ if normalizer is None:
+ settled = think_prefix + sampled[:cut]
+ # The prefill already went out, so a turn whose settled text is just
+ # the prefill owes no second snapshot saying the same thing.
+ if settled != think_prefix:
+ yield settled
+ else:
+ delta = normalizer.feed(sampled[released:cut])
+ if delta:
+ normalized_output += delta
+ yield normalized_output
if normalizer is not None:
- cancelled = cancel_event is not None and cancel_event.is_set()
+ # A sequence ends the turn as a stop token would, so a reasoning block it
+ # cut inside is closed. Only a cancelled turn drains: more was coming.
+ cancelled = not stopped and cancel_event is not None and cancel_event.is_set()
tail = normalizer.drain() if cancelled else normalizer.finish()
if tail:
normalized_output += tail
yield normalized_output
+ if stopped:
+ self._mark_stopped()
def _generate_vlm(
self,
@@ -1783,7 +2111,11 @@ class MLXInferenceBackend:
preserve_thinking = None,
continue_final_message = False,
presence_penalty = 0.0,
+ seed = None,
+ frequency_penalty = 0.0,
+ logit_bias = None,
_adapter_state = None,
+ stop = None,
):
from mlx_vlm import stream_generate as vlm_stream
@@ -1885,7 +2217,11 @@ class MLXInferenceBackend:
from core.inference.chat_template_helpers import detect_think_prefill
# Re-emit an open <think> prefill from the prompt (see _generate_text).
- cumulative = detect_think_prefill(prompt, getattr(chat_target, "all_special_tokens", None))
+ prefill = detect_think_prefill(prompt, getattr(chat_target, "all_special_tokens", None))
+ 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)
+ stopped = False
logger.info(
"VLM generating: prompt_len=%d, has_image=%s",
len(prompt),
@@ -1902,27 +2238,37 @@ class MLXInferenceBackend:
min_p = float(min_p or 0.0),
)
vlm_kwargs.update(self._kv_quant_generate_kwargs())
+ if seed is not None:
+ # generate_step builds its temperature/top_p/min_p/top_k sampler only
+ # when sampler is None, so a seeded request must supply the whole
+ # chain -- otherwise seeding would silently disable those controls.
+ vlm_kwargs["sampler"] = _make_seeded_mlx_sampler(
+ seed,
+ temp = temperature,
+ top_p = top_p,
+ top_k = int(top_k or 0),
+ min_p = float(min_p or 0.0),
+ )
_rep_active = repetition_penalty is not None and float(repetition_penalty) not in (
0.0,
1.0,
)
- if presence_penalty:
- # Presence needs a custom processor: pass the full list (repetition +
- # presence) instead of the repetition_penalty shortcut so both apply.
- from mlx_lm.sample_utils import make_logits_processors
-
- _vlm_processors = []
- if _rep_active:
- _vlm_processors.extend(
- make_logits_processors(repetition_penalty = float(repetition_penalty))
- )
- _vlm_processors.append(_make_mlx_presence_penalty_processor(float(presence_penalty)))
- vlm_kwargs["logits_processors"] = _vlm_processors
+ if presence_penalty or frequency_penalty or logit_bias:
+ # These need custom processors: pass the full list (repetition +
+ # the rest) instead of the repetition_penalty shortcut so all apply.
+ vlm_kwargs["logits_processors"] = _mlx_sampling_processors(
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
+ )
elif _rep_active:
vlm_kwargs["repetition_penalty"] = float(repetition_penalty)
def _stream_vlm_snapshots():
- nonlocal cumulative
+ nonlocal stopped
+ sampled = ""
+ released = 0
# Hold the generation lock AND the request-scoped adapter state for the
# whole stream so Base-vs-LoRA compare mode honors use_adapter and the
# wrapper tree is restored on completion, cancellation, or close.
@@ -1933,8 +2279,8 @@ class MLXInferenceBackend:
# UI renders it during prefill, matching _generate_text. Done
# inside the adapter context so an unsupported request raises
# before any output escapes.
- if cumulative:
- yield cumulative
+ if prefill:
+ yield prefill
for response in vlm_stream(
self._model,
self._processor,
@@ -1944,18 +2290,40 @@ class MLXInferenceBackend:
):
final_response = response
token_text = response.text if hasattr(response, "text") else str(response)
- cumulative += token_text
- yield cumulative
+ sampled += token_text
+ if not sequences:
+ yield prefill + sampled
+ else:
+ cut, stopped = _mlx_stop_cut(sampled, sequences)
+ # These deltas only append, so the cut never moves back
+ # over text already released.
+ if cut > released:
+ released = cut
+ yield prefill + sampled[:cut]
+ if stopped:
+ break
if cancel_event and cancel_event.is_set():
break
+ # As in _generate_text: what was withheld is ordinary text now.
+ if sequences and not stopped and released < len(sampled):
+ yield prefill + sampled
finally:
- # mlx_vlm exposes the same stats fields as mlx_lm.
+ # mlx_vlm exposes the same stats fields as mlx_lm, minus a
+ # finish reason, so that one is derived.
if final_response is not None:
+ tokenizer = getattr(self._processor, "tokenizer", self._processor)
+ stop_ids = _mlx_stop_token_ids(tokenizer, self._model)
self.last_generation_stats = _build_generation_stats(
getattr(final_response, "prompt_tokens", 0),
getattr(final_response, "prompt_tps", 0.0),
getattr(final_response, "generation_tokens", 0),
getattr(final_response, "generation_tps", 0.0),
+ finish_reason = _mlx_finish_reason(
+ final_response,
+ stop_ids,
+ getattr(final_response, "generation_tokens", 0),
+ max_new_tokens,
+ ),
)
yield from normalize_reasoning_snapshots(
@@ -1964,8 +2332,11 @@ class MLXInferenceBackend:
cancel_event,
tools = tools,
prompt = prompt,
- continued = bool(continue_final_message and trailing_assistant_text(messages)),
+ continued = vlm_continued,
+ ended = lambda: stopped,
)
+ if stopped:
+ self._mark_stopped()
def generate_audio_input_response(
self,
@@ -1975,6 +2346,7 @@ class MLXInferenceBackend:
max_new_tokens = 512,
use_adapter = None,
cancel_event = None,
+ stop = None,
**_sampler,
):
"""Audio-input chat (omni models): waveform in, incremental text deltas
@@ -2020,6 +2392,11 @@ class MLXInferenceBackend:
logger.info("MLX audio-input generating: prompt_len=%d", len(prompt))
markers = detect_reasoning_channel_markers(self._processor)
normalizer = ReasoningChannelNormalizer(*markers) if markers is not None else None
+ # Matched on the sampled deltas, for the reason _generate_text gives.
+ sequences = _mlx_stop_sequences(stop)
+ sampled = ""
+ released = 0
+ stopped = False
# Hold the adapter state for the whole stream, as text and vision do,
# so Base-vs-LoRA compare doesn't run the adapter on both sides.
with self._generation_lock, _temporary_mlx_adapter_state(self._model, use_adapter):
@@ -2036,26 +2413,55 @@ class MLXInferenceBackend:
**self._kv_quant_generate_kwargs(),
):
final_response = response
- token_text = response.text if hasattr(response, "text") else str(response)
+ sampled += response.text if hasattr(response, "text") else str(response)
+ if sequences:
+ cut, stopped = _mlx_stop_cut(sampled, sequences)
+ else:
+ cut = len(sampled)
+ # Cut before normalizing: the markers the normalizer writes are
+ # this layer's own, unmatched for the same reason the prefill is.
+ delta = sampled[released:cut]
+ released = cut
if normalizer is not None:
- token_text = normalizer.feed(token_text)
- if token_text:
- yield token_text
+ delta = normalizer.feed(delta)
+ if delta:
+ yield delta
+ if stopped:
+ break
if cancel_event and cancel_event.is_set():
break
finally:
+ # Derived as the vision path derives it: this backend reports no
+ # finish reason, and unset reads as a natural end.
if final_response is not None:
+ tokenizer = getattr(self._processor, "tokenizer", self._processor)
self.last_generation_stats = _build_generation_stats(
getattr(final_response, "prompt_tokens", 0),
getattr(final_response, "prompt_tps", 0.0),
getattr(final_response, "generation_tokens", 0),
getattr(final_response, "generation_tps", 0.0),
+ finish_reason = _mlx_finish_reason(
+ final_response,
+ _mlx_stop_token_ids(tokenizer, self._model),
+ getattr(final_response, "generation_tokens", 0),
+ max_new_tokens,
+ ),
)
+ # As in _generate_text: what was withheld is ordinary text now.
+ if sequences and not stopped:
+ delta = sampled[released:]
+ if normalizer is not None:
+ delta = normalizer.feed(delta)
+ if delta:
+ yield delta
if normalizer is not None:
- cancelled = cancel_event is not None and cancel_event.is_set()
+ # As in _generate_text: a sequence closes the block it cut inside.
+ cancelled = not stopped and cancel_event is not None and cancel_event.is_set()
tail = normalizer.drain() if cancelled else normalizer.finish()
if tail:
yield tail
+ if stopped:
+ self._mark_stopped()
def generate_with_adapter_control(
self,
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 4429d2afbd1..c1251b5d101 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -155,6 +155,59 @@ class GenStreamErrorRaised(RuntimeError):
self.public = bool(public)
+def _summed_tool_loop_stats(total, turn):
+ """Fold one tool-loop turn's report into the loop's running total.
+
+ Every turn spends its tokens on the same request, so the reply reports their
+ sum, as the llama.cpp tool loop does; reporting only the last turn hides the
+ tokens that produced the tool call. The prompt count is the last turn's to
+ report one, which already contains the tool results the earlier turns produced.
+ """
+ if not isinstance(turn, dict):
+ return total
+ if not isinstance(total, dict):
+ return turn
+ prior_usage = total.get("usage") or {}
+ usage = dict(turn.get("usage") or {})
+ completion = (usage.get("completion_tokens") or 0) + (prior_usage.get("completion_tokens") or 0)
+ usage["completion_tokens"] = completion
+ # The prompt is the loop's, not one turn's, so a turn that ended before
+ # reporting keeps the last count that arrived. Its details describe that same
+ # count and move with it, or cached tokens could outnumber prompt tokens.
+ if not usage.get("prompt_tokens"):
+ usage["prompt_tokens"] = prior_usage.get("prompt_tokens") or 0
+ usage.pop("prompt_tokens_details", None)
+ if prior_usage.get("prompt_tokens_details") is not None:
+ usage["prompt_tokens_details"] = prior_usage["prompt_tokens_details"]
+ usage["total_tokens"] = usage["prompt_tokens"] + completion
+ # Details describe the completion, so they sum with it rather than describing
+ # one turn against every turn's tokens.
+ details = dict(prior_usage.get("completion_tokens_details") or {})
+ for field, value in (usage.get("completion_tokens_details") or {}).items():
+ details[field] = (details.get(field) or 0) + (value or 0)
+ if details:
+ usage["completion_tokens_details"] = details
+ summed = dict(turn)
+ summed["usage"] = usage
+ timings = dict(turn.get("timings") or {})
+ prior = total.get("timings") or {}
+ # Seeded from the turn but folded unconditionally, as the llama.cpp loop does:
+ # a turn reporting no timings must not take the loop's totals with it.
+ if timings or prior:
+ for field in ("predicted_ms", "predicted_n"):
+ timings[field] = (timings.get(field) or 0) + (prior.get(field) or 0)
+ # Rates describe the totals above, not the turn they arrived with: leaving
+ # the last turn's would report a speed the summed counts contradict.
+ predicted_ms = timings.get("predicted_ms") or 0
+ predicted_n = timings.get("predicted_n") or 0
+ timings["predicted_per_token_ms"] = (predicted_ms / predicted_n) if predicted_n else 0.0
+ timings["predicted_per_second"] = (
+ (predicted_n / (predicted_ms / 1000.0)) if predicted_ms else 0.0
+ )
+ summed["timings"] = timings
+ return summed
+
+
class InferenceOrchestrator:
"""
Inference backend orchestrator — subprocess-based.
@@ -744,6 +797,10 @@ class InferenceOrchestrator:
preserve_thinking: Optional[bool] = None,
continue_final_message: bool = False,
presence_penalty: float = 0.0,
+ seed: Optional[int] = None,
+ frequency_penalty: float = 0.0,
+ logit_bias: Optional[dict] = None,
+ stop: Optional[list] = None,
) -> dict:
"""Build the 'generate' command shared by the locked and dispatched paths."""
cmd = {
@@ -759,7 +816,13 @@ class InferenceOrchestrator:
"max_new_tokens": max_new_tokens,
"repetition_penalty": repetition_penalty,
"presence_penalty": presence_penalty,
+ "frequency_penalty": frequency_penalty,
+ "logit_bias": logit_bias,
}
+ if seed is not None:
+ cmd["seed"] = seed
+ if stop:
+ cmd["stop"] = stop
# Only forward template kwargs the caller set, for older worker compat.
if use_adapter is not None:
cmd["use_adapter"] = use_adapter
@@ -979,6 +1042,10 @@ class InferenceOrchestrator:
continue_final_message: bool = False,
stats_holder: Optional[dict] = None,
presence_penalty: float = 0.0,
+ seed: Optional[int] = None,
+ frequency_penalty: float = 0.0,
+ logit_bias: Optional[dict] = None,
+ stop: Optional[list] = None,
) -> Generator[str, None, None]:
"""Dispatched generation — sends command without holding _gen_lock.
@@ -1036,12 +1103,16 @@ class InferenceOrchestrator:
max_new_tokens = max_new_tokens,
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
+ stop = stop,
use_adapter = use_adapter,
tools = tools,
enable_thinking = enable_thinking,
reasoning_effort = reasoning_effort,
preserve_thinking = preserve_thinking,
continue_final_message = continue_final_message,
+ seed = seed,
)
# Create the mailbox BEFORE sending, rechecking _unload_pending under
@@ -1708,6 +1779,10 @@ class InferenceOrchestrator:
continue_final_message: bool = False,
stats_holder: Optional[dict] = None,
presence_penalty: float = 0.0,
+ seed: Optional[int] = None,
+ frequency_penalty: float = 0.0,
+ logit_bias: Optional[dict] = None,
+ stop: Optional[list] = None,
) -> Generator[str, None, None]:
"""Generate response, streaming tokens from subprocess.
@@ -1716,7 +1791,8 @@ class InferenceOrchestrator:
schemas and reasoning controls.
``stats_holder``: caller-owned dict; on gen_done its "stats" key gets
- the worker's usage/timings. Request-scoped to avoid cross-stream reads.
+ the worker's usage, timings and terminal reason. Request-scoped to avoid
+ cross-stream reads.
``presence_penalty`` matches the GGUF sampling path (0 disables it).
"""
@@ -1739,6 +1815,10 @@ class InferenceOrchestrator:
continue_final_message = continue_final_message,
stats_holder = stats_holder,
presence_penalty = presence_penalty,
+ seed = seed,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
+ stop = stop,
)
def generate_chat_completion_with_tools(
@@ -1770,7 +1850,11 @@ class InferenceOrchestrator:
use_adapter: Optional[Union[bool, str]] = None,
stats_holder: Optional[dict] = None,
presence_penalty: float = 0.0,
+ frequency_penalty: float = 0.0,
+ logit_bias: Optional[dict] = None,
+ stop: Optional[list] = None,
reasoning_prefilled: bool = False,
+ seed: Optional[int] = None,
**_unused,
):
"""Run the safetensors agentic tool loop in the parent process,
@@ -1789,6 +1873,7 @@ class InferenceOrchestrator:
# run_safetensors_tool_loop drop one-shot tools (e.g. render_html) from
# later same-response prompts.
turn_tools = active_tools if active_tools is not None else tools
+ turn_stats: dict = {}
common_kwargs = dict(
messages = conv,
system_prompt = "",
@@ -1807,9 +1892,14 @@ class InferenceOrchestrator:
# Self-limiting: after a tool call the conversation ends on a tool
# result, so later turns render as ordinary new turns.
continue_final_message = continue_final_message,
- # last turn wins, like the GGUF tool loop
- stats_holder = stats_holder,
+ # Reported per turn and summed below, since the whole loop answers
+ # one request.
+ stats_holder = turn_stats,
presence_penalty = presence_penalty,
+ seed = seed,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
+ stop = stop,
)
if use_adapter is not None:
stream = self.generate_with_adapter_control(
@@ -1833,6 +1923,12 @@ class InferenceOrchestrator:
close()
except Exception:
logger.debug("failed to close errored generation stream", exc_info = True)
+ # A turn that never reported -- one a cancel interrupted -- folds in
+ # as nothing, leaving the turns that did.
+ if stats_holder is not None:
+ stats_holder["stats"] = _summed_tool_loop_stats(
+ stats_holder.get("stats"), turn_stats.get("stats")
+ )
initial = list(messages)
if system_prompt:
@@ -1936,6 +2032,10 @@ class InferenceOrchestrator:
continue_final_message: bool = False,
stats_holder: Optional[dict] = None,
presence_penalty: float = 0.0,
+ seed: Optional[int] = None,
+ frequency_penalty: float = 0.0,
+ logit_bias: Optional[dict] = None,
+ stop: Optional[list] = None,
) -> Generator[str, None, None]:
"""Inner generation logic — sends command to subprocess, yields tokens.
@@ -1985,12 +2085,16 @@ class InferenceOrchestrator:
max_new_tokens = max_new_tokens,
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
+ frequency_penalty = frequency_penalty,
+ logit_bias = logit_bias,
+ stop = stop,
use_adapter = use_adapter,
tools = tools,
enable_thinking = enable_thinking,
reasoning_effort = reasoning_effort,
preserve_thinking = preserve_thinking,
continue_final_message = continue_final_message,
+ seed = seed,
)
# Claim the worker BEFORE sending, so a Stop on some OTHER chat -- still queued on the
@@ -2297,6 +2401,7 @@ class InferenceOrchestrator:
use_adapter: Optional[Union[bool, str]] = None,
cancel_event = None,
stats_holder: Optional[dict] = None,
+ stop = None,
) -> Generator[str, None, None]:
"""Audio input generation (e.g. Gemma 3n) — streams text tokens."""
yield from self._generate_audio_input_inner(
@@ -2313,6 +2418,7 @@ class InferenceOrchestrator:
use_adapter = use_adapter,
cancel_event = cancel_event,
stats_holder = stats_holder,
+ stop = stop,
)
def _generate_audio_input_inner(
@@ -2330,6 +2436,7 @@ class InferenceOrchestrator:
use_adapter: Optional[Union[bool, str]] = None,
cancel_event = None,
stats_holder: Optional[dict] = None,
+ stop = None,
) -> Generator[str, None, None]:
"""Shared inner logic for audio input generation (Whisper + ASR).
@@ -2378,6 +2485,8 @@ class InferenceOrchestrator:
# As in the text path: key stays absent unless the caller selected one.
if use_adapter is not None:
cmd["use_adapter"] = use_adapter
+ if stop:
+ cmd["stop"] = stop
# Same shared-queue hazard as _generate_inner: see _direct_reader.
read_one, drain, release_mailbox = self._direct_reader(request_id)
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index bc04fd1256c..8cd93e138af 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -727,6 +727,10 @@ def run_safetensors_tool_loop(
if not isinstance(cumulative, str):
continue # defensive: pipeline yields only strings
+ # Deltas by length: this needs snapshots that only grow. A producer that
+ # rebuilds its text each step can revise one instead, and diffing that
+ # splices two renderings together -- which is why the MLX text producer
+ # withholds while it is matching stop sequences.
delta = cumulative[len(prev_cumulative) :]
prev_cumulative = cumulative
if not delta:
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 9702f5babce..cf7d23e5738 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -13,6 +13,7 @@ mp.Queue, and exits on shutdown or unload. Pattern follows core/training/worker.
from __future__ import annotations
import base64
+import inspect
import json
from loggers import get_logger
import os
@@ -572,6 +573,27 @@ def _prepare_generate_audio(cmd, resp_queue: Any, cancel_event, drain_event) ->
return True
+def _backend_declares(
+ backend,
+ name: str,
+ method: str = "generate_chat_response",
+) -> bool:
+ """Whether this backend's *method* declares *name*.
+
+ A signature check, not a capability claim: a backend honoring the option
+ through **kwargs would read as False here. That is accurate for the backends
+ that ship today, and failing closed costs the option -- an ignored seed, or
+ a request sampled without its penalty -- never a crash.
+ """
+ generate = getattr(backend, method, None)
+ if generate is None:
+ return False
+ try:
+ return name in inspect.signature(generate).parameters
+ except (TypeError, ValueError):
+ return False
+
+
def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
"""Handle a generate command: stream tokens back via resp_queue.
@@ -612,6 +634,13 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
if opt_key in cmd:
gen_kwargs[opt_key] = cmd[opt_key]
+ # These options are MLX-only. The transformers backend declares none of
+ # them and takes no **kwargs, so forwarding unconditionally would turn
+ # its documented "ignores them" behavior into a TypeError.
+ for gated in ("seed", "frequency_penalty", "logit_bias", "stop"):
+ if gated in cmd and _backend_declares(backend, gated):
+ gen_kwargs[gated] = cmd[gated]
+
use_adapter = cmd.get("use_adapter")
if use_adapter is not None:
generator = backend.generate_with_adapter_control(
@@ -813,6 +842,11 @@ def _handle_generate_audio_input(backend, cmd: dict, resp_queue: Any, cancel_eve
use_adapter = cmd.get("use_adapter")
if use_adapter is not None:
audio_kwargs["use_adapter"] = use_adapter
+ # MLX-only here too, for the reason the text branch gates it.
+ if "stop" in cmd and _backend_declares(
+ backend, "stop", "generate_audio_input_response"
+ ):
+ audio_kwargs["stop"] = cmd["stop"]
generator = backend.generate_audio_input_response(**audio_kwargs)
logger.info("Starting audio input generation for request_id=%s", request_id)
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 05f865706a3..430fbfa82b6 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1583,11 +1583,50 @@ class ChatCompletionRequest(BaseModel):
max_tokens: Optional[int] = Field(
None, ge = 1, description = "Maximum tokens to generate (None = until EOS)"
)
- presence_penalty: float = Field(0.0, ge = 0.0, le = 2.0, description = "Presence penalty")
+ # OpenAI's documented range is [-2, 2] on both penalties. Widening only
+ # admits requests that used to be rejected, so nothing that works today
+ # changes. A negative value boosts repetition wherever the backend applies
+ # the penalty at all.
+ presence_penalty: float = Field(
+ 0.0,
+ ge = -2.0,
+ le = 2.0,
+ description = (
+ "Presence penalty: charges a token once if it appears. MLX scores the completion"
+ " only; llama-server also counts the prompt, within its own window."
+ ),
+ )
+ frequency_penalty: float = Field(
+ 0.0,
+ ge = -2.0,
+ le = 2.0,
+ description = (
+ "Frequency penalty: charges a token per occurrence. MLX scores the completion"
+ " only; llama-server also counts the prompt, within its own window."
+ ),
+ )
+ # Ids are not range-checked here: MLX bounds-checks nothing either, so a
+ # stray is dropped at the processors rather than failing the request.
+ logit_bias: Optional[Dict[int, Annotated[float, Field(ge = -100.0, le = 100.0)]]] = Field(
+ None,
+ description = "Additive per-token logit bias keyed by token id, each in [-100, 100]. Ids past the model's logit width are ignored.",
+ )
stop: Optional[Union[str, list[str]]] = Field(
None,
description = "OpenAI stop sequences: a single string or list of strings at which generation halts.",
)
+ # Declared rather than left to model_extra so the schema documents it and a
+ # backend that cannot constrain decoding can refuse it by name.
+ response_format: Optional[Dict[str, Any]] = Field(
+ None,
+ description = (
+ 'Guided decoding contract, typically `{"type": "json_object"}` or'
+ ' a `json_schema`. `{"type": "text"}` names the default and'
+ " constrains nothing. Anything else needs a grammar engine, and a"
+ " backend without one rejects the request rather than answering text"
+ " that ignores the contract."
+ ),
+ )
tools: Optional[list[dict]] = Field(
None,
description = (
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 466f1ff4900..7efcdef055a 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -72,6 +72,7 @@ from core.inference.orchestrator import (
AUDIO_GENERATION_MAX_TOKENS,
GenStreamError,
GenStreamErrorRaised,
+ _summed_tool_loop_stats,
)
from core.inference.llama_admission import (
LlamaAdmissionCancelled,
@@ -582,8 +583,43 @@ def _raise_unsupported_openai_parameter(param: str, message: str) -> None:
)
-def _raise_unsupported_n(path_label: str) -> None:
- _raise_unsupported_openai_parameter("n", f"n > 1 is not supported for {path_label}.")
+def _choice_seed(
+ seed: Optional[int],
+ choice_index: int,
+ *,
+ negative_is_random: bool = False,
+) -> Optional[int]:
+ """A seed of its own per choice, so a seeded request samples n times rather
+ than repeating one run. Shared by both drains so they cannot disagree.
+
+ llama-server holds the seed as a uint32 and draws at random for exactly one
+ value, LLAMA_DEFAULT_SEED (0xFFFFFFFF); ``-1`` is the only request seed that
+ converts to it, and offsetting that would make every choice after the first
+ deterministic. Every other negative is an ordinary fixed seed there, so it
+ must be offset like any other or all n choices repeat one run. The offset is
+ taken in that same uint32 domain, so a shifted seed cannot land on the
+ sentinel and turn one choice random. MLX maps every seed onto its key domain
+ instead, so nothing is exempt on that side.
+ """
+ if seed is None or not choice_index:
+ return seed
+ if not negative_is_random:
+ return seed + choice_index
+ if seed == -1:
+ return seed
+ return ((seed & 0xFFFFFFFF) + choice_index) % 0xFFFFFFFF
+
+
+def _raise_unsupported_n(path_label: str, monitor_id: Optional[str] = None) -> None:
+ """Refuse n > 1 on a path that cannot sample twice.
+
+ Pass the monitor row when one is already open, or Studio keeps reporting a
+ generation that was refused before it began.
+ """
+ message = f"n > 1 is not supported for {path_label}."
+ if monitor_id:
+ api_monitor.fail(monitor_id, message)
+ _raise_unsupported_openai_parameter("n", message)
def _sse_streaming_response(content, *, unstarted_cleanup = None) -> StreamingResponse:
@@ -1173,13 +1209,16 @@ def _chat_final_chunk(completion_id, created, model_name, finish_reason) -> str:
def _stats_finish_reason(stats, default: str = "stop") -> str:
"""``"length"`` when the backend reports the turn ran out of token budget.
- Only the in-process backends fill ``truncated``. llama-server and MLX report their
- own finish reason and never set it, so they keep ``default``, as does a backend
- shipping no stats at all.
+ A backend that names its own reason is believed: MLX decides between a stop
+ token and exhaustion from the last token it sampled, which a count at the cap
+ cannot distinguish. The in-process backends instead fill ``truncated``, and a
+ backend reporting neither keeps ``default``.
"""
- if isinstance(stats, dict) and stats.get("truncated"):
- return "length"
- return default
+ if not isinstance(stats, dict):
+ return default
+ if stats.get("finish_reason") in ("stop", "length"):
+ return stats["finish_reason"]
+ return "length" if stats.get("truncated") else default
def _chat_tool_calls_chunk(completion_id, created, model_name, tool_calls) -> str:
@@ -3081,13 +3120,14 @@ def _tools_on_by_launcher_default_only(payload) -> bool:
def _request_states_tool_intent(payload) -> bool:
"""True when a request states its own tool intent through the standard
OpenAI fields: a `tool_choice: "none"` withdrawal, its own tool catalog,
- tool-result history to continue, or a `response_format` contract the tool
- loop would break. Such a request did not omit the question, so the launcher
- default must not answer it.
-
- Mirrors what `_takes_tool_passthrough` already withholds from the policy on
- the GGUF router, including its `bool(payload.tools)` reading of the catalog:
- an empty `tools: []` reads the same as an omitted one on both paths."""
+ tool-result history to continue, or a `response_format` of any kind. Such a
+ request did not omit the question, so the launcher default must not answer it.
+
+ Wider than what `_takes_tool_passthrough` does with the same field, and
+ deliberately: the router asks whether decoding must be constrained, while a
+ client that named an output contract at all has said enough about the reply
+ for a launcher default not to reshape it. Both read the catalog the same way,
+ so an empty `tools: []` reads as omitted on either path."""
if getattr(payload, "tool_choice", None) == "none":
return True
if payload.tools:
@@ -3230,7 +3270,10 @@ def _takes_tool_passthrough(payload, llama_backend) -> bool:
supports_passthrough = getattr(llama_backend, "supports_tool_passthrough", supports_tools)
if supports_passthrough and has_client_contract:
return True
- return _extract_response_format(payload) is not None
+ # Only a format that constrains decoding needs llama-server's grammar engine.
+ # `{"type": "text"}` names the default, so routing it here would withdraw
+ # whatever the ordinary path offers -- n > 1 among them -- for nothing.
+ return _response_format_constrains_decoding(payload)
def _passthrough_client_tools(payload):
@@ -15005,8 +15048,10 @@ async def openai_chat_completions(
# A JSON-schema response_format is guided-decoding structured output the
# router forwards to the llama-server passthrough, not Unsloth's tool
# loop, so a --enable-tools policy must not 400 it as a local-confirm
- # request under ask/auto.
- or bool(_extract_response_format(payload))
+ # request under ask/auto. Read with the predicate the router itself
+ # uses, so this gate cannot admit a request the router then rejects
+ # after a model switch, nor reject one the router would have served.
+ or _response_format_constrains_decoding(payload)
)
# permission_mode only implies the confirm gate for that local loop.
# Client-tool passthrough forwards to the provider branch and the validator
@@ -15157,6 +15202,10 @@ async def openai_chat_completions(
api_monitor.finish(tts_monitor_id)
return response
+ # Above the backend branch, because audio input returns from inside it and must
+ # read the same normalized sequences the text paths do.
+ normalized_stop = _normalize_stop_sequences(payload.stop)
+
if using_gguf:
# Advertised repo id after an auto-switch load, else a clean public id,
# never the absolute .gguf path.
@@ -15164,6 +15213,14 @@ async def openai_chat_completions(
if getattr(llama_backend, "_is_audio", False):
if _wants_multiple_choices(payload):
_raise_unsupported_n("GGUF audio chat completions")
+ if _response_format_constrains_decoding(payload):
+ # This branch returns before the routing that decides a contract's
+ # fate, and no grammar can constrain a waveform, so it refuses here.
+ _raise_unsupported_openai_parameter(
+ "response_format",
+ "response_format cannot be honored by an audio reply; send the "
+ "request to a text model to use guided decoding.",
+ )
_reject_audio_output_continuation(payload)
return await _monitored_generate_audio(
model_name,
@@ -15182,17 +15239,28 @@ async def openai_chat_completions(
# Clean public id so the response never echoes a local path; the audio
# branch below receives this sanitized label too.
model_name = public_model_id(backend.active_model_name) or payload.model
- if _wants_multiple_choices(payload):
- _raise_unsupported_n("non-GGUF chat completions")
+ # Restated here because the pre-switch check runs only when an automatic
+ # load may: one SSE stream carries a single choice either way.
+ if payload.stream and _wants_multiple_choices(payload):
+ _raise_unsupported_n("streaming chat completions")
+ if _response_format_constrains_decoding(payload):
+ _raise_unsupported_openai_parameter(
+ "response_format",
+ "response_format needs the llama.cpp grammar engine; load a GGUF model to use it.",
+ )
# ── Audio TTS path: auto-route to audio generation ────
# (Whisper is ASR not TTS -- handled below in audio input path)
model_info = backend.models.get(backend.active_model_name, {})
if model_info.get("is_audio") and model_info.get("audio_type") != "whisper":
+ if _wants_multiple_choices(payload):
+ _raise_unsupported_n("non-GGUF audio chat completions")
_reject_audio_output_continuation(payload)
return await _monitored_generate_audio(model_name)
# ── Whisper without audio: return clear error ──
+ if payload.audio_base64 and _wants_multiple_choices(payload):
+ _raise_unsupported_n("non-GGUF audio-input chat completions")
if model_info.get("audio_type") == "whisper" and not payload.audio_base64:
raise HTTPException(
status_code = 400,
@@ -15260,6 +15328,7 @@ async def openai_chat_completions(
use_adapter = payload.use_adapter,
cancel_event = cancel_event,
stats_holder = _audio_stats_holder,
+ stop = normalized_stop,
)
if payload.stream:
@@ -15395,6 +15464,7 @@ async def openai_chat_completions(
)
api_monitor.set_perf(monitor_id, stop_reason = _audio_json_finish)
api_monitor.finish(monitor_id)
+ _audio_usage = (_audio_json_stats or {}).get("usage") or {}
response = ChatCompletion(
id = completion_id,
created = created,
@@ -15405,6 +15475,18 @@ async def openai_chat_completions(
finish_reason = _audio_json_finish,
)
],
+ usage = CompletionUsage(
+ prompt_tokens = _audio_usage.get("prompt_tokens") or 0,
+ completion_tokens = _audio_usage.get("completion_tokens") or 0,
+ total_tokens = (
+ _audio_usage.get("total_tokens")
+ or (_audio_usage.get("prompt_tokens") or 0)
+ + (_audio_usage.get("completion_tokens") or 0)
+ ),
+ prompt_tokens_details = _prompt_tokens_details(
+ _audio_usage.get("prompt_tokens_details")
+ ),
+ ),
)
return _model_json_response(response)
@@ -15469,8 +15551,6 @@ async def openai_chat_completions(
# multi-turn client-side tool loops.
effective_max_tokens = _effective_openai_max_tokens(payload)
- normalized_stop = _normalize_stop_sequences(payload.stop)
-
_has_tool_messages = _has_openai_tool_history(payload.messages)
_has_tool_catalog = bool(payload.tools and len(payload.tools) > 0)
_has_active_tool_catalog = _has_tool_catalog and payload.tool_choice != "none"
@@ -15751,6 +15831,22 @@ async def openai_chat_completions(
if not tools_to_use:
use_tools = False
+ if _response_format_constrains_decoding(payload):
+ # Only an explicit request for Unsloth's tool loop reaches here with a
+ # contract; every other GGUF request took the passthrough above. Neither
+ # the loop nor the generator below forwards one, so serving it would
+ # answer with text that violates it silently.
+ raise _reject(
+ 400,
+ openai_error_body(
+ "response_format is not supported with Unsloth tool execution; "
+ "send the request without enable_tools to use guided decoding.",
+ status = 400,
+ code = "unsupported_parameter",
+ param = "response_format",
+ ),
+ )
+
if use_tools:
# permission_mode ask/auto require the confirm gate for Unsloth's own
# tool loop. The request validator self-enables confirm only for
@@ -15843,6 +15939,8 @@ async def openai_chat_completions(
max_tokens = effective_max_tokens,
repetition_penalty = payload.repetition_penalty,
presence_penalty = payload.presence_penalty,
+ frequency_penalty = payload.frequency_penalty,
+ logit_bias = payload.logit_bias,
stop = normalized_stop,
cancel_event = cancel_event,
seed = payload.seed,
@@ -16554,9 +16652,7 @@ async def openai_chat_completions(
# ── Standard GGUF path (no tools) ─────────────────────
def gguf_generate(choice_index: int = 0):
- _seed = payload.seed
- if _seed is not None and _seed >= 0 and choice_index:
- _seed += choice_index
+ _seed = _choice_seed(payload.seed, choice_index, negative_is_random = True)
return llama_backend.generate_chat_completion(
messages = gguf_messages,
image_b64 = image_b64,
@@ -16567,6 +16663,8 @@ async def openai_chat_completions(
max_tokens = effective_max_tokens,
repetition_penalty = payload.repetition_penalty,
presence_penalty = payload.presence_penalty,
+ frequency_penalty = payload.frequency_penalty,
+ logit_bias = payload.logit_bias,
stop = normalized_stop,
cancel_event = cancel_event,
enable_thinking = payload.enable_thinking,
@@ -17374,6 +17472,9 @@ async def openai_chat_completions(
if not _sf_tools_to_use:
_sf_use_tools = False
+ if _sf_use_tools and _wants_multiple_choices(payload):
+ _raise_unsupported_n("non-GGUF tool chat completions", monitor_id)
+
if _sf_use_tools:
# permission_mode ask/auto require the confirm gate for Unsloth's own tool
# loop; when a CLI policy (--enable-tools) forces the loop on without a
@@ -17462,6 +17563,10 @@ async def openai_chat_completions(
max_tokens = effective_max_tokens,
repetition_penalty = payload.repetition_penalty,
presence_penalty = payload.presence_penalty,
+ seed = payload.seed,
+ frequency_penalty = payload.frequency_penalty,
+ logit_bias = payload.logit_bias,
+ stop = normalized_stop,
cancel_event = cancel_event,
enable_thinking = payload.enable_thinking,
reasoning_effort = payload.reasoning_effort,
@@ -17630,9 +17735,10 @@ async def openai_chat_completions(
for _c in _sf_flush_reasoning():
yield _c
- # Usage chunk from the last turn, same shape as the
- # GGUF tool loop's metadata. Request-scoped holder, so
- # concurrent streams cannot read each other's stats.
+ # Usage chunk for the whole loop, same shape as the GGUF tool
+ # loop's metadata: every turn's tokens, the last turn's prompt.
+ # Request-scoped holder, so concurrent streams cannot read each
+ # other's stats. A cancelled stream reports the turns that finished.
_stats = _sf_stats_holder.get("stats")
# The last turn's own budget decides: an earlier turn stopping at the
# cap does not truncate the answer this one went on to write.
@@ -17773,6 +17879,7 @@ async def openai_chat_completions(
_sf_msg_kwargs = {"content": _visible_text}
if _reasoning_text:
_sf_msg_kwargs["reasoning_content"] = _reasoning_text
+ _sf_usage = (_stats or {}).get("usage") or {}
response = ChatCompletion(
id = completion_id,
created = created,
@@ -17783,6 +17890,18 @@ async def openai_chat_completions(
finish_reason = _sf_json_finish,
)
],
+ usage = CompletionUsage(
+ prompt_tokens = _sf_usage.get("prompt_tokens") or 0,
+ completion_tokens = _sf_usage.get("completion_tokens") or 0,
+ total_tokens = (
+ _sf_usage.get("total_tokens")
+ or (_sf_usage.get("prompt_tokens") or 0)
+ + (_sf_usage.get("completion_tokens") or 0)
+ ),
+ prompt_tokens_details = _prompt_tokens_details(
+ _sf_usage.get("prompt_tokens_details")
+ ),
+ ),
)
return _model_json_response(response)
except asyncio.CancelledError:
@@ -17823,6 +17942,10 @@ async def openai_chat_completions(
max_new_tokens = effective_max_tokens or 2048,
repetition_penalty = payload.repetition_penalty,
presence_penalty = payload.presence_penalty,
+ seed = payload.seed,
+ frequency_penalty = payload.frequency_penalty,
+ logit_bias = payload.logit_bias,
+ stop = normalized_stop,
)
# Forward reasoning kwargs; the worker/template wrapper peels off any the
# template doesn't accept.
@@ -17943,12 +18066,14 @@ async def openai_chat_completions(
if payload.use_adapter is not None:
- def generate(messages_override = None):
+ def generate(messages_override = None, choice_index = 0):
kw = (
gen_kwargs
if messages_override is None
else {**gen_kwargs, "messages": messages_override}
)
+ if choice_index:
+ kw = {**kw, "seed": _choice_seed(payload.seed, choice_index)}
return backend.generate_with_adapter_control(
use_adapter = payload.use_adapter,
cancel_event = cancel_event,
@@ -17957,12 +18082,14 @@ async def openai_chat_completions(
)
else:
- def generate(messages_override = None):
+ def generate(messages_override = None, choice_index = 0):
kw = (
gen_kwargs
if messages_override is None
else {**gen_kwargs, "messages": messages_override}
)
+ if choice_index:
+ kw = {**kw, "seed": _choice_seed(payload.seed, choice_index)}
return backend.generate_chat_response(
cancel_event = cancel_event,
stats_holder = stats_holder,
@@ -18198,105 +18325,144 @@ async def openai_chat_completions(
_tracker = _TrackedCancel.for_payload(cancel_event, payload, *_cancel_keys)
_tracker.__enter__()
try:
-
- def _drain_generate(messages_override = None):
+ _n = payload.n or 1
+ _choices = []
+ _monitor_replies = []
+ _prompt_tokens = 0
+ _sum_completion = 0
+ _prompt_details = None
+ _last_stats = None
+
+ def _drain_generate(messages_override = None, choice_index = 0):
final = ""
- for token in generate(messages_override):
+ for token in generate(messages_override, choice_index = choice_index):
if isinstance(token, GenStreamError):
return token
final = token
return final
- full_text = await _run_blocking_generation(
- _drain_generate,
- cancel_event,
- name = "openai-chat-nonstream",
- )
- if isinstance(full_text, GenStreamError):
- backend.reset_generation_state(cancel_event)
- _msg = _friendly_gen_stream_error(full_text)
- api_monitor.fail(monitor_id, _msg)
- raise HTTPException(status_code = 500, detail = _msg)
-
- # Split prefilled <think> reasoning (GGUF parity); also covers MLX via
- # the shared generate(). Client-tool healing then runs on the visible
- # text so tool markup inside a reasoning block is never promoted.
- _reasoning_text, _visible_text = _extract_responses_reasoning(
- full_text,
- parse_think_markers = _sf_parse_think,
- reasoning_prefilled = _sf_reasoning_prefilled and not _sf_continue,
- )
- # Client-tool passthrough: promote text-form calls; opt-in single
- # nudge retry on unparseable tool markup.
- _msg = {"role": "assistant", "content": _visible_text}
- if _reasoning_text:
- _msg["reasoning_content"] = _reasoning_text
- # Budget exhaustion unless a heal below promotes a tool call; a cancelled turn
- # stopped on request, not at the cap, so it stays "stop".
- _finish = (
- "stop" if cancel_event.is_set() else _stats_finish_reason(stats_holder.get("stats"))
- )
- if _sf_heal:
- if heal_openai_message(_msg, _sf_heal, _sf_healing_tools):
- _finish = "tool_calls"
- elif nudge_enabled(payload.nudge_tool_calls):
- _data = {
- "choices": [{"message": {"role": "assistant", "content": _visible_text}}]
- }
- if nudge_should_retry(_data, _sf_heal, _sf_healing_tools):
- # A failed retry must not 500 the request; keep the first
- # response (GGUF nudge parity). The retry's generate()
- # overwrites stats_holder, so save the first attempt's stats
- # and restore them if the retry is discarded.
- _first_stats = stats_holder.get("stats")
- try:
- retry_messages = [
- *gen_kwargs["messages"],
- *nudge_messages(_data, _sf_heal),
+ async def _one_choice(choice_index):
+ """One sampled answer, healing and nudge retry included.
+
+ A full generation of its own -- its own seed, its own stats --
+ exactly as the llama-server path drains its own ``n``.
+ """
+ # Cleared per choice: one cancelled before it publishes must report
+ # nothing rather than inherit the previous choice's token count.
+ stats_holder.pop("stats", None)
+ full_text = await _run_blocking_generation(
+ lambda: _drain_generate(choice_index = choice_index),
+ cancel_event,
+ name = "openai-chat-nonstream",
+ )
+ if isinstance(full_text, GenStreamError):
+ backend.reset_generation_state(cancel_event)
+ _msg = _friendly_gen_stream_error(full_text)
+ api_monitor.fail(monitor_id, _msg)
+ raise HTTPException(status_code = 500, detail = _msg)
+
+ # Split prefilled <think> reasoning (GGUF parity); also covers MLX via
+ # the shared generate(). Client-tool healing then runs on the visible
+ # text so tool markup inside a reasoning block is never promoted.
+ _reasoning_text, _visible_text = _extract_responses_reasoning(
+ full_text,
+ parse_think_markers = _sf_parse_think,
+ reasoning_prefilled = _sf_reasoning_prefilled and not _sf_continue,
+ )
+ # Client-tool passthrough: promote text-form calls; opt-in single
+ # nudge retry on unparseable tool markup.
+ _msg = {"role": "assistant", "content": _visible_text}
+ if _reasoning_text:
+ _msg["reasoning_content"] = _reasoning_text
+ # Budget exhaustion unless a heal below promotes a tool call; a cancelled turn
+ # stopped on request, not at the cap, so it stays "stop".
+ _finish = (
+ "stop"
+ if cancel_event.is_set()
+ else _stats_finish_reason(stats_holder.get("stats"))
+ )
+ if _sf_heal:
+ if heal_openai_message(_msg, _sf_heal, _sf_healing_tools):
+ _finish = "tool_calls"
+ elif nudge_enabled(payload.nudge_tool_calls):
+ _data = {
+ "choices": [
+ {"message": {"role": "assistant", "content": _visible_text}}
]
- retry_text = await _run_blocking_generation(
- lambda: _drain_generate(retry_messages),
- cancel_event,
- name = "openai-chat-nudge-nonstream",
- )
- # Re-split reasoning on the retry so its visible text is
- # what heals into a call (and reaches the monitor).
- # The nudge retry appends messages, so it is not a
- # continuation and normal prefill detection applies.
- _retry_reasoning, _retry_visible = _extract_responses_reasoning(
- retry_text,
- parse_think_markers = _sf_parse_think,
- reasoning_prefilled = _sf_reasoning_prefilled,
- )
- retry_msg = {"role": "assistant", "content": _retry_visible}
- if _retry_reasoning:
- retry_msg["reasoning_content"] = _retry_reasoning
- if heal_openai_message(retry_msg, _sf_heal, _sf_healing_tools):
- _visible_text, _msg, _finish = (
- _retry_visible,
- retry_msg,
- "tool_calls",
+ }
+ if nudge_should_retry(_data, _sf_heal, _sf_healing_tools):
+ # A failed retry must not 500 the request; keep the first
+ # response (GGUF nudge parity). Both attempts generated,
+ # so whichever loses is folded back in rather than
+ # dropped. Popped, not read: a retry that raises before
+ # publishing would leave its report indistinguishable
+ # from this one, and folding it into itself doubles the
+ # completion count.
+ _first_stats = stats_holder.pop("stats", None)
+ try:
+ retry_messages = [
+ *gen_kwargs["messages"],
+ *nudge_messages(_data, _sf_heal),
+ ]
+ retry_text = await _run_blocking_generation(
+ lambda: _drain_generate(
+ retry_messages, choice_index = choice_index
+ ),
+ cancel_event,
+ name = "openai-chat-nudge-nonstream",
)
- else:
- # Retry produced no healable call -> first response wins.
- stats_holder["stats"] = _first_stats
- except Exception as retry_exc:
- logger.debug(
- "Nudge retry failed; keeping first response: %s", retry_exc
- )
- stats_holder["stats"] = _first_stats
- # parallel_tool_calls=false: cap to one call (GGUF parity).
- if payload.parallel_tool_calls is False:
- _tcs = _msg.get("tool_calls")
- if isinstance(_tcs, list) and len(_tcs) > 1:
- _msg["tool_calls"] = _tcs[:1]
-
- response = ChatCompletion(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
+ # Re-split reasoning on the retry so its visible text is
+ # what heals into a call (and reaches the monitor).
+ # The nudge retry appends messages, so it is not a
+ # continuation and normal prefill detection applies.
+ _retry_reasoning, _retry_visible = _extract_responses_reasoning(
+ retry_text,
+ parse_think_markers = _sf_parse_think,
+ reasoning_prefilled = _sf_reasoning_prefilled,
+ )
+ retry_msg = {"role": "assistant", "content": _retry_visible}
+ if _retry_reasoning:
+ retry_msg["reasoning_content"] = _retry_reasoning
+ # The winning attempt's prompt is the one reported;
+ # the completions of both are summed.
+ if heal_openai_message(retry_msg, _sf_heal, _sf_healing_tools):
+ _visible_text, _msg, _finish = (
+ _retry_visible,
+ retry_msg,
+ "tool_calls",
+ )
+ stats_holder["stats"] = _summed_tool_loop_stats(
+ _first_stats, stats_holder.get("stats")
+ )
+ else:
+ # Retry produced no healable call -> first response wins.
+ stats_holder["stats"] = _summed_tool_loop_stats(
+ stats_holder.get("stats"), _first_stats
+ )
+ except Exception as retry_exc:
+ logger.debug(
+ "Nudge retry failed; keeping first response: %s", retry_exc
+ )
+ stats_holder["stats"] = _summed_tool_loop_stats(
+ stats_holder.get("stats"), _first_stats
+ )
+ # parallel_tool_calls=false: cap to one call (GGUF parity).
+ if payload.parallel_tool_calls is False:
+ _tcs = _msg.get("tool_calls")
+ if isinstance(_tcs, list) and len(_tcs) > 1:
+ _msg["tool_calls"] = _tcs[:1]
+ return _msg, _finish, stats_holder.get("stats")
+
+ for _idx in range(_n):
+ # Stop spawning the remaining choices once cancelled. Index 0 runs
+ # regardless, so a cancelled turn still answers with one choice
+ # rather than the empty `choices` a client indexes into.
+ if _idx and cancel_event.is_set():
+ break
+ _msg, _finish, _choice_stats = await _one_choice(_idx)
+ _choices.append(
CompletionChoice(
+ index = _idx,
message = CompletionMessage(
content = _msg["content"],
reasoning_content = _msg.get("reasoning_content"),
@@ -18304,29 +18470,72 @@ async def openai_chat_completions(
),
finish_reason = _finish,
)
- ],
+ )
+ _monitor_replies.append(_msg)
+ if _choice_stats:
+ _last_stats = _choice_stats
+ _choice_usage = _choice_stats.get("usage") or {}
+ # The prompt is shared across all n choices, so its tokens count
+ # ONCE; only generated tokens accumulate (llama-server parity).
+ if _choice_usage.get("prompt_tokens"):
+ _prompt_tokens = _choice_usage["prompt_tokens"]
+ # Details describe that same count, so they come from the
+ # choice that supplied it. Choosing them separately lets a
+ # reply report more cached tokens than prompt tokens, since
+ # the nudge rebuilds a longer prompt for some choices.
+ _prompt_details = _choice_usage.get("prompt_tokens_details")
+ _sum_completion += _choice_usage.get("completion_tokens") or 0
+ _msg, _finish = _monitor_replies[-1], _choices[-1].finish_reason
+
+ # Built once, so what the monitor is told below is this same object and
+ # cannot disagree with the body.
+ _usage = CompletionUsage(
+ prompt_tokens = _prompt_tokens,
+ completion_tokens = _sum_completion,
+ total_tokens = _prompt_tokens + _sum_completion,
+ prompt_tokens_details = _prompt_tokens_details(_prompt_details),
+ )
+ response = ChatCompletion(
+ id = completion_id,
+ created = created,
+ model = model_name,
+ choices = _choices,
+ usage = _usage,
)
- _monitor_reply = _msg.get("content") or ""
- if _finish == "tool_calls":
- _tcs = _msg.get("tool_calls") or []
+
+ def _reply_text(msg, finish):
+ _text = msg.get("content") or ""
+ if finish != "tool_calls":
+ return _text
_calls_text = "; ".join(
f"{(tc.get('function') or {}).get('name', '')}"
f"({(tc.get('function') or {}).get('arguments', '')})"
- for tc in _tcs
+ for tc in msg.get("tool_calls") or []
)
- _monitor_reply = (_msg.get("content") or "") + (
- f"[tool_calls] {_calls_text}" if _calls_text else ""
+ return _text + (f"[tool_calls] {_calls_text}" if _calls_text else "")
+
+ if len(_choices) > 1:
+ # Every choice, labelled, as the llama-server drain reports them:
+ # showing the last one alone would hide the rest of the turn.
+ _monitor_reply = "\n\n".join(
+ f"Choice {_i + 1}:\n{_reply_text(_reply, _choice.finish_reason)}"
+ for _i, (_reply, _choice) in enumerate(zip(_monitor_replies, _choices))
)
+ else:
+ _monitor_reply = _reply_text(_msg, _finish)
api_monitor.set_reply(monitor_id, _monitor_reply)
- # Reuse the response's finish_reason. Outside the stats block: a run
- # whose token count is unknown reports no stats.
- api_monitor.set_perf(monitor_id, stop_reason = _finish)
- _stats = stats_holder.get("stats")
- if _stats:
+ if len(_choices) <= 1:
+ # Outside the stats block, since a run with no token count still has
+ # a reason. Suppressed for n > 1: choices can end differently, and
+ # the last one's would describe the whole turn as uniformly that.
+ api_monitor.set_perf(monitor_id, stop_reason = _finish)
+ if _last_stats:
_monitor_usage(
monitor_id,
- _stats.get("usage"),
- timings = _stats.get("timings"),
+ _usage.model_dump(),
+ # Omitted for n > 1: the totals sum every choice while the
+ # timings describe only the last one, so they describe neither.
+ timings = _last_stats.get("timings") if len(_choices) <= 1 else None,
)
api_monitor.finish(monitor_id)
return _model_json_response(response)
@@ -19934,7 +20143,6 @@ def _build_chat_request(
response_format = _responses_text_format(payload.text)
if response_format is not None:
- # Lands in model_extra, where _extract_response_format reads it.
chat_kwargs["response_format"] = response_format
return ChatCompletionRequest(**chat_kwargs)
@@ -23280,6 +23488,8 @@ def _build_passthrough_payload(
min_p = None,
repetition_penalty = None,
presence_penalty = None,
+ frequency_penalty = None,
+ logit_bias = None,
tool_choice = "auto",
response_format = None,
chat_template_kwargs = None,
@@ -23336,6 +23546,12 @@ def _build_passthrough_payload(
body["repeat_penalty"] = repetition_penalty
if presence_penalty is not None:
body["presence_penalty"] = presence_penalty
+ if frequency_penalty is not None:
+ body["frequency_penalty"] = frequency_penalty
+ if logit_bias:
+ # llama-server's OpenAI endpoint takes the spec's {token id: bias}
+ # object (JSON stringifies the int keys) and ignores out-of-vocab ids.
+ body["logit_bias"] = logit_bias
if response_format is not None:
# llama-server applies a GBNF grammar derived from the JSON schema when
# response_format is present. The field is documented flat at the
@@ -24290,19 +24506,29 @@ async def _openai_messages_for_gguf_chat_async(payload, is_vision: bool) -> tupl
def _extract_response_format(payload):
- """Return the ``response_format`` field on an incoming ChatCompletionRequest
- (or None). The model uses ``extra="allow"`` so pydantic stashes unknown
- top-level fields in ``model_extra``; OpenAI-SDK clients spread ``extra_body``
- into the request body top level, where guided-decoding recipes park their
- JSON-schema response_format.
+ """The request's ``response_format``, or None if it named none.
+
+ Read by attribute rather than off the chat model's field, so a request type
+ that does not declare one is read the same way.
"""
- extra = getattr(payload, "model_extra", None)
- if not isinstance(extra, dict):
- return None
- rf = extra.get("response_format")
+ rf = getattr(payload, "response_format", None)
return rf if isinstance(rf, dict) else None
+def _response_format_constrains_decoding(payload) -> bool:
+ """Whether the request's ``response_format`` needs a grammar engine.
+
+ ``{"type": "text"}`` is the default spelled out, so it constrains nothing and a
+ backend without a grammar engine serves it exactly as it serves no field. That
+ exact object is the only one read that way: the field takes any object, and
+ anything else -- a type this build does not know, or a text format carrying
+ members it does not know -- is a contract the caller expects to be kept, so it
+ goes where such a contract can be answered or rejected rather than dropped.
+ """
+ rf = _extract_response_format(payload)
+ return isinstance(rf, dict) and rf != {"type": "text"}
+
+
def _build_openai_passthrough_body(
payload,
backend_ctx = None,
@@ -24346,6 +24572,8 @@ def _build_openai_passthrough_body(
min_p = payload.min_p,
repetition_penalty = payload.repetition_penalty,
presence_penalty = payload.presence_penalty,
+ frequency_penalty = payload.frequency_penalty,
+ logit_bias = payload.logit_bias,
tool_choice = tool_choice,
response_format = _extract_response_format(payload),
chat_template_kwargs = tpl_kwargs,
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index e6e35a68360..7df357212da 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -2929,6 +2929,183 @@ def test_a_vision_override_is_checked_even_when_the_native_render_needs_recovery
assert backend._processor.chat_template == "{{ native }}"
+# ── Per-request seed ────────────────────────────────────────────────
+
+
+def test_vlm_seed_rides_on_the_sampler_not_a_seed_kwarg(monkeypatch):
+ """The pinned mlx-vlm has no seed parameter, and a newer one ignores it at
+ Studio's default min_p/top_k -- so the seed must ride on the sampler, built
+ with the whole filtering chain the runtime would otherwise have built."""
+ from core.inference import mlx_inference
+ from core.inference.mlx_inference import MLXInferenceBackend
+
+ seen, built = [], []
+ mlx_vlm = types.ModuleType("mlx_vlm")
+ mlx_vlm.prompt_utils = SimpleNamespace(
+ MODEL_CONFIG = {}, apply_chat_template = lambda *_a, **_k: "<image> prompt"
+ )
+
+ def _vlm_stream(*_args, **kwargs):
+ seen.append(kwargs)
+ yield SimpleNamespace(text = "ok", prompt_tokens = 1, generation_tokens = 1)
+
+ mlx_vlm.stream_generate = _vlm_stream
+ monkeypatch.setitem(sys.modules, "mlx_vlm", mlx_vlm)
+ monkeypatch.setattr(
+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",
+ lambda *_a, **_k: "<image> prompt",
+ )
+ monkeypatch.setattr(
+ mlx_inference, "_temporary_mlx_adapter_state", lambda *_a, **_k: contextlib.nullcontext()
+ )
+ # Stubbed so the wiring is checked without an mlx wheel: what matters here is
+ # which seed and stages reach the builder, not the array maths inside it.
+ monkeypatch.setattr(
+ mlx_inference,
+ "_make_seeded_mlx_sampler",
+ lambda seed, **kw: built.append((seed, kw)) or (lambda _l: _l),
+ )
+ backend = MLXInferenceBackend()
+ backend._model = SimpleNamespace(config = {"model_type": "generic_vlm"})
+ backend._processor = SimpleNamespace(chat_template = "template")
+ args = (
+ [{"role": "user", "content": [{"type": "image"}]}],
+ object(),
+ 0.7,
+ 0.9,
+ 40,
+ 0.01,
+ 4,
+ 1.0,
+ None,
+ )
+
+ assert list(backend._generate_vlm(*args, seed = 4242)) == ["ok"]
+ assert callable(seen[-1]["sampler"]) and "seed" not in seen[-1]
+ assert built == [(4242, {"temp": 0.7, "top_p": 0.9, "top_k": 40, "min_p": 0.01})]
+ assert list(backend._generate_vlm(*args)) == ["ok"]
+ assert "sampler" not in seen[-1] and len(built) == 1
+
+
+ "factory_name, factory_args, vocab, sequence, expected",
+ [
+ # Frequency counts multiplicity where presence charges once.
+ (
+ "_make_mlx_frequency_penalty_processor",
+ (0.5,),
+ 20,
+ [10, 11, 5, 5, 5, 6, 99, -1],
+ {5: -1.5, 6: -0.5, 10: 0.0, 19: 0.0, 0: 0.0},
+ ),
+ # Bias is history-free, so it also applies on the prompt-only first call.
+ (
+ "_make_mlx_logit_bias_processor",
+ ({1: 4.0, 3: -2.5, 99: 100.0, -1: 100.0},),
+ 8,
+ [10, 11],
+ {1: 4.0, 3: -2.5, 0: 0.0, 7: 0.0},
+ ),
+ ],
+)
+def test_mlx_processors_penalize_in_range_ids_and_route_strays_away(
+ factory_name, factory_args, vocab, sequence, expected
+):
+ # MLX does no bounds checking, so a stray id is undefined behaviour.
+ mx = pytest.importorskip("mlx.core")
+ from core.inference import mlx_inference
+
+ proc = getattr(mlx_inference, factory_name)(*factory_args)
+ proc(mx.array([10, 11]), mx.zeros((1, vocab))) # first call latches prompt_len
+ out = proc(mx.array(sequence), mx.zeros((1, vocab)))
+ for token, value in expected.items():
+ assert float(out[0, token]) == pytest.approx(value), token
+
+
+ "model",
+ [
+ SimpleNamespace(config = {"model_type": "generic_vlm", "eos_token_id": [1, 2]}),
+ SimpleNamespace(config = SimpleNamespace(eos_token_id = [1, 2])),
+ SimpleNamespace(_config = {"eos_token_id": [1, 2]}),
+ SimpleNamespace(_config = SimpleNamespace(eos_token_id = [1, 2])),
+ SimpleNamespace(config = {"model_type": "g"}, _config = {"eos_token_id": [1, 2]}),
+ ],
+ ids = ["dict-config", "object-config", "dict-_config", "object-_config", "config-then-_config"],
+)
+def test_eos_ids_are_read_from_every_shape_a_config_arrives_in(model):
+ """A checkpoint's config is a dict on some models and an object on others,
+ under config or _config -- the spread _mlx_vlm_model_config already walks. A
+ getattr-only read silently fell through to the tokenizer, which is the source
+ the priority order exists to outrank, so an EOS sampled on the last allowed
+ token was reported as truncation."""
+ from core.inference.mlx_inference import _mlx_finish_reason, _mlx_stop_token_ids
+
+ tokenizer = SimpleNamespace(eos_token_id = 9) # disagrees with the config
+ stop_ids = _mlx_stop_token_ids(tokenizer, model)
+ assert stop_ids == (1, 2)
+ at_cap = SimpleNamespace(finish_reason = None, token = 2)
+ assert _mlx_finish_reason(at_cap, stop_ids, 10, 10) == "stop"
+
+
+def test_the_tokenizer_is_still_the_fallback_when_no_config_carries_eos():
+ from core.inference.mlx_inference import _mlx_stop_token_ids
+
+ tokenizer = SimpleNamespace(eos_token_id = 9)
+ assert _mlx_stop_token_ids(tokenizer, SimpleNamespace(config = {"model_type": "g"})) == (9,)
+ assert _mlx_stop_token_ids(tokenizer, None) == (9,)
+
+
+def test_finish_reason_separates_truncation_from_natural_end():
+ """At the limit the count alone is ambiguous -- a stop token sampled as the
+ final allowed token looks identical to exhaustion -- so the last token
+ decides, against the ids read from the source the runtime stops on. Those
+ sources disagree on real repos: Kimi-VL lists two config ids and a different
+ tokenizer id, and each may be a bare int (Qwen2-VL) rather than a list."""
+ from core.inference.mlx_inference import _mlx_finish_reason, _mlx_stop_token_ids
+
+ model = SimpleNamespace(config = SimpleNamespace(eos_token_id = [163584, 163586]))
+ ids = _mlx_stop_token_ids(SimpleNamespace(eos_token_ids = 163594), model)
+ assert ids == (163584, 163586)
+ assert _mlx_stop_token_ids(SimpleNamespace(eos_token_ids = 151645)) == (151645,)
+ assert _mlx_stop_token_ids(SimpleNamespace()) == ()
+ assert _mlx_finish_reason(SimpleNamespace(token = 5), ids, 3, 8) == "stop"
+ assert _mlx_finish_reason(SimpleNamespace(token = 5), ids, 8, 8) == "length"
+ assert _mlx_finish_reason(SimpleNamespace(token = 163584), ids, 8, 8) == "stop"
+
+
+# ── Stop sequences ──────────────────────────────────────────────────
+
+
+def test_stop_sequences_cut_the_reply_and_never_show_a_partial_match():
+ """The matcher decides how much of a reply may be shown: text that could still
+ grow into a sequence is held back, since a client cannot unsee a fragment the
+ next token completes."""
+ from core.inference.mlx_inference import _mlx_stop_cut
+
+ # Held back while it could still grow into "ab"; released once it cannot.
+ assert [_mlx_stop_cut(t, ["ab"]) for t in ("xa", "xac", "xab")] == [
+ (1, False),
+ (3, False),
+ (1, True),
+ ]
+ # A sequence at position 0 ends the turn with nothing shown.
+ assert _mlx_stop_cut("abc", ["a"]) == (0, True)
+ # The longest partial across all sequences wins; a shorter one cannot release it.
+ assert _mlx_stop_cut("aaAB", ["ABC", "BX"]) == (2, False)
+ # The earliest match ends the turn, whether one sequence matches twice or two
+ # sequences match in a different order than they were declared.
+ assert _mlx_stop_cut("a then a", ["a"]) == (0, True)
+ assert _mlx_stop_cut("early late", ["late", "early"]) == (0, True)
+ # An unresolved character is not a character yet: it can neither be shown nor
+ # complete a sequence, and dropping it can uncover the start of one. Only the
+ # trailing run is unresolved -- one the reply has already written past is text.
+ assert _mlx_stop_cut("hi\ufffd", ["END"]) == (2, False)
+ assert _mlx_stop_cut("a\ufffd", ["a"]) == (0, True)
+ assert _mlx_stop_cut("a\ufffd\ufffd", ["\ufffd"]) == (1, False)
+ assert _mlx_stop_cut("a\ufffdb", ["\ufffd"]) == (1, True)
+
+
def _fake_rng_state(monkeypatch, words):
from core.inference import mlx_inference
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 810e46d0686..c2a944204a3 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -375,20 +375,24 @@ class TestChatCompletionRequestToolFields:
assert req.stop is None
def test_extra_fields_accepted(self):
- # `frequency_penalty` and `response_format` are not yet explicitly
- # declared but must survive Pydantic parsing now that extra="allow" is
- # set. `seed` is declared and should land on the typed field instead.
+ """Declared fields bind and are typed; unknown ones still survive
+ extra="allow". Declaring response_format is what turns away a value of
+ the wrong shape -- a bare string names no schema to constrain to. What
+ is inside the object is the serving path's business, not the schema's."""
+ from pydantic import ValidationError
+
req = self._make(
- frequency_penalty = 0.5,
seed = 42,
+ frequency_penalty = 0.5,
response_format = {"type": "json_object"},
+ unknown = "kept",
)
- assert req.seed == 42
- # Extras land in model_extra
- assert req.model_extra is not None
- assert req.model_extra.get("frequency_penalty") == 0.5
- assert "seed" not in req.model_extra
- assert req.model_extra.get("response_format") == {"type": "json_object"}
+ assert (req.seed, req.frequency_penalty) == (42, 0.5)
+ assert req.response_format == {"type": "json_object"}
+ assert not {"seed", "frequency_penalty", "response_format"} & set(req.model_extra or {})
+ assert (req.model_extra or {}).get("unknown") == "kept"
+ with pytest.raises(ValidationError):
+ self._make(response_format = "json_object")
def test_unsloth_extensions_still_work(self):
req = self._make(
@@ -634,6 +638,59 @@ class TestChatCompletionRequestToolFields:
assert "n > 1 is not supported" in entry["error"]
assert monitor.active_count() == 0
+ def test_a_no_op_response_format_keeps_a_gguf_request_off_the_passthrough(self):
+ """The passthrough exists to reach llama-server's grammar engine, and
+ ``{"type": "text"}`` names the default rather than a grammar: routing it
+ there would withdraw what the ordinary path serves, n > 1 among them."""
+ from routes.inference import _takes_tool_passthrough
+
+ class _GGUFBackend:
+ supports_tools = False
+
+ backend = _GGUFBackend()
+ assert _takes_tool_passthrough(self._make(response_format = {"type": "json_object"}), backend)
+ # The field takes any object, and anything but the exact default -- an
+ # unknown type, or a text format carrying members this build does not know
+ # -- is a contract, so it keeps going where one can be answered or rejected.
+ assert _takes_tool_passthrough(self._make(response_format = {"type": "later"}), backend)
+ assert _takes_tool_passthrough(
+ self._make(response_format = {"type": "text", "strict": True}), backend
+ )
+ assert not _takes_tool_passthrough(self._make(response_format = {"type": "text"}), backend)
+
+ @pytest.mark.parametrize("enabled_tools", [None, []])
+ def test_the_gguf_tool_loop_refuses_a_contract_it_cannot_forward(
+ self, monkeypatch, enabled_tools
+ ):
+ """Unsloth's loop runs its own turns and never forwards response_format, so
+ serving the request would answer with text that violates the contract while
+ the client has no way to tell. A selection that resolves to no tool routes to
+ the ordinary generator, which forwards it no more than the loop does, and the
+ refusal lands after the monitor row opens, so it must close it."""
+ import routes.inference as inference_route
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = True
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ body = {
+ "messages": [{"role": "user", "content": "hi"}],
+ "enable_tools": True,
+ "response_format": {"type": "json_object"},
+ }
+ if enabled_tools is not None:
+ body["enabled_tools"] = enabled_tools
+ resp = client.post("/v1/chat/completions", json = body)
+ self._assert_unsupported_param(resp, "response_format")
+ assert monitor.active_count() == 0
+
def test_client_tools_rejected_when_gguf_template_has_no_tool_support(self, monkeypatch):
import routes.inference as inference_route
@@ -1045,24 +1102,49 @@ class TestChatCompletionRequestToolFields:
assert "does not advertise tools" in entry["error"]
assert monitor.active_count() == 0
- def test_n_rejected_for_non_gguf_path(self, monkeypatch):
+ @pytest.mark.parametrize(
+ "param, model_entry, extra_body, unreachable_pre_switch",
+ [
+ ("n", {"is_audio": True, "audio_type": "tts"}, {"n": 2}, False),
+ ("n", {"has_audio_input": True}, {"n": 2, "audio_base64": "AAAA"}, False),
+ ("n", {}, {"n": 2, "enable_tools": True}, False),
+ ("n", {}, {"n": 2, "stream": True}, True),
+ ("response_format", {}, {"response_format": {"type": "json_object"}}, False),
+ ("response_format", {}, {"response_format": {"type": "later"}}, False),
+ ],
+ )
+ def test_the_non_gguf_paths_refuse_what_they_cannot_serve(
+ self, monkeypatch, param, model_entry, extra_body, unreachable_pre_switch
+ ):
+ """Plain non-GGUF text now serves extra choices, so only the paths that
+ answer something other than a sample still refuse n: one waveform, one
+ transcript of the one recording, a loop that runs turns rather than
+ samples, and one SSE stream, which carries a single choice whether or not
+ the pre-switch check (reached only when a load may) ran. And no non-GGUF
+ backend can constrain decoding at all."""
+ import routes.inference as inference_route
+
class _NoGGUFBackend:
is_loaded = False
supports_tools = False
class _InferenceBackend:
active_model_name = "test-model"
- models = {"test-model": {}}
+ models = {"test-model": model_entry}
+ if unreachable_pre_switch:
+ monkeypatch.setattr(inference_route, "_automatic_model_load_may_run", lambda: False)
+ monkeypatch.setattr(
+ inference_route,
+ "_detect_safetensors_features",
+ lambda *a, **k: {"supports_tools": True},
+ )
client = self._v1_client(monkeypatch, _NoGGUFBackend(), _InferenceBackend())
resp = client.post(
"/v1/chat/completions",
- json = {
- "messages": [{"role": "user", "content": "hi"}],
- "n": 2,
- },
+ json = {"messages": [{"role": "user", "content": "hi"}], **extra_body},
)
- self._assert_unsupported_n(resp)
+ self._assert_unsupported_param(resp, param)
def test_confirm_tool_calls_requires_streaming_for_safetensors_tools(self, monkeypatch):
import routes.inference as inference_route
@@ -7351,6 +7433,19 @@ class TestApiMonitorAudioInput:
assert entry["reply"] == "[Generated audio]"
assert monitor.active_count() == 0
+ # This branch answers speech and returns before the routing that decides
+ # a decoding contract, so it refuses one itself rather than ignoring it.
+ payload.response_format = {"type": "json_object"}
+ with pytest.raises(HTTPException) as excinfo:
+ await inf_mod.openai_chat_completions(
+ payload, request = request, current_subject = "test"
+ )
+ assert excinfo.value.status_code == 400
+ assert excinfo.value.detail["error"]["param"] == "response_format"
+ # `{"type": "text"}` constrains nothing, so speech is still served.
+ payload.response_format = {"type": "text"}
+ await inf_mod.openai_chat_completions(payload, request = request, current_subject = "test")
+
asyncio.run(_run())
@@ -7679,3 +7774,35 @@ class TestGgufChatHistoryAlternation:
roles = [m["role"] for m in rebuilt]
assert roles == ["system", "user"]
assert all(roles[i] != roles[i + 1] for i in range(len(roles) - 1)), roles
+
+
+# ── Per-choice seeds on the GGUF drain ──────────────────────────────
+
+
+def test_every_gguf_choice_gets_a_seed_of_its_own():
+ """llama-server holds the seed as a uint32 and draws at random for exactly
+ one value, LLAMA_DEFAULT_SEED (0xFFFFFFFF). Only -1 converts to it, so every
+ other negative is an ordinary fixed seed there: exempting all of them from
+ the offset sent n identical requests and returned n copies of one run."""
+ from routes.inference import _choice_seed
+
+ sent = 0xFFFFFFFF
+ for seed in (-2, -3, 0, 5, 2**32 - 2):
+ served = [_choice_seed(seed, i, negative_is_random = True) for i in range(3)]
+ as_read = [v & 0xFFFFFFFF for v in served]
+ assert len(set(as_read)) == 3, (seed, served)
+ # A shifted seed that landed on the sentinel would sample at random where
+ # the caller asked for a fixed run.
+ assert sent not in as_read, (seed, served)
+
+ # -1 is the sentinel itself: offsetting it would make every choice after the
+ # first deterministic, which is the opposite of what was asked for.
+ assert [_choice_seed(-1, i, negative_is_random = True) for i in range(3)] == [-1, -1, -1]
+
+ # MLX maps every seed onto its key domain, so nothing is exempt there.
+ assert [_choice_seed(-2, i) for i in range(3)] == [-2, -1, 0]
+ assert [_choice_seed(5, i) for i in range(3)] == [5, 6, 7]
+
+ # Choice 0 is always the caller's own seed, on both drains.
+ assert _choice_seed(-2, 0, negative_is_random = True) == -2
+ assert _choice_seed(None, 2, negative_is_random = True) is None
diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.py
index 026051d7d2d..a005616211d 100644
--- a/studio/backend/tests/test_sf_client_tools_passthrough.py
+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py
@@ -92,8 +92,13 @@ class _ScriptedBackend:
):
self.calls.append({"messages": messages, "tools": tools, **kwargs})
snapshots = self._responder(messages, tools)
- if stats_holder is not None and self._stats is not None:
- stats_holder["stats"] = self._stats
+ # A list scripts stats per call, where None is a generation that ended
+ # without publishing any -- a cancelled one, say.
+ _stats = self._stats
+ if isinstance(_stats, list):
+ _stats = _stats[min(len(self.calls), len(_stats)) - 1]
+ if stats_holder is not None and _stats is not None:
+ stats_holder["stats"] = _stats
for snap in snapshots:
yield snap
@@ -485,6 +490,88 @@ def test_streaming_heals_split_call_into_one_delta(monkeypatch):
assert finishes == ["tool_calls"]
+def test_what_this_backend_can_serve_reaches_it_rather_than_being_refused(monkeypatch):
+ """An empty stop sequence is dropped rather than forwarded: it would match at
+ position 0 and end every turn before its first token. ``{"type": "text"}``
+ constrains nothing, so refusing it for want of a grammar engine would turn a
+ request this backend serves into a 400."""
+ backend = _ScriptedBackend(_fixed("hi"), stats = {"usage": {"prompt_tokens": 7}})
+ payload = _request(stop = ["END", ""], response_format = {"type": "text"})
+ body = _json_body(_call(payload, monkeypatch, backend, supports_tools = False))
+ assert backend.calls[0]["stop"] == ["END"]
+ assert body["choices"][0]["message"]["content"] == "hi"
+
+
+def test_n_serves_one_full_generation_per_choice(monkeypatch):
+ """Each choice is its own sampling run, as on the llama-server path: the
+ backend is asked once per choice rather than one reply being copied, and the
+ prompt they share is not re-counted. Two runs may sample the same text; what
+ is guaranteed is that each was generated."""
+ turns = iter(["first", "second"])
+ backend = _ScriptedBackend(
+ lambda messages, tools: [next(turns)],
+ stats = {"usage": {"prompt_tokens": 7, "completion_tokens": 3}},
+ )
+ body = _json_body(_call(_request(n = 2), monkeypatch, backend, supports_tools = False))
+ assert [c["index"] for c in body["choices"]] == [0, 1]
+ assert [c["message"]["content"] for c in body["choices"]] == ["first", "second"]
+ assert len(backend.calls) == 2 # a generation per choice, not one reused
+ # The shared prompt is counted once; only generated tokens accumulate.
+ assert _totals(body) == {"prompt_tokens": 7, "completion_tokens": 6, "total_tokens": 13}
+
+
+def _totals(body):
+ return {k: body["usage"][k] for k in ("prompt_tokens", "completion_tokens", "total_tokens")}
+
+
[email protected]("tool_loop", [False, True])
+def test_a_non_streaming_reply_reports_the_tokens_it_spent(monkeypatch, tool_loop):
+ """The response model defaults usage to a zero-filled object, so omitting it
+ reports zeros a client cannot tell from a real count. Both non-streaming
+ shapes answer from the same stats the monitor reads."""
+ spent = {"prompt_tokens": 11, "completion_tokens": 4, "total_tokens": 15}
+ build = _ToolLoopBackend if tool_loop else _ScriptedBackend
+ backend = build(_fixed("hello"), stats = {"usage": spent})
+ payload = _request(stream = False, enable_tools = True) if tool_loop else _request(stream = False)
+ body = _json_body(_call(payload, monkeypatch, backend, supports_tools = tool_loop))
+ assert _totals(body) == spent
+ assert body["usage"]["prompt_tokens_details"]["cached_tokens"] == 0
+
+
+def _monitor_entry(payload, monkeypatch, backend, **install_kwargs):
+ """The one monitor row a request leaves behind, and what it raised, if it did."""
+ from fastapi import HTTPException
+
+ monitor = _install(monkeypatch, backend, **install_kwargs)
+
+ async def _run():
+ return await openai_chat_completions(payload, request = _Request(), current_subject = "u")
+
+ error = None
+ try:
+ asyncio.run(_run())
+ except HTTPException as exc:
+ error = exc
+ [entry] = monitor.snapshot()
+ return entry, error
+
+
+def test_one_monitor_row_describes_the_whole_turn(monkeypatch):
+ """The last choice cannot speak for the turn: the row shows every reply, and a
+ choice that ended without publishing stats is not billed the previous one's."""
+ turns = iter(["first", "second"])
+ backend = _ScriptedBackend(
+ lambda messages, tools: [next(turns)],
+ stats = [{"usage": {"prompt_tokens": 7, "completion_tokens": 3}}, None],
+ )
+ entry, _ = _monitor_entry(_request(n = 2), monkeypatch, backend, supports_tools = False)
+ assert "first" in entry["reply"] and "second" in entry["reply"]
+ assert entry["prompt_tokens"] == 7 # the shared prompt, not 7 per choice
+ assert entry["completion_tokens"] == 3 # only the choice that published
+ # Per-choice reasons can differ, so the turn claims none of them.
+ assert entry.get("stop_reason") is None
+
+
def test_streaming_cancel_does_not_finalize_tool_call(monkeypatch):
# A stream cancelled via the registry ("Stop") must NOT promote the
# buffered-but-unclosed tool markup at finalize, else it executes a tool
@@ -708,10 +795,11 @@ def test_failed_nudge_retry_keeps_original_response(monkeypatch):
assert body["choices"][0]["message"]["content"] == '<tool_call>{"name":"lookup"'
-def test_discarded_nudge_retry_reports_first_attempt_usage(monkeypatch):
+def test_a_discarded_nudge_retry_still_bills_the_tokens_it_spent(monkeypatch):
# Double-failure nudge: the first response is delivered, but the retry's
- # generate() overwrites stats_holder. The monitor must record the FIRST
- # attempt's usage, not the discarded retry's.
+ # generate() overwrites stats_holder. The prompt reported is the delivered
+ # attempt's, never the discarded retry's -- but both attempts ran, so their
+ # completions are summed rather than one being dropped.
first_stats = {"usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}}
retry_stats = {"usage": {"prompt_tokens": 99, "completion_tokens": 99, "total_tokens": 198}}
@@ -746,11 +834,134 @@ def test_discarded_nudge_retry_reports_first_attempt_usage(monkeypatch):
asyncio.run(_run())
assert len(backend.calls) == 2 # first attempt + one discarded retry
[entry] = monitor.snapshot()
- # The delivered response is the first attempt, so its usage must be reported.
+ # The delivered response is the first attempt, so its prompt is the one
+ # reported; the retry's 99 completion tokens were still generated.
assert entry["prompt_tokens"] == 7
+ assert entry["completion_tokens"] == 3 + 99
+
+
+def test_a_nudge_retry_that_never_reported_is_not_billed_twice(monkeypatch):
+ # The retry raises before publishing, so stats_holder still holds the first
+ # attempt's report. Folding that into itself would double its completion count.
+ first_stats = {"usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}}
+
+ class _RetryRaisesBackend(_ScriptedBackend):
+ def __init__(self):
+ super().__init__(lambda m, t: ['<tool_call>{"name":"lookup"'])
+
+ def generate_chat_response(
+ self,
+ *,
+ messages,
+ tools = None,
+ stats_holder = None,
+ **kwargs,
+ ):
+ self.calls.append({"messages": messages, "tools": tools, **kwargs})
+ if len(self.calls) > 1:
+ raise RuntimeError("retry blew up before reporting anything")
+ if stats_holder is not None:
+ stats_holder["stats"] = first_stats
+ for snap in self._responder(messages, tools):
+ yield snap
+
+ backend = _RetryRaisesBackend()
+ payload = _request(tools = [LOOKUP_TOOL], nudge_tool_calls = True, stream = False)
+ monitor = _install(monkeypatch, backend)
+
+ async def _run():
+ return await openai_chat_completions(payload, request = _Request(), current_subject = "u")
+
+ body = _json_body(asyncio.run(_run()))
+ assert len(backend.calls) == 2
+ assert body["usage"]["prompt_tokens"] == 7
+ assert body["usage"]["completion_tokens"] == 3
+ [entry] = monitor.snapshot()
assert entry["completion_tokens"] == 3
+def test_cached_prompt_tokens_reach_the_usage_details(monkeypatch):
+ # MLX folds its reused prefix into prompt_tokens, so a caller reading the
+ # OpenAI field must see the same count rather than a flat zero.
+ stats = {
+ "usage": {
+ "prompt_tokens": 1200,
+ "completion_tokens": 4,
+ "total_tokens": 1204,
+ "prompt_tokens_details": {"cached_tokens": 1100},
+ }
+ }
+ backend = _ScriptedBackend(_fixed("hi"), stats = stats)
+ body = _json_body(_call(_request(stream = False), monkeypatch, backend))
+ details = body["usage"]["prompt_tokens_details"]
+ assert details["cached_tokens"] == 1100
+ assert details["cached_tokens"] <= body["usage"]["prompt_tokens"]
+
+
+def test_cached_tokens_never_exceed_the_prompt_they_describe(monkeypatch):
+ # Two choices can report different prompt counts (the nudge rebuilds a longer
+ # prompt), so the count and its details must come from the same choice.
+ rich = {
+ "usage": {
+ "prompt_tokens": 1200,
+ "completion_tokens": 4,
+ "prompt_tokens_details": {"cached_tokens": 1100},
+ }
+ }
+ lean = {"usage": {"prompt_tokens": 1000, "completion_tokens": 4}}
+ backend = _ScriptedBackend(_fixed("hi"), stats = [rich, lean])
+ body = _json_body(_call(_request(stream = False, n = 2), monkeypatch, backend))
+ usage = body["usage"]
+ assert usage["prompt_tokens"] == 1000
+ assert usage["prompt_tokens_details"]["cached_tokens"] == 0
+ assert usage["prompt_tokens_details"]["cached_tokens"] <= usage["prompt_tokens"]
+
+
+def test_a_successful_nudge_retry_bills_both_attempts(monkeypatch):
+ # The retry heals, so its reply is delivered and its prompt is reported --
+ # but the first attempt generated tokens on the way there, and reporting the
+ # retry alone hides them from the caller's usage.
+ first_stats = {"usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}}
+ retry_stats = {"usage": {"prompt_tokens": 20, "completion_tokens": 5, "total_tokens": 25}}
+
+ class _HealsOnRetryBackend(_ScriptedBackend):
+ def __init__(self):
+ super().__init__(
+ lambda m, t: [_CALL_XML if len(self.calls) > 1 else '<tool_call>{"name":"lookup"']
+ )
+ self._stats_seq = [first_stats, retry_stats]
+
+ def generate_chat_response(
+ self,
+ *,
+ messages,
+ tools = None,
+ stats_holder = None,
+ **kwargs,
+ ):
+ self.calls.append({"messages": messages, "tools": tools, **kwargs})
+ if stats_holder is not None:
+ stats_holder["stats"] = self._stats_seq[
+ min(len(self.calls) - 1, len(self._stats_seq) - 1)
+ ]
+ for snap in self._responder(messages, tools):
+ yield snap
+
+ backend = _HealsOnRetryBackend()
+ payload = _request(tools = [LOOKUP_TOOL], nudge_tool_calls = True, stream = False)
+ monitor = _install(monkeypatch, backend)
+
+ async def _run():
+ return await openai_chat_completions(payload, request = _Request(), current_subject = "u")
+
+ body = _json_body(asyncio.run(_run()))
+ assert len(backend.calls) == 2 # first attempt + the retry that healed
+ assert body["choices"][0]["message"]["tool_calls"]
+ assert body["usage"]["prompt_tokens"] == 20
+ assert body["usage"]["completion_tokens"] == 3 + 5
+ assert body["usage"]["total_tokens"] == 28
+
+
def test_monitor_records_healed_call_not_raw_xml(monkeypatch):
backend = _ScriptedBackend(_fixed(_CALL_XML))
payload = _request(tools = [LOOKUP_TOOL], stream = False)
@@ -893,3 +1104,71 @@ def test_mcp_enabled_without_server_tools_uses_passthrough(monkeypatch):
assert choice["finish_reason"] == "tool_calls"
assert choice["message"]["tool_calls"][0]["function"]["name"] == "lookup"
assert backend.calls[0]["tools"] == [LOOKUP_TOOL]
+
+
+def _fold(*turns):
+ """Run the tool loop's fold over turns in order, as the orchestrator does."""
+ from core.inference.orchestrator import _summed_tool_loop_stats
+
+ total = None
+ for turn in turns:
+ total = _summed_tool_loop_stats(total, turn)
+ return total
+
+
+def _turn(
+ prompt,
+ completion,
+ *,
+ timings = True,
+ **extra,
+):
+ usage = {
+ "prompt_tokens": prompt,
+ "completion_tokens": completion,
+ "total_tokens": prompt + completion,
+ **extra,
+ }
+ stats = {"usage": usage}
+ if timings:
+ stats["timings"] = {"predicted_ms": completion * 10.0, "predicted_n": completion}
+ return stats
+
+
+def test_every_tool_loop_turn_is_billed_not_just_the_last():
+ """The turns that produced the tool call spent tokens too, so the reply sums
+ them; only the prompt is the last turn's, since it already carries the
+ earlier results."""
+ folded = _fold(_turn(100, 20), _turn(160, 30), _turn(220, 5))
+
+ assert folded["usage"] == {"prompt_tokens": 220, "completion_tokens": 55, "total_tokens": 275}
+ # Rates describe the summed counts, not the last turn that arrived.
+ assert folded["timings"]["predicted_n"] == 55
+ assert folded["timings"]["predicted_ms"] == pytest.approx(550.0)
+ assert folded["timings"]["predicted_per_token_ms"] == pytest.approx(10.0)
+
+
+def test_a_turn_that_ends_before_reporting_does_not_erase_the_loop():
+ """A cancelled or errored final turn has no counts of its own. Seeding the
+ fold from it would drop everything the loop already spent."""
+ # No report at all, in every position.
+ assert _fold(_turn(100, 20), None, _turn(160, 30))["usage"]["completion_tokens"] == 50
+ assert _fold(_turn(100, 20), _turn(160, 30), None)["usage"]["completion_tokens"] == 50
+
+ # Reported usage but no timings: the loop's totals must survive it.
+ partial = _fold(_turn(100, 20), _turn(160, 30, timings = False))
+ assert partial["timings"]["predicted_n"] == 20
+ # Reported timings but no usage: the prompt is still the loop's.
+ errored = _fold(_turn(100, 20), {"timings": {"predicted_ms": 1.0, "predicted_n": 1}})
+ assert errored["usage"] == {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120}
+
+
+def test_completion_details_are_summed_with_the_completion_they_describe():
+ """Carrying the last turn's details would report them against every turn's
+ tokens."""
+ folded = _fold(
+ _turn(100, 20, completion_tokens_details = {"reasoning_tokens": 7}),
+ _turn(160, 30, completion_tokens_details = {"reasoning_tokens": 3}),
+ )
+ assert folded["usage"]["completion_tokens"] == 50
+ assert folded["usage"]["completion_tokens_details"] == {"reasoning_tokens": 10}
diff --git a/studio/backend/tests/test_tool_policy_gates.py b/studio/backend/tests/test_tool_policy_gates.py
index 5329ac8b3e6..840226076b0 100644
--- a/studio/backend/tests/test_tool_policy_gates.py
+++ b/studio/backend/tests/test_tool_policy_gates.py
@@ -107,6 +107,7 @@ def _req(**kw):
mcp_enabled = None,
tool_choice = None,
tools = None,
+ response_format = None,
messages = [_msg()],
model_extra = {},
)
@@ -142,7 +143,7 @@ class TestRequestStatesToolIntent:
def test_response_format_is_a_contract(self):
# The tool loop would break structured output; the GGUF passthrough
# already exempts these requests from the policy.
- payload = _req(model_extra = {"response_format": {"type": "json_object"}})
+ payload = _req(response_format = {"type": "json_object"})
assert _request_states_tool_intent(payload) is True
def test_empty_tools_reads_as_omitted(self):
@@ -191,7 +192,7 @@ class TestSafetensorsGateHonorsStatedIntent:
def test_response_format_keeps_structured_output(self):
set_tool_policy_default(True)
- payload = _req(model_extra = {"response_format": {"type": "json_object"}})
+ payload = _req(response_format = {"type": "json_object"})
assert _sf_tools_on(payload) is False
def test_explicit_ask_still_claims_a_catalog(self):