hysts HF Staff commited on
Commit
c0c1f2f
·
1 Parent(s): f2504e3

Enable ChatInterface stop button

Browse files
Files changed (1) hide show
  1. app.py +21 -5
app.py CHANGED
@@ -5,7 +5,7 @@ from threading import Thread
5
  import gradio as gr
6
  import spaces
7
  import torch
8
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
9
 
10
  DESCRIPTION = """\
11
  # Gemma 2 9B IT
@@ -32,6 +32,14 @@ model.config.sliding_window = 4096
32
  model.eval()
33
 
34
 
 
 
 
 
 
 
 
 
35
  @spaces.GPU(duration=90)
36
  def _generate_on_gpu(
37
  input_ids: torch.Tensor,
@@ -44,9 +52,11 @@ def _generate_on_gpu(
44
  input_ids = input_ids.to(model.device)
45
 
46
  streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
 
47
  generate_kwargs = {
48
  "input_ids": input_ids,
49
  "streamer": streamer,
 
50
  "max_new_tokens": max_new_tokens,
51
  "do_sample": True,
52
  "top_p": top_p,
@@ -69,9 +79,16 @@ def _generate_on_gpu(
69
  thread.start()
70
 
71
  chunks: list[str] = []
72
- for text in streamer:
73
- chunks.append(text)
74
- yield "".join(chunks)
 
 
 
 
 
 
 
75
 
76
  thread.join()
77
  if exception_holder:
@@ -165,7 +182,6 @@ demo = gr.ChatInterface(
165
  value=1.2,
166
  ),
167
  ],
168
- stop_btn=False,
169
  examples=[
170
  ["Hello there! How are you doing?"],
171
  ["Can you explain briefly to me what is the Python programming language?"],
 
5
  import gradio as gr
6
  import spaces
7
  import torch
8
+ from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, TextIteratorStreamer
9
 
10
  DESCRIPTION = """\
11
  # Gemma 2 9B IT
 
32
  model.eval()
33
 
34
 
35
+ class StopOnSignal(StoppingCriteria):
36
+ def __init__(self) -> None:
37
+ self.stopped = False
38
+
39
+ def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor, **kwargs: object) -> bool: # noqa: ARG002
40
+ return self.stopped
41
+
42
+
43
  @spaces.GPU(duration=90)
44
  def _generate_on_gpu(
45
  input_ids: torch.Tensor,
 
52
  input_ids = input_ids.to(model.device)
53
 
54
  streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
55
+ stop_criteria = StopOnSignal()
56
  generate_kwargs = {
57
  "input_ids": input_ids,
58
  "streamer": streamer,
59
+ "stopping_criteria": [stop_criteria],
60
  "max_new_tokens": max_new_tokens,
61
  "do_sample": True,
62
  "top_p": top_p,
 
79
  thread.start()
80
 
81
  chunks: list[str] = []
82
+ try:
83
+ for text in streamer:
84
+ chunks.append(text)
85
+ yield "".join(chunks)
86
+ except GeneratorExit:
87
+ stop_criteria.stopped = True
88
+ for _ in streamer:
89
+ pass
90
+ thread.join()
91
+ raise
92
 
93
  thread.join()
94
  if exception_holder:
 
182
  value=1.2,
183
  ),
184
  ],
 
185
  examples=[
186
  ["Hello there! How are you doing?"],
187
  ["Can you explain briefly to me what is the Python programming language?"],