-
Notifications
You must be signed in to change notification settings - Fork 15
[Draft] Experiment using api-inference-community for inference definitions #82
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
osanseviero
wants to merge
1
commit into
huggingface:main
Choose a base branch
from
osanseviero:unification
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,51 +1,38 @@ | ||
import importlib.util | ||
|
||
_sentence_transformers = importlib.util.find_spec("sentence_transformers") is not None | ||
_sentence_transformers = importlib.util.find_spec("hf_api_sentence_transformers") is not None | ||
|
||
|
||
def is_sentence_transformers_available(): | ||
return _sentence_transformers | ||
|
||
|
||
if is_sentence_transformers_available(): | ||
from sentence_transformers import CrossEncoder, SentenceTransformer, util | ||
from hf_api_sentence_transformers import FeatureExtractionPipeline | ||
from hf_api_sentence_transformers import SentenceSimilarityPipeline as SentenceSimilarityPipelineImpl | ||
|
||
|
||
class SentenceSimilarityPipeline: | ||
def __init__(self, model_dir: str, device: str = None, **kwargs): # needs "cuda" for GPU | ||
self.model = SentenceTransformer(model_dir, device=device, **kwargs) | ||
self.model = SentenceSimilarityPipelineImpl(model_dir) | ||
|
||
def __call__(self, inputs=None): | ||
embeddings1 = self.model.encode( | ||
inputs["source_sentence"], convert_to_tensor=True | ||
) | ||
embeddings2 = self.model.encode(inputs["sentences"], convert_to_tensor=True) | ||
similarities = util.pytorch_cos_sim(embeddings1, embeddings2).tolist()[0] | ||
return {"similarities": similarities} | ||
return {"similarities": self.model(inputs)} | ||
|
||
|
||
class SentenceEmbeddingPipeline: | ||
def __init__(self, model_dir: str, device: str = None, **kwargs): # needs "cuda" for GPU | ||
self.model = SentenceTransformer(model_dir, device=device, **kwargs) | ||
self.model = FeatureExtractionPipeline(model_dir) | ||
|
||
def __call__(self, inputs): | ||
embeddings = self.model.encode(inputs).tolist() | ||
return {"embeddings": embeddings} | ||
|
||
return {"embeddings": self.model(inputs)} | ||
|
||
class RankingPipeline: | ||
def __init__(self, model_dir: str, device: str = None, **kwargs): # needs "cuda" for GPU | ||
self.model = CrossEncoder(model_dir, device=device, **kwargs) | ||
|
||
def __call__(self, inputs): | ||
scores = self.model.predict(inputs).tolist() | ||
return {"scores": scores} | ||
|
||
|
||
SENTENCE_TRANSFORMERS_TASKS = { | ||
"sentence-similarity": SentenceSimilarityPipeline, | ||
"sentence-embeddings": SentenceEmbeddingPipeline, | ||
"sentence-ranking": RankingPipeline, | ||
#"sentence-ranking": RankingPipeline, # To be implemented | ||
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. removing for now as there's not one |
||
} | ||
|
||
|
||
|
@@ -59,6 +46,4 @@ def get_sentence_transformers_pipeline(task=None, model_dir=None, device=-1, **k | |
raise ValueError( | ||
f"Unknown task {task}. Available tasks are: {', '.join(SENTENCE_TRANSFORMERS_TASKS.keys())}" | ||
) | ||
return SENTENCE_TRANSFORMERS_TASKS[task]( | ||
model_dir=model_dir, device=device, **kwargs | ||
) | ||
return SENTENCE_TRANSFORMERS_TASKS[task](model_dir=model_dir) |
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 |
---|---|---|
|
@@ -43,19 +43,19 @@ def test_sentence_similarity(): | |
assert isinstance(res["similarities"], list) | ||
|
||
|
||
@require_torch | ||
def test_sentence_ranking(): | ||
with tempfile.TemporaryDirectory() as tmpdirname: | ||
storage_dir = _load_repository_from_hf("cross-encoder/ms-marco-MiniLM-L-6-v2", tmpdirname) | ||
pipe = get_sentence_transformers_pipeline("sentence-ranking", storage_dir.as_posix()) | ||
res = pipe( | ||
[ | ||
["Lets create an embedding", "Lets create an embedding"], | ||
["Lets create an embedding", "Lets create an embedding"], | ||
] | ||
) | ||
assert isinstance(res["scores"], list) | ||
res = pipe( | ||
["Lets create an embedding", "Lets create an embedding"], | ||
) | ||
assert isinstance(res["scores"], float) | ||
#@require_torch | ||
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. All other tests pass 🔥 |
||
#def test_sentence_ranking(): | ||
# with tempfile.TemporaryDirectory() as tmpdirname: | ||
# storage_dir = _load_repository_from_hf("cross-encoder/ms-marco-MiniLM-L-6-v2", tmpdirname) | ||
# pipe = get_sentence_transformers_pipeline("sentence-ranking", storage_dir.as_posix()) | ||
# res = pipe( | ||
# [ | ||
# ["Lets create an embedding", "Lets create an embedding"], | ||
# ["Lets create an embedding", "Lets create an embedding"], | ||
# ] | ||
# ) | ||
# assert isinstance(res["scores"], list) | ||
# res = pipe( | ||
# ["Lets create an embedding", "Lets create an embedding"], | ||
# ) | ||
# assert isinstance(res["scores"], float) |
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.
I'm doing this for backwards compatibility, but note that this is inconsistent with the other APIs and https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/tasks/sentence-similarity/inference.ts