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

TextIteratorStreamer & generate graceful interruption #29536

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
22 changes: 20 additions & 2 deletions src/transformers/generation/streamers.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ def end(self):
"""Function that is called by `.generate()` to signal the end of generation"""
raise NotImplementedError()

def is_running(self) -> bool:
"""Function that is called by `.generate()` to check if the streamer has ended"""
raise NotImplementedError()


class TextStreamer(BaseStreamer):
"""
Expand Down Expand Up @@ -69,7 +73,9 @@ class TextStreamer(BaseStreamer):
```
"""

def __init__(self, tokenizer: "AutoTokenizer", skip_prompt: bool = False, **decode_kwargs):
def __init__(
self, tokenizer: "AutoTokenizer", skip_prompt: bool = False, **decode_kwargs
):
self.tokenizer = tokenizer
self.skip_prompt = skip_prompt
self.decode_kwargs = decode_kwargs
Expand Down Expand Up @@ -203,19 +209,31 @@ class TextIteratorStreamer(TextStreamer):
"""

def __init__(
self, tokenizer: "AutoTokenizer", skip_prompt: bool = False, timeout: Optional[float] = None, **decode_kwargs
self,
tokenizer: "AutoTokenizer",
skip_prompt: bool = False,
timeout: Optional[float] = None,
**decode_kwargs
):
super().__init__(tokenizer, skip_prompt, **decode_kwargs)
self.text_queue = Queue()
self.stop_signal = None
self.timeout = timeout
self.stopped = False

def on_finalized_text(self, text: str, stream_end: bool = False):
"""Put the new text in the queue. If the stream is ending, also put a stop signal in the queue."""
self.text_queue.put(text, timeout=self.timeout)
if stream_end:
self.text_queue.put(self.stop_signal, timeout=self.timeout)

def end(self):
self.stopped = True
self.on_finalized_text("", stream_end=True)

def is_running(self) -> bool:
return not self.stopped

def __iter__(self):
return self

Expand Down
8 changes: 8 additions & 0 deletions src/transformers/generation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2164,6 +2164,8 @@ def _contrastive_search(
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
if streamer is not None:
streamer.put(next_tokens.cpu())
if not streamer.is_running():
break
model_kwargs = self._update_model_kwargs_for_generation(
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder, model_inputs=model_inputs
)
Expand Down Expand Up @@ -2450,6 +2452,8 @@ def _greedy_search(
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
if streamer is not None:
streamer.put(next_tokens.cpu())
if not streamer.is_running():
break
model_kwargs = self._update_model_kwargs_for_generation(
outputs,
model_kwargs,
Expand Down Expand Up @@ -2752,6 +2756,8 @@ def _sample(
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
if streamer is not None:
streamer.put(next_tokens.cpu())
if not streamer.is_running():
break
model_kwargs = self._update_model_kwargs_for_generation(
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder, model_inputs=model_inputs
)
Expand Down Expand Up @@ -4612,6 +4618,8 @@ def _assisted_decoding(
input_ids = torch.cat((input_ids, valid_tokens), dim=-1)
if streamer is not None:
streamer.put(valid_tokens.cpu())
if not streamer.is_running():
break
new_cur_len = input_ids.shape[-1]

# 4.2. Discard past key values relative to unused assistant tokens
Expand Down