Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 in #2447
- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
22 changes: 21 additions & 1 deletion llama_cpp/_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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):
Expand All @@ -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():
Expand Down
5 changes: 4 additions & 1 deletion llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
142 changes: 142 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading