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: stop completions at the earliest matching sequence by @remote-controlled-man in #2460
- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
4 changes: 2 additions & 2 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -1434,8 +1434,8 @@ def logit_bias_processor(

any_stop = [s for s in stop_sequences if s in all_text]
if len(any_stop) > 0:
first_stop = any_stop[0]
text = all_text[: all_text.index(first_stop)]
end = min(all_text.index(stop) for stop in any_stop)
text = all_text[:end]
finish_reason = "stop"
break

Expand Down
48 changes: 48 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,3 +662,51 @@ def test_real_llama_embeddings(llama_cpp_embedding_model_path):
repeated_embeddings = model.embed(list(reversed(prompts)))
assert len(repeated_embeddings) == len(prompts)
assert all(len(repeated) == len(embedding) for repeated in repeated_embeddings)


@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("logprobs", [None, 1])
def test_completion_earliest_stop(llama_cpp_model_path, stream, logprobs):
model = llama_cpp.Llama(
llama_cpp_model_path,
n_ctx=256,
n_batch=64,
n_ubatch=64,
n_gpu_layers=0,
logits_all=True,
verbose=False,
)
try:
# Keep both matches in one sampled token, independent of model wording.
tokens = model.tokenize(b" very", add_bos=False)
assert len(tokens) == 1
kwargs = dict(
prompt="Once upon a time",
max_tokens=1,
temperature=0,
logit_bias={str(tokens[0]): 1000},
logprobs=logprobs,
)
control = model.create_completion(**kwargs)
assert control["choices"][0]["text"] == " very"

for stop, expected_text, finish_reason in [
(["ry", "er"], " v", "stop"),
(["er", "ry"], " v", "stop"),
(["er", "very"], " ", "stop"),
(["very", "er"], " ", "stop"),
(["missing", "ry"], " ve", "stop"),
(["missing"], " very", "length"),
]:
response = model.create_completion(stop=stop, stream=stream, **kwargs)
choices = (
[chunk["choices"][0] for chunk in response]
if stream
else response["choices"]
)
assert "".join(choice["text"] for choice in choices) == expected_text, stop
assert choices[-1]["finish_reason"] == finish_reason
if logprobs is not None:
assert choices[0]["logprobs"] is not None
finally:
model.close()
Loading