-
Notifications
You must be signed in to change notification settings - Fork 263
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
Fix: Total number of tokens in each stop word should be 1 #1892
Merged
Merged
Changes from all commits
Commits
Show all changes
2 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,12 @@ | |
import torch | ||
from dataclasses import asdict | ||
from transformers import AutoModelForCausalLM, AutoTokenizer | ||
from transformers.generation.stopping_criteria import ( | ||
StoppingCriteria, | ||
StoppingCriteriaList, | ||
STOPPING_CRITERIA_INPUTS_DOCSTRING, | ||
add_start_docstrings, | ||
) | ||
from typing import Any, Dict, List, Optional | ||
|
||
from helm.common.cache import Cache, CacheConfig | ||
|
@@ -35,6 +41,21 @@ def resolve_alias(model_name: str) -> str: | |
return _MODEL_NAME_ALIASES.get(model_name, model_name) | ||
|
||
|
||
class StopAtSpecificTokenCriteria(StoppingCriteria): | ||
def __init__(self, stop_sequence: List[int] = None): | ||
super().__init__() | ||
self.stop_sequence = stop_sequence | ||
|
||
# @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING) | ||
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: | ||
# Create a tensor from the stop_sequence | ||
stop_sequence_tensor = torch.tensor(self.stop_sequence, device=input_ids.device, dtype=input_ids.dtype) | ||
|
||
# Check if the current sequence ends with the stop_sequence | ||
current_sequence = input_ids[:, -len(self.stop_sequence) :] | ||
return torch.all(current_sequence == stop_sequence_tensor).item() | ||
|
||
|
||
class HuggingFaceServer: | ||
"""A thin wrapper around a Hugging Face AutoModelForCausalLM for HuggingFaceClient to call.""" | ||
|
||
|
@@ -72,9 +93,10 @@ def serve_request(self, raw_request: Dict[str, Any]): | |
raw_request["stop_sequences"], return_token_type_ids=False, add_special_tokens=False | ||
) | ||
assert len(stop_sequence_ids.input_ids) == 1, "Total number of stop words should be 1." | ||
assert len(stop_sequence_ids.input_ids[0]) == 1, "Total number of tokens in each stop word should be 1." | ||
# assert len(stop_sequence_ids.input_ids[0]) == 1, "Total number of tokens in each stop word should be 1." | ||
if len(stop_sequence_ids.input_ids[0]) == 1: | ||
raw_request["eos_token_id"] = stop_sequence_ids.input_ids[0][0] | ||
del raw_request["stop_sequences"] | ||
raw_request["eos_token_id"] = stop_sequence_ids.input_ids[0][0] | ||
|
||
# Strip out irrelevant parameters | ||
relevant_raw_request = { | ||
|
@@ -83,8 +105,16 @@ def serve_request(self, raw_request: Dict[str, Any]): | |
if key not in ["engine", "prompt", "echo_prompt", "stop_sequences"] | ||
} | ||
|
||
stopping_criteria = StoppingCriteriaList() | ||
if stop_sequence_ids != None: | ||
stopping_criteria.append(StopAtSpecificTokenCriteria(stop_sequence=stop_sequence_ids.input_ids[0])) | ||
|
||
# Use HuggingFace's `generate` method. | ||
output = self.model.generate(**encoded_input, **relevant_raw_request) | ||
output = self.model.generate( | ||
**encoded_input, | ||
**relevant_raw_request, | ||
stopping_criteria=stopping_criteria if len(stop_sequence_ids.input_ids[0]) > 1 else None, | ||
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. However, the good news is that only few model have to use stopping_criteria. |
||
) | ||
sequences = output.sequences | ||
scores = output.scores | ||
|
||
|
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 loads a tensor onto the model's device at every step, which seems slow; is there any way we can just load the tensor once in the constructor? Can you get the device and dtype from the model?
Separately, would you have an idea about how large the performance impact is?
cc @dlwh for PyTorch expertise - David would you have any advice here?
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.
Sorry I have not resolved the issue yet for poor knowledge on transformers library. In terms of efficiency, there are different reductions on different datasets and adapters. Usually it costs no more than 5 times the original time.