-
Notifications
You must be signed in to change notification settings - Fork 95
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
Add bge-m3 and Nomic 1.5 embeddings. #1182
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
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 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 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,92 @@ | ||
"""Gegeral Text Embeddings (GTE) model. Open-source model, designed to run on device.""" | ||
import gc | ||
from typing import TYPE_CHECKING, ClassVar, Optional | ||
|
||
from typing_extensions import override | ||
|
||
from ..utils import log | ||
|
||
if TYPE_CHECKING: | ||
from FlagEmbedding import BGEM3FlagModel | ||
|
||
|
||
import functools | ||
|
||
from ..schema import Item | ||
from ..signal import TextEmbeddingSignal | ||
from ..splitters.spacy_splitter import clustering_spacy_chunker | ||
from ..tasks import TaskExecutionType | ||
from .embedding import chunked_compute_embedding | ||
from .transformer_utils import SENTENCE_TRANSFORMER_BATCH_SIZE | ||
|
||
# See https://huggingface.co/spaces/mteb/leaderboard for leaderboard of models. | ||
BGE_M3 = 'BAAI/bge-m3' | ||
|
||
|
||
@functools.cache | ||
def _get_and_cache_bge_m3(model_name: str) -> 'BGEM3FlagModel': | ||
try: | ||
from FlagEmbedding import BGEM3FlagModel | ||
except ImportError: | ||
raise ImportError( | ||
'Could not import the "FlagEmbedding" python package. ' | ||
'Please install it with `pip install "lilac[bge]".' | ||
) | ||
model = BGEM3FlagModel( | ||
'BAAI/bge-m3', use_fp16=True | ||
) # Setting use_fp16 to True speeds up computation with a slight performance degradation | ||
|
||
log(f'[{model_name}] Using device:', model.device) | ||
|
||
# NOTE: we don't call setup model and device here as this happens internally. | ||
return model | ||
|
||
|
||
class BGEM3(TextEmbeddingSignal): | ||
"""Computes BGE-M3 embeddings. | ||
|
||
<br>This embedding runs on-device. See the [model card](https://huggingface.co/BAAI/bge-m3) | ||
for details. | ||
""" | ||
|
||
name: ClassVar[str] = 'bge-m3' | ||
display_name: ClassVar[str] = 'BGE-M3' | ||
local_batch_size: ClassVar[int] = SENTENCE_TRANSFORMER_BATCH_SIZE | ||
local_parallelism: ClassVar[int] = 1 | ||
local_strategy: ClassVar[TaskExecutionType] = 'threads' | ||
supports_garden: ClassVar[bool] = False | ||
|
||
_model_name = BGE_M3 | ||
_model: 'BGEM3FlagModel' | ||
|
||
@override | ||
def setup(self) -> None: | ||
self._model = _get_and_cache_bge_m3(self._model_name) | ||
|
||
@override | ||
def compute(self, docs: list[str]) -> list[Optional[Item]]: | ||
"""Call the embedding function.""" | ||
# While we get docs in batches of 1024, the chunker expands that by a factor of 3-10. | ||
# The sentence transformer API actually does batching internally, so we pass | ||
# local_batch_size * 16 to allow the library to see all the chunks at once. | ||
return chunked_compute_embedding( | ||
lambda docs: self._model.encode(docs)['dense_vecs'], | ||
docs, | ||
self.local_batch_size * 16, | ||
chunker=clustering_spacy_chunker, | ||
) | ||
|
||
@override | ||
def teardown(self) -> None: | ||
if not hasattr(self, '_model'): | ||
return | ||
|
||
del self._model | ||
gc.collect() | ||
|
||
try: | ||
import torch | ||
|
||
torch.cuda.empty_cache() | ||
except ImportError: | ||
pass |
This file contains 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,109 @@ | ||
"""Gegeral Text Embeddings (GTE) model. Open-source model, designed to run on device.""" | ||
import gc | ||
from typing import TYPE_CHECKING, ClassVar, Optional | ||
|
||
import numpy as np | ||
from typing_extensions import override | ||
|
||
if TYPE_CHECKING: | ||
from sentence_transformers import SentenceTransformer | ||
|
||
import functools | ||
|
||
from ..schema import Item | ||
from ..signal import TextEmbeddingSignal | ||
from ..splitters.spacy_splitter import clustering_spacy_chunker | ||
from ..tasks import TaskExecutionType | ||
from .embedding import chunked_compute_embedding | ||
from .transformer_utils import SENTENCE_TRANSFORMER_BATCH_SIZE, setup_model_device | ||
|
||
# See https://huggingface.co/spaces/mteb/leaderboard for leaderboard of models. | ||
NOMIC_EMBED = 'nomic-ai/nomic-embed-text-v1.5' | ||
|
||
|
||
@functools.cache | ||
def _get_and_cache_model(model_name: str) -> 'SentenceTransformer': | ||
try: | ||
from sentence_transformers import SentenceTransformer | ||
except ImportError: | ||
raise ImportError( | ||
'Could not import the "sentence_transformers" python package. ' | ||
'Please install it with `pip install "sentence_transformers".' | ||
) | ||
return setup_model_device(SentenceTransformer(model_name, trust_remote_code=True), model_name) | ||
|
||
|
||
class NomicEmbed15(TextEmbeddingSignal): | ||
"""Computes Nomic Embeddings 1.5 full (768 dimensions). | ||
|
||
<br>This embedding runs on-device. See the [model card](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5) | ||
for details. | ||
""" | ||
|
||
name: ClassVar[str] = 'nomic-embed-1.5-768' | ||
display_name: ClassVar[str] = 'Nomic Embeddings 1.5 784' | ||
local_batch_size: ClassVar[int] = SENTENCE_TRANSFORMER_BATCH_SIZE | ||
local_parallelism: ClassVar[int] = 1 | ||
local_strategy: ClassVar[TaskExecutionType] = 'threads' | ||
supports_garden: ClassVar[bool] = False | ||
|
||
_model_name = NOMIC_EMBED | ||
_model: 'SentenceTransformer' | ||
_matryoshka_dim = 768 | ||
|
||
@override | ||
def setup(self) -> None: | ||
self._model = _get_and_cache_model(self._model_name) | ||
|
||
@override | ||
def compute(self, docs: list[str]) -> list[Optional[Item]]: | ||
"""Call the embedding function.""" | ||
try: | ||
import torch.nn.functional as F | ||
except ImportError: | ||
raise ImportError( | ||
'Could not import the "sentence_transformers" python package. ' | ||
'Please install it with `pip install "sentence_transformers".' | ||
) | ||
|
||
def _encode(doc: list[str]) -> list[np.ndarray]: | ||
embeddings = self._model.encode(doc, convert_to_tensor=True) | ||
# Extract the dense vectors from the model. | ||
embeddings = F.layer_norm(embeddings, normalized_shape=(embeddings.shape[1],)) | ||
embeddings = embeddings[:, : self._matryoshka_dim] | ||
return embeddings.cpu().numpy() | ||
|
||
# While we get docs in batches of 1024, the chunker expands that by a factor of 3-10. | ||
# The sentence transformer API actually does batching internally, so we pass | ||
# local_batch_size * 16 to allow the library to see all the chunks at once. | ||
return chunked_compute_embedding( | ||
_encode, docs, self.local_batch_size * 16, chunker=clustering_spacy_chunker | ||
) | ||
|
||
@override | ||
def teardown(self) -> None: | ||
if not hasattr(self, '_model'): | ||
return | ||
|
||
self._model.cpu() | ||
del self._model | ||
gc.collect() | ||
|
||
try: | ||
import torch | ||
|
||
torch.cuda.empty_cache() | ||
except ImportError: | ||
pass | ||
|
||
|
||
class NomicEmbed15_256(NomicEmbed15): | ||
"""Computes Nomic Embeddings 1.5 (256 dimensions). | ||
|
||
<br>This embedding runs on-device. See the [model card](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5) | ||
for details. | ||
""" | ||
|
||
name: ClassVar[str] = 'nomic-embed-1.5-256' | ||
display_name: ClassVar[str] = 'Nomic Embeddings 1.5 256' | ||
_matryoshka_dim = 256 |
This file contains 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 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.
are dimensions sorted by importance , like PCA ? curious why we can just take the last 256/512 dimensions
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.
thats the magic of matryoshka_dim.. it's not PCA exactly, afaict it's baked into the loss function: https://aniketrege.github.io/blog/2024/mrl/