-
Notifications
You must be signed in to change notification settings - Fork 127
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
instructor - new secret management #417
Merged
Merged
Changes from all commits
Commits
Show all changes
3 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 |
---|---|---|
@@ -1,8 +1,9 @@ | ||
# SPDX-FileCopyrightText: 2023-present deepset GmbH <[email protected]> | ||
# | ||
# SPDX-License-Identifier: Apache-2.0 | ||
from typing import ClassVar, Dict, List, Optional, Union | ||
from typing import ClassVar, Dict, List, Optional | ||
|
||
from haystack.utils.auth import Secret | ||
from InstructorEmbedding import INSTRUCTOR | ||
|
||
|
||
|
@@ -14,16 +15,14 @@ class _InstructorEmbeddingBackendFactory: | |
_instances: ClassVar[Dict[str, "_InstructorEmbeddingBackend"]] = {} | ||
|
||
@staticmethod | ||
def get_embedding_backend( | ||
model_name_or_path: str, device: Optional[str] = None, use_auth_token: Union[bool, str, None] = None | ||
): | ||
embedding_backend_id = f"{model_name_or_path}{device}{use_auth_token}" | ||
def get_embedding_backend(model_name_or_path: str, device: Optional[str] = None, token: Optional[Secret] = None): | ||
embedding_backend_id = f"{model_name_or_path}{device}{token}" | ||
|
||
if embedding_backend_id in _InstructorEmbeddingBackendFactory._instances: | ||
return _InstructorEmbeddingBackendFactory._instances[embedding_backend_id] | ||
|
||
embedding_backend = _InstructorEmbeddingBackend( | ||
model_name_or_path=model_name_or_path, device=device, use_auth_token=use_auth_token | ||
model_name_or_path=model_name_or_path, device=device, token=token | ||
) | ||
_InstructorEmbeddingBackendFactory._instances[embedding_backend_id] = embedding_backend | ||
return embedding_backend | ||
|
@@ -34,10 +33,12 @@ class _InstructorEmbeddingBackend: | |
Class to manage INSTRUCTOR embeddings. | ||
""" | ||
|
||
def __init__( | ||
self, model_name_or_path: str, device: Optional[str] = None, use_auth_token: Union[bool, str, None] = None | ||
): | ||
self.model = INSTRUCTOR(model_name_or_path=model_name_or_path, device=device, use_auth_token=use_auth_token) | ||
def __init__(self, model_name_or_path: str, device: Optional[str] = None, token: Optional[Secret] = None): | ||
self.model = INSTRUCTOR( | ||
model_name_or_path=model_name_or_path, | ||
device=device, | ||
use_auth_token=token.resolve_value() if token else None, | ||
) | ||
|
||
def embed(self, data: List[List[str]], **kwargs) -> List[List[float]]: | ||
embeddings = self.model.encode(data, **kwargs).tolist() | ||
|
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 |
---|---|---|
@@ -1,9 +1,10 @@ | ||
# SPDX-FileCopyrightText: 2023-present deepset GmbH <[email protected]> | ||
# | ||
# SPDX-License-Identifier: Apache-2.0 | ||
from typing import Any, Dict, List, Optional, Union | ||
from typing import Any, Dict, List, Optional | ||
|
||
from haystack import Document, component, default_from_dict, default_to_dict | ||
from haystack.utils import Secret, deserialize_secrets_inplace | ||
|
||
from .embedding_backend.instructor_backend import _InstructorEmbeddingBackendFactory | ||
|
||
|
@@ -62,7 +63,7 @@ def __init__( | |
self, | ||
model: str = "hkunlp/instructor-base", | ||
device: Optional[str] = None, | ||
use_auth_token: Union[bool, str, None] = None, | ||
token: Optional[Secret] = Secret.from_env_var("HF_API_TOKEN", strict=False), # noqa: B008 | ||
instruction: str = "Represent the document", | ||
batch_size: int = 32, | ||
progress_bar: bool = True, | ||
|
@@ -98,7 +99,7 @@ def __init__( | |
self.model_name_or_path = model | ||
# TODO: remove device parameter and use Haystack's device management once migrated | ||
self.device = device or "cpu" | ||
self.use_auth_token = use_auth_token | ||
self.token = token | ||
self.instruction = instruction | ||
self.batch_size = batch_size | ||
self.progress_bar = progress_bar | ||
|
@@ -114,7 +115,7 @@ def to_dict(self) -> Dict[str, Any]: | |
self, | ||
model=self.model_name_or_path, | ||
device=self.device, | ||
use_auth_token=self.use_auth_token, | ||
token=self.token.to_dict() if self.token else None, | ||
instruction=self.instruction, | ||
batch_size=self.batch_size, | ||
progress_bar=self.progress_bar, | ||
|
@@ -128,6 +129,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "InstructorDocumentEmbedder": | |
""" | ||
Deserialize this component from a dictionary. | ||
""" | ||
deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) | ||
return default_from_dict(cls, data) | ||
|
||
def warm_up(self): | ||
|
@@ -136,7 +138,7 @@ def warm_up(self): | |
""" | ||
if not hasattr(self, "embedding_backend"): | ||
self.embedding_backend = _InstructorEmbeddingBackendFactory.get_embedding_backend( | ||
model_name_or_path=self.model_name_or_path, device=self.device, use_auth_token=self.use_auth_token | ||
model_name_or_path=self.model_name_or_path, device=self.device, token=self.token | ||
) | ||
|
||
@component.output_types(documents=List[Document]) | ||
|
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 |
---|---|---|
@@ -1,9 +1,10 @@ | ||
# SPDX-FileCopyrightText: 2023-present deepset GmbH <[email protected]> | ||
# | ||
# SPDX-License-Identifier: Apache-2.0 | ||
from typing import Any, Dict, List, Optional, Union | ||
from typing import Any, Dict, List, Optional | ||
|
||
from haystack import component, default_from_dict, default_to_dict | ||
from haystack.utils import Secret, deserialize_secrets_inplace | ||
|
||
from .embedding_backend.instructor_backend import _InstructorEmbeddingBackendFactory | ||
|
||
|
@@ -38,7 +39,7 @@ def __init__( | |
self, | ||
model: str = "hkunlp/instructor-base", | ||
device: Optional[str] = None, | ||
use_auth_token: Union[bool, str, None] = None, | ||
token: Optional[Secret] = Secret.from_env_var("HF_API_TOKEN", strict=False), # noqa: B008 | ||
instruction: str = "Represent the sentence", | ||
batch_size: int = 32, | ||
progress_bar: bool = True, | ||
|
@@ -51,9 +52,7 @@ def __init__( | |
such as ``'hkunlp/instructor-base'``. | ||
:param device: Device (like 'cuda' / 'cpu') that should be used for computation. | ||
If None, checks if a GPU can be used. | ||
:param use_auth_token: The API token used to download private models from Hugging Face. | ||
If this parameter is set to `True`, then the token generated when running | ||
`transformers-cli login` (stored in ~/.huggingface) will be used. | ||
:param token: The API token used to download private models from Hugging Face. | ||
:param instruction: The instruction string to be used while computing domain-specific embeddings. | ||
The instruction follows the unified template of the form: | ||
"Represent the 'domain' 'text_type' for 'task_objective'", where: | ||
|
@@ -70,7 +69,7 @@ def __init__( | |
self.model_name_or_path = model | ||
# TODO: remove device parameter and use Haystack's device management once migrated | ||
self.device = device or "cpu" | ||
self.use_auth_token = use_auth_token | ||
self.token = token | ||
self.instruction = instruction | ||
self.batch_size = batch_size | ||
self.progress_bar = progress_bar | ||
|
@@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: | |
self, | ||
model=self.model_name_or_path, | ||
device=self.device, | ||
use_auth_token=self.use_auth_token, | ||
token=self.token.to_dict() if self.token else None, | ||
instruction=self.instruction, | ||
batch_size=self.batch_size, | ||
progress_bar=self.progress_bar, | ||
|
@@ -96,6 +95,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "InstructorTextEmbedder": | |
""" | ||
Deserialize this component from a dictionary. | ||
""" | ||
deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) | ||
return default_from_dict(cls, data) | ||
|
||
def warm_up(self): | ||
|
@@ -104,7 +104,7 @@ def warm_up(self): | |
""" | ||
if not hasattr(self, "embedding_backend"): | ||
self.embedding_backend = _InstructorEmbeddingBackendFactory.get_embedding_backend( | ||
model_name_or_path=self.model_name_or_path, device=self.device, use_auth_token=self.use_auth_token | ||
model_name_or_path=self.model_name_or_path, device=self.device, token=self.token | ||
) | ||
|
||
@component.output_types(embedding=List[float]) | ||
|
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.
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.
that's actually a better idea, to have those
ignore
statements inline, instead of globally defined 👍🏽