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: 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

Expand Down
38 changes: 19 additions & 19 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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

Expand Down
56 changes: 56 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading