Skip to content
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 2 commits into from
Oct 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions src/helm/proxy/clients/huggingface_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Copy link
Collaborator

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?

Copy link
Contributor Author

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.


# 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."""

Expand Down Expand Up @@ -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 = {
Expand All @@ -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,
Copy link
Contributor Author

Choose a reason for hiding this comment

The 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

Expand Down
Loading