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

Expand Down
12 changes: 9 additions & 3 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
77 changes: 77 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ctypes
import itertools
import multiprocessing
from contextlib import closing

import numpy as np
from scipy.special import log_softmax
Expand Down Expand Up @@ -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,
Expand Down
Loading