Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Store image-index embeddings as fp16 (#9696)
Jonathan0830f0dbaad5
diff --git a/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdx b/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdxindex 5804d802ef..2b9577e952 100644--- a/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdx@@ -33,6 +33,21 @@ collection, initial indexing may take a while -- expect a gallery of20,000 images to take about 15 minutes to index. After this, the indexis updated incrementally in the background.+### Embedding storage++On first startup after this update, InvokeAI converts saved image and video+embeddings in one database transaction. It reuses saved vectors and does+not run the embedding model again. InvokeAI creates a database backup+before conversion. Large indexes can add one-time startup time. Restore+that pre-upgrade backup before running an older application version.++New embeddings use float16 on disk and decode to float32 for search and+projections. This halves raw embedding BLOB storage. SQLite may retain+freed pages, so the database file may not shrink by half. Search and+projection calculations still use float32 in memory. Float16 quantization+can slightly change similarity scores, so items with nearly equal scores+can change order.+### Inactivating the Image MapIf you wish to turn off Image Map indexing and hide its panel@@ -88,4 +103,3 @@ the gallery, preview, or another browser tab) onto the search box. Allsimilar images will be shown in the gallery.To exit search mode, click the "X" to the right of the search box.-diff --git a/invokeai/app/services/image_index/image_index_common.py b/invokeai/app/services/image_index/image_index_common.pyindex 19057ec2b0..d2c8b4c86b 100644--- a/invokeai/app/services/image_index/image_index_common.py+++ b/invokeai/app/services/image_index/image_index_common.py@@ -1,11 +1,15 @@"""Common types and helpers for the semantic image index services."""+from collections.abc import Sequencefrom typing import Literal, NamedTupleimport numpy as npfrom pydantic import BaseModel, ConfigDict, FieldEMBEDDING_DTYPE = np.float32+EMBEDDING_STORAGE_DTYPE = np.dtype("<f2")+_ENCODING_DTYPES = {"float32": np.dtype(EMBEDDING_DTYPE), "float16": EMBEDDING_STORAGE_DTYPE}+_DECODE_CHUNK_ROWS = 4096MediaKind = Literal["image", "video"]@@ -64,51 +68,86 @@ class ProjectionRecord(BaseModel):def embedding_to_blob(embedding: np.ndarray) -> bytes:- """Serialize a 1-D embedding vector to bytes for BLOB storage.+ """Serialize a 1-D embedding vector as contiguous little-endian float16 bytes.- The vector is stored as float32; a float64 input is narrowed. Callers are responsible for- L2-normalizing — this only rejects vectors that could not have been normalized, because a- non-finite value silently poisons every similarity and projection computation that later- touches the same batch, with no way to attribute it after the fact.+ Callers are responsible for L2-normalizing. Narrowing can overflow or underflow, so validate+ the stored representation as well as the input."""if embedding.ndim != 1:raise ValueError(f"Expected a 1-D embedding, got shape {embedding.shape}")if embedding.shape[0] == 0:- # A zero-dim row would be stored with dim=0 and then fail every batch it appears in,- # because `get_embeddings` requires one consistent dim across the result set.raise ValueError("Refusing to store a zero-length embedding")if not np.issubdtype(embedding.dtype, np.floating):- # Checked before the cast, which would otherwise raise TypeError (not the documented- # ValueError) on a structured dtype, and would silently discard the imaginary part of a- # complex one.raise ValueError(f"Expected a floating-point embedding, got dtype {embedding.dtype}")+ if not np.isfinite(embedding).all():+ raise ValueError("Embedding contains NaN or infinite values")+with np.errstate(all="ignore"):- # Narrowing can overflow to inf or underflow to zero; both are reported below as- # ValueError. Suppressing every flag here keeps that true even if some caller has set- # `np.seterr(all="raise")` process-wide, which would otherwise surface as- # FloatingPointError and break this function's documented contract.- narrowed = np.ascontiguousarray(embedding, dtype=EMBEDDING_DTYPE)+ narrowed = np.ascontiguousarray(embedding, dtype=EMBEDDING_STORAGE_DTYPE)if not np.isfinite(narrowed).all():- # Also catches a float64 magnitude that overflows to inf when narrowed to float32.- raise ValueError("Embedding contains NaN or infinite values")+ raise ValueError("Embedding contains NaN or infinite values after narrowing to float16")if not narrowed.any():- # All-zero cannot be an L2-normalized vector. It arrives either from an encoder failure- # or from float64 components that underflowed to zero when narrowed, and it produces- # NaN in every cosine similarity it takes part in.raise ValueError("Refusing to store an all-zero embedding; it cannot be L2-normalized")return narrowed.tobytes()-def blob_to_embedding(blob: bytes, dim: int) -> np.ndarray:- """Deserialize an embedding BLOB, validating its length against the stored dim.+def blobs_to_embeddings(blobs: Sequence[bytes], encodings: Sequence[str], dim: int) -> np.ndarray:+ """Deserialize explicitly encoded embedding BLOBs into one float32 matrix, validating every row.- Returns a read-only view over the blob; copy before mutating.+ Rows keep the order of `blobs`. Legacy float32 rows retain their stored values. Float16 rows+ are renormalized in float64 after quantization, then narrowed to float32.+ """+ if isinstance(dim, (bool, np.bool_)) or not isinstance(dim, (int, np.integer)) or dim <= 0:+ raise ValueError(f"Embedding dimension must be a positive integer, got {dim!r}")+ dim = int(dim)+ if len(blobs) != len(encodings):+ raise ValueError(f"Got {len(blobs)} embedding blobs but {len(encodings)} encodings")+ unsupported = set(encodings) - _ENCODING_DTYPES.keys()+ if unsupported:+ raise ValueError(f"Unsupported embedding encoding: {min(unsupported)!r}")++ # Each encoding is decoded as one buffer, then validated and renormalized in row chunks that+ # bound the float64 temporaries: per-row decoding dominated reads of a full gallery, which+ # happen whenever the accessible item set changes.+ matrix = np.empty((len(blobs), dim), dtype=EMBEDDING_DTYPE)+ for encoding, dtype in _ENCODING_DTYPES.items():+ rows = [index for index, row_encoding in enumerate(encodings) if row_encoding == encoding]+ if not rows:+ continue+ expected = dim * dtype.itemsize+ for index in rows:+ if len(blobs[index]) != expected:+ raise ValueError(+ f"Embedding blob is {len(blobs[index])} bytes; expected {expected} for {encoding} dimension {dim}"+ )+ decoded = np.frombuffer(b"".join(blobs[index] for index in rows), dtype=dtype).reshape(len(rows), dim)+ for start in range(0, len(rows), _DECODE_CHUNK_ROWS):+ stop = start + _DECODE_CHUNK_ROWS+ chunk = decoded[start:stop]+ if encoding == "float16":+ # Exact widening, done before validating because numpy's float16 kernels are slow.+ chunk = chunk.astype(np.float64)+ if not np.isfinite(chunk).all():+ raise ValueError("Embedding contains NaN or infinite values")+ if not chunk.any(axis=1).all():+ raise ValueError("Refusing to read an all-zero embedding; it cannot be L2-normalized")+ if encoding == "float16":+ chunk /= np.sqrt(np.einsum("ij,ij->i", chunk, chunk))[:, None]+ if len(rows) == len(blobs):+ matrix[start:stop] = chunk+ else:+ matrix[rows[start:stop]] = chunk+ return matrix+++def blob_to_embedding(blob: bytes, dim: int, encoding: str) -> np.ndarray:+ """Deserialize one explicitly encoded embedding BLOB; see `blobs_to_embeddings`.++ Returns a read-only float32 vector."""- if len(blob) != dim * EMBEDDING_DTYPE().itemsize:- raise ValueError(- f"Embedding blob is {len(blob)} bytes; expected {dim * EMBEDDING_DTYPE().itemsize} for dim {dim}"- )- return np.frombuffer(blob, dtype=EMBEDDING_DTYPE)+ vector = blobs_to_embeddings([blob], [encoding], dim)[0]+ vector.setflags(write=False)+ return vectordef coords_to_blob(coords: np.ndarray) -> bytes:diff --git a/invokeai/app/services/image_index/image_index_records_sqlite.py b/invokeai/app/services/image_index/image_index_records_sqlite.pyindex 1185381ae7..e7d2677864 100644--- a/invokeai/app/services/image_index/image_index_records_sqlite.py+++ b/invokeai/app/services/image_index/image_index_records_sqlite.py@@ -11,7 +11,7 @@ from invokeai.app.services.image_index.image_index_common import (MediaKind,ProjectionRecord,blob_to_coords,- blob_to_embedding,+ blobs_to_embeddings,coords_to_blob,embedding_to_blob,)@@ -95,13 +95,13 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):# genuine bug and is allowed to propagate.cursor.execute(f"""--sql- INSERT INTO {namespace.embeddings_table} ({namespace.name_column}, model_id, dim, embedding)- SELECT ?, ?, ?, ?+ INSERT INTO {namespace.embeddings_table} ({namespace.name_column}, model_id, dim, embedding, encoding)+ SELECT ?, ?, ?, ?, 'float16'WHERE EXISTS (SELECT 1 FROM {namespace.table} WHERE {namespace.table}.{namespace.name_column} = ?)ON CONFLICT ({namespace.name_column}, model_id)- DO UPDATE SET dim = excluded.dim, embedding = excluded.embedding;+ DO UPDATE SET dim = excluded.dim, embedding = excluded.embedding, encoding = excluded.encoding;""",(item.name, model_id, embedding.shape[0], blob, item.name),)@@ -112,7 +112,7 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):# Dedupe while preserving order so repeated input items cannot# double-count rows in downstream projection/similarity math.items = list(dict.fromkeys(items))- rows: dict[IndexedItem, tuple[int, bytes]] = {}+ rows: dict[IndexedItem, tuple[int, bytes, str]] = {}# Only the reads happen under the transaction. Deserialization and validation are done# afterwards so a malformed row raises outside it: `transaction()` rolls the shared@@ -126,31 +126,30 @@ class ImageIndexRecordsSqlite(ImageIndexRecordsBase):placeholders = ",".join("?" * len(chunk))cursor.execute(f"""--sql- SELECT {namespace.name_column}, dim, embedding+ SELECT {namespace.name_column}, dim, embedding, encodingFROM {namespace.embeddings_table}WHERE model_id = ? AND {namespace.name_column} IN ({placeholders});""",(model_id, *chunk),)- for name, dim, blob in cursor.fetchall():- rows[IndexedItem(namespace.kind, name)] = (dim, blob)+ for name, dim, blob, encoding in cursor.fetchall():+ rows[IndexedItem(namespace.kind, name)] = (dim, blob, encoding)# Read back in the caller's order: the returned matrix's rows align with it.found_items = [item for item in items if item in rows]- dim: int | None = None- vectors: list[np.ndarray] = []+ if not found_items:+ return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)++ dim = rows[found_items[0]][0]for item in found_items:- row_dim, blob = rows[item]- if dim is None:- dim = row_dim- elif row_dim != dim:+ row_dim = rows[item][0]+ if row_dim != dim:raise ValueError(f"Inconsistent embedding dims for model {model_id}: found {row_dim} and {dim}")- vectors.append(blob_to_embedding(blob, row_dim))-- if not vectors:- return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)- return found_items, np.stack(vectors)+ matrix = blobs_to_embeddings(+ [rows[item][1] for item in found_items], [rows[item][2] for item in found_items], dim+ )+ return found_items, matrixdef delete_embedding(self, item: IndexedItem) -> None:namespace = _NAMESPACE_BY_KIND[item.kind]diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_30_store_embeddings_fp16.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_30_store_embeddings_fp16.pynew file mode 100644index 0000000000..fede5cf3ba--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_30_store_embeddings_fp16.py@@ -0,0 +1,125 @@+"""Store image and video semantic embeddings as little-endian float16 BLOBs.++After this migration commits, rollback to older application code requires restoring the pre-migration database backup.+"""++import sqlite3+import time+from logging import Logger++from invokeai.app.services.image_index.image_index_common import blob_to_embedding, embedding_to_blob+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration++_BATCH_SIZE = 256+_PROGRESS_INTERVAL = 10_000+_EMBEDDING_TABLES = (("image_embeddings", "image_name"), ("video_embeddings", "video_name"))+++class StoreEmbeddingsFp16Callback:+ """Add explicit encoding metadata and convert legacy float32 embedding rows."""++ def __init__(self, logger: Logger) -> None:+ self._logger = logger++ def __call__(self, cursor: sqlite3.Cursor) -> None:+ started_at = time.perf_counter()+ self._logger.info("Starting image and video embedding fp16 migration")++ converted_by_table: dict[str, int] = {}+ converted_total = 0+ try:+ for table, _ in _EMBEDDING_TABLES:+ if not self._has_encoding_column(cursor, table):+ cursor.execute(+ f"""ALTER TABLE {table}+ ADD COLUMN encoding TEXT NOT NULL DEFAULT 'float32'+ CHECK (encoding IN ('float32', 'float16'));"""+ )++ for table, name_column in _EMBEDDING_TABLES:+ converted_by_table[table] = self._convert_table(cursor, table, name_column, converted_total)+ converted_total += converted_by_table[table]+ except Exception:+ elapsed = time.perf_counter() - started_at+ image_count = converted_by_table.get("image_embeddings", 0)+ video_count = converted_by_table.get("video_embeddings", 0)+ self._logger.info(+ "Embedding fp16 migration failed after %.2f seconds; converted image rows=%d, video rows=%d",+ elapsed,+ image_count,+ video_count,+ )+ raise++ elapsed = time.perf_counter() - started_at+ self._logger.info(+ "Completed image and video embedding fp16 migration: image rows=%d, video rows=%d, total rows=%d, "+ "elapsed=%.2f seconds",+ converted_by_table["image_embeddings"],+ converted_by_table["video_embeddings"],+ converted_total,+ elapsed,+ )++ @staticmethod+ def _has_encoding_column(cursor: sqlite3.Cursor, table: str) -> bool:+ cursor.execute(f"PRAGMA table_info({table});")+ return any(row[1] == "encoding" for row in cursor.fetchall())++ def _convert_table(self, cursor: sqlite3.Cursor, table: str, name_column: str, converted_before: int) -> int:+ last_rowid: int | None = None+ converted = 0+ next_progress = (converted_before // _PROGRESS_INTERVAL + 1) * _PROGRESS_INTERVAL+ while True:+ if last_rowid is None:+ cursor.execute(+ f"""SELECT rowid, {name_column}, model_id, dim, embedding+ FROM {table}+ WHERE encoding = 'float32'+ ORDER BY rowid+ LIMIT {_BATCH_SIZE};"""+ )+ else:+ cursor.execute(+ f"""SELECT rowid, {name_column}, model_id, dim, embedding+ FROM {table}+ WHERE rowid > ? AND encoding = 'float32'+ ORDER BY rowid+ LIMIT {_BATCH_SIZE};""",+ (last_rowid,),+ )+ batch = cursor.fetchall()+ if not batch:+ return converted++ for row in batch:+ rowid, record_name, model_id, dim, embedding = row+ last_rowid = rowid+ identity = f"{record_name} (model_id={model_id})"+ try:+ decoded = blob_to_embedding(embedding, dim, "float32")+ encoded = embedding_to_blob(decoded)+ cursor.execute(+ f"UPDATE {table} SET embedding = ?, encoding = 'float16' "+ "WHERE rowid = ? AND encoding = 'float32';",+ (encoded, rowid),+ )+ if cursor.rowcount != 1:+ raise RuntimeError("row changed while migration was running")+ except Exception as e:+ raise RuntimeError(f"Failed converting {table} record {identity!r}: {e}") from e++ converted += 1+ total = converted_before + converted+ if total >= next_progress:+ self._logger.info(f"Converted {total} image and video embeddings to fp16")+ next_progress = (total // _PROGRESS_INTERVAL + 1) * _PROGRESS_INTERVAL+++def build_migration(logger: Logger) -> Migration:+ """Build the transactionally safe conversion from legacy float32 embedding BLOBs."""+ return Migration(+ id="2026_09_30_store_embeddings_fp16",+ depends_on="2026_09_12_add_video_embeddings",+ callback=StoreEmbeddingsFp16Callback(logger=logger),+ )diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 5a4379e4fa..7769114a4b 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -1675,7 +1675,10 @@ def test_image_labels_rank_the_vocabulary_for_one_image(mock_invoker: Invoker, cassert body["label"] == "beta"assert body["alternates"] == ["alpha", "gamma"]- assert body["score"] == pytest.approx(0.8 / float(np.linalg.norm(vector)))+ stored_vector = (vector / np.linalg.norm(vector)).astype("<f2")+ expected_embedding = stored_vector.astype(np.float32)+ expected_embedding /= np.linalg.norm(expected_embedding.astype(np.float64))+ assert body["score"] == pytest.approx(float(expected_embedding[1]))# top_k bounds the total label count (best + alternates).body = client.get("/api/v1/image_map/image_labels", params={"image_name": "leaning.png", "top_k": 1}).json()diff --git a/tests/app/services/image_index/test_image_index_records.py b/tests/app/services/image_index/test_image_index_records.pyindex 1b61583171..11cd4a33b1 100644--- a/tests/app/services/image_index/test_image_index_records.py+++ b/tests/app/services/image_index/test_image_index_records.py@@ -10,10 +10,12 @@ from invokeai.app.services.board_records.board_records_common import BoardChangefrom invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStoragefrom invokeai.app.services.board_video_records.board_video_records_sqlite import SqliteBoardVideoRecordStoragefrom invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.image_index import image_index_commonfrom invokeai.app.services.image_index.image_index_common import (IndexedItem,blob_to_coords,blob_to_embedding,+ blobs_to_embeddings,coords_to_blob,embedding_to_blob,)@@ -137,19 +139,108 @@ def _vec(seed: int) -> np.ndarray:return v / np.linalg.norm(v)+def _expected_fp16_roundtrip(vector: np.ndarray) -> np.ndarray:+ narrowed = np.asarray(vector, dtype=np.dtype("<f2")).astype(np.float64)+ norm = np.sqrt(np.sum(narrowed * narrowed, dtype=np.float64))+ return (narrowed / norm).astype(np.float32)++# --- Blob helpers ----def test_embedding_blob_roundtrip_is_bit_exact() -> None:- v = _vec(1)- assert np.array_equal(blob_to_embedding(embedding_to_blob(v), DIM), v)+def test_embedding_blob_stores_little_endian_fp16_and_renormalizes_on_read() -> None:+ vector = _vec(1)+ blob = embedding_to_blob(vector)++ assert blob == np.asarray(vector, dtype=np.dtype("<f2")).tobytes()+ decoded = blob_to_embedding(blob, DIM, "float16")+ expected = _expected_fp16_roundtrip(vector)++ assert decoded.dtype == np.float32+ assert not decoded.flags.writeable+ np.testing.assert_allclose(decoded, expected, rtol=0, atol=1e-7)+ assert abs(np.linalg.norm(decoded.astype(np.float64)) - 1.0) <= 1e-6+ assert 1.0 - float(np.dot(vector.astype(np.float64), decoded.astype(np.float64))) <= 1e-6+++def test_embedding_blob_preserves_legacy_float32_values_read_only() -> None:+ vector = _vec(1)+ blob = vector.tobytes()++ decoded = blob_to_embedding(blob, DIM, "float32")++ assert len(blob) == DIM * 4+ assert np.array_equal(decoded, vector)+ assert decoded.dtype == np.float32+ assert not decoded.flags.writeable-def test_embedding_blob_rejects_bad_shapes() -> None:+def test_768_dim_embedding_blob_uses_half_storage_bytes() -> None:+ vector = np.random.default_rng(821).standard_normal(768).astype(np.float32)+ vector /= np.linalg.norm(vector)++ assert len(embedding_to_blob(vector)) == 1536+ assert len(vector.tobytes()) == 3072+ decoded = blob_to_embedding(embedding_to_blob(vector), 768, "float16")+ cosine = float(np.dot(vector.astype(np.float64), decoded.astype(np.float64)))+ assert abs(np.linalg.norm(decoded.astype(np.float64)) - 1.0) <= 1e-6+ assert 1.0 - cosine <= 1e-6++ query = np.random.default_rng(822).standard_normal(768).astype(np.float32)+ query /= np.linalg.norm(query)+ orthogonal = np.random.default_rng(823).standard_normal(768).astype(np.float32)+ orthogonal -= query * np.dot(query, orthogonal)+ orthogonal /= np.linalg.norm(orthogonal)+ candidates = [query, query + orthogonal * 1e-3, query + orthogonal * 0.1]+ candidates = [candidate / np.linalg.norm(candidate) for candidate in candidates]+ decoded_candidates = [blob_to_embedding(embedding_to_blob(candidate), 768, "float16") for candidate in candidates]+ source_scores = [float(np.dot(query, candidate)) for candidate in candidates]+ stored_scores = [float(np.dot(query, candidate)) for candidate in decoded_candidates]++ assert max(abs(source - stored) for source, stored in zip(source_scores, stored_scores, strict=True)) <= 1e-3+ assert source_scores[0] - source_scores[1] < 2e-3+ assert source_scores[0] - source_scores[2] > 2e-3+ assert stored_scores[0] > stored_scores[2]+++def test_embedding_blob_rejects_bad_shapes_and_dimensions() -> None:with pytest.raises(ValueError):embedding_to_blob(np.zeros((2, 2), dtype=np.float32))- with pytest.raises(ValueError):- blob_to_embedding(embedding_to_blob(_vec(1)), DIM + 1)+ with pytest.raises(ValueError, match="dimension"):+ blob_to_embedding(embedding_to_blob(_vec(1)), DIM + 1, "float16")+ for dim in (0, -1):+ with pytest.raises(ValueError, match="positive"):+ blob_to_embedding(b"", dim, "float16")+++def test_embedding_blob_requires_explicit_supported_encoding_and_exact_length() -> None:+ fp16 = np.asarray(_vec(1), dtype=np.dtype("<f2")).tobytes()+ fp32 = _vec(1).tobytes()++ with pytest.raises(ValueError, match="encoding"):+ blob_to_embedding(fp16, DIM, "float64")+ with pytest.raises(ValueError, match="expected"):+ blob_to_embedding(fp16[:-2], DIM, "float16")+ with pytest.raises(ValueError, match="expected"):+ blob_to_embedding(fp16, DIM, "float32")+ # This payload has exactly the size of a valid fp16 vector, but its declared+ # encoding is float32. The decoder must reject it instead of guessing by size.+ with pytest.raises(ValueError, match="expected"):+ blob_to_embedding(fp32[: len(fp16)], DIM, "float32")+++def test_embedding_blob_rejects_nonfinite_and_zero_decoded_vectors() -> None:+ for vector in (+ np.array([np.nan, 1, 1, 1], dtype=np.dtype("<f2")),+ np.array([np.inf, 1, 1, 1], dtype=np.dtype("<f2")),+ np.zeros(4, dtype=np.dtype("<f2")),+ np.array([np.nan, 1, 1, 1], dtype=np.float32),+ np.array([np.inf, 1, 1, 1], dtype=np.float32),+ np.zeros(4, dtype=np.float32),+ ):+ encoding = "float16" if vector.dtype.itemsize == 2 else "float32"+ with pytest.raises(ValueError):+ blob_to_embedding(vector.tobytes(), len(vector), encoding)def test_embedding_blob_rejects_non_finite_values() -> None:@@ -211,7 +302,9 @@ def test_embedding_blob_survives_global_numpy_error_state() -> None:def test_embedding_blob_narrows_float64_input() -> None:v64 = (np.arange(DIM, dtype=np.float64) + 1.0) / 10.0- assert np.array_equal(blob_to_embedding(embedding_to_blob(v64), DIM), v64.astype(np.float32))+ np.testing.assert_allclose(+ blob_to_embedding(embedding_to_blob(v64), DIM, "float16"), _expected_fp16_roundtrip(v64), rtol=0, atol=1e-7+ )def test_coords_blob_roundtrip_and_validation() -> None:@@ -233,7 +326,7 @@ def test_coords_from_blob_are_writable() -> None:def test_upsert_and_get_roundtrip(- image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite+ db: SqliteDatabase, image_records: SqliteImageRecordStorage, index_records: ImageIndexRecordsSqlite) -> None:_save_image(image_records, "a.png")_save_image(image_records, "b.png")@@ -241,12 +334,19 @@ def test_upsert_and_get_roundtrip(index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, va)index_records.upsert_embedding(IndexedItem("image", "b.png"), MODEL_ID, vb)+ with db.transaction() as cursor:+ cursor.execute(+ "SELECT encoding, LENGTH(embedding) FROM image_embeddings WHERE image_name = ? AND model_id = ?;",+ ("a.png", MODEL_ID),+ )+ assert tuple(cursor.fetchone()) == ("float16", DIM * 2)+names, matrix = index_records.get_embeddings(imgs("b.png", "a.png", "missing.png"), MODEL_ID)assert names == imgs("b.png", "a.png")assert matrix.dtype == np.float32- assert np.array_equal(matrix[0], vb)- assert np.array_equal(matrix[1], va)+ np.testing.assert_allclose(matrix[0], _expected_fp16_roundtrip(vb), rtol=0, atol=1e-7)+ np.testing.assert_allclose(matrix[1], _expected_fp16_roundtrip(va), rtol=0, atol=1e-7)def test_upsert_replaces_existing_embedding(@@ -259,7 +359,7 @@ def test_upsert_replaces_existing_embedding(names, matrix = index_records.get_embeddings(imgs("a.png"), MODEL_ID)assert names == imgs("a.png")- assert np.array_equal(matrix[0], replacement)+ np.testing.assert_allclose(matrix[0], _expected_fp16_roundtrip(replacement), rtol=0, atol=1e-7)def test_get_embeddings_empty_input_and_no_matches(@@ -294,8 +394,8 @@ def test_get_embeddings_chunks_large_requests(assert names == requestedassert matrix.shape == (count, DIM)# Rows must still align with the names after chunking and reordering.- assert np.array_equal(matrix[0], _vec(count - 1))- assert np.array_equal(matrix[-1], _vec(0))+ np.testing.assert_allclose(matrix[0], _expected_fp16_roundtrip(_vec(count - 1)), rtol=0, atol=1e-7)+ np.testing.assert_allclose(matrix[-1], _expected_fp16_roundtrip(_vec(0)), rtol=0, atol=1e-7)def test_get_embeddings_rejects_inconsistent_dims(@@ -777,8 +877,87 @@ def test_videos_are_stored_counted_and_listed_alongside_images()# Rows follow the caller's order across both namespaces, not one namespace after the other.assert items == [IndexedItem("video", "clip.mp4"), IndexedItem("image", "a.png")]- assert np.array_equal(matrix[0], _vec(2))- assert np.array_equal(matrix[1], _vec(1))+ np.testing.assert_allclose(matrix[0], _expected_fp16_roundtrip(_vec(2)), rtol=0, atol=1e-7)+ np.testing.assert_allclose(matrix[1], _expected_fp16_roundtrip(_vec(1)), rtol=0, atol=1e-7)+++def test_records_read_mixed_legacy_and_fp16_encodings_across_media_kinds(+ db: SqliteDatabase,+ image_records: SqliteImageRecordStorage,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ _save_image(image_records, "legacy.png")+ _save_video(video_records, "half.mp4")+ legacy = _vec(1)+ half = _vec(2)++ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES (?, ?, ?, ?);",+ ("legacy.png", MODEL_ID, DIM, legacy.tobytes()),+ )+ cursor.execute(+ "INSERT INTO video_embeddings (video_name, model_id, dim, embedding, encoding) VALUES (?, ?, ?, ?, ?);",+ ("half.mp4", MODEL_ID, DIM, embedding_to_blob(half), "float16"),+ )++ items, matrix = index_records.get_embeddings(+ [IndexedItem("video", "half.mp4"), IndexedItem("image", "legacy.png")], MODEL_ID+ )++ assert items == [IndexedItem("video", "half.mp4"), IndexedItem("image", "legacy.png")]+ assert matrix.dtype == np.float32+ np.testing.assert_allclose(matrix[0], _expected_fp16_roundtrip(half), rtol=0, atol=1e-7)+ assert np.array_equal(matrix[1], legacy)+++def test_embedding_matrix_decode_keeps_rows_aligned_across_encodings_and_chunks(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(image_index_common, "_DECODE_CHUNK_ROWS", 2)+ vectors = [_vec(seed) for seed in range(7)]+ encodings = ["float16", "float32", "float32", "float16", "float16", "float32", "float16"]+ blobs = [embedding_to_blob(v) if e == "float16" else v.tobytes() for v, e in zip(vectors, encodings, strict=True)]++ matrix = blobs_to_embeddings(blobs, encodings, DIM)++ assert matrix.shape == (7, DIM)+ for row, vector, encoding in zip(matrix, vectors, encodings, strict=True):+ if encoding == "float32":+ assert np.array_equal(row, vector)+ else:+ np.testing.assert_allclose(row, _expected_fp16_roundtrip(vector), rtol=0, atol=1e-7)++ uniform = blobs_to_embeddings([embedding_to_blob(v) for v in vectors], ["float16"] * len(vectors), DIM)+ np.testing.assert_allclose(uniform, np.stack([_expected_fp16_roundtrip(v) for v in vectors]), rtol=0, atol=1e-7)++ # A degenerate row in an encoding group's last, partial chunk must still be rejected: row 5 is+ # the third float32 row, and row 4 the third float16 row once row 6 is dropped.+ zero_last = [*blobs[:5], np.zeros(DIM, np.float32).tobytes(), blobs[6]]+ with pytest.raises(ValueError, match="all-zero"):+ blobs_to_embeddings(zero_last, encodings, DIM)+ nan_last = [*blobs[:4], np.full(DIM, np.nan, "<f2").tobytes(), blobs[5]]+ with pytest.raises(ValueError, match="NaN or infinite"):+ blobs_to_embeddings(nan_last, encodings[:6], DIM)+++def test_image_and_video_upserts_set_fp16_encoding(+ db: SqliteDatabase,+ image_records: SqliteImageRecordStorage,+ video_records: SqliteVideoRecordStorage,+ index_records: ImageIndexRecordsSqlite,+) -> None:+ _save_image(image_records, "a.png")+ _save_video(video_records, "clip.mp4")+ index_records.upsert_embedding(IndexedItem("image", "a.png"), MODEL_ID, _vec(1))+ index_records.upsert_embedding(IndexedItem("video", "clip.mp4"), MODEL_ID, _vec(2))++ with db.transaction() as cursor:+ cursor.execute("SELECT encoding, LENGTH(embedding) FROM image_embeddings WHERE image_name = 'a.png';")+ assert tuple(cursor.fetchone()) == ("float16", DIM * 2)+ cursor.execute("SELECT encoding, LENGTH(embedding) FROM video_embeddings WHERE video_name = 'clip.mp4';")+ assert tuple(cursor.fetchone()) == ("float16", DIM * 2)def test_an_image_and_a_video_are_different_items(@@ -793,8 +972,18 @@ def test_an_image_and_a_video_are_different_items(index_records.upsert_embedding(IndexedItem("image", "same.png"), MODEL_ID, _vec(1))index_records.upsert_embedding(IndexedItem("video", "same.png"), MODEL_ID, _vec(2))- assert np.array_equal(index_records.get_embeddings(imgs("same.png"), MODEL_ID)[1][0], _vec(1))- assert np.array_equal(index_records.get_embeddings(vids("same.png"), MODEL_ID)[1][0], _vec(2))+ np.testing.assert_allclose(+ index_records.get_embeddings(imgs("same.png"), MODEL_ID)[1][0],+ _expected_fp16_roundtrip(_vec(1)),+ rtol=0,+ atol=1e-7,+ )+ np.testing.assert_allclose(+ index_records.get_embeddings(vids("same.png"), MODEL_ID)[1][0],+ _expected_fp16_roundtrip(_vec(2)),+ rtol=0,+ atol=1e-7,+ )index_records.delete_embedding(IndexedItem("image", "same.png"))assert index_records.get_embeddings(imgs("same.png"), MODEL_ID)[0] == []diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 2f78fbfea9..8602c3fb86 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -881,7 +881,9 @@ def test_reinstalled_encoder_keeping_its_key_embeds_with_the_new_weights(expected = (expected / expected.norm()).numpy()stored = index_records.get_embeddings([item], replacement.hash)[1][0]assert not np.allclose(expected, retired_embedding, atol=1e-3), "the two encoders must disagree"- np.testing.assert_allclose(stored, expected, atol=1e-5)+ np.testing.assert_allclose(stored, expected, atol=1e-4)+ cosine = float(np.dot(stored.astype(np.float64), expected.astype(np.float64)))+ assert 1.0 - cosine <= 1e-6finally:service.stop()cache.shutdown()diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_30_store_embeddings_fp16.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_30_store_embeddings_fp16.pynew file mode 100644index 0000000000..b208428776--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_30_store_embeddings_fp16.py@@ -0,0 +1,341 @@+import logging+import sqlite3+from pathlib import Path++import numpy as np+import pytest++from invokeai.app.services.image_index.image_index_common import blob_to_embedding, embedding_to_blob+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.app.services.shared.sqlite_migrator.migration_loader import (+ MigrationBuildContext,+ build_migrations,+ discover_migration_builders,+)+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_30_store_embeddings_fp16 import (+ build_migration,+)+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration, MigrationError+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import SqliteMigrator++MIGRATION_ID = "2026_09_30_store_embeddings_fp16"+DEPENDENCY_ID = "2026_09_12_add_video_embeddings"+++class _FakeConfig:+ def __init__(self, root_path: Path) -> None:+ self.root_path = root_path+ self.models_path = root_path / "models"+ self.convert_cache_path = self.models_path / ".cache"+ self.legacy_conf_path = root_path / "models.yaml"+ self.legacy_conf_dir = root_path+++def _vector(seed: int) -> np.ndarray:+ values = np.random.default_rng(seed).standard_normal(8).astype(np.float32)+ return values / np.linalg.norm(values)+++def _create_schema(connection: sqlite3.Connection, *, image_encoding: bool = False) -> None:+ connection.execute("PRAGMA foreign_keys = ON;")+ connection.execute("CREATE TABLE images (image_name TEXT PRIMARY KEY);")+ connection.execute("CREATE TABLE videos (video_name TEXT PRIMARY KEY);")+ image_encoding_sql = (+ ", encoding TEXT NOT NULL DEFAULT 'float32' CHECK (encoding IN ('float32', 'float16'))"+ if image_encoding+ else ""+ )+ connection.execute(+ f"""CREATE TABLE image_embeddings (+ image_name TEXT NOT NULL,+ model_id TEXT NOT NULL,+ dim INTEGER NOT NULL,+ embedding BLOB NOT NULL{image_encoding_sql},+ created_at DATETIME NOT NULL DEFAULT 'image-created',+ PRIMARY KEY (image_name, model_id),+ FOREIGN KEY (image_name) REFERENCES images(image_name) ON DELETE CASCADE+ );"""+ )+ connection.execute(+ """CREATE TABLE video_embeddings (+ video_name TEXT NOT NULL,+ model_id TEXT NOT NULL,+ dim INTEGER NOT NULL,+ embedding BLOB NOT NULL,+ created_at DATETIME NOT NULL DEFAULT 'video-created',+ PRIMARY KEY (video_name, model_id),+ FOREIGN KEY (video_name) REFERENCES videos(video_name) ON DELETE CASCADE+ );"""+ )+ connection.execute("CREATE INDEX idx_image_embeddings_model_id ON image_embeddings(model_id);")+ connection.execute("CREATE INDEX idx_video_embeddings_model_id ON video_embeddings(model_id);")+ connection.commit()+++def _make_db(tmp_path: Path) -> SqliteDatabase:+ db = SqliteDatabase(db_path=tmp_path / "embeddings.db", logger=logging.getLogger(__name__))+ _create_schema(db._conn)+ return db+++def _migrator(db: SqliteDatabase) -> SqliteMigrator:+ migrator = SqliteMigrator(db)+ migrator.register_migration(Migration(id=DEPENDENCY_ID, callback=lambda cursor: None))+ migrator.register_migration(build_migration(logger=logging.getLogger(__name__)))+ return migrator+++def _insert(+ connection: sqlite3.Connection,+ table: str,+ record_name: str,+ model_id: str,+ vector_blob: bytes,+ *,+ dim: int = 8,+ encoding: str | None = None,+ created_at: str = "2026-09-01 12:00:00.000",+) -> None:+ parent_table = "images" if table == "image_embeddings" else "videos"+ parent_column = "image_name" if table == "image_embeddings" else "video_name"+ connection.execute(f"INSERT OR IGNORE INTO {parent_table} ({parent_column}) VALUES (?);", (record_name,))+ if encoding is None:+ connection.execute(+ f"INSERT INTO {table} ({parent_column}, model_id, dim, embedding, created_at) VALUES (?, ?, ?, ?, ?);",+ (record_name, model_id, dim, vector_blob, created_at),+ )+ else:+ connection.execute(+ f"""INSERT INTO {table} ({parent_column}, model_id, dim, embedding, created_at, encoding)+ VALUES (?, ?, ?, ?, ?, ?);""",+ (record_name, model_id, dim, vector_blob, created_at, encoding),+ )+++def _has_encoding(connection: sqlite3.Connection, table: str) -> bool:+ return any(row[1] == "encoding" for row in connection.execute(f"PRAGMA table_info({table});"))+++def test_migration_is_discovered_with_stable_id_and_dependency(tmp_path: Path) -> None:+ context = MigrationBuildContext(+ app_config=_FakeConfig(tmp_path),+ logger=logging.getLogger(__name__),+ image_files=object(), # type: ignore[arg-type]+ )+ migrations = build_migrations(context)+ migration = next(migration for migration in migrations if migration.id == MIGRATION_ID)+ module_names = {builder.module_name for builder in discover_migration_builders()}++ assert migration.depends_on == DEPENDENCY_ID+ assert "invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_30_store_embeddings_fp16" in (+ module_names+ )+++def test_actual_migrator_converts_both_tables_and_preserves_metadata_and_relations(tmp_path: Path) -> None:+ db = _make_db(tmp_path)+ connection = db._conn+ image_vector = _vector(1)+ video_vector = _vector(2)+ image_blob = image_vector.astype(np.float32).tobytes()+ video_blob = video_vector.astype(np.float32).tobytes()+ _insert(connection, "image_embeddings", "image.png", "model-a", image_blob, created_at="image-time")+ _insert(connection, "video_embeddings", "video.mp4", "model-b", video_blob, created_at="video-time")+ image_indexes_before = connection.execute("PRAGMA index_list(image_embeddings);").fetchall()+ video_indexes_before = connection.execute("PRAGMA index_list(video_embeddings);").fetchall()+ image_fks_before = connection.execute("PRAGMA foreign_key_list(image_embeddings);").fetchall()+ video_fks_before = connection.execute("PRAGMA foreign_key_list(video_embeddings);").fetchall()+ connection.commit()++ _migrator(db).run_migrations()++ rows = {+ "image_embeddings": connection.execute(+ "SELECT image_name, model_id, dim, embedding, created_at, encoding FROM image_embeddings;"+ ).fetchall(),+ "video_embeddings": connection.execute(+ "SELECT video_name, model_id, dim, embedding, created_at, encoding FROM video_embeddings;"+ ).fetchall(),+ }+ assert rows["image_embeddings"][0][0:3] == ("image.png", "model-a", 8)+ assert rows["image_embeddings"][0][4:] == ("image-time", "float16")+ assert rows["video_embeddings"][0][0:3] == ("video.mp4", "model-b", 8)+ assert rows["video_embeddings"][0][4:] == ("video-time", "float16")+ assert len(rows["image_embeddings"][0][3]) == 8 * 2+ assert len(rows["video_embeddings"][0][3]) == 8 * 2+ assert np.allclose(blob_to_embedding(rows["image_embeddings"][0][3], 8, "float16"), image_vector, atol=1e-3)+ assert np.allclose(blob_to_embedding(rows["video_embeddings"][0][3], 8, "float16"), video_vector, atol=1e-3)+ assert connection.execute("PRAGMA index_list(image_embeddings);").fetchall() == image_indexes_before+ assert connection.execute("PRAGMA index_list(video_embeddings);").fetchall() == video_indexes_before+ assert connection.execute("PRAGMA foreign_key_list(image_embeddings);").fetchall() == image_fks_before+ assert connection.execute("PRAGMA foreign_key_list(video_embeddings);").fetchall() == video_fks_before+ for table in ("image_embeddings", "video_embeddings"):+ encoding_column = next(+ row for row in connection.execute(f"PRAGMA table_info({table});") if row[1] == "encoding"+ )+ assert encoding_column[2] == "TEXT"+ assert encoding_column[3] == 1+ assert encoding_column[4] == "'float32'"+ assert connection.execute(+ "SELECT migration_id FROM applied_migrations WHERE migration_id = ?;", (MIGRATION_ID,)+ ).fetchone()+ with pytest.raises(sqlite3.IntegrityError):+ connection.execute("UPDATE image_embeddings SET encoding = 'float64';")+ connection.rollback()+ connection.execute("DELETE FROM images WHERE image_name = 'image.png';")+ connection.execute("DELETE FROM videos WHERE video_name = 'video.mp4';")+ assert tuple(connection.execute("SELECT COUNT(*) FROM image_embeddings;").fetchone()) == (0,)+ assert tuple(connection.execute("SELECT COUNT(*) FROM video_embeddings;").fetchone()) == (0,)+ db._conn.close()+++def test_empty_and_mixed_rows_are_safe_and_callback_is_idempotent(tmp_path: Path) -> None:+ db = SqliteDatabase(db_path=tmp_path / "mixed.db", logger=logging.getLogger(__name__))+ _create_schema(db._conn, image_encoding=True)+ connection = db._conn+ preserved_blob = embedding_to_blob(_vector(4))+ _insert(connection, "image_embeddings", "already-fp16.png", "model-a", preserved_blob, encoding="float16")+ legacy_vector = _vector(5)+ _insert(+ connection,+ "image_embeddings",+ "legacy.png",+ "model-b",+ legacy_vector.astype(np.float32).tobytes(),+ encoding="float32",+ )+ connection.commit()++ _migrator(db).run_migrations()+ after_first_run = connection.execute(+ "SELECT image_name, embedding, encoding FROM image_embeddings ORDER BY image_name;"+ ).fetchall()+ build_migration(logger=logging.getLogger(__name__)).callback(connection.cursor())+ after_repeat = connection.execute(+ "SELECT image_name, embedding, encoding FROM image_embeddings ORDER BY image_name;"+ ).fetchall()++ assert after_repeat == after_first_run+ assert after_repeat[0][1] == preserved_blob+ assert after_repeat[0][2] == "float16"+ assert after_repeat[1][2] == "float16"+ assert tuple(connection.execute("SELECT COUNT(*) FROM video_embeddings;").fetchone()) == (0,)+ db._conn.rollback()+ db._conn.close()+++def test_keyset_batches_convert_more_than_two_batches_across_models(tmp_path: Path) -> None:+ db = _make_db(tmp_path)+ connection = db._conn+ row_count = 514+ for index in range(257):+ vector = _vector(index + 20)+ for model_id in ("model-a", "model-b"):+ _insert(+ connection,+ "image_embeddings",+ f"image-{index:03d}.png",+ model_id,+ vector.astype(np.float32).tobytes(),+ )+ connection.commit()+ statements: list[str] = []+ connection.set_trace_callback(statements.append)++ _migrator(db).run_migrations()++ assert tuple(+ connection.execute("SELECT COUNT(*) FROM image_embeddings WHERE encoding = 'float16';").fetchone()+ ) == (row_count,)+ assert [+ tuple(row)+ for row in connection.execute(+ "SELECT model_id, COUNT(*) FROM image_embeddings GROUP BY model_id ORDER BY model_id;"+ )+ ] == [("model-a", 257), ("model-b", 257)]+ selects = [+ statement.lower()+ for statement in statements+ if "from image_embeddings" in statement.lower() and "order by rowid" in statement.lower()+ ]+ assert len(selects) >= 3+ assert all("limit 256" in statement for statement in selects)+ assert all("offset" not in statement for statement in selects)+ db._conn.close()+++def test_migration_logs_progress_and_row_totals(caplog: pytest.LogCaptureFixture, tmp_path: Path) -> None:+ db = _make_db(tmp_path)+ connection = db._conn+ vector_blob = _vector(30).astype(np.float32).tobytes()+ names = [(f"image-{index:05d}.png",) for index in range(10_001)]+ connection.executemany("INSERT INTO images (image_name) VALUES (?);", names)+ connection.executemany(+ "INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES (?, 'model-a', 8, ?);",+ ((name[0], vector_blob) for name in names),+ )+ connection.commit()++ with caplog.at_level(logging.INFO, logger=__name__):+ _migrator(db).run_migrations()++ messages = [record.getMessage() for record in caplog.records if record.name == __name__]+ assert "Starting image and video embedding fp16 migration" in messages+ assert messages.count("Converted 10000 image and video embeddings to fp16") == 1+ assert any(+ "Completed image and video embedding fp16 migration: image rows=10001, video rows=0, total rows=10001, "+ "elapsed=" in message+ for message in messages+ )+ db._conn.close()+++def test_late_bad_video_rolls_back_schema_and_prior_updates_then_retries(tmp_path: Path) -> None:+ db = _make_db(tmp_path)+ connection = db._conn+ image_blob = _vector(6).astype(np.float32).tobytes()+ video_blob = _vector(7).astype(np.float32).tobytes()+ for index in range(257):+ _insert(connection, "image_embeddings", f"good-{index:03d}.png", "model-a", image_blob)+ _insert(connection, "video_embeddings", "first.mp4", "model-a", video_blob)+ _insert(connection, "video_embeddings", "broken.mp4", "model-b", b"bad-vector", dim=8)+ connection.commit()+ migrator = _migrator(db)++ with pytest.raises(MigrationError, match=r"video_embeddings.*broken\.mp4.*model-b"):+ migrator.run_migrations()++ assert not _has_encoding(connection, "image_embeddings")+ assert not _has_encoding(connection, "video_embeddings")+ assert tuple(+ connection.execute("SELECT COUNT(*) FROM image_embeddings WHERE length(embedding) = 32;").fetchone()+ ) == (257,)+ assert tuple(+ connection.execute("SELECT embedding FROM video_embeddings WHERE video_name = 'first.mp4';").fetchone()+ ) == (video_blob,)+ assert (+ connection.execute(+ "SELECT migration_id FROM applied_migrations WHERE migration_id = ?;", (MIGRATION_ID,)+ ).fetchone()+ is None+ )++ connection.execute(+ "UPDATE video_embeddings SET embedding = ? WHERE video_name = 'broken.mp4' AND model_id = 'model-b';",+ (_vector(8).astype(np.float32).tobytes(),),+ )+ connection.commit()+ migrator.run_migrations()++ assert _has_encoding(connection, "image_embeddings")+ assert _has_encoding(connection, "video_embeddings")+ assert tuple(+ connection.execute("SELECT COUNT(*) FROM image_embeddings WHERE encoding = 'float16';").fetchone()+ ) == (257,)+ assert tuple(+ connection.execute("SELECT COUNT(*) FROM video_embeddings WHERE encoding = 'float16';").fetchone()+ ) == (2,)+ assert connection.execute(+ "SELECT migration_id FROM applied_migrations WHERE migration_id = ?;", (MIGRATION_ID,)+ ).fetchone()+ db._conn.close()