Skip to content

Studio: serve /v1/completions from MLX models - #13796

Merged
danielhanchen merged 19 commits into
unslothai:mainfrom
Lyxot:feat/mlx-completions
Oct 15, 2026
Merged

danielhanchen merged 19 commits into
unslothai:mainfrom
Lyxot:feat/mlx-completions

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

/v1/completions (raw prompt, no chat template) returned 503 whenever the resident model was MLX. MLX models could only generate from chat messages rendered through the chat template, so completion-style clients had no MLX path at all. Those clients include FIM/autocomplete plugins, eval harnesses that send raw prompts, and llama-server-style tooling.

What changed

The request is read the way llama-server reads it, so the same request behaves the same on the GGUF and MLX routes.

Backend: generate from a raw prompt.

  • Prompt resolution: MLXInferenceBackend.resolve_completion_prompt takes llama-server's single-prompt forms: a string, token ids, a mixed list, or {"prompt_string": …}.
    • It tokenizes with special-token parsing.
    • It adds BOS only when the prompt starts with a string.
    • It range-checks ids against the vocabulary.
    • It returns the prompt text decoded with special tokens, for echo.
  • Generation: generate_completion runs the ids with no template. On text models, raw prompts reuse the prompt cache like rendered chat prompts.
  • repeat_last_n: implemented as one window over prompt and completion for the repetition, presence and frequency penalties.
    • mlx_lm and mlx_vlm hand logits processors only the prompt tokens left after prefill, so each windowed penalty rebuilds the withheld head from the full prompt.
  • Worker: it gains a resolve_prompt command, since the parent process has no tokenizer.

Route: /v1/completions on MLX.

  • Prompts: every llama-server prompt form. Several prompts and n / n_cmpl up to 128 are served non-stream, in llama-server's choice order (index = prompt_index * n + j), with chat's per-choice seeding.
  • Field names: llama-server's names, aliases, soft clamps, hard limits, seed sentinel and defaults.
  • Other fields served:
    • logit_bias in both of its forms;
    • echo, which a GGUF model still refuses because llama-server ignores it;
    • stream_options.include_usage.
  • Grammar and schema: a GBNF grammar or a json_schema is compiled to an llguidance grammar in llama-server's precedence: a grammar key first, then json_schema, where {} means any object. response_format is honored last, as an MLX extension (llama-server ignores it on this endpoint).
    • Compilation happens before any model switch, so an invalid grammar is a 400 before anything loads.
    • The grammar constrains both text and vision decodes.
    • grammar_lazy is still refused.
  • Unsupported fields: fields with no MLX equivalent are refused with a typed 400 unless set to their neutral value, so clients that send a full default parameter set keep working. These are:
    • typical_p, XTC, mirostat, DRY;
    • logprobs, n_probs;
    • multiple completions in one stream.
  • Auto-switch: an MLX target is loaded only for a request it can serve.
  • Lifecycle: the same as in-process chat:
    • cancellable while queued;
    • Stop and disconnect handling;
    • an API monitor entry;
    • cancelled responses are marked failed for keepwarm.

Vision prompt cache. A raw prompt on a vision model now opens the prompt-cache session, which keys on token ids. A repeated or extended prompt therefore resumes from the stored prefix instead of prefilling from scratch.

Batching. Raw prompts join the resident MLX batch like chat replies do. A request's prompts × n choices go out as one rows command.

  • Text rows are planned from token ids, with no template, prefill or reasoning normalizer.
  • Vision raw rows decode one at a time and are decoded from their sampled ids: the vision batch's streaming detokenizer keeps control tokens and trims the first piece's leading space. _vlm_batch_prompt still passes prompt_token_ids (feat(mlx): take token-id prompts in batched vision generation unsloth-zoo#1758) for when the batch decodes from ids too.
  • Grammar-constrained rows never batch.
  • A declined batch decodes each raw row on its own.

Behavior notes / risks

  • Cancellation: choices of one request now decode together. A cancelled multi-choice request therefore answers every choice as stopped with what it produced, rather than answering only the first.
  • Empty prompt: refused with a 400, where llama-server returns an empty 200, because MLX cannot prefill zero tokens.
  • Sampler order (pre-existing, shared with MLX chat): MLX applies top-p → min-p → top-k, while llama-server applies top-k → top-p → min-p, so combining top-k and top-p can sample differently from llama-server.
  • Logprob scoring: logprobs stays GGUF-only, so logprob-scoring harnesses still need a GGUF model.
  • Transformers: a transformers model still gets the existing GGUF-only error for /v1/completions, refused before any load.
  • Vision n > 1: served, decoded one row at a time, with or without feat(mlx): take token-id prompts in batched vision generation unsloth-zoo#1758.

Validation

  • Unit tests:
    cd studio/backend
    python -m pytest -q tests/test_openai_tool_passthrough.py tests/test_mlx_inference_backend.py tests/test_mlx_resident_batch.py tests/test_presence_penalty.py tests/test_openai_auto_switch.py
    # 1740 passed (one auto-switch case that fails identically on main on case-insensitive filesystems deselected)
  • Live on MLX, text model (mlx-community/Qwen2.5-0.5B-Instruct-4bit):
    • Batching:
      • Greedy n = 3 decodes as one batch and equals the single greedy reply.
      • Two prompts × n = 2 with a seed are reproducible, in llama-server order, with distinct choices.
      • Three concurrent raw requests are admitted to one resident batch.
    • Constraints:
      • A root ::= " yes" | " no" grammar constrains every choice.
      • json_schema and response_format: json_object produce parseable matching documents.
      • An invalid grammar and grammar_lazy return 400.
    • Penalties: a windowed repeat_last_n penalty works inside a batch.
  • Live on MLX, vision model (mlx-community/Qwen3.5-0.8B-4bit):
    • A second identical 331-token raw prompt reports cached_tokens: 330.
    • Raw n = 2 is answered with both choices, decoded one row at a time.
    • The grammar constrains vision decodes.
  • Prompt resolution: greedy raw-prompt tokens equal direct mlx_lm / mlx_vlm runs, and the BOS rules were checked on Llama-3.2-3B.
  • Live on CUDA transformers:
    • /v1/completions gets the GGUF-only 400 before any load.
    • With a transformers model resident, it gets the existing 503.
    • Chat is unaffected.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-15T14:10:20.970055Z 4f1ea06 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7459a5f82e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
@Lyxot
Lyxot force-pushed the feat/mlx-completions branch from 7459a5f to 98439be Compare October 15, 2026 06:03
@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 98439be900

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved
@Lyxot
Lyxot force-pushed the feat/mlx-completions branch from 98439be to 451afa4 Compare October 15, 2026 06:36
@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 451afa4dd2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e581b2dd73

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved
@Lyxot
Lyxot force-pushed the feat/mlx-completions branch from e581b2d to 011605a Compare October 15, 2026 07:35
@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 011605a3b4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
@Lyxot
Lyxot force-pushed the feat/mlx-completions branch from 011605a to 0b676a2 Compare October 15, 2026 07:54
@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0b676a2b9b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Lyxot
Lyxot force-pushed the feat/mlx-completions branch from 0b676a2 to 148f41c Compare October 15, 2026 08:21
@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Lyxot

Lyxot commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 148f41c502

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 15, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-zoo-staging-2 that referenced this pull request Oct 15, 2026
…hai#1758)

## Problem

Batched vision generation (`stream_batch`, `generate_batch`,
`BatchStream`) refused `prompt_token_ids`. A caller holding an
already-tokenized prompt had to decode it alone on a vision model, while
text models batched it. This affected, for example, raw-prompt
`/v1/completions` in Unsloth Studio.

## What changed

**Token-id prompts.** A media-free vision request may now give
`prompt_token_ids`.
- **Prefill:** `stream_batch`, `generate_batch` and `BatchStream` (plain
and speculative) prefill exactly those ids with a full attention mask,
instead of running the processor.
- **Grouping:** `stream_batch` groups token-id rows apart from rendered
prompts of the same length.
- **Validation:** `_validated_prompt_ids` is shared by text and vision
request validation.

**Media still needs a rendered prompt.** A request with an image or
audio must still give a rendered prompt, since only the processor places
media tokens.

**Capability marker.** `VLM_TOKEN_ID_PROMPTS = True` is exported so
callers can feature-detect the capability. Unsloth Studio gates its
vision raw-prompt batching on it (unslothai/unsloth#13796); without it,
those rows decode one at a time.

## Validation

- **Unit tests:**
  ```bash
python -m pytest -q tests/test_mlx_generate.py
tests/test_mlx_speculative_metal.py -k "token or vlm or vision"
  # 35 passed
  ```
`test_mlx_speculative_metal.py` adds a token-id twin of an existing
speculative vision row, run on Metal.
- **Live** (`mlx-community/Qwen3.5-0.8B-4bit`):
- A greedy token-id row in `stream_batch` matches plain `mlx_vlm` greedy
decoding of the same prompt.
- Unsloth Studio's raw-prompt `/v1/completions` with `n = 2` on that
model decodes as one vision batch.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 15, 2026
@danielhanchen
danielhanchen merged commit 3de513d into unslothai:main Oct 15, 2026
iam-knoit pushed a commit to SynhalaAI/unsloth that referenced this pull request Oct 20, 2026
…lothai#14229)

## Problem

`/v1/completions` on an MLX model refused `logprobs` (and its
llama-server alias `n_probs`) with a 400 (unslothai#13796 left it GGUF-only).
Log-likelihood evaluation, for example lm-evaluation-harness's `gguf`
backend that scores MMLU and HellaSwag, therefore only worked with a
GGUF model loaded. That backend also calls `POST /tokenize` first, which
Studio only forwarded to llama-server, so with an MLX model resident it
got a 503.

Part of unslothai#7703.

## What changed

**Logprobs on MLX `/v1/completions`.**
- When `logprobs` / `n_probs` is above 0, a recorder runs as the first
logits processor and keeps the log-softmax of the model's own logits for
each generated token, before `logit_bias`, penalties or a grammar touch
them. llama-server reports logprobs the same way, which is what lets a
client force a token with `logit_bias` and read back its real
probability. mlx_lm and mlx_vlm compute their own logprobs after the
processors, so passing those through would report about 0 for any forced
token.
- Each choice gets `logprobs: {"content": [{id, token, bytes, logprob,
top_logprobs: [{id, token, bytes, logprob}]}]}`, the shape llama-server
returns, so a client sees the same response on a GGUF and an MLX model.
`n_probs` is capped at the vocabulary size.
- Text and vision models are both covered. On the vision path a request
with logprobs skips the speculative draft, since its verify pass would
record tokens it then rejects. Diffusion vision models refuse `logprobs`
with a 400.
- A request with logprobs decodes on its own instead of joining the
resident MLX batch, like grammar-constrained rows already do.

**`POST /tokenize` for a resident MLX model.** Same owner-only route as
the llama-server passthrough. It takes `content` and `add_special`,
parses special tokens like llama-server, and refuses `with_pieces`.

## What does not change

- Requests without `logprobs` build exactly the same generation command
and batch as before.
- GGUF is untouched: `/v1/completions` and `/tokenize` still go to
llama-server whenever a GGUF is loaded.
- Still refused on MLX with a typed 400: `logprobs` with `stream: true`,
with `echo` (prompt logprobs), with several prompts or `n > 1`, and
`post_sampling_probs` together with `logprobs`, which llama-server
answers from the sampled distribution under different field names
(`prob` / `top_probs`).
- `/tokenize` refuses `with_pieces` and `parse_special: false`, rather
than ignoring them and returning ids that differ from the GGUF answer.
It takes llama-server's mixed arrays of strings and token ids, and
reports a model that unloaded mid-call as 503 rather than 500.

Two differences from llama-server remain, both in auxiliary fields
rather than the values a scorer reads:

- when a stop sequence ends generation, the entries for the tokens the
stop cut removed are still reported, where llama-server trims them;
- for a token whose bytes are not valid UTF-8 on their own, `token` and
`bytes` come from decoding that id alone, so they show the replacement
character instead of the raw piece.
- No UI change.

## Tests

Linux (MLX faked):
- `test_openai_tool_passthrough.py`: logprobs served in the llama-server
shape; only what MLX cannot reproduce is refused.
- `test_mlx_inference_backend.py`: a token forced by `logit_bias`
reports its unbiased logprob (log 0.04, not about 0); the vision path
skips the draft.
- `test_presence_penalty.py`: `n_probs` crosses the worker only to a
backend that serves it.
- `test_llama_compat_routes.py`: `/tokenize` answers from a resident MLX
model, with and without specials.

These fail on main and pass here.

Apple Silicon (`test_mlx_completions_apple.py`,
`mlx-community/SmolLM-135M-Instruct-4bit`): greedy logprobs match
mlx_lm's own, and a token forced with `logit_bias` reports its real
logprob rather than the biased value near 0.

mlx_lm reduces its log_softmax in the model's dtype, which is bf16 for a
4-bit checkpoint, so the reference carries a few ulps of that dtype
while this path reports float32 as llama-server does. The comparison
therefore allows 4 ulps of the reference's own dtype, with a 1e-3 floor
that a float32 model still gets. On macOS 15 Apple Silicon the whole
selection is 1152 passed.

```bash
cd studio/backend
python -m pytest -q tests/test_openai_tool_passthrough.py tests/test_mlx_inference_backend.py tests/test_presence_penalty.py tests/test_llama_compat_routes.py tests/test_mlx_completions_apple.py
```

---------

Co-authored-by: Nilay Yadav <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants