Spaces:
Running
on
Zero
Running
on
Zero
Commit
·
97629be
1
Parent(s):
e6127a4
revert to sequential processing
Browse files- utils/models.py +26 -150
utils/models.py
CHANGED
@@ -6,10 +6,7 @@ import torch
|
|
6 |
from transformers import pipeline, AutoTokenizer, StoppingCriteria, StoppingCriteriaList
|
7 |
from .prompts import format_rag_prompt
|
8 |
from .shared import generation_interrupt
|
9 |
-
|
10 |
-
import queue
|
11 |
-
import time # Added for sleep
|
12 |
-
from vllm import LLM, SamplingParams
|
13 |
models = {
|
14 |
"Qwen2.5-1.5b-Instruct": "qwen/qwen2.5-1.5b-instruct",
|
15 |
"Llama-3.2-1b-Instruct": "meta-llama/llama-3.2-1b-instruct",
|
@@ -27,9 +24,10 @@ class InterruptCriteria(StoppingCriteria):
|
|
27 |
def __call__(self, input_ids, scores, **kwargs):
|
28 |
return self.interrupt_event.is_set()
|
29 |
|
|
|
30 |
def generate_summaries(example, model_a_name, model_b_name):
|
31 |
"""
|
32 |
-
Generates summaries for the given example using the assigned models.
|
33 |
"""
|
34 |
if generation_interrupt.is_set():
|
35 |
return "", ""
|
@@ -49,76 +47,28 @@ def generate_summaries(example, model_a_name, model_b_name):
|
|
49 |
if generation_interrupt.is_set():
|
50 |
return "", ""
|
51 |
|
52 |
-
#
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
summary_a = ""
|
58 |
-
while thread_a.is_alive():
|
59 |
-
if generation_interrupt.is_set():
|
60 |
-
print(f"Interrupting model A ({model_a_name})...")
|
61 |
-
# The InterruptCriteria within the thread will handle stopping generate
|
62 |
-
# We return early from the main control flow.
|
63 |
-
thread_a.join(timeout=1.0) # Give thread a moment to potentially stop
|
64 |
-
return "", ""
|
65 |
-
try:
|
66 |
-
summary_a = result_queue_a.get(timeout=0.1) # Check queue periodically
|
67 |
-
break # Got result
|
68 |
-
except queue.Empty:
|
69 |
-
continue # Still running, check interrupt again
|
70 |
-
|
71 |
-
# If thread finished but we didn't get a result (e.g., interrupted just before putting in queue)
|
72 |
-
if not summary_a and not result_queue_a.empty():
|
73 |
-
summary_a = result_queue_a.get_nowait()
|
74 |
-
elif not summary_a and generation_interrupt.is_set(): # Check interrupt again if thread finished quickly
|
75 |
-
return "", ""
|
76 |
-
|
77 |
-
|
78 |
-
if generation_interrupt.is_set(): # Check between models
|
79 |
return summary_a, ""
|
80 |
-
|
81 |
-
#
|
82 |
-
|
83 |
-
|
84 |
-
thread_b.start()
|
85 |
-
|
86 |
-
summary_b = ""
|
87 |
-
while thread_b.is_alive():
|
88 |
-
if generation_interrupt.is_set():
|
89 |
-
print(f"Interrupting model B ({model_b_name})...")
|
90 |
-
thread_b.join(timeout=1.0)
|
91 |
-
return summary_a, "" # Return summary_a obtained so far
|
92 |
-
try:
|
93 |
-
summary_b = result_queue_b.get(timeout=0.1)
|
94 |
-
break
|
95 |
-
except queue.Empty:
|
96 |
-
continue
|
97 |
-
|
98 |
-
if not summary_b and not result_queue_b.empty():
|
99 |
-
summary_b = result_queue_b.get_nowait()
|
100 |
-
elif not summary_b and generation_interrupt.is_set():
|
101 |
-
return summary_a, ""
|
102 |
-
|
103 |
-
|
104 |
return summary_a, summary_b
|
105 |
|
106 |
-
|
107 |
-
# Modified run_inference to run in a thread and use a queue for results
|
108 |
@spaces.GPU
|
109 |
-
def run_inference(model_name, context, question
|
110 |
"""
|
111 |
-
Run inference using the specified model.
|
112 |
-
|
113 |
"""
|
114 |
-
# Check interrupt at the
|
115 |
if generation_interrupt.is_set():
|
116 |
-
|
117 |
-
return
|
118 |
|
119 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
120 |
-
model = None
|
121 |
-
tokenizer = None
|
122 |
result = ""
|
123 |
|
124 |
try:
|
@@ -127,15 +77,13 @@ def run_inference(model_name, context, question, result_queue):
|
|
127 |
"System role not supported" not in tokenizer.chat_template
|
128 |
if tokenizer.chat_template else False # Handle missing chat_template
|
129 |
)
|
130 |
-
outputs = ""
|
131 |
|
132 |
if tokenizer.pad_token is None:
|
133 |
tokenizer.pad_token = tokenizer.eos_token
|
134 |
|
135 |
# Check interrupt before loading the model
|
136 |
if generation_interrupt.is_set():
|
137 |
-
|
138 |
-
return
|
139 |
|
140 |
pipe = pipeline(
|
141 |
"text-generation",
|
@@ -148,94 +96,22 @@ def run_inference(model_name, context, question, result_queue):
|
|
148 |
top_p=0.9,
|
149 |
)
|
150 |
|
151 |
-
# model = AutoModelForCausalLM.from_pretrained(
|
152 |
-
# model_name, torch_dtype=torch.bfloat16, attn_implementation="eager", token=True
|
153 |
-
# ).to(device)
|
154 |
-
# model.eval() # Set model to evaluation mode
|
155 |
-
|
156 |
text_input = format_rag_prompt(question, context, accepts_sys)
|
157 |
|
158 |
-
# Check interrupt before
|
159 |
if generation_interrupt.is_set():
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
# actual_input = tokenizer.apply_chat_template(
|
164 |
-
# text_input,
|
165 |
-
# return_tensors="pt",
|
166 |
-
# tokenize=True,
|
167 |
-
# # Consider reducing max_length if context/question is very long
|
168 |
-
# # max_length=tokenizer.model_max_length, # Use model's max length
|
169 |
-
# # truncation=True, # Ensure truncation if needed
|
170 |
-
# max_length=2048, # Keep original max_length for now
|
171 |
-
# add_generation_prompt=True,
|
172 |
-
# ).to(device)
|
173 |
outputs = pipe(text_input, max_new_tokens=512)
|
174 |
result = outputs[0]['generated_text'][-1]['content']
|
175 |
-
# # Ensure input does not exceed model max length after adding generation prompt
|
176 |
-
# # This check might be redundant if tokenizer handles it, but good for safety
|
177 |
-
# # if actual_input.shape[1] > tokenizer.model_max_length:
|
178 |
-
# # # Handle too long input - maybe truncate manually or raise error
|
179 |
-
# # print(f"Warning: Input length {actual_input.shape[1]} exceeds model max length {tokenizer.model_max_length}")
|
180 |
-
# # # Simple truncation (might lose important info):
|
181 |
-
# # # actual_input = actual_input[:, -tokenizer.model_max_length:]
|
182 |
-
|
183 |
-
# input_length = actual_input.shape[1]
|
184 |
-
# attention_mask = torch.ones_like(actual_input).to(device)
|
185 |
-
|
186 |
-
# # Check interrupt before generation
|
187 |
-
# if generation_interrupt.is_set():
|
188 |
-
# result_queue.put("")
|
189 |
-
# return
|
190 |
-
|
191 |
-
# stopping_criteria = StoppingCriteriaList([InterruptCriteria(generation_interrupt)])
|
192 |
-
|
193 |
-
# with torch.inference_mode():
|
194 |
-
# outputs = model.generate(
|
195 |
-
# actual_input,
|
196 |
-
# attention_mask=attention_mask,
|
197 |
-
# max_new_tokens=512,
|
198 |
-
# pad_token_id=tokenizer.pad_token_id,
|
199 |
-
# stopping_criteria=stopping_criteria,
|
200 |
-
# do_sample=True, # Consider adding sampling parameters if needed
|
201 |
-
# temperature=0.6,
|
202 |
-
# top_p=0.9,
|
203 |
-
# )
|
204 |
-
|
205 |
-
# # Check interrupt immediately after generation finishes or stops
|
206 |
-
# if generation_interrupt.is_set():
|
207 |
-
# result = "" # Discard potentially partial result if interrupted
|
208 |
-
# else:
|
209 |
-
# # Decode the generated tokens, excluding the input tokens
|
210 |
-
# result = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
|
211 |
-
# llm = LLM(model_name, dtype=torch.bfloat16, hf_token=True, enforce_eager=True, device="cpu")
|
212 |
-
# params = SamplingParams(
|
213 |
-
# max_tokens=512,
|
214 |
-
# )
|
215 |
-
|
216 |
-
# # Check interrupt before generation
|
217 |
-
# if generation_interrupt.is_set():
|
218 |
-
# result_queue.put("")
|
219 |
-
# return
|
220 |
-
# # Generate the response
|
221 |
-
# outputs = llm.chat(
|
222 |
-
# text_input,
|
223 |
-
# sampling_params=params,
|
224 |
-
# # stopping_criteria=StoppingCriteriaList([InterruptCriteria(generation_interrupt)]),
|
225 |
-
# )
|
226 |
-
# # Check interrupt immediately after generation finishes or stops
|
227 |
-
result_queue.put(result)
|
228 |
|
229 |
except Exception as e:
|
230 |
-
print(f"Error in inference
|
231 |
-
|
232 |
-
result_queue.put(f"Error generating response: {str(e)[:200]}...")
|
233 |
|
234 |
finally:
|
235 |
-
# Clean up resources
|
236 |
-
del model
|
237 |
-
del tokenizer
|
238 |
-
del text_input
|
239 |
-
del outputs
|
240 |
if torch.cuda.is_available():
|
241 |
-
torch.cuda.empty_cache()
|
|
|
|
|
|
6 |
from transformers import pipeline, AutoTokenizer, StoppingCriteria, StoppingCriteriaList
|
7 |
from .prompts import format_rag_prompt
|
8 |
from .shared import generation_interrupt
|
9 |
+
|
|
|
|
|
|
|
10 |
models = {
|
11 |
"Qwen2.5-1.5b-Instruct": "qwen/qwen2.5-1.5b-instruct",
|
12 |
"Llama-3.2-1b-Instruct": "meta-llama/llama-3.2-1b-instruct",
|
|
|
24 |
def __call__(self, input_ids, scores, **kwargs):
|
25 |
return self.interrupt_event.is_set()
|
26 |
|
27 |
+
@spaces.GPU
|
28 |
def generate_summaries(example, model_a_name, model_b_name):
|
29 |
"""
|
30 |
+
Generates summaries for the given example using the assigned models sequentially.
|
31 |
"""
|
32 |
if generation_interrupt.is_set():
|
33 |
return "", ""
|
|
|
47 |
if generation_interrupt.is_set():
|
48 |
return "", ""
|
49 |
|
50 |
+
# Run model A
|
51 |
+
summary_a = run_inference(models[model_a_name], context_text, question)
|
52 |
+
|
53 |
+
if generation_interrupt.is_set():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
return summary_a, ""
|
55 |
+
|
56 |
+
# Run model B
|
57 |
+
summary_b = run_inference(models[model_b_name], context_text, question)
|
58 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
return summary_a, summary_b
|
60 |
|
|
|
|
|
61 |
@spaces.GPU
|
62 |
+
def run_inference(model_name, context, question):
|
63 |
"""
|
64 |
+
Run inference using the specified model.
|
65 |
+
Returns the generated text or empty string if interrupted.
|
66 |
"""
|
67 |
+
# Check interrupt at the beginning
|
68 |
if generation_interrupt.is_set():
|
69 |
+
return ""
|
|
|
70 |
|
71 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
|
72 |
result = ""
|
73 |
|
74 |
try:
|
|
|
77 |
"System role not supported" not in tokenizer.chat_template
|
78 |
if tokenizer.chat_template else False # Handle missing chat_template
|
79 |
)
|
|
|
80 |
|
81 |
if tokenizer.pad_token is None:
|
82 |
tokenizer.pad_token = tokenizer.eos_token
|
83 |
|
84 |
# Check interrupt before loading the model
|
85 |
if generation_interrupt.is_set():
|
86 |
+
return ""
|
|
|
87 |
|
88 |
pipe = pipeline(
|
89 |
"text-generation",
|
|
|
96 |
top_p=0.9,
|
97 |
)
|
98 |
|
|
|
|
|
|
|
|
|
|
|
99 |
text_input = format_rag_prompt(question, context, accepts_sys)
|
100 |
|
101 |
+
# Check interrupt before generation
|
102 |
if generation_interrupt.is_set():
|
103 |
+
return ""
|
104 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
outputs = pipe(text_input, max_new_tokens=512)
|
106 |
result = outputs[0]['generated_text'][-1]['content']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
|
108 |
except Exception as e:
|
109 |
+
print(f"Error in inference for {model_name}: {e}")
|
110 |
+
result = f"Error generating response: {str(e)[:200]}..."
|
|
|
111 |
|
112 |
finally:
|
113 |
+
# Clean up resources
|
|
|
|
|
|
|
|
|
114 |
if torch.cuda.is_available():
|
115 |
+
torch.cuda.empty_cache()
|
116 |
+
|
117 |
+
return result
|