Skip to content

Sampler: presence/frequency penalties and DRY to stop repetition loops - #54

Merged
Vasyl-Trefilov merged 2 commits into
RustingStudio:mainfrom
dinukasal:fix/repetition-penalties
Nov 19, 2026
Merged

Vasyl-Trefilov merged 2 commits into
RustingStudio:mainfrom
dinukasal:fix/repetition-penalties

Conversation

@dinukasal

@dinukasal dinukasal commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem

serve decodes greedily unless a request sends temperature (--temp defaults to 0), and the sampler has no repetition control. Many OpenAI-compatible clients and agent harnesses never send sampling fields. With a low-bit quant of a thinking model, the reasoning then falls into loops it never leaves, rewriting the same line until max_tokens runs out.

Seen with Qwen3.6-35B-A3B-MTP-UD-Q2_K_XL (CUDA, RTX 2060 Super, MTP on): the server log showed repeated finish=cut and finish=length replies at 16384 tokens, mostly long thinking blocks in agent sessions.

Fix

OpenAI-style presence_penalty and frequency_penalty in ops::Sampler:

  • The sampler counts every token it returns (seen). Before choosing, presence + frequency * count is subtracted from those tokens' logits. Only the reply is penalized, not the prompt, as in OpenAI and vLLM.
  • Applied in both pick and accept, so plain decoding and the MTP / n-gram / hybrid speculative paths behave the same. An accepted draft and a resampled token are both counted. accept keeps the distribution of pick because both use the same penalized logits.
  • Nothing changes when both penalties are 0 (the defaults): penalized returns None and no logits are copied.
  • serve accepts presence_penalty / frequency_penalty in requests (validated to [-2, 2]). The new --presence-penalty / --frequency-penalty flags set the defaults for requests that leave them out.
  • serve logs the effective sampling once per request (sampling: temp=… top_k=… top_p=… presence=… frequency=…), so you can tell from the log when a client is silently decoding greedily.

The greedy fast path (step_greedy, temp == 0 on the GPU) skips the sampler, so the penalties only apply when temp > 0. The flag help says so.

Results

Same model, serve --temp 0.6 --top-k 20 --top-p 0.95 (Qwen's recommended settings), prompt "List 40 distinct uses for a paperclip, numbered. Be brief.", max_tokens 6000:

presence_penalty finish completion tokens distinct / total reasoning lines
0.0 length (stuck rewriting item 39) 6000 181 / 393
1.0 stop 2679 155 / 185

With presence_penalty 1.0, a two-call tool request still returns valid JSON arguments ({"city": "Colombo", "unit": "c"}, {"city": "Kandy", "unit": "c"}).

DRY sampler (second commit)

Presence penalty alone was not enough in a long agent session (pi, ~100k-token prompt, 49 tools, temp 0.7 top_p 0.8 presence 1): the reasoning cycled through the same five paragraphs for 5871 tokens. Once a cycle has been written once, every token in it carries the same flat presence penalty, so nothing favors leaving the cycle.

The second commit adds DRY, as in llama.cpp:

  • A token that would extend a sequence of n >= dry_allowed_length tokens that already appeared in the reply loses dry_multiplier * dry_base^(n - dry_allowed_length) of logit.
  • The lookback is the last 4096 reply tokens, and matches are capped at 64 tokens.
  • Matches stop at tokens whose text contains a newline, :, " or * (llama.cpp's default breakers). These are computed once per model from the vocabulary.
  • New flags --dry-multiplier (0 = off, the default), --dry-base (1.75) and --dry-allowed-length (2), plus the llama.cpp server request fields dry_multiplier, dry_base and dry_allowed_length.
  • Tool calls are exempt: between <tool_call> and </tool_call> no penalty applies and no token is counted. Arguments often copy a path or name the reasoning already wrote, and a penalty there would change it.

With pi's settings plus --dry-multiplier 0.8, on the paperclip prompt: 204 / 204 reasoning lines were distinct (139 / 176 without DRY). A tool request that reads two files repeated both full paths exactly.

Tests

  • New penalties_push_away_from_returned_tokens in tests/ops.rs: covers presence, frequency, and a rejected draft whose resampled token is counted.
  • New dry_penalizes_extending_a_repeat (penalty size, and breakers cutting a match) and no_penalties_inside_tool_calls.
  • Existing Sampler { .. } literals in tests/ops.rs use ..Sampler::greedy() for the new fields.
  • cargo test --release --test ops --test serve passes (13 + 28).

🤖 Generated with Claude Code

dinukasal and others added 2 commits November 19, 2026 11:18
Requests and the CLI default (--presence-penalty, --frequency-penalty) can now
penalize tokens already generated; both plain and MTP/ngram speculative paths
go through Sampler::pick/accept. Log the effective sampling per request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A presence penalty does not stop paragraph-length loops: once a cycle has been
written once, all its tokens carry the same penalty. DRY (as in llama.cpp)
penalizes the token that would extend a sequence the reply already wrote,
growing with the length of the repeat; matches stop at newline, colon, quote
and asterisk tokens. --dry-multiplier (0 = off), --dry-base, --dry-allowed-length
and the request fields dry_multiplier, dry_base, dry_allowed_length.

Between <tool_call> and </tool_call> no penalty applies and no token is
counted, so tool arguments can copy paths the reply already mentioned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dinukasal dinukasal changed the title Sampler: presence/frequency penalties to stop repetition loops Sampler: presence/frequency penalties and DRY to stop repetition loops Nov 19, 2026
ybenyedder pushed a commit to ybenyedder/RustingStrata that referenced this pull request Nov 19, 2026
@Vasyl-Trefilov
Vasyl-Trefilov merged commit b81b1cd into RustingStudio:main Nov 19, 2026
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Merged, thank you!

Vasyl-Trefilov added a commit that referenced this pull request Nov 19, 2026
…ockerfile

- hy4: Hy4-flash (hy_v4_flash) in chat, generate, serve, bench and check
- drafts: DFlash/DFlash2 Q4_0, FlashCascade, external draft models; q4/q2 KV; RDNA3.5 WMMA and AVX-512 paths
- sampler: presence and frequency penalties and DRY (#54), repeat_penalty and penalty_last_n (#45)
- calibrate: the file names its GPU and one from another GPU is ignored; XDG_CACHE_HOME moves the folder (#52)
- weights: model files that fit in RAM are read into the page cache at start (#49)
- cpu experts: all (token, expert) pairs in one batched pass
- mtp: chunked prefill keeps the last hidden state on Flash-Next with a draft head
- lora: dimension check for routed-expert adapters
- serve: chunked request bodies, the Host error names --allowed-hosts (#48); keyless MCP routes refuse proxy headers (#18)
- docker: Dockerfile for the server image, CUDA and Vulkan (#58)
Vasyl-Trefilov added a commit that referenced this pull request Nov 20, 2026
Adds OpenAI presence_penalty and frequency_penalty and a llama.cpp-style DRY sampler (flags and request fields,
off by default, need temperature above 0). Tool-call bodies are exempt.

Maintainer changes in the merge:
- tests/ops.rs: both sides added tests at the same place; kept all.
- accept_dist (DFlash and external draft models, added after the branch point) applies the penalties and records
  the tokens it returns, like pick and accept.
- chat: the penalty history is cleared before each reply.
- docs/USAGE.md: the new request fields and flags.
Vasyl-Trefilov added a commit that referenced this pull request Nov 20, 2026
…ockerfile

- hy4: Hy4-flash (hy_v4_flash) in chat, generate, serve, bench and check
- drafts: DFlash/DFlash2 Q4_0, FlashCascade, external draft models; q4/q2 KV; RDNA3.5 WMMA and AVX-512 paths
- sampler: presence and frequency penalties and DRY (#54), repeat_penalty and penalty_last_n (#45)
- calibrate: the file names its GPU and one from another GPU is ignored; XDG_CACHE_HOME moves the folder (#52)
- weights: model files that fit in RAM are read into the page cache at start (#49)
- cpu experts: all (token, expert) pairs in one batched pass
- mtp: chunked prefill keeps the last hidden state on Flash-Next with a draft head
- lora: dimension check for routed-expert adapters
- serve: chunked request bodies, the Host error names --allowed-hosts (#48); keyless MCP routes refuse proxy headers (#18)
- docker: Dockerfile for the server image, CUDA and Vulkan (#58)
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.

2 participants