-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
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
[FEATURE] Enables offline /score for embedding models #12021
Open
gmarinho2
wants to merge
13
commits into
vllm-project:main
Choose a base branch
from
gmarinho2:main
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.
+216
−44
Open
Changes from 2 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
9b0ce65
[FEATURE] Enables offline /score for embedding models
gmarinho2 74cd2dd
Merge branch 'upstream_main'
gmarinho2 590ab4d
Changes variable name and uses tuple instead of list.
gmarinho2 f219024
Separates scoring logic and makes small ajustments
gmarinho2 47211e5
Separates scoring logic and makes small ajustments
gmarinho2 1a89033
Moves scoring functions declaration to llm class
gmarinho2 db7919b
Completes embedding_score function signature
gmarinho2 41b11be
Passes new parameters to self.encode() in embeddind_score
gmarinho2 b57e01a
Adds type annotations for the parameters
gmarinho2 4956eae
Minor adjustments
gmarinho2 f8b8d8c
Minor adjustments in embedding_score
gmarinho2 cd835de
trigger ci
gmarinho2 0e95ead
trigger ci
gmarinho2 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 | ||||
---|---|---|---|---|---|---|
|
@@ -6,6 +6,7 @@ | |||||
|
||||||
import cloudpickle | ||||||
import torch.nn as nn | ||||||
import torch | ||||||
from tqdm import tqdm | ||||||
from typing_extensions import TypeVar, deprecated | ||||||
|
||||||
|
@@ -1032,6 +1033,7 @@ def score( | |||||
A list of ``ScoringRequestOutput`` objects containing the | ||||||
generated scores in the same order as the input prompts. | ||||||
""" | ||||||
|
||||||
runner_type = self.llm_engine.model_config.runner_type | ||||||
if runner_type != "pooling": | ||||||
messages = ["LLM.score() is only supported for pooling models."] | ||||||
|
@@ -1047,25 +1049,20 @@ def score( | |||||
|
||||||
raise ValueError(" ".join(messages)) | ||||||
|
||||||
if not self.llm_engine.model_config.is_cross_encoder: | ||||||
raise ValueError("Your model does not support cross encoding") | ||||||
if self.llm_engine.model_config.task != "score": | ||||||
raise ValueError("Score API is only enabled for `--task score`") | ||||||
|
||||||
tokenizer = self.llm_engine.get_tokenizer() | ||||||
|
||||||
if isinstance(tokenizer, MistralTokenizer): | ||||||
if self.llm_engine.model_config.task not in ["embed", "score"]: | ||||||
DarkLight1337 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
raise ValueError( | ||||||
"MistralTokenizer not supported for cross-encoding") | ||||||
"Score API is only enabled for `--task embed or score`") | ||||||
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.
Suggested change
|
||||||
|
||||||
# the tokenizer for models such as | ||||||
# "cross-encoder/ms-marco-MiniLM-L-6-v2" doesn't support passing | ||||||
# lists of tokens to the `text` and `text_pair` kwargs | ||||||
tokenizer = self.llm_engine.get_tokenizer() | ||||||
|
||||||
def ensure_str(prompt: SingletonPrompt): | ||||||
if isinstance(prompt, dict): | ||||||
if "multi_modal_data" in prompt: | ||||||
raise ValueError("Multi-modal prompt is not " | ||||||
"supported for cross encoding") | ||||||
"supported for scoring") | ||||||
elif "prompt_token_ids" in prompt: | ||||||
prompt = tokenizer.decode( | ||||||
cast(TokensPrompt, prompt)["prompt_token_ids"]) | ||||||
|
@@ -1091,40 +1088,84 @@ def ensure_str(prompt: SingletonPrompt): | |||||
if len(text_2) == 0: | ||||||
raise ValueError("At least one text_pair element must be given") | ||||||
|
||||||
if len(text_1) == 1: | ||||||
text_1 = text_1 * len(text_2) | ||||||
if self.llm_engine.model_config.is_cross_encoder: | ||||||
if isinstance(tokenizer, MistralTokenizer): | ||||||
gmarinho2 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
raise ValueError( | ||||||
"MistralTokenizer not supported for cross-encoding") | ||||||
|
||||||
input_pairs = [(t1, t2) for t1, t2 in zip(text_1, text_2)] | ||||||
pooling_params = PoolingParams() | ||||||
if len(text_1) == 1: | ||||||
text_1 = text_1 * len(text_2) | ||||||
|
||||||
tokenization_kwargs: Dict[str, Any] = {} | ||||||
if truncate_prompt_tokens is not None: | ||||||
tokenization_kwargs["truncation"] = True | ||||||
tokenization_kwargs["max_length"] = truncate_prompt_tokens | ||||||
input_pairs = [(t1, t2) for t1, t2 in zip(text_1, text_2)] | ||||||
|
||||||
parsed_prompts = [] | ||||||
pooling_params = PoolingParams() | ||||||
|
||||||
for q, t in input_pairs: | ||||||
prompt_inputs = tokenizer(text=q, | ||||||
text_pair=t, | ||||||
**tokenization_kwargs) | ||||||
engine_prompt = TokensPrompt( | ||||||
prompt_token_ids=prompt_inputs["input_ids"], | ||||||
token_type_ids=prompt_inputs.get("token_type_ids")) | ||||||
parsed_prompts.append(engine_prompt) | ||||||
tokenization_kwargs: Dict[str, Any] = {} | ||||||
if truncate_prompt_tokens is not None: | ||||||
tokenization_kwargs["truncation"] = True | ||||||
tokenization_kwargs["max_length"] = truncate_prompt_tokens | ||||||
|
||||||
parsed_prompts = [] | ||||||
|
||||||
for q, t in input_pairs: | ||||||
prompt_inputs = tokenizer(text=q, | ||||||
text_pair=t, | ||||||
**tokenization_kwargs) | ||||||
engine_prompt = TokensPrompt( | ||||||
prompt_token_ids=prompt_inputs["input_ids"], | ||||||
token_type_ids=prompt_inputs.get("token_type_ids")) | ||||||
parsed_prompts.append(engine_prompt) | ||||||
|
||||||
self._validate_and_add_requests( | ||||||
prompts=parsed_prompts, | ||||||
params=pooling_params, | ||||||
lora_request=lora_request, | ||||||
prompt_adapter_request=prompt_adapter_request, | ||||||
) | ||||||
|
||||||
self._validate_and_add_requests( | ||||||
prompts=parsed_prompts, | ||||||
params=pooling_params, | ||||||
lora_request=lora_request, | ||||||
prompt_adapter_request=prompt_adapter_request, | ||||||
) | ||||||
outputs = self._run_engine(use_tqdm=use_tqdm) | ||||||
items = self.engine_class.validate_outputs(outputs, | ||||||
PoolingRequestOutput) | ||||||
|
||||||
outputs = self._run_engine(use_tqdm=use_tqdm) | ||||||
items = self.engine_class.validate_outputs(outputs, | ||||||
PoolingRequestOutput) | ||||||
return [ScoringRequestOutput.from_base(item) for item in items] | ||||||
|
||||||
elif self.llm_engine.model_config.runner_type == "pooling": | ||||||
encoded_text = self.encode(text_1 + text_2) | ||||||
encoded_text_1 = encoded_text[0:len(text_1)] | ||||||
encoded_text_2 = encoded_text[len(text_1):] | ||||||
DarkLight1337 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
if len(encoded_text_1) == 1: | ||||||
encoded_text_1 = encoded_text_1 * len(encoded_text_2) | ||||||
DarkLight1337 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
output_pairs = [(t1, t2) | ||||||
for t1, t2 in zip(encoded_text_1, encoded_text_2)] | ||||||
|
||||||
scores = [] | ||||||
cosSim = torch.nn.CosineSimilarity(0) | ||||||
|
||||||
for embed_1, embed_2 in output_pairs: | ||||||
pair_score = cosSim(embed_1.outputs.data, embed_2.outputs.data) | ||||||
DarkLight1337 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
if getattr(tokenizer, "pad_token", None) is None: | ||||||
tokens = embed_1.prompt_token_ids + embed_2.prompt_token_ids | ||||||
else: | ||||||
tokens = embed_1.prompt_token_ids + [ | ||||||
tokenizer.pad_token_type_id | ||||||
] + embed_2.prompt_token_ids | ||||||
|
||||||
scores.append( | ||||||
PoolingRequestOutput( | ||||||
request_id=f"{embed_1.request_id}_{embed_2.request_id}", | ||||||
outputs=pair_score, | ||||||
prompt_token_ids=tokens, | ||||||
finished=True)) | ||||||
|
||||||
items = self.engine_class.validate_outputs(scores, | ||||||
PoolingRequestOutput) | ||||||
return [ScoringRequestOutput.from_base(item) for item in items] | ||||||
|
||||||
return [ScoringRequestOutput.from_base(item) for item in items] | ||||||
raise ValueError( | ||||||
"Your model does not support cross encoding and pooling.") | ||||||
|
||||||
def start_profile(self) -> None: | ||||||
self.llm_engine.start_profile() | ||||||
|
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.
Avoid unnecessary line changes