From a921facfa94e235f797a2b26cd65db7ec67d6bf7 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:40:05 +0800 Subject: [PATCH 1/2] fix: honor max_tokens when completions end with partial UTF-8 --- CHANGELOG.md | 1 + llama_cpp/llama.py | 38 +++++++++++++++--------------- tests/test_llama.py | 56 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917b..ce2732d44 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: honor max_tokens when completions end with partial UTF-8 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/llama.py b/llama_cpp/llama.py index 1b4daf6b9..3594425b8 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -1427,8 +1427,9 @@ def logit_bias_processor( if num > k and pattern & char == pattern: multibyte_fix = num - k - # Stop incomplete bytes from passing - if multibyte_fix > 0: + reached_token_limit = len(completion_tokens) >= max_tokens + # Wait for a complete UTF-8 character while the token budget allows it. + if multibyte_fix > 0 and not reached_token_limit: multibyte_fix -= 1 continue @@ -1447,16 +1448,16 @@ def logit_bias_processor( ) remaining_length = len(remaining_text) - # We want to avoid yielding any characters from - # the generated text if they are part of a stop - # sequence. + # Hold possible stop prefixes while generation can continue. + # Log probabilities retain their existing per-token flush. first_stop_position = 0 - for s in stop_sequences: - for i in range(min(len(s), remaining_length), 0, -1): - if remaining_text.endswith(s[:i]): - if i > first_stop_position: - first_stop_position = i - break + if not reached_token_limit or logprobs is not None: + for s in stop_sequences: + for i in range(min(len(s), remaining_length), 0, -1): + if remaining_text.endswith(s[:i]): + if i > first_stop_position: + first_stop_position = i + break token_end_position = 0 @@ -1539,7 +1540,6 @@ def logit_bias_processor( } else: while len(remaining_tokens) > 0: - decode_success = False for i in range(1, len(remaining_tokens) + 1): try: bs = self.detokenize( @@ -1548,15 +1548,15 @@ def logit_bias_processor( + completion_tokens[:returned_tokens], ) ts = bs.decode("utf-8") - decode_success = True break except UnicodeError: pass else: - break - if not decode_success: - # all remaining tokens cannot be decoded to a UTF-8 character - break + if not reached_token_limit: + break + # Keep complete characters when the final bytes are partial. + bs = remaining_text[token_end_position:] + ts = bs.decode("utf-8", errors="ignore") token_end_position += len(bs) if token_end_position > ( remaining_length - first_stop_position @@ -1580,8 +1580,8 @@ def logit_bias_processor( ], } - if len(completion_tokens) >= max_tokens: - text = self.detokenize(completion_tokens, prev_tokens=prompt_tokens) + if reached_token_limit: + text = all_text finish_reason = "length" break diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d49..c16a053dd 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -370,6 +370,62 @@ def _create_test_model(model_path): ) +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize( + "max_tokens, stop, expected_text, finish_reason", + [ + (3, None, "ab", "length"), + (4, None, "abé", "length"), + (5, "éé", "abé", "length"), + (6, "éé", "ab", "stop"), + ], +) +def test_completion_token_limit_with_split_utf8( + llama_cpp_transformer_model_path, + stream, + max_tokens, + stop, + expected_text, + finish_reason, +): + model = _create_test_model(llama_cpp_transformer_model_path) + try: + # Force two ASCII bytes, then two characters split across byte tokens. + pieces = [b"a", b"b", b"\xc3", b"\xa9", b"\xc3", b"\xa9"] + tokens = [ + next(i for i in range(model.n_vocab()) if model.detokenize([i]) == piece) + for piece in pieces + ] + sampled = [] + + def force_next_token(input_ids, scores): + token = tokens[len(sampled)] + scores[:] = -np.inf + scores[token] = 0 + sampled.append(token) + return scores + + result = model.create_completion( + "Once upon a time", + max_tokens=max_tokens, + stop=stop, + temperature=0.0, + stream=stream, + logits_processor=llama_cpp.LogitsProcessorList([force_next_token]), + ) + if stream: + choices = [chunk["choices"][0] for chunk in result] + else: + choices = result["choices"] + assert result["usage"]["completion_tokens"] == max_tokens + + assert "".join(choice["text"] for choice in choices) == expected_text + assert choices[-1]["finish_reason"] == finish_reason + assert sampled == tokens[:max_tokens] + finally: + model.close() + + def _generate_test_tokens(model, tokens, max_tokens=3): return list( itertools.islice( From 33c8c288105ee49b50a494406ebaa8d6a6e97d59 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:50:52 +0800 Subject: [PATCH 2/2] docs: link the UTF-8 token limit change to its PR --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce2732d44..7694480e1 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: honor max_tokens when completions end with partial UTF-8 by @remote-controlled-man +- fix: honor max_tokens when completions end with partial UTF-8 by @remote-controlled-man in #2481 - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds