-
Notifications
You must be signed in to change notification settings - Fork 33.6k
Generate: basic token streaming #22449
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
36ed5d7
haha tokens go brrrr
gante bb48f34
docstring
gante be24b6c
add test
gante 2b5f574
make fixup
gante f401488
PR comments -- simpler implementation, proper import structure
gante 9f7c907
final nits
gante 8d481e8
Add documentation; More robust word-by-word printing in TextStreamer;…
gante 1e18199
More references to streaming in docs
gante 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
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 |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| # coding=utf-8 | ||
| # Copyright 2023 The HuggingFace Inc. team. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from ..models.auto import AutoTokenizer | ||
|
|
||
|
|
||
| class BaseStreamer: | ||
| """ | ||
| Base class from which `.generate()` streamers should inherit. | ||
| """ | ||
|
|
||
| def put(self, value): | ||
| """Function that is called by `.generate()` to push new tokens""" | ||
| raise NotImplementedError() | ||
|
|
||
| def end(self): | ||
| """Function that is called by `.generate()` to signal the end of generation""" | ||
| raise NotImplementedError() | ||
|
|
||
|
|
||
| class TextStreamer(BaseStreamer): | ||
| """ | ||
| Simple text streamer that prints a token as soon as it gets them. | ||
|
|
||
| Parameters: | ||
| tokenizer (`AutoTokenizer`): | ||
| The tokenized used to decode the tokens. | ||
|
|
||
| Examples: | ||
|
|
||
| ```python | ||
| >>> from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer | ||
|
|
||
| >>> tok = AutoTokenizer.from_pretrained("distilgpt2") | ||
| >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2") | ||
| >>> inputs = tok(["This cat is"], return_tensors="pt") | ||
| >>> streamer = TextStreamer(tok) | ||
| >>> model.generate(**inputs, streamer=streamer) | ||
| ``` | ||
| """ | ||
|
|
||
| def __init__(self, tokenizer: "AutoTokenizer"): | ||
| self.tokenizer = tokenizer | ||
|
|
||
| def put(self, value): | ||
| """Prints the token(s) to stdout""" | ||
| if len(value.shape) > 1 and value.shape[0] > 1: | ||
| raise ValueError("TextStreamer only supports batch size 1") | ||
| elif len(value.shape) > 1: | ||
| value = value[0] | ||
| text = self.tokenizer.decode(value) | ||
| print(text, flush=True, end="") | ||
|
|
||
| def end(self): | ||
| """Prints a newline to stdout""" | ||
| print("", flush=True) |
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 |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| # coding=utf-8 | ||
| # Copyright 2023 The HuggingFace Team Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a clone of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import unittest | ||
|
|
||
| from transformers import AutoTokenizer, TextStreamer, is_torch_available | ||
| from transformers.testing_utils import CaptureStdout, require_torch, torch_device | ||
|
|
||
| from ..test_modeling_common import ids_tensor | ||
|
|
||
|
|
||
| if is_torch_available(): | ||
| from transformers import AutoModelForCausalLM | ||
|
|
||
|
|
||
| @require_torch | ||
| class StreamerTester(unittest.TestCase): | ||
| def test_text_streamer_stdout(self): | ||
| tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2") | ||
| model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device) | ||
| model.config.eos_token_id = -1 | ||
|
|
||
| input_ids = ids_tensor((1, 5), vocab_size=model.config.vocab_size).to(torch_device) | ||
| greedy_ids = model.generate(input_ids, max_new_tokens=10, do_sample=False) | ||
| greedy_text = tokenizer.decode(greedy_ids[0]) | ||
|
|
||
| with CaptureStdout() as cs: | ||
| streamer = TextStreamer(tokenizer) | ||
| model.generate(input_ids, max_new_tokens=10, do_sample=False, streamer=streamer) | ||
|
|
||
| # The greedy text should be printed to stdout, except for the final "\n" in the streamer | ||
| self.assertEqual(cs.out[:-1], greedy_text) |
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.
Uh oh!
There was an error while loading. Please reload this page.