-
Notifications
You must be signed in to change notification settings - Fork 27k
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
Add chat support to text generation pipeline #28945
Merged
Merged
Changes from 12 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e7c4172
Add chat support to text generation pipeline
Rocketknight1 a2e190a
Better handling of single elements
Rocketknight1 a5e1ccc
Deprecate ConversationalPipeline
Rocketknight1 4444a1e
stash commit
Rocketknight1 6772615
Add missing add_special_tokens kwarg
Rocketknight1 de3d88a
Update chat templating docs to refer to TextGenerationPipeline instea…
Rocketknight1 7eb468d
Add ✨TF✨ tests
Rocketknight1 6fae42d
@require_tf
Rocketknight1 3164035
Add type hint
Rocketknight1 01fc1a6
Add specific deprecation version
Rocketknight1 1b3f53f
Remove unnecessary do_sample
Rocketknight1 bbd8cfc
Remove todo - the discrepancy has been resolved
Rocketknight1 ecea9b5
Update src/transformers/tokenization_utils_base.py
Rocketknight1 f985755
Update src/transformers/pipelines/text_generation.py
Rocketknight1 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
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,5 +1,6 @@ | ||
import enum | ||
import warnings | ||
from typing import Dict | ||
|
||
from ..utils import add_end_docstrings, is_tf_available, is_torch_available | ||
from .base import Pipeline, build_pipeline_init_args | ||
|
@@ -20,11 +21,24 @@ class ReturnType(enum.Enum): | |
FULL_TEXT = 2 | ||
|
||
|
||
class Chat: | ||
"""This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats | ||
to this format because the rest of the pipeline code tends to assume that lists of messages are | ||
actually a batch of samples rather than messages in the same conversation.""" | ||
|
||
def __init__(self, messages: Dict): | ||
for message in messages: | ||
if not ("role" in message and "content" in message): | ||
raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.") | ||
self.messages = messages | ||
|
||
|
||
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) | ||
class TextGenerationPipeline(Pipeline): | ||
""" | ||
Language generation pipeline using any `ModelWithLMHead`. This pipeline predicts the words that will follow a | ||
specified text prompt. | ||
specified text prompt. It can also accept one or more chats. Each chat takes the form of a list of dicts, | ||
where each dict contains "role" and "content" keys. | ||
|
||
Example: | ||
|
||
|
@@ -216,7 +230,15 @@ def __call__(self, text_inputs, **kwargs): | |
- **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token | ||
ids of the generated text. | ||
""" | ||
return super().__call__(text_inputs, **kwargs) | ||
if isinstance(text_inputs, (list, tuple)) and isinstance(text_inputs[0], (list, tuple, dict)): | ||
# We have one or more prompts in list-of-dicts format, so this is chat mode | ||
if isinstance(text_inputs[0], dict): | ||
return super().__call__(Chat(text_inputs), **kwargs) | ||
else: | ||
chats = [Chat(chat) for chat in text_inputs] # 🐈 🐈 🐈 | ||
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. best comment 😂 |
||
return super().__call__(chats, **kwargs) | ||
else: | ||
return super().__call__(text_inputs, **kwargs) | ||
|
||
def preprocess( | ||
self, | ||
|
@@ -229,14 +251,25 @@ def preprocess( | |
max_length=None, | ||
**generate_kwargs, | ||
): | ||
inputs = self.tokenizer( | ||
prefix + prompt_text, | ||
return_tensors=self.framework, | ||
truncation=truncation, | ||
padding=padding, | ||
max_length=max_length, | ||
add_special_tokens=add_special_tokens, | ||
) | ||
if isinstance(prompt_text, Chat): | ||
inputs = self.tokenizer.apply_chat_template( | ||
prompt_text.messages, | ||
padding=padding, | ||
add_generation_prompt=True, | ||
return_tensors=self.framework, | ||
max_length=max_length, | ||
truncation=truncation, | ||
return_dict=True, | ||
) | ||
else: | ||
inputs = self.tokenizer( | ||
prefix + prompt_text, | ||
return_tensors=self.framework, | ||
truncation=truncation, | ||
padding=padding, | ||
max_length=max_length, | ||
add_special_tokens=add_special_tokens, | ||
) | ||
Rocketknight1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
inputs["prompt_text"] = prompt_text | ||
|
||
if handle_long_generation == "hole": | ||
|
@@ -331,7 +364,10 @@ def postprocess(self, model_outputs, return_type=ReturnType.FULL_TEXT, clean_up_ | |
|
||
all_text = text[prompt_length:] | ||
if return_type == ReturnType.FULL_TEXT: | ||
all_text = prompt_text + all_text | ||
if isinstance(prompt_text, str): | ||
all_text = prompt_text + all_text | ||
elif isinstance(prompt_text, Chat): | ||
all_text = prompt_text.messages + [{"role": "assistant", "content": all_text}] | ||
|
||
record = {"generated_text": all_text} | ||
records.append(record) | ||
|
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.
Just to make sure - is it not possible for someone to pass this to the pipeline:
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 tried that on
main
- it just results in aTypeError: can only concatenate str (not "list") to str
. The existing pipeline will only accept either a single string or a non-nested list/tuple of strings, so I don't think this check makes a mistake for any valid inputs!