From df16c3b8b53374be50677dc1508a584f3acd3045 Mon Sep 17 00:00:00 2001 From: dinukasal <9583917+dinukasal@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:18:35 +0530 Subject: [PATCH 1/2] Add presence/frequency penalties to the sampler 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 --- src/main.rs | 12 +++++++++++- src/ops.rs | 47 ++++++++++++++++++++++++++++++++++++++--------- src/serve.rs | 6 +++++- tests/ops.rs | 27 ++++++++++++++++++++++----- 4 files changed, 76 insertions(+), 16 deletions(-) diff --git a/src/main.rs b/src/main.rs index ce5c4efb..4defdc02 100644 --- a/src/main.rs +++ b/src/main.rs @@ -77,6 +77,12 @@ struct Engine { top_k: usize, #[arg(long, default_value_t = 1.0)] top_p: f32, + /// Default presence penalty (OpenAI `presence_penalty`); needs --temp > 0. Qwen recommends 1.5 against loops. + #[arg(long, default_value_t = 0.0)] + presence_penalty: f32, + /// Default frequency penalty (OpenAI `frequency_penalty`); needs --temp > 0. + #[arg(long, default_value_t = 0.0)] + frequency_penalty: f32, /// Random seed for sampling [default: from the clock]. #[arg(long)] seed: Option, @@ -411,7 +417,8 @@ impl Engine { }) } fn sampler(&self) -> Sampler { - Sampler { temp: self.temp, top_k: self.top_k, top_p: self.top_p, rng: seed(self.seed) } + Sampler { temp: self.temp, top_k: self.top_k, top_p: self.top_p, rng: seed(self.seed), + presence: self.presence_penalty, frequency: self.frequency_penalty, seen: Default::default() } } fn chunk(&self) -> usize { self.chunk.unwrap_or(4096) } fn mtp(&self) -> usize { self.mtp.unwrap_or(0) } @@ -2327,6 +2334,9 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo smp.temp = req.temperature.unwrap_or(smp.temp); smp.top_k = req.top_k.unwrap_or(smp.top_k); smp.top_p = req.top_p.unwrap_or(smp.top_p); + smp.presence = req.presence_penalty.unwrap_or(smp.presence); + smp.frequency = req.frequency_penalty.unwrap_or(smp.frequency); + eprintln!("sampling: temp={} top_k={} top_p={} presence={} frequency={}", smp.temp, smp.top_k, smp.top_p, smp.presence, smp.frequency); if req.seed.is_some() { smp.rng = seed(req.seed); } let n = room(e, ids.len(), req.max_tokens.unwrap_or(usize::MAX).min(s.max_tokens)); if n == 0 { return send(&mut w, "400 Bad Request", json!({"error": {"message": format!("prompt of {} tokens fills the context", ids.len()), "type": "invalid_request_error"}})); } diff --git a/src/ops.rs b/src/ops.rs index 69d7a5db..f16ddf0b 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -122,29 +122,58 @@ pub struct Sampler { pub top_p: f32, /// xorshift64 state; must not be 0. pub rng: u64, + /// OpenAI `presence_penalty`: subtracted once from the logit of every token this sampler already returned. + pub presence: f32, + /// OpenAI `frequency_penalty`: subtracted from a returned token's logit once per time it was returned. + pub frequency: f32, + /// How often each token was returned, for the penalties (only the reply, not the prompt). + pub seen: std::collections::HashMap, } impl Sampler { - pub fn greedy() -> Self { Sampler { temp: 0.0, top_k: 0, top_p: 1.0, rng: 1 } } + pub fn greedy() -> Self { + Sampler { temp: 0.0, top_k: 0, top_p: 1.0, rng: 1, presence: 0.0, frequency: 0.0, seen: Default::default() } + } + + /// The logits with the presence and frequency penalties applied, or None when there is nothing to change. + /// Without them a quantized model that samples greedily (or nearly) falls into loops it never leaves. + fn penalized(&self, logits: &[f32]) -> Option> { + if self.seen.is_empty() || (self.presence == 0.0 && self.frequency == 0.0) { return None; } + let mut l = logits.to_vec(); + for (&t, &n) in &self.seen { + if let Some(x) = l.get_mut(t) { *x -= self.presence + self.frequency * n as f32; } + } + Some(l) + } + + fn note(&mut self, t: usize) { *self.seen.entry(t).or_insert(0) += 1; } pub fn pick(&mut self, logits: &[f32]) -> anyhow::Result { - if self.temp <= 0.0 { + let pen = self.penalized(logits); + let logits = pen.as_deref().unwrap_or(logits); + let i = if self.temp <= 0.0 { let i = argmax(logits); anyhow::ensure!(logits[i].is_finite(), NON_FINITE); - return Ok(i); - } - let c = self.cands(logits); - self.draw(&c) + i + } else { + let c = self.cands(logits); + self.draw(&c)? + }; + self.note(i); + Ok(i) } /// Speculative sampling with a fixed draft `d`: keeps `d` (None) with its probability under this sampler, else /// returns a token drawn from the others, renormalized. The result has the distribution of `pick`. `temp` > 0. pub fn accept(&mut self, logits: &[f32], d: usize) -> anyhow::Result> { - let c = self.cands(logits); + let pen = self.penalized(logits); + let c = self.cands(pen.as_deref().unwrap_or(logits)); anyhow::ensure!(!c.is_empty(), NON_FINITE); let q = c.iter().find(|x| x.0 == d).map_or(0.0, |x| x.1); - if self.rand() * c.iter().map(|x| x.1).sum::() < q { return Ok(None); } - Ok(Some(self.draw(&c.into_iter().filter(|x| x.0 != d).collect::>())?)) + if self.rand() * c.iter().map(|x| x.1).sum::() < q { self.note(d); return Ok(None); } + let x = self.draw(&c.into_iter().filter(|x| x.0 != d).collect::>())?; + self.note(x); + Ok(Some(x)) } /// The tokens `pick` draws from, with their weights (exp of the scaled logit, not normalized), most likely first. diff --git a/src/serve.rs b/src/serve.rs index d275aa0e..f817d311 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -274,6 +274,8 @@ pub struct ChatRequest { pub temperature: Option, pub top_k: Option, pub top_p: Option, + pub presence_penalty: Option, + pub frequency_penalty: Option, pub seed: Option, /// The reply ends before the first of these strings (`stop`). pub stop: Vec, @@ -320,7 +322,9 @@ pub fn chat_request(body: &[u8]) -> anyhow::Result { Ok(ChatRequest { messages, tools, tool_calls, max_tokens, stream: v["stream"].as_bool().unwrap_or(false), think, preserve_thinking: v["chat_template_kwargs"]["preserve_thinking"].as_bool(), temperature: num("temperature", |f| f >= 0.0, "a number >= 0")?, top_k: int("top_k", 0)?.map(|n| n as usize), - top_p: num("top_p", |f| f > 0.0 && f <= 1.0, "a number in (0, 1]")?, seed: int("seed", 0)?, stop }) + top_p: num("top_p", |f| f > 0.0 && f <= 1.0, "a number in (0, 1]")?, + presence_penalty: num("presence_penalty", |f| (-2.0..=2.0).contains(&f), "a number in [-2, 2]")?, + frequency_penalty: num("frequency_penalty", |f| (-2.0..=2.0).contains(&f), "a number in [-2, 2]")?, seed: int("seed", 0)?, stop }) } /// What the chat page's side panel shows about the server, kept by the request loop and answered by the reader diff --git a/tests/ops.rs b/tests/ops.rs index d67cefa0..c2b65e28 100644 --- a/tests/ops.rs +++ b/tests/ops.rs @@ -55,16 +55,16 @@ fn softmax_sums_to_one() { fn sampler_cuts_and_matches_softmax() { let l = [2.0f32.ln(), 1.0f32.ln(), 1.0f32.ln(), -50.0]; // probabilities 1/2, 1/4, 1/4, ~0 assert_eq!(Sampler::greedy().pick(&l).unwrap(), 0); - let mut s = Sampler { temp: 1.0, top_k: 0, top_p: 1.0, rng: 7 }; + let mut s = Sampler { temp: 1.0, top_k: 0, top_p: 1.0, rng: 7, ..Sampler::greedy() }; let mut n = [0usize; 4]; for _ in 0..20000 { n[s.pick(&l).unwrap()] += 1; } assert!(n[3] == 0 && (n[0] as f32 / 20000.0 - 0.5).abs() < 0.02 && (n[1] as f32 / 20000.0 - 0.25).abs() < 0.02, "{n:?}"); - let mut s = Sampler { temp: 1.0, top_k: 0, top_p: 0.5, rng: 7 }; + let mut s = Sampler { temp: 1.0, top_k: 0, top_p: 0.5, rng: 7, ..Sampler::greedy() }; assert!((0..100).all(|_| s.pick(&l).unwrap() == 0)); - let mut s = Sampler { temp: 1.0, top_k: 2, top_p: 1.0, rng: 7 }; + let mut s = Sampler { temp: 1.0, top_k: 2, top_p: 1.0, rng: 7, ..Sampler::greedy() }; assert!((0..100).all(|_| s.pick(&l).unwrap() < 2)); // A temperature so small that m - 21 * temp rounds to m must still keep the best token. - let mut s = Sampler { temp: 1e-9, top_k: 0, top_p: 1.0, rng: 7 }; + let mut s = Sampler { temp: 1e-9, top_k: 0, top_p: 1.0, rng: 7, ..Sampler::greedy() }; assert_eq!(s.pick(&[1.0, 10.0, 3.0]).unwrap(), 1); // Logits with no finite value are an error, not a panic, sampled or greedy. let bad = [f32::NAN, f32::INFINITY, f32::NAN]; @@ -76,10 +76,27 @@ fn sampler_accept_keeps_the_distribution() { // likely draft, an unlikely one and one outside the candidates. let l = [2.0f32.ln(), 1.0f32.ln(), 1.0f32.ln(), -50.0]; // 1/2, 1/4, 1/4, ~0 for d in [0, 1, 3] { - let mut s = Sampler { temp: 1.0, top_k: 0, top_p: 1.0, rng: 7 }; + let mut s = Sampler { temp: 1.0, top_k: 0, top_p: 1.0, rng: 7, ..Sampler::greedy() }; let mut n = [0usize; 4]; for _ in 0..40000 { n[s.accept(&l, d).unwrap().unwrap_or(d)] += 1; } let f = |i: usize| n[i] as f32 / 40000.0; assert!(n[3] == 0 && (f(0) - 0.5).abs() < 0.015 && (f(1) - 0.25).abs() < 0.015, "d {d}: {n:?}"); } } + +#[test] +fn penalties_push_away_from_returned_tokens() { + // Token 0 is a bit more likely; a presence penalty larger than the gap makes the sampler leave it after once. + let l = [1.0f32, 0.5, -10.0]; + let mut s = Sampler { presence: 2.0, ..Sampler::greedy() }; + assert_eq!(s.pick(&l).unwrap(), 0); + assert_eq!(s.pick(&l).unwrap(), 1); + let mut s = Sampler { temp: 1e-3, top_k: 0, top_p: 1.0, rng: 7, frequency: 0.3, ..Sampler::greedy() }; + let picks: Vec<_> = (0..4).map(|_| s.pick(&l).unwrap()).collect(); + assert_eq!(picks, [0, 0, 1, 0]); + // A rejected draft draws from the rest, and that draw counts too. + let mut s = Sampler { temp: 1e-3, presence: 5.0, ..Sampler::greedy() }; + s.seen.insert(0, 1); + assert_eq!(s.accept(&l, 0).unwrap(), Some(1)); + assert_eq!(s.seen.get(&1), Some(&1)); +} From 64b21ac233439936fdca7282b27faf24bba95102 Mon Sep 17 00:00:00 2001 From: dinukasal <9583917+dinukasal@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:30:22 +0530 Subject: [PATCH 2/2] Add the DRY sampler and exempt tool calls from penalties 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 and 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 --- src/main.rs | 33 ++++++++++++++++++++++-- src/ops.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++---- src/serve.rs | 9 ++++++- src/tokenizer.rs | 2 ++ tests/ops.rs | 33 ++++++++++++++++++++++++ 5 files changed, 136 insertions(+), 8 deletions(-) diff --git a/src/main.rs b/src/main.rs index 4defdc02..e1d1df9c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -83,6 +83,15 @@ struct Engine { /// Default frequency penalty (OpenAI `frequency_penalty`); needs --temp > 0. #[arg(long, default_value_t = 0.0)] frequency_penalty: f32, + /// DRY multiplier (0 = off; 0.8 is the usual value): penalizes a token that would repeat a sequence the reply + /// already wrote, more the longer the repeat. Stops paragraph loops that a presence penalty does not. Needs --temp > 0. + #[arg(long, default_value_t = 0.0)] + dry_multiplier: f32, + #[arg(long, default_value_t = 1.75)] + dry_base: f32, + /// Repeats up to this many tokens long are free. + #[arg(long, default_value_t = 2)] + dry_allowed_length: usize, /// Random seed for sampling [default: from the clock]. #[arg(long)] seed: Option, @@ -418,7 +427,8 @@ impl Engine { } fn sampler(&self) -> Sampler { Sampler { temp: self.temp, top_k: self.top_k, top_p: self.top_p, rng: seed(self.seed), - presence: self.presence_penalty, frequency: self.frequency_penalty, seen: Default::default() } + presence: self.presence_penalty, frequency: self.frequency_penalty, dry_mult: self.dry_multiplier, + dry_base: self.dry_base, dry_allowed: self.dry_allowed_length, ..Sampler::greedy() } } fn chunk(&self) -> usize { self.chunk.unwrap_or(4096) } fn mtp(&self) -> usize { self.mtp.unwrap_or(0) } @@ -1694,6 +1704,19 @@ fn calibrate(model: &Path, ctx: usize, margin: &[usize], kind: Option<&str>, dev Ok(()) } +/// Which tokens end a DRY match: those whose text has a newline, colon, double quote or asterisk (llama.cpp's +/// default breakers). Built once per model, as decoding the whole vocabulary takes a moment. +fn dry_breakers(tok: &Tokenizer, model: &str) -> std::sync::Arc> { + static CACHE: std::sync::Mutex>)>> = std::sync::Mutex::new(None); + let mut c = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((m, b)) = c.as_ref() { if m == model { return b.clone(); } } + let b: Vec = (0..tok.vocab_size() as u32) + .map(|i| tok.decode(&[i]).is_ok_and(|s| s.contains(['\n', ':', '"', '*']))).collect(); + let b = std::sync::Arc::new(b); + *c = Some((model.to_owned(), b.clone())); + b +} + /// Decoding of up to `n` tokens after `logits`; `emit` gets each new complete piece of text and returns true to stop. /// Returns the tokens and whether an end-of-turn token or `emit` stopped it. fn decode(r: &mut Runner, tok: &Tokenizer, mtp: bool, smp: &mut Sampler, mut logits: Vec, n: usize, @@ -2336,7 +2359,13 @@ fn handle(mut w: TcpStream, q: anyhow::Result, l: Option<&mut Lo smp.top_p = req.top_p.unwrap_or(smp.top_p); smp.presence = req.presence_penalty.unwrap_or(smp.presence); smp.frequency = req.frequency_penalty.unwrap_or(smp.frequency); - eprintln!("sampling: temp={} top_k={} top_p={} presence={} frequency={}", smp.temp, smp.top_k, smp.top_p, smp.presence, smp.frequency); + smp.dry_mult = req.dry_multiplier.unwrap_or(smp.dry_mult); + smp.dry_base = req.dry_base.unwrap_or(smp.dry_base); + smp.dry_allowed = req.dry_allowed_length.unwrap_or(smp.dry_allowed); + if smp.dry_mult > 0.0 { smp.dry_breakers = dry_breakers(tok, name); } + smp.tool_tags = tok.token_id("").zip(tok.token_id("")).map(|(a, b)| (a as usize, b as usize)); + eprintln!("sampling: temp={} top_k={} top_p={} presence={} frequency={} dry={}/{}/{}", smp.temp, smp.top_k, smp.top_p, + smp.presence, smp.frequency, smp.dry_mult, smp.dry_base, smp.dry_allowed); if req.seed.is_some() { smp.rng = seed(req.seed); } let n = room(e, ids.len(), req.max_tokens.unwrap_or(usize::MAX).min(s.max_tokens)); if n == 0 { return send(&mut w, "400 Bad Request", json!({"error": {"message": format!("prompt of {} tokens fills the context", ids.len()), "type": "invalid_request_error"}})); } diff --git a/src/ops.rs b/src/ops.rs index f16ddf0b..06486fcf 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -128,25 +128,82 @@ pub struct Sampler { pub frequency: f32, /// How often each token was returned, for the penalties (only the reply, not the prompt). pub seen: std::collections::HashMap, + /// DRY ("don't repeat yourself") multiplier; 0 is off. A token that would extend a sequence of `n >= + /// dry_allowed` tokens that already appeared in the reply loses `dry_mult * dry_base^(n - dry_allowed)` of logit. + pub dry_mult: f32, + pub dry_base: f32, + pub dry_allowed: usize, + /// Tokens a DRY match does not cross (their text has a newline, colon, quote or asterisk); empty for none. + pub dry_breakers: std::sync::Arc>, + /// The ids of `` and ``: no penalty applies between them (and those tokens are not + /// counted), so tool arguments may copy paths and names the reply already wrote. + pub tool_tags: Option<(usize, usize)>, + /// The returned tokens in order (outside tool calls), for DRY. + pub hist: Vec, + pub in_tool: bool, } +/// DRY looks back this many reply tokens, and matches at most this long. +const DRY_WINDOW: usize = 4096; +const DRY_MAX_MATCH: usize = 64; + impl Sampler { pub fn greedy() -> Self { - Sampler { temp: 0.0, top_k: 0, top_p: 1.0, rng: 1, presence: 0.0, frequency: 0.0, seen: Default::default() } + Sampler { temp: 0.0, top_k: 0, top_p: 1.0, rng: 1, presence: 0.0, frequency: 0.0, seen: Default::default(), + dry_mult: 0.0, dry_base: 1.75, dry_allowed: 2, dry_breakers: Default::default(), tool_tags: None, + hist: Vec::new(), in_tool: false } } /// The logits with the presence and frequency penalties applied, or None when there is nothing to change. /// Without them a quantized model that samples greedily (or nearly) falls into loops it never leaves. fn penalized(&self, logits: &[f32]) -> Option> { - if self.seen.is_empty() || (self.presence == 0.0 && self.frequency == 0.0) { return None; } + if self.in_tool { return None; } + let rep = !self.seen.is_empty() && (self.presence != 0.0 || self.frequency != 0.0); + let dry = self.dry_penalties(); + if !rep && dry.is_empty() { return None; } let mut l = logits.to_vec(); - for (&t, &n) in &self.seen { - if let Some(x) = l.get_mut(t) { *x -= self.presence + self.frequency * n as f32; } + if rep { + for (&t, &n) in &self.seen { + if let Some(x) = l.get_mut(t) { *x -= self.presence + self.frequency * n as f32; } + } + } + for (t, p) in dry { + if let Some(x) = l.get_mut(t) { *x -= p; } } Some(l) } - fn note(&mut self, t: usize) { *self.seen.entry(t).or_insert(0) += 1; } + /// DRY penalties for the next token: for every earlier place where the reply's last tokens already appeared, + /// the token that followed them there, with the longest such match (as llama.cpp's DRY sampler). + pub fn dry_penalties(&self) -> Vec<(usize, f32)> { + let h = &self.hist[self.hist.len().saturating_sub(DRY_WINDOW)..]; + let n = h.len(); + if self.dry_mult <= 0.0 || n < 2 { return vec![]; } + let brk = |t: usize| self.dry_breakers.get(t).copied().unwrap_or(false); + let last = h[n - 1]; + if brk(last) { return vec![]; } + let mut best: std::collections::HashMap = Default::default(); + for i in 0..n - 1 { + if h[i] != last { continue; } + let mut len = 1; + while len < DRY_MAX_MATCH && len <= i && !brk(h[i - len]) && h[i - len] == h[n - 1 - len] { len += 1; } + let e = best.entry(h[i + 1]).or_insert(0); + *e = (*e).max(len); + } + best.into_iter().filter(|&(_, len)| len >= self.dry_allowed.max(1)) + .map(|(t, len)| (t, self.dry_mult * self.dry_base.powi((len - self.dry_allowed.max(1)) as i32))).collect() + } + + /// Records a token the reply now has (done by `pick` and `accept` for the tokens they return). + pub fn note(&mut self, t: usize) { + if let Some((open, close)) = self.tool_tags { + if t == open { self.in_tool = true; return; } + if t == close { self.in_tool = false; return; } + } + if self.in_tool { return; } + *self.seen.entry(t).or_insert(0) += 1; + self.hist.push(t); + } pub fn pick(&mut self, logits: &[f32]) -> anyhow::Result { let pen = self.penalized(logits); diff --git a/src/serve.rs b/src/serve.rs index f817d311..61d9de38 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -276,6 +276,10 @@ pub struct ChatRequest { pub top_p: Option, pub presence_penalty: Option, pub frequency_penalty: Option, + /// DRY sampler (llama.cpp server names): multiplier, base, allowed length. + pub dry_multiplier: Option, + pub dry_base: Option, + pub dry_allowed_length: Option, pub seed: Option, /// The reply ends before the first of these strings (`stop`). pub stop: Vec, @@ -324,7 +328,10 @@ pub fn chat_request(body: &[u8]) -> anyhow::Result { temperature: num("temperature", |f| f >= 0.0, "a number >= 0")?, top_k: int("top_k", 0)?.map(|n| n as usize), top_p: num("top_p", |f| f > 0.0 && f <= 1.0, "a number in (0, 1]")?, presence_penalty: num("presence_penalty", |f| (-2.0..=2.0).contains(&f), "a number in [-2, 2]")?, - frequency_penalty: num("frequency_penalty", |f| (-2.0..=2.0).contains(&f), "a number in [-2, 2]")?, seed: int("seed", 0)?, stop }) + frequency_penalty: num("frequency_penalty", |f| (-2.0..=2.0).contains(&f), "a number in [-2, 2]")?, + dry_multiplier: num("dry_multiplier", |f| (0.0..=5.0).contains(&f), "a number in [0, 5]")?, + dry_base: num("dry_base", |f| f > 1.0 && f <= 4.0, "a number in (1, 4]")?, + dry_allowed_length: int("dry_allowed_length", 1)?.map(|n| n as usize), seed: int("seed", 0)?, stop }) } /// What the chat page's side panel shows about the server, kept by the request loop and answered by the reader diff --git a/src/tokenizer.rs b/src/tokenizer.rs index defa0c1a..142256c7 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -140,4 +140,6 @@ impl Tokenizer { } pub fn eos_ids(&self) -> Vec { self.eos.clone() } + + pub fn vocab_size(&self) -> usize { self.inner.get_vocab_size(true) } } diff --git a/tests/ops.rs b/tests/ops.rs index c2b65e28..cb29ff06 100644 --- a/tests/ops.rs +++ b/tests/ops.rs @@ -100,3 +100,36 @@ fn penalties_push_away_from_returned_tokens() { assert_eq!(s.accept(&l, 0).unwrap(), Some(1)); assert_eq!(s.seen.get(&1), Some(&1)); } + +#[test] +fn dry_penalizes_extending_a_repeat() { + // The reply so far is 1 2 3 4 1 2 3: after "1 2 3" came 4 before, so 4 loses 0.8 * 1.75^(3-2). + let l = [-10.0f32, -10.0, -10.0, -10.0, 1.0, 0.0]; + let mut s = Sampler { dry_mult: 0.8, ..Sampler::greedy() }; + s.hist = vec![1, 2, 3, 4, 1, 2, 3]; + let p = s.dry_penalties(); + assert_eq!(p.len(), 1); + assert_eq!(p[0].0, 4); + assert!((p[0].1 - 1.4).abs() < 1e-5); + assert_eq!(s.pick(&l).unwrap(), 5); + // A breaker inside the match cuts it to 1 token, below the allowed length: no penalty. + let mut s = Sampler { dry_mult: 0.8, dry_breakers: std::sync::Arc::new(vec![false, false, true, false, false, false]), ..Sampler::greedy() }; + s.hist = vec![1, 2, 3, 4, 1, 2, 3]; + assert!(s.dry_penalties().is_empty()); + assert_eq!(s.pick(&l).unwrap(), 4); +} + +#[test] +fn no_penalties_inside_tool_calls() { + let l = [1.0f32, 0.5, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0]; + let mut s = Sampler { presence: 5.0, tool_tags: Some((8, 9)), ..Sampler::greedy() }; + assert_eq!(s.pick(&l).unwrap(), 0); + assert_eq!(s.pick(&l).unwrap(), 1); // 0 is penalized outside a tool call + s.note(8); + assert!(s.in_tool); + assert_eq!(s.pick(&l).unwrap(), 0); // inside: the plain logits + s.note(9); + assert!(!s.in_tool); + assert_eq!(s.seen.get(&0), Some(&1)); // the token inside the tool call was not counted + assert_eq!(s.hist, vec![0, 1]); +}