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: reject logit_bias token ids outside the vocabulary by @suryacks in #2480
- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
6 changes: 6 additions & 0 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,12 @@ def _create_completion(
# because of the extra space added to the start of the prompt_tokens
if logit_bias is not None:
logit_bias_map = {int(k): float(v) for k, v in logit_bias.items()}
for input_id in logit_bias_map:
if not 0 <= input_id < self._n_vocab:
raise ValueError(
f"logit_bias token id {input_id} is out of range for a "
f"vocabulary of {self._n_vocab} tokens"
)

def logit_bias_processor(
input_ids: npt.NDArray[np.intc],
Expand Down
32 changes: 32 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,3 +662,35 @@ 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)


def test_logit_bias_rejects_out_of_vocab_token_ids(llama_cpp_transformer_model_path):
model = llama_cpp.Llama(
llama_cpp_transformer_model_path,
n_ctx=32,
n_batch=32,
n_ubatch=32,
logits_all=False,
verbose=False,
)
n_vocab = model.n_vocab()

for token_id in (n_vocab, -1):
with pytest.raises(ValueError, match="logit_bias token id"):
model.create_completion(
"Once upon a time",
max_tokens=1,
temperature=0.0,
logit_bias={str(token_id): 100.0},
)

target = model.tokenize(b" dragon", add_bos=False)[0]
output = model.create_completion(
"Once upon a time",
max_tokens=1,
temperature=0.0,
logit_bias={str(target): 100.0},
)
assert output["choices"][0]["text"] == model.detokenize([target]).decode()

model.close()