From 43c8d33dd45b4f610f13ce9e0f73a61351947a69 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:51:03 +0800 Subject: [PATCH 1/2] fix: avoid empty embedding decode batches --- CHANGELOG.md | 1 + llama_cpp/llama.py | 12 +++++-- tests/test_llama.py | 77 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917b..50f3d8f9f 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: avoid empty embedding decode batches 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..ab2d8f2c4 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -1072,7 +1072,10 @@ def embed( truncate: bool = True, return_count: bool = False, ): - """Embed a string. + """Embed a string or list of strings. + + An empty list returns no embeddings. Each text must tokenize to at least + one token, including any special tokens added by the tokenizer. Args: input: The utf-8 encoded string to embed. @@ -1154,6 +1157,8 @@ def decode_batch(seq_sizes: List[int]): tokens = tokens[:n_batch] n_tokens = len(tokens) + if n_tokens == 0: + raise ValueError("Input text must tokenize to at least one token") total_tokens += n_tokens # check for overrun @@ -1177,8 +1182,9 @@ def decode_batch(seq_sizes: List[int]): t_batch += n_tokens p_batch += 1 - # hanlde last batch - decode_batch(s_batch) + # handle last batch + if s_batch: + decode_batch(s_batch) if self.verbose: llama_cpp.llama_perf_context_print(self._ctx.ctx) diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d49..68dc178ad 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -1,6 +1,7 @@ import ctypes import itertools import multiprocessing +from contextlib import closing import numpy as np from scipy.special import log_softmax @@ -636,6 +637,82 @@ def test_shorter_prompt_prefix_reuse_matches_fresh( ) +@pytest.mark.parametrize( + "pooling_type", + [llama_cpp.LLAMA_POOLING_TYPE_NONE, llama_cpp.LLAMA_POOLING_TYPE_CLS], +) +@pytest.mark.parametrize("method", ["embed", "create_embedding"]) +def test_empty_embedding_batch(llama_cpp_embedding_model_path, pooling_type, method): + with closing( + llama_cpp.Llama( + llama_cpp_embedding_model_path, + n_ctx=32, + n_batch=32, + n_ubatch=32, + n_gpu_layers=0, + n_threads=2, + n_threads_batch=2, + embedding=True, + pooling_type=pooling_type, + verbose=False, + ) + ) as model: + expected = model.embed("Hello World") + if method == "embed": + assert model.embed([]) == [] + assert model.embed([], normalize=True, return_count=True) == ([], 0) + else: + response = model.create_embedding([]) + assert response["data"] == [] + assert response["usage"] == {"prompt_tokens": 0, "total_tokens": 0} + np.testing.assert_allclose(model.embed("Hello World"), expected) + + +@pytest.mark.parametrize("input_text", ["", [""], ["Hello", ""], ["", "Hello"]]) +@pytest.mark.parametrize("method", ["embed", "create_embedding"]) +def test_embedding_rejects_zero_token_input(llama_cpp_model_path, input_text, method): + with closing( + llama_cpp.Llama( + llama_cpp_model_path, + n_ctx=32, + n_batch=32, + n_ubatch=32, + n_gpu_layers=0, + n_threads=2, + n_threads_batch=2, + embedding=True, + verbose=False, + ) + ) as model: + assert model.tokenize(b"") == [] + with pytest.raises(ValueError, match="at least one token"): + getattr(model, method)(input_text) + assert len(model.embed("Hello")) > 0 + + +def test_embedding_accepts_empty_text_with_special_tokens( + llama_cpp_embedding_model_path, +): + with closing( + llama_cpp.Llama( + llama_cpp_embedding_model_path, + n_ctx=32, + n_batch=32, + n_ubatch=32, + n_gpu_layers=0, + n_threads=2, + n_threads_batch=2, + embedding=True, + verbose=False, + ) + ) as model: + assert len(model.tokenize(b"")) > 0 + embedding, count = model.embed("", return_count=True) + assert len(embedding) == model.n_embd() + assert count == len(model.tokenize(b"")) + assert np.isfinite(embedding).all() + + def test_real_llama_embeddings(llama_cpp_embedding_model_path): model = llama_cpp.Llama( llama_cpp_embedding_model_path, From 25f510926eb56f62af64b3bfbe01bb08610ca3e2 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:01:11 +0800 Subject: [PATCH 2/2] docs: link embedding fix to PR 2442 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50f3d8f9f..8d2e3e259 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: avoid empty embedding decode batches by @remote-controlled-man +- fix: avoid empty embedding decode batches by @remote-controlled-man in #2442 - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds