diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917b..aaa2e9750 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: size embeddings by the model's output embedding length by @0xArx in #2479 - 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/_internals.py b/llama_cpp/_internals.py index b45d34b2c..b78a00441 100644 --- a/llama_cpp/_internals.py +++ b/llama_cpp/_internals.py @@ -100,6 +100,9 @@ def n_ctx_train(self) -> int: def n_embd(self) -> int: return llama_cpp.llama_model_n_embd(self.model) + def n_embd_out(self) -> int: + return llama_cpp.llama_model_n_embd_out(self.model) + def rope_freq_scale_train(self) -> float: return llama_cpp.llama_model_rope_freq_scale_train(self.model) diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 1b4daf6b9..1d0b3fc4d 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -1080,7 +1080,9 @@ def embed( Returns: A list of embeddings """ - n_embd = self.n_embd() + # llama.cpp writes embeddings with the model's output size, which can + # differ from its hidden size (n_embd). + n_embd = self.n_embd_out() n_batch = self.n_batch n_seq_max = self.context_params.n_seq_max @@ -2269,6 +2271,14 @@ def n_embd(self) -> int: """Return the embedding size.""" return self._model.n_embd() + def n_embd_out(self) -> int: + """Return the size of the embeddings the model outputs. + + Same as n_embd unless the model sets a separate output embedding + length, as EmbeddingGemma 2 does. + """ + return self._model.n_embd_out() + def n_vocab(self) -> int: """Return the vocabulary size.""" return self._model.n_vocab() diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d49..5aa90e573 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -1,6 +1,7 @@ import ctypes import itertools import multiprocessing +from types import SimpleNamespace import numpy as np from scipy.special import log_softmax @@ -11,6 +12,7 @@ import llama_cpp import llama_cpp._internals as internals +from llama_cpp import llama as llama_module MODEL = "./vendor/llama.cpp/models/ggml-vocab-llama-spm.gguf" @@ -636,6 +638,67 @@ def test_shorter_prompt_prefix_reuse_matches_fresh( ) +def _fake_embedding_model(pooling_type, n_embd, n_embd_out, n_tokens): + # Mimic llama.cpp, which writes n_embd_out floats per token (unpooled) or + # per sequence (pooled), whatever the model's hidden size n_embd is. + values = [float(i) for i in range(n_tokens * n_embd_out)] + buffer = (ctypes.c_float * len(values))(*values) + pointer = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_float)) + + def get_embeddings_seq(ctx, seq_id): + return ctypes.cast( + ctypes.byref(buffer, seq_id * n_embd_out * ctypes.sizeof(ctypes.c_float)), + ctypes.POINTER(ctypes.c_float), + ) + + model = SimpleNamespace( + n_embd=lambda: n_embd, + n_embd_out=lambda: n_embd_out, + n_batch=32, + context_params=SimpleNamespace(n_seq_max=4, embeddings=True), + pooling_type=lambda: pooling_type, + verbose=False, + tokenize=lambda text: list(range(1, len(text) + 1)), + _batch=SimpleNamespace( + reset=lambda: None, add_sequence=lambda tokens, seq_id, logits_all: None + ), + _ctx=SimpleNamespace( + ctx=None, kv_cache_clear=lambda: None, decode=lambda b: None + ), + reset=lambda: None, + ) + return model, pointer, get_embeddings_seq + + +def test_embed_uses_model_output_size(monkeypatch): + # EmbeddingGemma 2 has n_embd 512 and n_embd_out 768; embed() must return + # n_embd_out floats instead of the first n_embd (abetlen/llama-cpp-python#2478). + n_embd, n_embd_out = 2, 3 + + model, _, get_embeddings_seq = _fake_embedding_model( + llama_cpp.LLAMA_POOLING_TYPE_MEAN, n_embd, n_embd_out, n_tokens=2 + ) + monkeypatch.setattr( + llama_module.llama_cpp, "llama_get_embeddings_seq", get_embeddings_seq + ) + assert llama_module.Llama.embed(model, "ab") == [0.0, 1.0, 2.0] + assert llama_module.Llama.embed(model, ["ab", "cd"]) == [ + [0.0, 1.0, 2.0], + [3.0, 4.0, 5.0], + ] + + model, pointer, _ = _fake_embedding_model( + llama_cpp.LLAMA_POOLING_TYPE_NONE, n_embd, n_embd_out, n_tokens=2 + ) + monkeypatch.setattr( + llama_module.llama_cpp, "llama_get_embeddings", lambda ctx: pointer + ) + assert llama_module.Llama.embed(model, "ab") == [ + [0.0, 1.0, 2.0], + [3.0, 4.0, 5.0], + ] + + def test_real_llama_embeddings(llama_cpp_embedding_model_path): model = llama_cpp.Llama( llama_cpp_embedding_model_path, @@ -649,7 +712,7 @@ def test_real_llama_embeddings(llama_cpp_embedding_model_path): embedding=True, ) embedding = model.embed("Hello World") - assert len(embedding) > 0 + assert len(embedding) == model.n_embd_out() > 0 prompts = ["Hello World", "A different prompt"] individual_embeddings = [model.embed(prompt) for prompt in prompts]