-
Notifications
You must be signed in to change notification settings - Fork 31
Add: python API method to add custom embeddings #1615
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
IgorSusmelj
wants to merge
11
commits into
main
Choose a base branch
from
igor-lig-10159-figure-out-use-custom-embedding-model-in-studio
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a2b0790
Add set_embedding method
IgorSusmelj f37abb5
Add unit test
IgorSusmelj 778c7c9
Add docs for custom embeddings
IgorSusmelj 02519ce
Update docs. Make a full section for custom embeddings.
IgorSusmelj 2d1b642
Add example for custom embeddings
IgorSusmelj eeb76a2
Update embedding resolver with upsert
IgorSusmelj 3ff2c30
Add integration test for custom embeddings
IgorSusmelj e6af782
Update changelog
IgorSusmelj 9760f38
Update embedding model to explicitly state if it has text embeddings
IgorSusmelj b6df6c6
Add frontend changes
IgorSusmelj 0136bd6
Update docs
IgorSusmelj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,36 +2,63 @@ | |
|
|
||
| from uuid import UUID | ||
|
|
||
| from sqlmodel import Session | ||
| from sqlmodel import Session, SQLModel | ||
|
|
||
| from lightly_studio.dataset.embedding_manager import EmbeddingManagerProvider | ||
| from lightly_studio.resolvers import ( | ||
| embedding_model_resolver, | ||
| sample_embedding_resolver, | ||
| ) | ||
|
|
||
|
|
||
| def collection_has_embeddings(session: Session, collection_id: UUID) -> bool: | ||
| """Check if there are any embeddings available for the given collection. | ||
| class CollectionEmbeddingsStatus(SQLModel): | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This was refactored. The new status tells us whether we have embeddings and whether we have text embeddings for search. We can later allow the user to hook up their own text encoder model to do also text based search with custom models. |
||
| """Which embedding-based features are available for a collection.""" | ||
|
|
||
| has_embeddings: bool | ||
| """At least one sample embedding is stored, under any embedding model. | ||
|
|
||
| Enables the embedding plot, image similarity, and embedding-based sampling. | ||
| """ | ||
|
|
||
| has_text_search_embeddings: bool | ||
| """At least one sample embedding is stored under a text-capable embedding model. | ||
|
|
||
| Enables text-based search. Custom embeddings (``Sample.set_embedding``) have no | ||
| matching text encoder and do not count here. | ||
| """ | ||
|
|
||
|
|
||
| def get_collection_embeddings_status( | ||
| session: Session, collection_id: UUID | ||
| ) -> CollectionEmbeddingsStatus: | ||
| """Report which embedding-based features are available for the given collection. | ||
|
|
||
| Reads only the database (``embedding_model`` and ``sample_embedding`` tables); it | ||
| never registers or loads embedding models as a side effect. | ||
|
|
||
| Args: | ||
| session: Database session for resolver operations. | ||
| collection_id: The ID of the collection to check for embeddings. | ||
| collection_id: The ID of the collection to check. | ||
|
|
||
| Returns: | ||
| True if embeddings exist for the collection, False otherwise. | ||
| The embeddings status of the collection. | ||
| """ | ||
| embedding_manager = EmbeddingManagerProvider.get_embedding_manager() | ||
| model_id = embedding_manager.load_or_get_default_model( | ||
| embedding_models = embedding_model_resolver.get_all_by_collection_id( | ||
| session=session, collection_id=collection_id | ||
| ) | ||
| has_embeddings = sample_embedding_resolver.has_any_embedding( | ||
| session=session, | ||
| collection_id=collection_id, | ||
| embedding_model_ids=[model.embedding_model_id for model in embedding_models], | ||
| ) | ||
| if not has_embeddings: | ||
| return CollectionEmbeddingsStatus(has_embeddings=False, has_text_search_embeddings=False) | ||
| has_text_search_embeddings = sample_embedding_resolver.has_any_embedding( | ||
| session=session, | ||
| collection_id=collection_id, | ||
| embedding_model_ids=[ | ||
| model.embedding_model_id for model in embedding_models if model.supports_text_search | ||
| ], | ||
| ) | ||
| if model_id is None: | ||
| # No default embedding model loaded for this collection. | ||
| return False | ||
|
|
||
| return ( | ||
| sample_embedding_resolver.get_embedding_count( | ||
| session=session, collection_id=collection_id, embedding_model_id=model_id | ||
| ) | ||
| > 0 | ||
| return CollectionEmbeddingsStatus( | ||
| has_embeddings=True, has_text_search_embeddings=has_text_search_embeddings | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
lightly_studio/src/lightly_studio/examples/example_custom_embeddings.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| """Example of adding custom, precomputed embeddings to a dataset. | ||
|
|
||
| Use `Sample.set_embedding` to plug in embeddings from your own model instead of | ||
| relying on the built-in embedding pipeline. This enables the embedding plot, | ||
| image-based similarity, and embedding-based sampling strategies. Load the dataset | ||
| with `embed=False` so the built-in model never runs. | ||
|
|
||
| Note: text-based search does not work with custom embeddings, since there is no | ||
| text encoder for a custom embedding space. The GUI hides the search bar | ||
| automatically. | ||
| """ | ||
|
|
||
| import numpy as np | ||
| from environs import Env | ||
| from PIL import Image | ||
|
|
||
| import lightly_studio as ls | ||
| from lightly_studio.database import db_manager | ||
|
|
||
| # Read environment variables | ||
| env = Env() | ||
| env.read_env() | ||
|
|
||
| # Cleanup an existing database | ||
| db_manager.connect(cleanup_existing=True) | ||
|
|
||
| # Define the path to the dataset directory | ||
| dataset_path = env.path("EXAMPLES_DATASET_PATH", "/path/to/your/dataset") | ||
|
|
||
| # Create a Dataset from a path, skipping the built-in embedding pipeline. | ||
| dataset = ls.ImageDataset.create() | ||
| dataset.add_images_from_path(path=dataset_path, embed=False) | ||
|
|
||
|
|
||
| def compute_custom_embedding(file_path: str) -> list[float]: | ||
| """Stand-in for your own model: the mean RGB color of the image.""" | ||
| with Image.open(file_path) as image: | ||
| pixels = np.asarray(image.convert("RGB"), dtype=np.float32) | ||
| return [float(value) for value in pixels.mean(axis=(0, 1))] | ||
|
|
||
|
|
||
| for sample in dataset: | ||
| embedding = compute_custom_embedding(sample.file_path_abs) | ||
| sample.set_embedding(embedding) | ||
|
|
||
| ls.start_gui() |
39 changes: 39 additions & 0 deletions
39
...dio/migrations/versions/1783577705_0c5e19664860_add_supports_text_search_to_embedding_.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| """add_supports_text_search_to_embedding_model. | ||
|
|
||
| Revision ID: 0c5e19664860 | ||
| Revises: a1b2c3d4e5f6 | ||
| Create Date: 2026-07-09 10:15:00.000000 | ||
|
|
||
| """ | ||
|
|
||
| from collections.abc import Sequence | ||
| from typing import Union | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = "0c5e19664860" | ||
| down_revision: Union[str, Sequence[str], None] = "a1b2c3d4e5f6" | ||
| branch_labels: Union[str, Sequence[str], None] = None | ||
| depends_on: Union[str, Sequence[str], None] = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| """Upgrade schema.""" | ||
| # Defaults to true because all rows created before this column existed came | ||
| # from CLIP-style vision-text generators. | ||
| op.add_column( | ||
| "embedding_model", | ||
| sa.Column( | ||
| "supports_text_search", | ||
| sa.Boolean(), | ||
| server_default=sa.true(), | ||
| nullable=False, | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| """Downgrade schema.""" | ||
| op.drop_column("embedding_model", "supports_text_search") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This we could also leave away