From 570e7051768930a48182afa80bae63476fde95d0 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:06:27 +0800 Subject: [PATCH 1/2] fix: apply sampling penalties to prompt tokens --- CHANGELOG.md | 1 + llama_cpp/_internals.py | 22 ++++++- llama_cpp/llama.py | 5 +- tests/test_llama.py | 142 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 168 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917bd..26b3683062 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- fix: apply sampling penalties to prompt tokens by @remote-controlled-man - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds diff --git a/llama_cpp/_internals.py b/llama_cpp/_internals.py index b45d34b2c4..fb724b7898 100644 --- a/llama_cpp/_internals.py +++ b/llama_cpp/_internals.py @@ -679,6 +679,7 @@ def __init__(self): params = llama_cpp.llama_sampler_chain_default_params() self.sampler = llama_cpp.llama_sampler_chain_init(params) self.custom_samplers: List[Tuple[int, CustomSampler]] = [] + self._penalties: List[Tuple[int, int]] = [] self._exit_stack = ExitStack() def free_sampler(): @@ -800,6 +801,12 @@ def add_penalties( penalty_present, ) llama_cpp.llama_sampler_chain_add(self.sampler, sampler) + if penalty_last_n > 0 and ( + penalty_repeat != 1.0 or penalty_freq != 0.0 or penalty_present != 0.0 + ): + self._penalties.append( + (llama_cpp.llama_sampler_chain_n(self.sampler) - 1, penalty_last_n) + ) def add_dry( self, @@ -856,7 +863,19 @@ def add_custom( def get_seed(self) -> int: return llama_cpp.llama_sampler_get_seed(self.sampler) - def sample(self, ctx: LlamaContext, idx: int = -1) -> int: + def sample( + self, + ctx: LlamaContext, + idx: int = -1, + penalty_tokens: Optional[Sequence[int]] = None, + ) -> int: + if penalty_tokens is not None: + # Refresh the evaluated prefix without advancing grammar samplers. + for index, last_n in self._penalties: + sampler = llama_cpp.llama_sampler_chain_get(self.sampler, index) + llama_cpp.llama_sampler_reset(sampler) + for token in penalty_tokens[-last_n:]: + llama_cpp.llama_sampler_accept(sampler, int(token)) return llama_cpp.llama_sampler_sample(self.sampler, ctx.ctx, idx) def accept(self, token: int): @@ -877,6 +896,7 @@ def clone(self): new_sampler = LlamaSampler.__new__(LlamaSampler) new_sampler.sampler = cloned_sampler new_sampler.custom_samplers = [] + new_sampler._penalties = self._penalties.copy() new_sampler._exit_stack = ExitStack() def free_sampler(): diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 1b4daf6b95..e122851ae7 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -847,7 +847,10 @@ def sample( ridx = idx - self.n_tokens if idx is not None else -1 assert self.ctx is not None - token = self._sampler.sample(self._ctx, ridx) + prefix_len = self.n_tokens if idx is None else idx + 1 + token = self._sampler.sample( + self._ctx, ridx, penalty_tokens=self.input_ids[:prefix_len] + ) if tmp_sampler: self._sampler = None return token diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d496..73e8f3b348 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -382,6 +382,148 @@ def _generate_test_tokens(model, tokens, max_tokens=3): ) +@pytest.mark.parametrize( + "entrypoint", ["sample", "generate", "cached_generate", "continue_generate"] +) +@pytest.mark.parametrize( + "penalty", + [ + {"repeat_penalty": 2.0}, + {"frequency_penalty": 2.0}, + {"presence_penalty": 2.0}, + ], +) +def test_sampling_penalizes_prompt_tokens( + llama_cpp_transformer_model_path, entrypoint, penalty +): + model = _create_test_model(llama_cpp_transformer_model_path) + try: + prompt = model.tokenize(b"Hello") + repeated = prompt[-1] + alternative = model.tokenize(b" world", add_bos=False)[-1] + + def fixed_logits(input_ids, scores): + scores[:] = -np.inf + scores[repeated] = 10.0 + scores[alternative] = 9.0 + return scores + + processors = llama_cpp.LogitsProcessorList([fixed_logits]) + + def sample_next(**kwargs): + model.reset() + if entrypoint == "sample": + model.eval(prompt) + return model.sample(temp=0.0, logits_processor=processors, **kwargs) + if entrypoint == "cached_generate": + model.eval(prompt) + elif entrypoint == "continue_generate": + model.eval(prompt[:-1]) + generation = model.generate( + prompt[-1:] if entrypoint == "continue_generate" else prompt, + reset=entrypoint != "continue_generate", + temp=0.0, + logits_processor=processors, + **kwargs, + ) + try: + return next(generation) + finally: + generation.close() + + assert sample_next() == repeated + assert sample_next(**penalty) == alternative + finally: + model.close() + + +@pytest.mark.parametrize( + "prompt,last_n,idx,penalized", + [ + ([1, 15043, 15043], 0, None, False), + ([1, 15043, 15043], 1, None, True), + ([1, 15043, 15043], 1, 0, False), + ([15043, 1, 1], 2, None, False), + ([15043, 1, 1], 3, None, True), + ], +) +def test_sampling_penalty_window( + llama_cpp_transformer_model_path, prompt, last_n, idx, penalized +): + model = llama_cpp.Llama( + llama_cpp_transformer_model_path, + n_ctx=64, + n_batch=64, + logits_all=True, + last_n_tokens_size=last_n, + verbose=False, + ) + try: + model.eval(prompt) + + def fixed_logits(input_ids, scores): + scores[:] = -np.inf + scores[15043] = 10.0 + scores[3186] = 9.0 + return scores + + token = model.sample( + temp=0.0, + frequency_penalty=2.0, + logits_processor=llama_cpp.LogitsProcessorList([fixed_logits]), + idx=idx, + ) + assert token == (3186 if penalized else 15043) + finally: + model.close() + + +def test_generate_penalty_history_continues(llama_cpp_transformer_model_path): + model = _create_test_model(llama_cpp_transformer_model_path) + try: + + def fixed_logits(input_ids, scores): + scores[:] = -np.inf + scores[15043] = 10.0 + scores[3186] = 9.0 + return scores + + generation = model.generate( + model.tokenize(b"Hello"), + temp=0.0, + frequency_penalty=2.0, + logits_processor=llama_cpp.LogitsProcessorList([fixed_logits]), + ) + try: + assert list(itertools.islice(generation, 3)) == [3186, 15043, 3186] + finally: + generation.close() + finally: + model.close() + + +def test_prompt_penalties_do_not_advance_grammar(llama_cpp_transformer_model_path): + model = _create_test_model(llama_cpp_transformer_model_path) + try: + model.eval(model.tokenize(b"Hello")) + + def fixed_logits(input_ids, scores): + scores[:] = -np.inf + scores[15043] = 10.0 + scores[3186] = 9.0 + return scores + + token = model.sample( + temp=0.0, + frequency_penalty=2.0, + grammar=llama_cpp.LlamaGrammar.from_string('root ::= " world"'), + logits_processor=llama_cpp.LogitsProcessorList([fixed_logits]), + ) + assert model.detokenize([token]) == b" world" + finally: + model.close() + + MODEL_CACHE_CASES = ( ("llama_cpp_transformer_model_path", False, False), ("llama_cpp_recurrent_model_path", True, False), From 9f07d589cda8787a2d6e0841237d05403c9b8ba9 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:14:56 +0800 Subject: [PATCH 2/2] docs: link sampling penalties changelog to PR --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26b3683062..1738768953 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- fix: apply sampling penalties to prompt tokens by @remote-controlled-man +- fix: apply sampling penalties to prompt tokens by @remote-controlled-man in #2447 - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds