Repository navigation
Studio: apply presence_penalty on the safetensors and MLX inference paths - #6782
danielhanchen wants to merge 5 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for presence_penalty in both the safetensors (transformers) and MLX inference backends to ensure parity with the GGUF path. It implements the penalty calculation, threads the parameter through the orchestrator, worker, and API routes, and adds comprehensive unit tests. The review feedback highlights a performance bottleneck in the MLX presence penalty implementation, where converting tokens to a Python list forces an expensive CPU-GPU synchronization. It is recommended to use native MLX operations to apply the penalty directly on the GPU and avoid this overhead.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| # Dedup to unique ids so presence is applied once per token. | ||
| seen = list({int(t) for t in generated.tolist()}) | ||
| if not seen: | ||
| return logits | ||
| idx = mx.array(seen) | ||
| logits[:, idx] = logits[:, idx] - penalty |
There was a problem hiding this comment.
The current implementation of the presence penalty processor in MLX converts the generated array to a Python list using generated.tolist() and performs a set comprehension to deduplicate tokens. Doing this at every single generation step forces a CPU-GPU synchronization (blocking the Metal execution pipeline) and introduces significant Python loop overhead, which severely degrades generation throughput on Apple Silicon.
Since index assignment in MLX is naturally idempotent (writing the same value to the same index multiple times results in the value being written once), we can apply the penalty directly on the GPU using native MLX operations without any deduplication or CPU-GPU roundtrips.
vocab_size = logits.shape[-1]
idx = generated[generated < vocab_size]
logits[:, idx] = logits[:, idx] - penalty|
@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". |
…aths The GGUF backend applies presence_penalty (Qwen3.5/3.6 recommend 1.5 in inference_defaults.json), but the transformers safetensors path resolved the same config and then dropped the value before generation, so the same model looked worse served as safetensors (more repetition on prompts like "Create a Flappy Bird game in HTML"). transformers .generate() has no native presence_penalty, and the parameter was absent from the orchestrator command, the worker gen_kwargs, and the backend generate paths. - inference.py: add apply_presence_penalty plus a LogitsProcessor factory (OpenAI/llama.cpp style: subtract the penalty once from every distinct completion token, prompt excluded, presence not frequency, zero is a no-op, negatives raise). Thread presence_penalty through generate_chat_response, generate_chat_completion_with_tools, the vision path, and generate_stream, and attach the processor at both model.generate() sites. - orchestrator.py / worker.py: carry presence_penalty in the generate command and worker gen_kwargs so the already-resolved request value reaches the subprocess backend (no re-derivation). - routes/inference.py: forward payload.presence_penalty on the safetensors chat branch (tool, plain, and adapter paths) and add presence_penalty plus min_p to the legacy /generate/stream route. - models/inference.py: add min_p to GenerateRequest (it was dropped on the stream route while the chat route already passed it). - mlx_inference.py: add an OpenAI-style presence-penalty logits processor for the MLX text and vision paths so MLX matches too. - tests: PresencePenaltyLogitsProcessor unit tests (seen gets -penalty, unseen unchanged, multiplicity ignored, negatives, batch isolation, prompt excluded, zero no-op, dtype/device preserved) plus a route -> orchestrator cmd -> worker gen_kwargs param-propagation regression covering all six sampling params. Backwards compatible: presence_penalty defaults to 0.0 (byte-identical to before when unset) and the GGUF path is unchanged. Verified end to end on unsloth/Qwen3.5-4B: under greedy decoding pp=0 and pp=1.5 now produce different completions, proving the processor is applied on the safetensors path.
c6f17f2 to
1fd43a5
Compare
|
Good catch on the MLX path, fixed in 1fd43a5. Dropped the per-step |
|
Empirical follow-up for this PR. I ran "Create a Flappy Bird game in HTML" end to end through the secure Studio API to confirm that applying presence_penalty on the safetensors and MLX paths does not regress output, and to quantify any GGUF-vs-safetensors gap. Matrix: unsloth/Qwen3.5-{2B,4B,9B} and unsloth/gemma-4-E2B-it, each served as GGUF bf16, GGUF UD-Q4_K_XL, and HF bf16, under three sampling conditions: greedy (temperature=0, presence_penalty=0), recommended sampling without presence_penalty, and recommended sampling with presence_penalty=1.5 (gemma keeps its recommended 0.0 but is forced to 1.5 as a control). Structural score is out of 10 (single complete html doc, closed script/style, game loop, bird physics, pipe spawn, collision, score, restart, no runaway repetition, not truncated); maxrun is the longest repeated-line run. Findings:
Reading notes:
Structural score is out of 10; maxrun is the longest repeated-line run (lower is better, no runaway repetition).
Per-condition raw rows (timings)
|
|
MLX path validation. Since this dev host is Linux/CUDA, I ran the MLX presence-penalty logits processor on a real Apple Silicon (macos-14) runner with the real mlx / mlx-lm wheels:
So both the transformers (safetensors/vision) and MLX paths apply presence_penalty with matching semantics. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9e78200ff
ℹ️ 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".
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
When presence_penalty is non-zero, this slice does not match the GGUF path this PR is trying to mirror: Studio does not send repeat_last_n to llama-server, so the server seeds the penalty sampler with the prompt and uses its default recent-token window, while this implementation ignores every prompt token and later keeps penalizing the entire completion. That makes safetensors/MLX logits diverge under the Qwen default presence_penalty=1.5 for prompts whose next useful token already appears in the prompt, and for long outputs that need to reuse an identifier/topic generated more than the GGUF window ago.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9e78200ff
ℹ️ 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".
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Include prompt tokens in presence penalty history
When presence_penalty is set, this slices off the prompt and only penalizes tokens generated earlier in the same response. The GGUF path this is meant to match forwards presence_penalty to llama-server, whose sampler is initialized with the full prompt before sampling, so a token that appears in the user/system prompt is already penalized for the first generated token. Requests that rely on GGUF/safetensors parity will therefore get different distributions whenever the model might repeat prompt terms; the MLX processor added in this commit has the same prompt-latching assumption and should be updated consistently.
Useful? React with 👍 / 👎.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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 |
|
Codex Review: Didn't find any major issues. Breezy! 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 28beeb6ad6
ℹ️ 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".
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Include prompt tokens in presence-penalty history
When presence_penalty is non-zero and the prompt contains tokens that are likely candidates in the answer, slicing from prompt_len means the safetensors path does not penalize those prompt tokens on the first generation steps. The GGUF path forwards the same parameter directly to llama-server, whose sampler is primed with the prompt history, so safetensors/MLX still diverge from GGUF for prompts containing repeated keywords or formats; include the prompt tokens in the penalty history if this is meant to provide GGUF parity.
Useful? React with 👍 / 👎.
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Bound presence penalty to the same recent-token window
For completions longer than the sampler's repeat window, this slice keeps every token ever generated in the request penalized, so an early token remains suppressed hundreds or thousands of tokens later. The GGUF/llama.cpp path applies presence penalties through its repeat-penalty history window rather than the entire completion, so long safetensors generations with presence_penalty set will drift from GGUF and can over-penalize common syntax or words; limit the history to the same recent-token window before taking the unique set.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 28beeb6ad6
ℹ️ 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".
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Match llama.cpp's penalty window
When presence_penalty is non-zero, this slice only considers the generated suffix and omits prompt tokens. The GGUF path this is meant to match leaves repeat_last_n at llama-server's default 64 and initializes the sampler with the prompt tokens, so early decoding penalizes prompt tokens and later decoding drops tokens outside that recent-token window; this code does neither. Requests that rely on GGUF/safetensors parity, such as prompts containing words the model tends to echo or completions longer than 64 tokens, will get different logits. Use the same recent-token window instead of input_ids[b, prompt_len:].
Useful? React with 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
… collects The backend-CI matrix installs torch and transformers but not unsloth/peft, and test_presence_penalty.py imported through inference.py, whose module-scope from unsloth import ... raised PackageNotFoundError and aborted collection for the whole session. Move the pure torch+transformers helpers (apply_presence_penalty, _make_presence_penalty_processor) into core/inference/presence_penalty.py; inference.py re-imports them for its runtime use and the test imports the leaf directly, so the unit tests run in the lightweight env. Also run the PR's MLX additions through the repo formatter (pre-commit.ci).
|
@codex review |
|
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 502754f192
ℹ️ 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".
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Include prompt tokens in presence-penalty history
When presence_penalty is nonzero on the safetensors path, this slice only considers tokens generated after prompt_len, so tokens already present in the prompt are not penalized when choosing the first completion token. I checked the existing GGUF path and it forwards the same field to llama-server (studio/backend/core/inference/llama_cpp.py:7896), whose penalty sampler is fed the accepted prompt history; prompts that mention a token they ask the model to repeat therefore decode differently between GGUF and safetensors with identical settings. Please seed the processor with the prompt history (or otherwise match the llama-server/OpenAI penalty history) instead of starting at prompt_len.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is intentional. The safetensors path follows the OpenAI/vLLM convention where the presence penalty applies to generated tokens only, with the prompt excluded. Seeding the full prompt would not match llama-server either, since its penalty runs over a bounded penalty_last_n window (default 64) rather than the whole prompt, so exact parity would require replicating that windowing, not full-prompt seeding. Leaving the behaviour as-is.
inference.py only calls _make_presence_penalty_processor; apply_presence_penalty was hoisted in alongside it but never used there (the tests import it directly from the presence_penalty leaf module, and nothing re-exports it from inference). The import-hoist / alias-rename safety check flagged it as a HOISTED-IMPORT-UNUSED blocker, red-failing Source lint. Import only the symbol inference.py actually uses.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 95263cec9f
ℹ️ 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".
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Include prompt tokens in presence penalties
With this slice, a nonzero presence_penalty only starts after a token has already been emitted. The GGUF/llama-server path this is trying to match initializes its sampler by accepting every prompt token before decoding, so tokens that appear in the prompt are penalized on the very first completion step. For prompts that contain words or code identifiers the model might repeat, safetensors output will still diverge from GGUF and allow prompt-token repetition until after the first generated occurrence.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same as the earlier note: this is intentional. The safetensors path follows the OpenAI/vLLM output-only convention (prompt excluded). Exact llama-server parity would require replicating its penalty_last_n sliding window (default 64), which penalizes only the most recent tokens rather than the whole prompt, so seeding the full prompt would not match it either. Keeping the output-only behaviour.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 95263cec9f
ℹ️ 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".
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Include prompt tokens in presence penalty history
When presence_penalty is set and a candidate token appears in the prompt but has not yet been generated, slicing the history at prompt_len leaves that token unpenalized on the safetensors path. The GGUF path this is meant to match forwards presence_penalty to llama-server, whose penalty sampler is seeded with prompt tokens before generation, so prompts that contain repeated/candidate terms still produce different logits and outputs between GGUF and safetensors/MLX (notably for models with a nonzero default such as 1.5).
Useful? React with 👍 / 👎.
| return scores | ||
| vocab_size = scores.shape[-1] | ||
| for b in range(input_ids.shape[0]): | ||
| generated = input_ids[b, prompt_len:] |
There was a problem hiding this comment.
Cap presence history to the GGUF penalty window
For long completions with a nonzero presence_penalty, this slice feeds the processor every generated token seen so far, so tokens emitted hundreds or thousands of tokens ago remain suppressed. The GGUF path only forwards presence_penalty/repeat_penalty in LlamaCppBackend.generate_chat_completion and does not override llama-server's repeat-last-n penalty window, so safetensors/MLX outputs diverge once generation exceeds that window; cap this history to the same window or thread an equivalent setting through.
Useful? React with 👍 / 👎.
|
@codex review |
|
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". |
Summary
The GGUF backend applies
presence_penalty(Qwen3.5/3.6 recommend1.5ininference_defaults.json), but the transformers safetensors path resolved the same inference config and then dropped the value before generation. The parameter was missing from the orchestrator command, the workergen_kwargs, and the backend generate paths, andtransformers.generate()has no nativepresence_penalty. So the same model applied1.5as GGUF and0as safetensors, which shows up as more repetition on prompts like "Create a Flappy Bird game in HTML".This threads the already-resolved
presence_penaltythrough to the safetensors and MLX generate calls and applies it with a small logits processor. It is backwards compatible:presence_penaltydefaults to0.0(byte-identical output when unset) and the GGUF path is unchanged.Changes
core/inference/inference.py: addapply_presence_penaltyand aLogitsProcessorfactory (OpenAI/llama.cpp semantics: subtract the penalty once from each distinct completion token, prompt excluded, presence not frequency, zero is a no-op, negatives raise). Threadpresence_penaltythroughgenerate_chat_response,generate_chat_completion_with_tools, the vision path, andgenerate_stream, and attach the processor at bothmodel.generate()sites (text and vision).core/inference/orchestrator.pyandcore/inference/worker.py: carrypresence_penaltyin the generate command and workergen_kwargsso the resolved request value reaches the subprocess backend.routes/inference.py: forwardpayload.presence_penaltyon the safetensors chat branches (tool, plain, adapter), and addpresence_penaltyplusmin_pto the legacy/generate/streamroute.models/inference.py: add the missingmin_pfield toGenerateRequest(the chat route already passedmin_p; the stream route dropped it).core/inference/mlx_inference.py: matching presence-penalty logits processor for the MLX text and vision paths.Tests
studio/backend/tests/test_presence_penalty.py:apply_presence_penaltyand the processor: seen token gets exactly-penalty, unseen unchanged, multiplicity ignored, negatives raise, batch rows isolated, prompt excluded, zero is a no-op, dtype/device preserved, composes with an existing processor.temperature,top_p,top_k,min_p,repetition_penalty,presence_penaltyis dropped across the route to orchestrator command to workergen_kwargsboundary.Verification
Verified end to end on
unsloth/Qwen3.5-4B: under greedy decoding,presence_penalty=0andpresence_penalty=1.5now produce different completions. Before this change they were byte-identical, which confirms the value was silently dropped and is now applied on the safetensors path.