Spaces:
Running
on
Zero
Running
on
Zero
Update utils/models.py
Browse files- utils/models.py +44 -25
utils/models.py
CHANGED
|
@@ -1,7 +1,4 @@
|
|
| 1 |
import os
|
| 2 |
-
# Keep Dynamo error suppression
|
| 3 |
-
import torch._dynamo
|
| 4 |
-
torch._dynamo.config.suppress_errors = True
|
| 5 |
|
| 6 |
os.environ["MKL_THREADING_LAYER"] = "GNU"
|
| 7 |
import spaces
|
|
@@ -17,8 +14,7 @@ from transformers import (
|
|
| 17 |
BitNetForCausalLM
|
| 18 |
)
|
| 19 |
from .prompts import format_rag_prompt
|
| 20 |
-
|
| 21 |
-
# from .shared import generation_interrupt
|
| 22 |
|
| 23 |
models = {
|
| 24 |
"Qwen2.5-1.5b-Instruct": "qwen/qwen2.5-1.5b-instruct",
|
|
@@ -48,13 +44,13 @@ tokenizer_cache = {}
|
|
| 48 |
model_names = list(models.keys())
|
| 49 |
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
|
| 59 |
|
| 60 |
@spaces.GPU
|
|
@@ -62,7 +58,9 @@ def generate_summaries(example, model_a_name, model_b_name):
|
|
| 62 |
"""
|
| 63 |
Generates summaries for the given example using the assigned models sequentially.
|
| 64 |
"""
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
context_text = ""
|
| 67 |
context_parts = []
|
| 68 |
|
|
@@ -90,15 +88,18 @@ def generate_summaries(example, model_a_name, model_b_name):
|
|
| 90 |
|
| 91 |
question = example.get("question", "")
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
# Run model A
|
| 95 |
summary_a = run_inference(models[model_a_name], context_text, question)
|
| 96 |
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
# Run model B
|
| 99 |
summary_b = run_inference(models[model_b_name], context_text, question)
|
| 100 |
|
| 101 |
-
print("Both models completed successfully")
|
| 102 |
return summary_a, summary_b
|
| 103 |
|
| 104 |
|
|
@@ -106,8 +107,12 @@ def generate_summaries(example, model_a_name, model_b_name):
|
|
| 106 |
def run_inference(model_name, context, question):
|
| 107 |
"""
|
| 108 |
Run inference using the specified model.
|
| 109 |
-
Returns the generated text.
|
| 110 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 112 |
result = ""
|
| 113 |
tokenizer_kwargs = {
|
|
@@ -145,18 +150,25 @@ def run_inference(model_name, context, question):
|
|
| 145 |
if tokenizer.pad_token is None:
|
| 146 |
tokenizer.pad_token = tokenizer.eos_token
|
| 147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
print("REACHED HERE BEFORE pipe")
|
| 149 |
print(f"Loading model {model_name}...")
|
| 150 |
-
|
| 151 |
if "bitnet" in model_name.lower():
|
| 152 |
bitnet_model = BitNetForCausalLM.from_pretrained(
|
| 153 |
model_name,
|
|
|
|
| 154 |
torch_dtype=torch.bfloat16,
|
|
|
|
| 155 |
)
|
| 156 |
pipe = pipeline(
|
| 157 |
"text-generation",
|
| 158 |
model=bitnet_model,
|
| 159 |
tokenizer=tokenizer,
|
|
|
|
|
|
|
| 160 |
torch_dtype=torch.bfloat16,
|
| 161 |
model_kwargs={
|
| 162 |
"attn_implementation": "eager",
|
|
@@ -189,14 +201,12 @@ def run_inference(model_name, context, question):
|
|
| 189 |
)
|
| 190 |
|
| 191 |
text_input = format_rag_prompt(question, context, accepts_sys)
|
| 192 |
-
|
| 193 |
-
print(f"Starting generation for {model_name}")
|
| 194 |
if "Gemma-3".lower() in model_name.lower():
|
| 195 |
print("REACHED HERE BEFORE GEN")
|
| 196 |
result = pipe(
|
| 197 |
text_input,
|
| 198 |
max_new_tokens=512,
|
| 199 |
-
generation_kwargs={"skip_special_tokens": True}
|
| 200 |
)[0]["generated_text"]
|
| 201 |
|
| 202 |
result = result[-1]["content"]
|
|
@@ -211,6 +221,7 @@ def run_inference(model_name, context, question):
|
|
| 211 |
**tokenizer_kwargs,
|
| 212 |
)
|
| 213 |
|
|
|
|
| 214 |
model_inputs = model_inputs.to(model.device)
|
| 215 |
|
| 216 |
input_ids = model_inputs.input_ids
|
|
@@ -219,12 +230,16 @@ def run_inference(model_name, context, question):
|
|
| 219 |
prompt_tokens_length = input_ids.shape[1]
|
| 220 |
|
| 221 |
with torch.inference_mode():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
output_sequences = model.generate(
|
| 223 |
input_ids=input_ids,
|
| 224 |
attention_mask=attention_mask,
|
| 225 |
max_new_tokens=512,
|
| 226 |
eos_token_id=tokenizer.eos_token_id,
|
| 227 |
-
pad_token_id=tokenizer.pad_token_id
|
| 228 |
)
|
| 229 |
|
| 230 |
generated_token_ids = output_sequences[0][prompt_tokens_length:]
|
|
@@ -238,10 +253,14 @@ def run_inference(model_name, context, question):
|
|
| 238 |
# **tokenizer_kwargs,
|
| 239 |
# ).to(bitnet_model.device)
|
| 240 |
# with torch.inference_mode():
|
|
|
|
|
|
|
|
|
|
| 241 |
# output_sequences = bitnet_model.generate(
|
| 242 |
# **formatted,
|
| 243 |
# max_new_tokens=512,
|
| 244 |
# )
|
|
|
|
| 245 |
# result = tokenizer.decode(output_sequences[0][formatted['input_ids'].shape[-1]:], skip_special_tokens=True)
|
| 246 |
else: # For other models
|
| 247 |
formatted = pipe.tokenizer.apply_chat_template(
|
|
@@ -251,16 +270,16 @@ def run_inference(model_name, context, question):
|
|
| 251 |
)
|
| 252 |
|
| 253 |
input_length = len(formatted)
|
|
|
|
| 254 |
|
| 255 |
outputs = pipe(
|
| 256 |
formatted,
|
| 257 |
max_new_tokens=512,
|
| 258 |
-
generation_kwargs={"skip_special_tokens": True}
|
| 259 |
)
|
|
|
|
| 260 |
result = outputs[0]["generated_text"][input_length:]
|
| 261 |
|
| 262 |
-
print(f"Generation completed for {model_name}")
|
| 263 |
-
|
| 264 |
except Exception as e:
|
| 265 |
print(f"Error in inference for {model_name}: {e}")
|
| 266 |
print(traceback.format_exc())
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
os.environ["MKL_THREADING_LAYER"] = "GNU"
|
| 4 |
import spaces
|
|
|
|
| 14 |
BitNetForCausalLM
|
| 15 |
)
|
| 16 |
from .prompts import format_rag_prompt
|
| 17 |
+
from .shared import generation_interrupt
|
|
|
|
| 18 |
|
| 19 |
models = {
|
| 20 |
"Qwen2.5-1.5b-Instruct": "qwen/qwen2.5-1.5b-instruct",
|
|
|
|
| 44 |
model_names = list(models.keys())
|
| 45 |
|
| 46 |
|
| 47 |
+
# Custom stopping criteria that checks the interrupt flag
|
| 48 |
+
class InterruptCriteria(StoppingCriteria):
|
| 49 |
+
def __init__(self, interrupt_event):
|
| 50 |
+
self.interrupt_event = interrupt_event
|
| 51 |
+
|
| 52 |
+
def __call__(self, input_ids, scores, **kwargs):
|
| 53 |
+
return self.interrupt_event.is_set()
|
| 54 |
|
| 55 |
|
| 56 |
@spaces.GPU
|
|
|
|
| 58 |
"""
|
| 59 |
Generates summaries for the given example using the assigned models sequentially.
|
| 60 |
"""
|
| 61 |
+
if generation_interrupt.is_set():
|
| 62 |
+
return "", ""
|
| 63 |
+
|
| 64 |
context_text = ""
|
| 65 |
context_parts = []
|
| 66 |
|
|
|
|
| 88 |
|
| 89 |
question = example.get("question", "")
|
| 90 |
|
| 91 |
+
if generation_interrupt.is_set():
|
| 92 |
+
return "", ""
|
| 93 |
+
|
| 94 |
# Run model A
|
| 95 |
summary_a = run_inference(models[model_a_name], context_text, question)
|
| 96 |
|
| 97 |
+
if generation_interrupt.is_set():
|
| 98 |
+
return summary_a, ""
|
| 99 |
+
|
| 100 |
# Run model B
|
| 101 |
summary_b = run_inference(models[model_b_name], context_text, question)
|
| 102 |
|
|
|
|
| 103 |
return summary_a, summary_b
|
| 104 |
|
| 105 |
|
|
|
|
| 107 |
def run_inference(model_name, context, question):
|
| 108 |
"""
|
| 109 |
Run inference using the specified model.
|
| 110 |
+
Returns the generated text or empty string if interrupted.
|
| 111 |
"""
|
| 112 |
+
# Check interrupt at the beginning
|
| 113 |
+
if generation_interrupt.is_set():
|
| 114 |
+
return ""
|
| 115 |
+
|
| 116 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 117 |
result = ""
|
| 118 |
tokenizer_kwargs = {
|
|
|
|
| 150 |
if tokenizer.pad_token is None:
|
| 151 |
tokenizer.pad_token = tokenizer.eos_token
|
| 152 |
|
| 153 |
+
# Check interrupt before loading the model
|
| 154 |
+
if generation_interrupt.is_set():
|
| 155 |
+
return ""
|
| 156 |
+
|
| 157 |
print("REACHED HERE BEFORE pipe")
|
| 158 |
print(f"Loading model {model_name}...")
|
|
|
|
| 159 |
if "bitnet" in model_name.lower():
|
| 160 |
bitnet_model = BitNetForCausalLM.from_pretrained(
|
| 161 |
model_name,
|
| 162 |
+
#device_map="auto",
|
| 163 |
torch_dtype=torch.bfloat16,
|
| 164 |
+
#trust_remote_code=True,
|
| 165 |
)
|
| 166 |
pipe = pipeline(
|
| 167 |
"text-generation",
|
| 168 |
model=bitnet_model,
|
| 169 |
tokenizer=tokenizer,
|
| 170 |
+
#device_map="auto",
|
| 171 |
+
#trust_remote_code=True,
|
| 172 |
torch_dtype=torch.bfloat16,
|
| 173 |
model_kwargs={
|
| 174 |
"attn_implementation": "eager",
|
|
|
|
| 201 |
)
|
| 202 |
|
| 203 |
text_input = format_rag_prompt(question, context, accepts_sys)
|
|
|
|
|
|
|
| 204 |
if "Gemma-3".lower() in model_name.lower():
|
| 205 |
print("REACHED HERE BEFORE GEN")
|
| 206 |
result = pipe(
|
| 207 |
text_input,
|
| 208 |
max_new_tokens=512,
|
| 209 |
+
generation_kwargs={"skip_special_tokens": True},
|
| 210 |
)[0]["generated_text"]
|
| 211 |
|
| 212 |
result = result[-1]["content"]
|
|
|
|
| 221 |
**tokenizer_kwargs,
|
| 222 |
)
|
| 223 |
|
| 224 |
+
|
| 225 |
model_inputs = model_inputs.to(model.device)
|
| 226 |
|
| 227 |
input_ids = model_inputs.input_ids
|
|
|
|
| 230 |
prompt_tokens_length = input_ids.shape[1]
|
| 231 |
|
| 232 |
with torch.inference_mode():
|
| 233 |
+
# Check interrupt before generation
|
| 234 |
+
if generation_interrupt.is_set():
|
| 235 |
+
return ""
|
| 236 |
+
|
| 237 |
output_sequences = model.generate(
|
| 238 |
input_ids=input_ids,
|
| 239 |
attention_mask=attention_mask,
|
| 240 |
max_new_tokens=512,
|
| 241 |
eos_token_id=tokenizer.eos_token_id,
|
| 242 |
+
pad_token_id=tokenizer.pad_token_id # Addresses the warning
|
| 243 |
)
|
| 244 |
|
| 245 |
generated_token_ids = output_sequences[0][prompt_tokens_length:]
|
|
|
|
| 253 |
# **tokenizer_kwargs,
|
| 254 |
# ).to(bitnet_model.device)
|
| 255 |
# with torch.inference_mode():
|
| 256 |
+
# # Check interrupt before generation
|
| 257 |
+
# if generation_interrupt.is_set():
|
| 258 |
+
# return ""
|
| 259 |
# output_sequences = bitnet_model.generate(
|
| 260 |
# **formatted,
|
| 261 |
# max_new_tokens=512,
|
| 262 |
# )
|
| 263 |
+
|
| 264 |
# result = tokenizer.decode(output_sequences[0][formatted['input_ids'].shape[-1]:], skip_special_tokens=True)
|
| 265 |
else: # For other models
|
| 266 |
formatted = pipe.tokenizer.apply_chat_template(
|
|
|
|
| 270 |
)
|
| 271 |
|
| 272 |
input_length = len(formatted)
|
| 273 |
+
# Check interrupt before generation
|
| 274 |
|
| 275 |
outputs = pipe(
|
| 276 |
formatted,
|
| 277 |
max_new_tokens=512,
|
| 278 |
+
generation_kwargs={"skip_special_tokens": True},
|
| 279 |
)
|
| 280 |
+
# print(outputs[0]['generated_text'])
|
| 281 |
result = outputs[0]["generated_text"][input_length:]
|
| 282 |
|
|
|
|
|
|
|
| 283 |
except Exception as e:
|
| 284 |
print(f"Error in inference for {model_name}: {e}")
|
| 285 |
print(traceback.format_exc())
|