diff --git a/llama_cpp/_internals.py b/llama_cpp/_internals.py index b45d34b2c..eb0ebdfe0 100644 --- a/llama_cpp/_internals.py +++ b/llama_cpp/_internals.py @@ -565,6 +565,17 @@ def normalize_embedding(embedding): return [v / norm for v in embedding] +def truncate_embedding_tokens( + tokens: List[int], limit: int, sentinels_to_preserve: set[int] +) -> List[int]: + """Head-truncate `tokens` to `limit`, preserving any trailing sentinel token.""" + if len(tokens) <= limit: + return tokens + if limit > 0 and tokens[-1] in sentinels_to_preserve: + return tokens[: limit - 1] + [tokens[-1]] + return tokens[:limit] + + # Python wrappers over common/sampling structs diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 5e8cc6563..e8e43820b 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -480,6 +480,8 @@ def free_lora_adapter(): self.n_tokens = 0 # Restored or truncated state must decode before sampling. self._requires_eval = True + # Embedding inputs are truncated silently by default, warn at most once per model + self._embedding_truncation_warned = False self.input_ids: npt.NDArray[np.intc] = np.ndarray((self._n_ctx,), dtype=np.intc) self.scores: npt.NDArray[np.single] = np.ndarray( (self._n_ctx if logits_all == True else n_batch, self._n_vocab), @@ -1065,6 +1067,20 @@ def create_embedding( }, } + def _warn_embedding_truncation(self, n_tokens: int, limit: int) -> None: + """Warn, at most once per model, that an embedding input was truncated.""" + if self._embedding_truncation_warned: + return + self._embedding_truncation_warned = True + warnings.warn( + f"Embedding input of {n_tokens} tokens was truncated to {limit} to fit the " + f"batch size. Raise n_batch and n_ubatch together to embed longer inputs " + f"(a single embedding sequence has to fit in one batch), or pass " + f"truncate=False to raise an error instead. Further truncations by this " + f"model will not be reported.", + RuntimeWarning, + ) + def embed( self, input: Union[str, List[str]], @@ -1086,6 +1102,15 @@ def embed( # get pooling information pooling_type = self.pooling_type() + + # Token the tokenizer appends to frame the input, if any. Truncation has to + # preserve it so that LAST pooling still reads a sentinel rather than a + # mid-sentence token. + sentinels_to_preserve_in_truncation = { + self._model.token_eos(), + self._model.token_sep(), + } + # In embedding mode every input token must be marked as an output, regardless of # pooling type. llama.cpp would otherwise override per-token `logits[i]` and emit # "embeddings required but some input tokens were not marked as outputs -> @@ -1151,7 +1176,12 @@ def decode_batch(seq_sizes: List[int]): for text in inputs: tokens = self.tokenize(text.encode("utf-8")) if truncate: - tokens = tokens[:n_batch] + n_before = len(tokens) + tokens = internals.truncate_embedding_tokens( + tokens, n_batch, sentinels_to_preserve_in_truncation + ) + if len(tokens) < n_before: + self._warn_embedding_truncation(n_before, n_batch) n_tokens = len(tokens) total_tokens += n_tokens diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d49..e559d4469 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -662,3 +662,34 @@ 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_real_llama_embedding_truncation_preserves_sentinel( + llama_cpp_embedding_model_path, +): + model = llama_cpp.Llama( + llama_cpp_embedding_model_path, + n_ctx=32, + n_batch=32, + n_ubatch=32, + embedding=True, + verbose=False, + ) + sentinels = {model._model.token_eos(), model._model.token_sep()} + + # Inputs that already fit are returned as-is, with no duplicated trailing sentinel. + short = model.tokenize(b"a short input") + assert internals.truncate_embedding_tokens(short, model.n_batch, sentinels) == short + + tokens = model.tokenize(("the quick brown fox " * 50).encode("utf-8")) + # Premise: llama.cpp frames the input with a trailing sentinel token. + assert len(tokens) > model.n_batch + assert tokens[-1] in sentinels + + # A plain head slice drops it + assert tokens[: model.n_batch][-1] not in sentinels + + # Truncation code re-adds it + truncated = internals.truncate_embedding_tokens(tokens, model.n_batch, sentinels) + assert len(truncated) == model.n_batch + assert truncated[-1] in sentinels