diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917b..f1e6c6806 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: preserve completion results when stopping criteria fire by @remote-controlled-man in #2482 - 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/llama.py b/llama_cpp/llama.py index 1b4daf6b9..9e9e669c4 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -1585,9 +1585,8 @@ def logit_bias_processor( finish_reason = "length" break - if stopping_criteria is not None and stopping_criteria( - self._input_ids, self._scores[-1, :] - ): + else: + # generate() returns when a stopping criterion is met. text = self.detokenize(completion_tokens, prev_tokens=prompt_tokens) finish_reason = "stop" diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d49..a0b8a8098 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -267,6 +267,65 @@ def logit_processor_func(input_ids, logits): assert number_1 == number_3 +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize( + ("max_tokens", "stop_on_text", "expected_reason", "expected_calls"), + [ + pytest.param(4, False, "stop", 2, id="criterion"), + pytest.param(1, False, "length", 1, id="token-budget"), + pytest.param(4, True, "stop", 1, id="stop-sequence"), + ], +) +def test_completion_stopping_criteria( + llama_cpp_transformer_model_path, + stream, + max_tokens, + stop_on_text, + expected_reason, + expected_calls, +): + model = _create_test_model(llama_cpp_transformer_model_path) + prompt = "Once upon a time" + token = model.tokenize(b" a", add_bos=False)[-1] + token_text = model.detokenize([token], prev_tokens=model.tokenize(prompt.encode())) + token_text = token_text.decode("ascii") + assert token_text.strip() == "a" + + def force_token(input_ids, scores): + scores[:] = -np.inf + scores[token] = 0 + return scores + + calls = 0 + + def stop_on_second_call(input_ids, scores): + nonlocal calls + calls += 1 + return calls == 2 + + try: + output = model.create_completion( + prompt, + max_tokens=max_tokens, + temperature=0.0, + stream=stream, + stop=[token_text] if stop_on_text else None, + logits_processor=llama_cpp.LogitsProcessorList([force_token]), + stopping_criteria=llama_cpp.StoppingCriteriaList([stop_on_second_call]), + ) + choices = ( + [chunk["choices"][0] for chunk in output] if stream else output["choices"] + ) + finally: + model.close() + + assert "".join(choice["text"] for choice in choices) == ( + "" if stop_on_text else token_text + ) + assert choices[-1]["finish_reason"] == expected_reason + assert calls == expected_calls + + def test_real_llama_repeated_prompt_cache(llama_cpp_model_path): model = llama_cpp.Llama( llama_cpp_model_path,