Repository navigation
Studio: logprobs on /v1/completions and /tokenize for MLX models - #14229
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…esolution [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if recorded: | ||
| token_logprobs.append( | ||
| _mlx_token_logprob( | ||
| recorded.popleft(), response.token, n_probs, self._tokenizer | ||
| ) | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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")) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…ces and post_sampling_probs [skip ci]
… abandoned one [skip ci]
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
## 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.
#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>
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Review + reproduction evidencePinned review: I reproduced an lm-eval style scoring flow (
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 |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |

Problem
/v1/completionson an MLX model refusedlogprobs(and its llama-server aliasn_probs) with a 400 (#13796 left it GGUF-only). Log-likelihood evaluation, for example lm-evaluation-harness'sggufbackend that scores MMLU and HellaSwag, therefore only worked with a GGUF model loaded. That backend also callsPOST /tokenizefirst, 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.logprobs/n_probsis 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, beforelogit_bias, penalties or a grammar touch them. llama-server reports logprobs the same way, which is what lets a client force a token withlogit_biasand 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.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_probsis capped at the vocabulary size.logprobswith a 400.POST /tokenizefor a resident MLX model. Same owner-only route as the llama-server passthrough. It takescontentandadd_special, parses special tokens like llama-server, and refuseswith_pieces.What does not change
logprobsbuild exactly the same generation command and batch as before./v1/completionsand/tokenizestill go to llama-server whenever a GGUF is loaded.logprobswithstream: true, withecho(prompt logprobs), with several prompts orn > 1, andpost_sampling_probstogether withlogprobs, which llama-server answers from the sampled distribution under different field names (prob/top_probs)./tokenizerefuseswith_piecesandparse_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:
tokenandbytescome from decoding that id alone, so they show the replacement character instead of the raw piece.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 bylogit_biasreports its unbiased logprob (log 0.04, not about 0); the vision path skips the draft.test_presence_penalty.py:n_probscrosses the worker only to a backend that serves it.test_llama_compat_routes.py:/tokenizeanswers 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 withlogit_biasreports 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