From d31c1568e002d64f1f5086a5ea6007d77fa0ed71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20Castillo=20Gonz=C3=A1lez?= <82875882+pcbeingused333@users.noreply.github.com> Date: Mon, 30 Nov 2026 07:23:42 -0500 Subject: [PATCH] fix(python)!: compute JinaEmbeddings.ndims() per model (#4840) BREAKING CHANGE: `JinaEmbeddings.ndims()` previously returned 768 for unlisted model names. It now raises `ValueError`. When creating a schema with an unlisted model, pass its documented output width to `Vector(width)`. Fixes the `# TODO: fix hardcoding` in `JinaEmbeddings.ndims()` (same kind of fix as #4737, which made the OpenAI-compatible models use their real dimension). **Root cause:** `ndims()` returned 768 for every model. Any model whose default output is not 768 (jina-clip-v2 and jina-embeddings-v3: 1024, jina-embeddings-v4: 2048, jina-embeddings-v2-small-en: 512) produced a vector column of the wrong size. **Fix:** per-model lookup table of default output dimensions, only for models whose dimension is documented (model configs on Hugging Face `hidden_size`/`projection_dim`, and https://jina.ai/models/ pages). Unknown models raise a `ValueError` listing the supported names instead of silently guessing 768. The default `jina-clip-v1` still returns 768. When appending to a table, generated vectors are validated against the width of the stored fixed-size column, so existing tables that use an unlisted model keep working. **Test:** `python/tests/test_jina_embeddings.py` (no network, no API key), including reopening a table with an unlisted model, appending a matching vector and rejecting a mismatched width. This change was prepared with an AI coding assistant (Claude). --------- Co-authored-by: Claude Sonnet 5.5 --- docs/web/integrations/embedding/jina.mdx | 19 +++++++ python/python/lancedb/embeddings/jinaai.py | 38 ++++++++++++- python/python/lancedb/table.py | 15 ++++- python/python/tests/test_jina_embeddings.py | 63 +++++++++++++++++++++ 4 files changed, 131 insertions(+), 4 deletions(-) create mode 100644 python/python/tests/test_jina_embeddings.py diff --git a/docs/web/integrations/embedding/jina.mdx b/docs/web/integrations/embedding/jina.mdx index 588500d36..7fb6537f5 100644 --- a/docs/web/integrations/embedding/jina.mdx +++ b/docs/web/integrations/embedding/jina.mdx @@ -8,6 +8,25 @@ import { PyEmbeddingJinaMultimodal, } from '/snippets/provider_examples.mdx'; +## Vector Dimensions {#vector-dimensions} + +`ndims()`, used when declaring a schema such as `Vector(func.ndims())`, returns the default width of these models: + +| Model | Dimensions | +|---|---| +| `jina-clip-v1` | 768 | +| `jina-clip-v2` | 1024 | +| `jina-embeddings-v2-small-en` | 512 | +| `jina-embeddings-v2-base-en` | 768 | +| `jina-embeddings-v2-base-code` | 768 | +| `jina-embeddings-v2-base-de` | 768 | +| `jina-embeddings-v2-base-zh` | 768 | +| `jina-embeddings-v2-base-es` | 768 | +| `jina-embeddings-v3` | 1024 | +| `jina-embeddings-v4` | 2048 | + +For any other model name, `ndims()` raises `ValueError`. Appending to an existing table whose vector column is a fixed-size list does not call `ndims()`: the generated vectors are checked against the width stored in the table. + ## Text Embedding Models {#text-embedding-models} Jina embeddings are used to generate embeddings for text and image data. diff --git a/python/python/lancedb/embeddings/jinaai.py b/python/python/lancedb/embeddings/jinaai.py index d038b6793..85ef9a569 100644 --- a/python/python/lancedb/embeddings/jinaai.py +++ b/python/python/lancedb/embeddings/jinaai.py @@ -9,7 +9,7 @@ from functools import cached_property from urllib.parse import urlparse from urllib.request import url2pathname from pathlib import Path -from typing import TYPE_CHECKING, List, Union, Optional, Any, Dict +from typing import TYPE_CHECKING, ClassVar, List, Union, Optional, Any, Dict import numpy as np import pyarrow as pa @@ -49,14 +49,46 @@ class JinaEmbeddings(EmbeddingFunction): The api key to access Jina API. If you pass None, you can set JINA_API_KEY environment variable + Notes + ----- + ``ndims()`` knows the default width of these models and raises + ``ValueError`` for any other name: jina-clip-v1, jina-clip-v2, + jina-embeddings-v2-small-en, jina-embeddings-v2-base-en, + jina-embeddings-v2-base-code, jina-embeddings-v2-base-de, + jina-embeddings-v2-base-zh, jina-embeddings-v2-base-es, + jina-embeddings-v3 and jina-embeddings-v4. + + Appending to a table whose vector column is a fixed-size list does not call + ``ndims()``: generated vectors are checked against the stored width. """ name: str = "jina-clip-v1" api_key: Optional[str] = None + # Default output dimensions of the Jina embedding models, from the model + # configs / model pages: https://huggingface.co/jinaai and + # https://jina.ai/models/ + _MODEL_DIMS: ClassVar[Dict[str, int]] = { + "jina-clip-v1": 768, + "jina-clip-v2": 1024, + "jina-embeddings-v2-small-en": 512, + "jina-embeddings-v2-base-en": 768, + "jina-embeddings-v2-base-code": 768, + "jina-embeddings-v2-base-de": 768, + "jina-embeddings-v2-base-zh": 768, + "jina-embeddings-v2-base-es": 768, + "jina-embeddings-v3": 1024, + "jina-embeddings-v4": 2048, + } + def ndims(self): - # TODO: fix hardcoding - return 768 + try: + return self._MODEL_DIMS[self.name] + except KeyError: + raise ValueError( + f"Unknown Jina model {self.name!r}: cannot determine the embedding " + f"dimension. Supported models: {sorted(self._MODEL_DIMS)}" + ) from None @staticmethod def sensitive_keys() -> List[str]: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5a0cbb6f1..299243b45 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1450,6 +1450,7 @@ def _append_vector_columns( if not functions: return reader + target_schema = schema fields = list(reader.schema) for vector_column, conf in functions.items(): if vector_column not in reader.schema.names: @@ -1475,7 +1476,19 @@ def _append_vector_columns( # _handle_bad_vectors can process them according to the # on_bad_vectors policy instead of crashing when PyArrow # tries to cast them into a fixed-size list array. - expected_ndims = conf.function.ndims() + # A fixed-size column already records the width, so only ask + # the function when it doesn't. Tables can use models whose + # dimension the function doesn't know. + field = schema.field(vector_column) + if ( + target_schema is not None + and vector_column in target_schema.names + ): + field = target_schema.field(vector_column) + if pa.types.is_fixed_size_list(field.type): + expected_ndims = field.type.list_size + else: + expected_ndims = conf.function.ndims() col_data = [ v if v is not None and len(v) == expected_ndims else None for v in col_data diff --git a/python/python/tests/test_jina_embeddings.py b/python/python/tests/test_jina_embeddings.py new file mode 100644 index 000000000..ad054299e --- /dev/null +++ b/python/python/tests/test_jina_embeddings.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pyarrow as pa +import pytest + +import lancedb +from lancedb.embeddings import EmbeddingFunctionConfig, get_registry + + +@pytest.mark.parametrize( + "name,dims", + [ + ("jina-clip-v1", 768), + ("jina-clip-v2", 1024), + ("jina-embeddings-v2-small-en", 512), + ("jina-embeddings-v2-base-en", 768), + ("jina-embeddings-v3", 1024), + ("jina-embeddings-v4", 2048), + ], +) +def test_jina_ndims_per_model(name, dims): + func = get_registry().get("jina").create(name=name) + assert func.ndims() == dims + + +def test_jina_ndims_unknown_model(): + func = get_registry().get("jina").create(name="not-a-jina-model") + with pytest.raises(ValueError, match="Unknown Jina model"): + func.ndims() + + +@pytest.mark.parametrize("width", [512, 768]) +def test_jina_append_uses_stored_width_for_unknown_model(tmp_path, monkeypatch, width): + func = get_registry().get("jina").create(name="jina-embeddings-v5-text-nano") + returned_width = width + monkeypatch.setattr( + type(func), + "_generate_embeddings", + lambda self, input, *args, **kwargs: [[0.5] * returned_width for _ in input], + ) + schema = pa.schema( + [ + pa.field("text", pa.string()), + pa.field("vector", pa.list_(pa.float32(), width)), + ] + ) + config = EmbeddingFunctionConfig( + source_column="text", vector_column="vector", function=func + ) + lancedb.connect(tmp_path).create_table( + "t", schema=schema, embedding_functions=[config] + ) + + table = lancedb.connect(tmp_path).open_table("t") + table.add([{"text": "hello"}]) + assert table.to_arrow()["vector"].to_pylist() == [[0.5] * width] + + returned_width = width + 1 + # Mismatched vectors go through on_bad_vectors, which errors by default. + with pytest.raises(RuntimeError, match="Vector column .vector. has"): + table.add([{"text": "world"}]) + assert table.count_rows() == 1