fix(python): add opt-in normalization for truncated gemini embeddings (#4827)

`gemini-embedding-001` returns only its full 3072-dimensional output
normalized. Reduced outputs, including the 768 default of `GeminiText`,
are not unit length, and the [Gemini embeddings
docs](https://ai.google.dev/gemini-api/docs/embeddings) say to normalize
them manually.

**Change:** a new `normalize` setting on `gemini-text`, off by default.
With `normalize=True`, outputs of `gemini-embedding-001` (also spelled
`models/gemini-embedding-001`) below 3072 dimensions are L2-normalized.
The setting is saved in the table's embedding function config. When it
is omitted, vectors are stored and queried as before, so existing tables
need no migration.

**Tests:** `test_gemini_text_embeddings.py` stubs the Gemini client. It
covers the opt-in for both model spellings, the cases left untouched,
and text search plus append after reopening both a table without the
setting and a table created with `normalize=True`.

This change was prepared with the help of an AI assistant (Claude), and
the submitter is responsible for it.

---------

Signed-off-by: Alex Castillo <alex.castillog33@gmail.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Alex Castillo González
2026-11-30 20:14:45 +08:00
committed by GitHub
co-authored by Claude Sonnet 5.5
parent 7c6ffe94c2
commit 2e09dc1144
2 changed files with 114 additions and 0 deletions
@@ -15,6 +15,9 @@ from .registry import register
from .utils import TEXT, api_key_not_found_help
EMBEDDING_BATCH_SIZE = 100
# Only the full 3072-dimensional output of gemini-embedding-001 is returned
# L2-normalized by the API; truncated outputs have to be normalized by the caller.
FULL_EMBEDDING_DIMS = 3072
@register("gemini-text")
@@ -58,6 +61,11 @@ class GeminiText(TextEmbeddingFunction):
Sets the task type for the queries.
source_task_type : str, default "retrieval_document"
Sets the task type for ingestion.
normalize : bool, default False
L2-normalize gemini-embedding-001 outputs with fewer than 3072
dimensions, which the API does not return normalized. The setting is
saved with the table. Enable it for new tables only: existing rows
are not rewritten.
Examples
--------
@@ -85,6 +93,7 @@ class GeminiText(TextEmbeddingFunction):
dim: Optional[int] = None
query_task_type: str = "retrieval_query"
source_task_type: str = "retrieval_document"
normalize: bool = False
model_config = ConfigDict(ignored_types=(cached_property,))
@@ -148,8 +157,20 @@ class GeminiText(TextEmbeddingFunction):
)
embeddings.extend([np.array(e.values) for e in response.embeddings])
if (
self.normalize
and self.name.removeprefix("models/") == "gemini-embedding-001"
and self.ndims() < FULL_EMBEDDING_DIMS
):
embeddings = [self._l2_normalize(e) for e in embeddings]
return embeddings
@staticmethod
def _l2_normalize(vector: np.ndarray) -> np.ndarray:
norm = np.linalg.norm(vector)
return vector / norm if norm > 0 else vector
@cached_property
def client(self):
attempt_import_or_raise("google.genai", "google-genai")
@@ -0,0 +1,93 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import sys
from types import ModuleType, SimpleNamespace
import numpy as np
import pytest
import lancedb
from lancedb.embeddings import get_registry
from lancedb.embeddings.gemini_text import GeminiText
from lancedb.pydantic import LanceModel, Vector
# Leading components of the unnormalized vector returned for each text
RAW = {"a": [0.25, 0.0], "b": [0.75, 0.5]}
@pytest.fixture
def fake_genai(monkeypatch):
google = ModuleType("google")
genai = ModuleType("google.genai")
types = ModuleType("google.genai.types")
types.EmbedContentConfig = lambda **kwargs: SimpleNamespace(**kwargs)
genai.types = types
google.genai = genai
monkeypatch.setitem(sys.modules, "google", google)
monkeypatch.setitem(sys.modules, "google.genai", genai)
monkeypatch.setitem(sys.modules, "google.genai.types", types)
def embed_content(model, contents, config):
embeddings = []
for content in contents:
raw = RAW[content["parts"][-1]["text"]]
values = raw + [0.0] * (config.output_dimensionality - len(raw))
embeddings.append(SimpleNamespace(values=values))
return SimpleNamespace(embeddings=embeddings)
client = SimpleNamespace(models=SimpleNamespace(embed_content=embed_content))
monkeypatch.setattr(GeminiText, "client", property(lambda self: client))
def _embed(**kwargs):
model = get_registry().get("gemini-text").create(**kwargs)
return model.compute_source_embeddings(["b"])[0]
@pytest.mark.parametrize(
"name", ["gemini-embedding-001", "models/gemini-embedding-001"]
)
def test_normalize_truncated_embeddings(fake_genai, name):
out = _embed(name=name, normalize=True)
assert np.linalg.norm(out) == pytest.approx(1.0)
assert out[:2].tolist() == pytest.approx([0.75 / 0.8125**0.5, 0.5 / 0.8125**0.5])
@pytest.mark.parametrize(
"kwargs",
[
{},
{"normalize": False},
{"normalize": True, "dim": 3072},
{"normalize": True, "name": "models/embedding-001"},
],
)
def test_embeddings_left_as_returned(fake_genai, kwargs):
assert _embed(**kwargs)[:2].tolist() == RAW["b"]
@pytest.mark.parametrize("normalize", [None, True])
def test_search_and_append_after_reopen(fake_genai, tmp_path, normalize):
kwargs = {} if normalize is None else {"normalize": normalize}
model = get_registry().get("gemini-text").create(**kwargs)
class Row(LanceModel):
text: str = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
db = lancedb.connect(tmp_path)
db.create_table("t", schema=Row).add([{"text": "a"}])
table = lancedb.connect(tmp_path).open_table("t")
assert table.search("a").limit(1).to_list()[0]["text"] == "a"
table.add([{"text": "b"}])
result = table.search("a").limit(2).to_list()
assert [row["text"] for row in result] == ["a", "b"]
assert result[0]["_distance"] == pytest.approx(0.0)
for row in result:
expected = np.array(RAW[row["text"]])
if normalize:
expected = expected / np.linalg.norm(expected)
assert row["vector"][:2] == pytest.approx(expected.tolist())