Skip to content

Studio: logprobs on /v1/completions and /tokenize for MLX models - #14229

Merged
danielhanchen merged 11 commits into
mainfrom
studio-mlx-completion-logprobs
Oct 20, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-mlx-completion-logprobs

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Problem

/v1/completions on an MLX model refused logprobs (and its llama-server alias n_probs) with a 400 (#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 #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.

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

@danielhanchen danielhanchen self-assigned this Oct 19, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 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 ✅ Completed 2026-10-20T06:59:24.876198Z 6082fa7 Manual request
🔒 Security Review ⚠️ Failed 2026-10-19T09:09:37.472444Z 53ce3bd PR opened
ℹ️ 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.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member 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: 6e383875b7

ℹ️ 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 on lines +5917 to +5922
if recorded:
token_logprobs.append(
_mlx_token_logprob(
recorded.popleft(), response.token, n_probs, self._tokenizer
)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Trim logprobs for matched stop sequences

When a non-streaming completion generates a suffix matching stop, the text path records that suffix's token probabilities before _mlx_stop_cut removes it from the returned text, and the VLM path does the same. The response therefore contains extra logprobs.content entries that do not correspond to choices[0].text; llama-server removes the matched stop tokens from its non-streaming probability output. Trim the recorded entries when a stop sequence ends generation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Real difference from llama-server, but it only adds trailing entries for text the stop cut removed, and the kept entries stay correct. The cut is a character index, so trimming means mapping it back through token boundaries; not worth that risk for a combination lm-eval never sends. Recorded as a known difference in the description instead.

Comment on lines +3318 to +3322
def _token_bytes_text(tokenizer, token_id):
text = tokenizer.decode(
[token_id], skip_special_tokens = False, clean_up_tokenization_spaces = False
)
return text, list(text.encode("utf-8"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve raw bytes for byte-fallback tokens

For a token whose bytes are not valid standalone UTF-8, such as one byte of a multibyte character in byte-fallback/BPE tokenizers, decoding the single ID produces U+FFFD and re-encoding it reports [239, 191, 189] rather than the token's actual bytes. This makes both sampled-token and top-token bytes fields incorrect and can also misstate token; derive these values from the tokenizer's raw token piece instead of an isolated decoded string.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct about the mechanism, and llama.cpp does return raw piece bytes. Getting real bytes back generically needs per-tokenizer piece handling (sentencepiece <0xNN> against GPT-2 byte-level), which is more risk than the auxiliary bytes field is worth here; id and logprob, which scoring reads, are unaffected. Recorded as a known difference in the description.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: c6e45a8fb4

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 19, 2026
danielhanchen added a commit that referenced this pull request Oct 19, 2026
## Summary


`tests/test_formatter_fixed_point.py::test_every_tracked_python_file_is_already_formatted`
fails in `Repo tests (CPU, rest)` on PRs based on current main (seen on
#14229):

```
these tracked files are not a fixed point of the ruff-format-with-kwargs hook, so pre-commit.ci will fail the next PR that edits them
```

That run listed eight files. Most were reformatted on main since then.
Running the hook (`scripts/run_ruff_format.py`, ruff 0.6.9 as pinned)
over every tracked file inside the hook's scope, at main `6c159816c5`,
leaves two:

- `studio/backend/routes/settings.py`: one `logger.info(...)` call the
hook joins onto one line.
- `studio/backend/tests/test_video_cpu_developer_mode.py`: one `from
utils.account_context import ...` the hook splits.

Both came in with #14247, which merged without its pre-commit.ci format
commit.

## Change

The hook's own output for those two files, nothing else. No behavior
change.

## Testing

- **The hook over every tracked `.py`:** I ran it and then reverted
everything the hook's `exclude` pattern skips (read from
`.pre-commit-config.yaml` the same way the guard does). Exactly these
two files remain changed.
- **Running it again on this branch:** no further changes.
danielhanchen added a commit that referenced this pull request Oct 19, 2026
#14271)

## Summary

Two tests in `studio/backend/tests/test_diffusion_segment.py` fail in
the `(Python 3.13, a-k)` shard on PRs with different bases (#14229,
#14245):

```
test_choose_device_needs_room_on_the_card
test_choose_device_reads_bf16_on_the_chosen_card
E   AssertionError: assert ('cpu', torch.float32) == ('cuda:1', torch.bfloat16)
```

Both pass when the file runs on its own (64 passed).

## Cause

`choose_device()` (from #14235, SAM 3 masks) puts SAM 3 on the CPU when
another GPU arbiter owner holds the card (`_other_owner_on` ->
`gpu_arbiter.residents()`). The arbiter's `_owner` / `_residents` are
module globals. These two tests stub torch and the free-memory probe but
not the arbiter. So when an earlier test in the same xdist worker leaves
a CHAT owner behind, they see the card as taken and pick the CPU. The
product is right to refuse a card another owner holds. The tests were
order dependent.

## Change

Test-only: an autouse fixture in `test_diffusion_segment.py` clears
`gpu_arbiter._owner` and `_residents` before each test (with
`monkeypatch`, so they are restored). Tests that exercise ownership
already set their own owner, and still do.

## Testing

- **`test_diffusion_segment.py`:** 64 passed.
- **Sabotage:** I added a throwaway test that sets `gpu_arbiter._owner =
gpu_arbiter.CHAT` and ran it first in the same process:
- **Without the fixture:** `test_choose_device_needs_room_on_the_card`
and `test_choose_device_reads_bf16_on_the_chosen_card` fail. These are
the two CI failures.
  - **With it:** all pass.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@NilayYadav NilayYadav self-assigned this Oct 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 2851a23091

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 2b5bc71a60

ℹ️ 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".

@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: 6082fa7a1. 2 findings fixed in 2851a2309 and 2b5bc71a6; 2 low-severity suggestions inline.

I reproduced an lm-eval style scoring flow (POST /tokenize, then POST /v1/completions with logprobs and logit_bias) against a real Studio install on the merge base a33463f and on this branch (macOS, Apple Silicon, mlx-community/SmolLM-135M-Instruct-4bit loaded as MLX):

  • Before (run): /v1/completions with "logprobs": 3 returns 400 'logprobs' is not supported for MLX models.; /tokenize returns 503 No llama.cpp model is loaded. With the fix reverted and the tests kept, the new tests fail on generate_completion() got an unexpected keyword argument 'n_probs' and on the missing _token_bytes_text.
  • PR head (run): 200 with 6 logprobs.content entries, the first {"id": 260, "token": " the", "logprob": -2.2316} with 3 top_logprobs; /tokenize "Hello world" returns [19556, 905], identical to the tokenizer. Token 1217 forced with logit_bias 100 reports -2.29411, the same as its unforced logprob. Every reported logprob over 6 greedy steps matches a direct forward pass at that position.

PR 14229 chat page on main and on the PR, no visible change

  • Fixed on the branch: "logprobs": false was accepted on main and returned 400 here (2851a2309); on a SentencePiece tokenizer (Llama style) the reported tokens lost their leading spaces, joining to HandlerintentcenterAuthhingroups for the text Handler intent center Authhin groups, and now join to the text exactly (2b5bc71a6). Both have regression tests.
  • Unchanged: plain completions without logprobs give the same text on both sides ( the second-largest country in), chat replies and the chat page look the same, and logprobs with stream is still a typed 400. The added check on the default decode path costs about 6 ns per token.
  • Tests: 10 tests fail on main and pass here; on macOS 15 Apple Silicon the PR's test files give 1158 passed, including the real-model logprob tests; Linux gives 1023 passed (2 skipped for a missing transformers). On Windows, 2 API monitor tests outside this diff failed (GGUF stream and safetensors cancel), plus 2 that need transformers (run).

Conclusion: the gap is real on main and this branch closes it for text and vision MLX models; with the two fixes above it is ready to merge once CI on 6082fa7a1 is green. The two inline suggestions would make bytes and stop-trimmed replies match llama-server exactly.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 20, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 6082fa7a1e

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 6a19cb2 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-mlx-completion-logprobs branch October 20, 2026 07:22
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