diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917b..cf393dbd7 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: 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 diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 1b4daf6b9..c04312ae9 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -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], diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d49..99b37ea7e 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -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()