From 1a945b25461fdcc01d0fba4a197702c5a33b0ebb Mon Sep 17 00:00:00 2001 From: CloudGPU <129925370+cloudgpuapp@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:54:15 +0800 Subject: [PATCH] fix: preserve split UTF-8 before streaming stop sequences --- CHANGELOG.md | 1 + llama_cpp/llama.py | 85 +++++++++++++++++++++-------------- tests/test_llama_streaming.py | 48 ++++++++++++++++++++ 3 files changed, 101 insertions(+), 33 deletions(-) create mode 100644 tests/test_llama_streaming.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 139e9a47c..3ed014928 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 split UTF-8 characters before a streaming stop sequence by @cloudgpuapp - fix: size Python buffers to the actual context by @remote-controlled-man in #2436 - feat: update llama.cpp to ggml-org/llama.cpp@afe77e18f - fix(ci): remove unsupported macOS 14 release runners by @abetlen in #2416 diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 5e8cc6563..72d53e439 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -1606,17 +1606,36 @@ def logit_bias_processor( else: end = len(remaining_text) - token_end_position = 0 - for token in remaining_tokens: - token_end_position += len( - self.detokenize( - [token], - prev_tokens=prompt_tokens + completion_tokens[:returned_tokens], + if logprobs is None: + # Decode the buffered tail together so a Unicode character can + # span tokens even when generation ends at a stop sequence. + tail = remaining_text[:end].decode("utf-8", errors="ignore") + if tail: + yield { + "id": completion_id, + "object": "text_completion", + "created": created, + "model": model_name, + "choices": [ + { + "text": tail, + "index": 0, + "logprobs": None, + "finish_reason": None, + } + ], + } + else: + token_end_position = 0 + for token in remaining_tokens: + token_end_position += len( + self.detokenize( + [token], + prev_tokens=prompt_tokens + + completion_tokens[:returned_tokens], + ) ) - ) - logprobs_or_none: Optional[CompletionLogprobs] = None - if logprobs is not None: if token == bos_token_id: continue token_str = self.detokenize([token]).decode( @@ -1652,9 +1671,27 @@ def logit_bias_processor( "top_logprobs": [top_logprob], } - if token_end_position >= end: - last_text = self.detokenize([token]) - if token_end_position == end - 1: + if token_end_position >= end: + last_text = self.detokenize([token]) + if token_end_position == end - 1: + break + returned_tokens += 1 + yield { + "id": completion_id, + "object": "text_completion", + "created": created, + "model": model_name, + "choices": [ + { + "text": last_text[ + : len(last_text) - (token_end_position - end) + ].decode("utf-8", errors="ignore"), + "index": 0, + "logprobs": logprobs_or_none, + "finish_reason": None, + } + ], + } break returned_tokens += 1 yield { @@ -1664,33 +1701,15 @@ def logit_bias_processor( "model": model_name, "choices": [ { - "text": last_text[ - : len(last_text) - (token_end_position - end) - ].decode("utf-8", errors="ignore"), + "text": self.detokenize([token]).decode( + "utf-8", errors="ignore" + ), "index": 0, "logprobs": logprobs_or_none, "finish_reason": None, } ], } - break - returned_tokens += 1 - yield { - "id": completion_id, - "object": "text_completion", - "created": created, - "model": model_name, - "choices": [ - { - "text": self.detokenize([token]).decode( - "utf-8", errors="ignore" - ), - "index": 0, - "logprobs": logprobs_or_none, - "finish_reason": None, - } - ], - } yield { "id": completion_id, "object": "text_completion", diff --git a/tests/test_llama_streaming.py b/tests/test_llama_streaming.py new file mode 100644 index 000000000..cccaa882f --- /dev/null +++ b/tests/test_llama_streaming.py @@ -0,0 +1,48 @@ +from contextlib import ExitStack +from types import SimpleNamespace + +import pytest + +import llama_cpp +import llama_cpp.llama_cpp as bindings + + +@pytest.mark.parametrize( + ("pieces", "expected"), + [ + ([b"\xc3", b"\xa9STOP"], "é"), + ([b"helloSTOP"], "hello"), + ([b"STOP"], ""), + ], +) +def test_stream_flushes_utf8_before_stop(monkeypatch, pieces, expected): + llama = llama_cpp.Llama.__new__(llama_cpp.Llama) + llama._stack = ExitStack() + llama._model = SimpleNamespace( + vocab=None, + token_cls=lambda: -1, + token_sep=lambda: -1, + ) + llama.metadata = {} + llama.spm_infill = False + llama.model_path = "synthetic" + llama.verbose = False + llama._n_ctx = 32 + llama.cache = None + llama.token_bos = lambda: 1 + llama.token_eos = lambda: 2 + llama.set_seed = lambda seed: None + token_ids = list(range(3, 3 + len(pieces))) + token_bytes = dict(zip(token_ids, pieces)) + llama.generate = lambda *_args, **_kwargs: iter(token_ids) + llama.detokenize = lambda tokens, prev_tokens=None: b"".join( + token_bytes[token] for token in tokens + ) + monkeypatch.setattr(bindings, "llama_vocab_is_eog", lambda _vocab, _token: False) + + chunks = list(llama.create_completion([9], stop=["STOP"], stream=True, seed=1)) + choices = [chunk["choices"][0] for chunk in chunks] + + assert "".join(choice["text"] for choice in choices) == expected + assert choices[-1]["finish_reason"] == "stop" + assert all(choice["finish_reason"] is None for choice in choices[:-1])