Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,73 +1,130 @@
|
|
| 1 |
-
import torch
|
| 2 |
import spaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
#
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
#
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
def generate(submission: list[dict[str, str]], team_id: str) -> list[dict[str, str | float]]:
|
| 61 |
print("GENERATE")
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
|
| 72 |
chat_model_name = "sapienzanlp/Minerva-7B-instruct-v1.0"
|
| 73 |
ids = [s["id"] for s in submission]
|
|
@@ -76,7 +133,14 @@ def generate(submission: list[dict[str, str]], team_id: str) -> list[dict[str, s
|
|
| 76 |
scores = [0.5 for _ in prompts]
|
| 77 |
|
| 78 |
outputs = [
|
| 79 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
for id, prompt, response, score in zip(ids, prompts, responses, scores)
|
| 81 |
]
|
| 82 |
|
|
@@ -87,6 +151,6 @@ with gr.Blocks() as demo:
|
|
| 87 |
print("START")
|
| 88 |
gr.api(generate, api_name="scores", concurrency_limit=None, batch=False)
|
| 89 |
|
| 90 |
-
|
| 91 |
-
print("LAUNCH")
|
| 92 |
-
demo.launch()
|
|
|
|
|
|
|
| 1 |
import spaces
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
import gradio as gr
|
| 8 |
|
| 9 |
+
from transformers import (
|
| 10 |
+
AutoModelForCausalLM,
|
| 11 |
+
AutoTokenizer,
|
| 12 |
+
AutoModelForSequenceClassification,
|
| 13 |
+
PreTrainedModel,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
print("\n=== Environment Setup ===")
|
| 17 |
+
|
| 18 |
+
if torch.cuda.is_available():
|
| 19 |
+
print(f"GPU detected: {torch.cuda.get_device_name(0)}")
|
| 20 |
+
try:
|
| 21 |
+
subprocess.run(
|
| 22 |
+
"pip install flash-attn --no-build-isolation",
|
| 23 |
+
shell=True,
|
| 24 |
+
check=True,
|
| 25 |
+
)
|
| 26 |
+
print("✅ flash-attn installed successfully")
|
| 27 |
+
except subprocess.CalledProcessError as e:
|
| 28 |
+
print("⚠️ flash-attn installation failed:", e)
|
| 29 |
+
else:
|
| 30 |
+
print("⚙️ CPU detected — skipping flash-attn installation")
|
| 31 |
+
# Disable flash-attn references safely
|
| 32 |
+
os.environ["DISABLE_FLASH_ATTN"] = "1"
|
| 33 |
+
os.environ["FLASH_ATTENTION_SKIP_CUDA_BUILD"] = "TRUE"
|
| 34 |
+
try:
|
| 35 |
+
from transformers.utils import import_utils
|
| 36 |
+
|
| 37 |
+
if "flash_attn" not in import_utils.PACKAGE_DISTRIBUTION_MAPPING: # type: ignore
|
| 38 |
+
import_utils.PACKAGE_DISTRIBUTION_MAPPING["flash_attn"] = "flash-attn" # type: ignore
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print("⚠️ Patch skipped:", e)
|
| 41 |
+
|
| 42 |
+
if torch.cuda.is_available():
|
| 43 |
+
device = torch.device("cuda")
|
| 44 |
+
print(f"Using GPU: {torch.cuda.get_device_name(device)}")
|
| 45 |
+
else:
|
| 46 |
+
device = torch.device("cpu")
|
| 47 |
+
print("Using CPU")
|
| 48 |
+
|
| 49 |
+
print("\n=== Model Loading ===")
|
| 50 |
+
|
| 51 |
+
chat_model_name = "sapienzanlp/Minerva-7B-instruct-v1.0"
|
| 52 |
+
cls_model_name = "saiteki-kai/QA-DeBERTa-v3-large-binary-3"
|
| 53 |
+
|
| 54 |
+
chat_model = AutoModelForCausalLM.from_pretrained(chat_model_name, dtype=torch.bfloat16)
|
| 55 |
+
cls_model = AutoModelForSequenceClassification.from_pretrained(cls_model_name, dtype=torch.bfloat16)
|
| 56 |
+
|
| 57 |
+
chat_tokenizer = AutoTokenizer.from_pretrained(chat_model_name)
|
| 58 |
+
cls_tokenizer = AutoTokenizer.from_pretrained(cls_model_name)
|
| 59 |
+
|
| 60 |
+
chat_model = chat_model.to(device) # type: ignore
|
| 61 |
+
cls_model = cls_model.to(device)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@spaces.GPU(duration=1500) # maximum duration allowed during startup
|
| 65 |
+
def compile_transformer():
|
| 66 |
+
with spaces.aoti_capture(chat_model) as call:
|
| 67 |
+
chat_model("arbitrary example prompt")
|
| 68 |
+
|
| 69 |
+
exported = torch.export.export(chat_model, args=call.args, kwargs=call.kwargs)
|
| 70 |
+
return spaces.aoti_compile(exported)
|
| 71 |
+
|
| 72 |
+
print("\n=== Model Compilation ===")
|
| 73 |
+
|
| 74 |
+
compiled_transformer = compile_transformer()
|
| 75 |
+
spaces.aoti_apply(compiled_transformer, chat_model)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def generate_responses(model, tokenizer, prompts):
|
| 79 |
+
messages = [[{"role": "user", "content": message}] for message in prompts]
|
| 80 |
+
|
| 81 |
+
texts = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 82 |
+
print(texts)
|
| 83 |
+
model_inputs = tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors="pt").to(model.device)
|
| 84 |
+
|
| 85 |
+
print(tokenizer.batch_decode(model_inputs["input_ids"]))
|
| 86 |
+
|
| 87 |
+
with torch.inference_mode():
|
| 88 |
+
generated_ids = model.generate(
|
| 89 |
+
**model_inputs,
|
| 90 |
+
do_sample=False,
|
| 91 |
+
temperature=0,
|
| 92 |
+
repetition_penalty=1.1,
|
| 93 |
+
max_new_tokens=512,
|
| 94 |
+
)
|
| 95 |
+
prompt_lengths = model_inputs["attention_mask"].sum(dim=1) - 1
|
| 96 |
+
generated_ids = [output_ids[length:] for length, output_ids in zip(prompt_lengths, generated_ids)]
|
| 97 |
+
responses = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 98 |
+
|
| 99 |
+
return responses
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def classify_pairs(model, tokenizer, prompts, responses):
|
| 103 |
+
texts = [prompt + "[SEP]" + response for prompt, response in zip(prompts, responses)]
|
| 104 |
+
|
| 105 |
+
input_ids = tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors="pt").to(model.device)
|
| 106 |
+
print(tokenizer.batch_decode(input_ids["input_ids"]))
|
| 107 |
+
|
| 108 |
+
with torch.inference_mode():
|
| 109 |
+
outputs = model(**input_ids)
|
| 110 |
+
scores = torch.softmax(outputs.logits, dim=-1).detach().cpu()
|
| 111 |
+
unsafety_scores = [float(s[1]) for s in scores] # get unsafe axis
|
| 112 |
+
|
| 113 |
+
return unsafety_scores
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@spaces.GPU(duration=60)
|
| 117 |
def generate(submission: list[dict[str, str]], team_id: str) -> list[dict[str, str | float]]:
|
| 118 |
print("GENERATE")
|
| 119 |
|
| 120 |
+
ids = [s["id"] for s in submission]
|
| 121 |
+
prompts = [s["prompt"] for s in submission]
|
| 122 |
|
| 123 |
+
responses = generate_responses(chat_model, chat_tokenizer, prompts)
|
| 124 |
+
print(responses)
|
| 125 |
|
| 126 |
+
scores = classify_pairs(cls_model, cls_tokenizer, prompts, responses)
|
| 127 |
+
print(scores)
|
| 128 |
|
| 129 |
chat_model_name = "sapienzanlp/Minerva-7B-instruct-v1.0"
|
| 130 |
ids = [s["id"] for s in submission]
|
|
|
|
| 133 |
scores = [0.5 for _ in prompts]
|
| 134 |
|
| 135 |
outputs = [
|
| 136 |
+
{
|
| 137 |
+
"id": id,
|
| 138 |
+
"prompt": prompt,
|
| 139 |
+
"response": response,
|
| 140 |
+
"score": score,
|
| 141 |
+
"model": chat_model_name,
|
| 142 |
+
"team_id": team_id,
|
| 143 |
+
}
|
| 144 |
for id, prompt, response, score in zip(ids, prompts, responses, scores)
|
| 145 |
]
|
| 146 |
|
|
|
|
| 151 |
print("START")
|
| 152 |
gr.api(generate, api_name="scores", concurrency_limit=None, batch=False)
|
| 153 |
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
print("LAUNCH")
|
| 156 |
+
demo.launch()
|