Skip to content

Studio: apply presence_penalty on the safetensors and MLX inference paths - #6782

Closed
danielhanchen wants to merge 5 commits into
unslothai:mainfrom
danielhanchen:studio-presence-penalty-parity
Closed

danielhanchen wants to merge 5 commits into
unslothai:mainfrom
danielhanchen:studio-presence-penalty-parity

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

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 inference config and then dropped the value before generation. The parameter was missing from the orchestrator command, the worker gen_kwargs, and the backend generate paths, and transformers .generate() has no native presence_penalty. So the same model applied 1.5 as GGUF and 0 as safetensors, which shows up as more repetition on prompts like "Create a Flappy Bird game in HTML".

This threads the already-resolved presence_penalty through to the safetensors and MLX generate calls and applies it with a small logits processor. It is backwards compatible: presence_penalty defaults to 0.0 (byte-identical output when unset) and the GGUF path is unchanged.

Changes

  • core/inference/inference.py: add apply_presence_penalty and a LogitsProcessor factory (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). 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 (text and vision).
  • core/inference/orchestrator.py and core/inference/worker.py: carry presence_penalty in the generate command and worker gen_kwargs so the resolved request value reaches the subprocess backend.
  • routes/inference.py: forward payload.presence_penalty on the safetensors chat branches (tool, plain, adapter), and add presence_penalty plus min_p to the legacy /generate/stream route.
  • models/inference.py: add the missing min_p field to GenerateRequest (the chat route already passed min_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:

  • Unit tests for apply_presence_penalty and 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.
  • MLX callable test (skipped off an MLX host).
  • A param-propagation regression that fails if any of temperature, top_p, top_k, min_p, repetition_penalty, presence_penalty is dropped across the route to orchestrator command to worker gen_kwargs boundary.
PYTHONPATH=studio/backend python -m pytest -q studio/backend/tests/test_presence_penalty.py
14 passed, 1 skipped

Verification

Verified end to end on unsloth/Qwen3.5-4B: under greedy decoding, presence_penalty=0 and presence_penalty=1.5 now 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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +66 to +71
# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c6f17f2b44

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

…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.
@danielhanchen
danielhanchen force-pushed the studio-presence-penalty-parity branch from c6f17f2 to 1fd43a5 Compare July 1, 2026 12:45
@danielhanchen

Copy link
Copy Markdown
Member Author

Good catch on the MLX path, fixed in 1fd43a5. Dropped the per-step tolist() + set dedup and index natively now: MLX scatter-assignment is idempotent for duplicate ids, so logits[:, generated] = logits[:, generated] - penalty applies the penalty once per token on-device with no host sync.

@danielhanchen

danielhanchen commented Jul 2, 2026 •

Copy link
Copy Markdown
Member Author

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:

  • Every backend and condition produces a complete, playable game (8 to 10 of 10, maxrun <= 4). There is no catastrophic safetensors gap. The earlier "safetensors looks worse" report is explained by presence_penalty being silently dropped on that path, which this PR fixes.
  • With the fix, presence_penalty=1.5 engages on safetensors (and MLX, via the mirrored logits processor) without breaking structure or causing runaway repetition, matching GGUF behaviour.
  • The greedy control (temperature=0) isolates quantization and template from sampling: safetensors greedy is as complete as GGUF greedy.

Reading notes:

  • I dropped the hf_bnb4 rows: Studio no-ops a load when model_path is unchanged, so the bnb-4bit pass reused the bf16 weights already resident (identical char counts gave it away). HF bf16 is the safetensors reference here.
  • Any residual GGUF-vs-safetensors difference is quantization (GGUF UD-Q4_K_XL vs the HF bnb-4bit default), not a bug. bf16-vs-bf16 is the clean comparison and it matches.

Structural score is out of 10; maxrun is the longest repeated-line run (lower is better, no runaway repetition).

model precision greedy (pp=0) recommended, no pp recommended, pp=1.5
Qwen3.5-2B GGUF BF16 9/10 (maxrun 2) 8/10 (maxrun 3) 9/10 (maxrun 2)
Qwen3.5-2B GGUF Q4 9/10 (maxrun 2) 9/10 (maxrun 2) 8/10 (maxrun 2)
Qwen3.5-2B HF bf16 9/10 (maxrun 2) 9/10 (maxrun 3) 9/10 (maxrun 3)
Qwen3.5-4B GGUF BF16 10/10 (maxrun 3) 9/10 (maxrun 2) 9/10 (maxrun 3)
Qwen3.5-4B GGUF Q4 9/10 (maxrun 2) 9/10 (maxrun 2) 9/10 (maxrun 3)
Qwen3.5-4B HF bf16 9/10 (maxrun 3) 9/10 (maxrun 3) 9/10 (maxrun 3)
Qwen3.5-9B GGUF BF16 9/10 (maxrun 3) 9/10 (maxrun 3) 8/10 (maxrun 3)
Qwen3.5-9B GGUF Q4 9/10 (maxrun 3) 9/10 (maxrun 2) 9/10 (maxrun 2)
Qwen3.5-9B HF bf16 9/10 (maxrun 3) 9/10 (maxrun 3) 8/10 (maxrun 3)
gemma-4-E2B-it GGUF BF16 9/10 (maxrun 3) 9/10 (maxrun 3) 9/10 (maxrun 3)
gemma-4-E2B-it GGUF Q4 9/10 (maxrun 3) 9/10 (maxrun 4) 9/10 (maxrun 3)
gemma-4-E2B-it HF bf16 9/10 (maxrun 3) 9/10 (maxrun 3) 9/10 (maxrun 3)
Per-condition raw rows (timings)
model precision condition struct score notes
Qwen3.5-2B gguf_bf16 greedy (pp=0.0) 9/10 chars=9215 maxrun=2 11.3s
Qwen3.5-2B gguf_bf16 rec_nopp (pp=0.0) 8/10 chars=12733 maxrun=3 8.9s
Qwen3.5-2B gguf_bf16 rec_pp (pp=1.5) 9/10 chars=8722 maxrun=2 9.5s
Qwen3.5-2B gguf_q4 greedy (pp=0.0) 9/10 chars=10237 maxrun=2 10.7s
Qwen3.5-2B gguf_q4 rec_nopp (pp=0.0) 9/10 chars=11383 maxrun=2 6.9s
Qwen3.5-2B gguf_q4 rec_pp (pp=1.5) 8/10 chars=11948 maxrun=2 11.5s
Qwen3.5-2B hf_bf16 greedy (pp=0.0) 9/10 chars=9876 maxrun=2 83.6s
Qwen3.5-2B hf_bf16 rec_nopp (pp=0.0) 9/10 chars=10648 maxrun=3 88.5s
Qwen3.5-2B hf_bf16 rec_pp (pp=1.5) 9/10 chars=10793 maxrun=3 89.7s
Qwen3.5-4B gguf_bf16 greedy (pp=0.0) 10/10 chars=11513 maxrun=3 21.0s
Qwen3.5-4B gguf_bf16 rec_nopp (pp=0.0) 9/10 chars=11669 maxrun=2 14.0s
Qwen3.5-4B gguf_bf16 rec_pp (pp=1.5) 9/10 chars=10816 maxrun=3 17.4s
Qwen3.5-4B gguf_q4 greedy (pp=0.0) 9/10 chars=11297 maxrun=2 16.4s
Qwen3.5-4B gguf_q4 rec_nopp (pp=0.0) 9/10 chars=9629 maxrun=2 9.5s
Qwen3.5-4B gguf_q4 rec_pp (pp=1.5) 9/10 chars=9915 maxrun=3 14.1s
Qwen3.5-4B hf_bf16 greedy (pp=0.0) 9/10 chars=12891 maxrun=3 126.6s
Qwen3.5-4B hf_bf16 rec_nopp (pp=0.0) 9/10 chars=11772 maxrun=3 116.6s
Qwen3.5-4B hf_bf16 rec_pp (pp=1.5) 9/10 chars=11072 maxrun=3 129.1s
Qwen3.5-9B gguf_bf16 greedy (pp=0.0) 9/10 chars=10560 maxrun=3 185.5s
Qwen3.5-9B gguf_bf16 rec_nopp (pp=0.0) 9/10 chars=12405 maxrun=3 230.6s
Qwen3.5-9B gguf_bf16 rec_pp (pp=1.5) 8/10 chars=13115 maxrun=3 240.4s
Qwen3.5-9B gguf_q4 greedy (pp=0.0) 9/10 chars=11127 maxrun=3 17.5s
Qwen3.5-9B gguf_q4 rec_nopp (pp=0.0) 9/10 chars=10106 maxrun=2 12.0s
Qwen3.5-9B gguf_q4 rec_pp (pp=1.5) 9/10 chars=9389 maxrun=2 14.7s
Qwen3.5-9B hf_bf16 greedy (pp=0.0) 9/10 chars=11625 maxrun=3 116.3s
Qwen3.5-9B hf_bf16 rec_nopp (pp=0.0) 9/10 chars=11129 maxrun=3 113.7s
Qwen3.5-9B hf_bf16 rec_pp (pp=1.5) 8/10 chars=11730 maxrun=3 130.3s
gemma-4-E2B-it gguf_bf16 greedy (pp=0.0) 9/10 chars=12373 maxrun=3 14.4s
gemma-4-E2B-it gguf_bf16 rec_nopp (pp=0.0) 9/10 chars=9765 maxrun=3 7.4s
gemma-4-E2B-it gguf_bf16 rec_pp_forced (pp=1.5) 9/10 chars=10882 maxrun=3 11.8s
gemma-4-E2B-it gguf_q4 greedy (pp=0.0) 9/10 chars=10331 maxrun=3 11.9s
gemma-4-E2B-it gguf_q4 rec_nopp (pp=0.0) 9/10 chars=12350 maxrun=4 8.2s
gemma-4-E2B-it gguf_q4 rec_pp_forced (pp=1.5) 9/10 chars=12017 maxrun=3 12.1s
gemma-4-E2B-it hf_bf16 greedy (pp=0.0) 9/10 chars=12274 maxrun=3 142.4s
gemma-4-E2B-it hf_bf16 rec_nopp (pp=0.0) 9/10 chars=10506 maxrun=3 125.1s
gemma-4-E2B-it hf_bf16 rec_pp_forced (pp=1.5) 9/10 chars=10140 maxrun=3 123.4s

@danielhanchen

Copy link
Copy Markdown
Member Author

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:

  • On-device scatter semantics hold: a completion token repeated N times is still penalized once (presence, not frequency), the prompt is excluded, negatives raise the seen logits, and dtype is preserved. These mirror the transformers processor exactly.
  • End to end through mlx_lm.stream_generate on a tiny MLX model: logits_processors reaches the processor as fn(tokens, logits) with tokens 1-D and logits [1, vocab], and presence_penalty=1.5 changes the greedy continuation.

So both the transformers (safetensors/vision) and MLX paths apply presence_penalty with matching semantics.

@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: 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:]

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 Match GGUF's penalty context

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 👍 / 👎.

@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: 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:]

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 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

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

@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: 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:]

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 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:]

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 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 👍 / 👎.

@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: 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:]

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 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

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

… 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).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

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

@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: 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:]

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 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 👍 / 👎.

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.

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.
@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: 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:]

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 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 👍 / 👎.

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.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@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: 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:]

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 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:]

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 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

2 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

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

@danielhanchen

Copy link
Copy Markdown
Member Author

Re-created as a same-repo PR onto current main in #6923 (the fork branch could not merge cross-repo). Net changes reapplied and conflicts resolved against the refactored safetensors/MLX inference paths; tests pass. Superseded by #6923.

@danielhanchen

Copy link
Copy Markdown
Member Author

Superseded by #6923, the same-repo version of this change, which is now merged into main. The cross-repo branch cannot land directly, so closing this one. #6923 carries the identical presence_penalty support for the safetensors and MLX paths plus the out-of-range id bounding on both paths.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant