MindLabUnimib commited on
Commit
3702146
·
verified ·
1 Parent(s): 2d8a10d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -66
app.py CHANGED
@@ -1,73 +1,130 @@
1
- import torch
2
  import spaces
 
 
 
 
 
3
  import gradio as gr
4
 
5
- # from transformers import (
6
- # AutoModelForCausalLM,
7
- # AutoTokenizer,
8
- # AutoModelForSequenceClassification,
9
- # )
10
-
11
- # chat_model_name = "sapienzanlp/Minerva-7B-instruct-v1.0"
12
- # chat_model = AutoModelForCausalLM.from_pretrained(chat_model_name, dtype=torch.bfloat16, device_map="cpu")
13
- # chat_model.to("cuda")
14
- # chat_tokenizer = AutoTokenizer.from_pretrained(chat_model_name)
15
-
16
- # moderator_model_name = "saiteki-kai/QA-DeBERTa-v3-large-binary-3"
17
- # moderator_model = AutoModelForSequenceClassification.from_pretrained(moderator_model_name, device_map="cpu")
18
- # moderator_model.to("cuda")
19
- # moderator_tokenizer = AutoTokenizer.from_pretrained(moderator_model_name, padding_side="right")
20
-
21
- # def generate_responses(model, tokenizer, prompts):
22
- # messages = [[{"role": "user", "content": message}] for message in prompts]
23
-
24
- # texts = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
25
- # model_inputs = tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors="pt").to(model.device)
26
-
27
- # with torch.inference_mode():
28
- # generated_ids = model.generate(
29
- # **model_inputs,
30
- # do_sample=False,
31
- # temperature=0,
32
- # repetition_penalty=1.1,
33
- # max_new_tokens=512,
34
- # )
35
- # prompt_lengths = model_inputs["attention_mask"].sum(dim=1) - 1
36
- # generated_ids = [
37
- # output_ids[length:] for length, output_ids in zip(prompt_lengths, generated_ids)
38
- # ]
39
- # responses = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
40
-
41
- # return responses
42
-
43
- # def classify_pairs(model, tokenizer, prompts, responses):
44
- # texts = [
45
- # prompt + "[SEP]" + response for prompt, response in zip(prompts, responses)
46
- # ]
47
-
48
- # input_ids = tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors="pt").to(model.device)
49
- # print(tokenizer.batch_decode(input_ids["input_ids"]))
50
-
51
- # with torch.inference_mode():
52
- # outputs = model(**input_ids)
53
- # scores = torch.softmax(outputs.logits, dim=-1).detach().cpu()
54
- # unsafety_scores = [float(s[1]) for s in scores] # get unsafe axis
55
-
56
- # return unsafety_scores
57
-
58
-
59
- @spaces.GPU(duration=120)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def generate(submission: list[dict[str, str]], team_id: str) -> list[dict[str, str | float]]:
61
  print("GENERATE")
62
 
63
- # ids = [s["id"] for s in submission]
64
- # prompts = [s["prompt"] for s in submission]
65
 
66
- # responses = generate_responses(chat_model, chat_tokenizer, prompts)
67
- # print(responses)
68
 
69
- # scores = classify_pairs(moderator_model, moderator_tokenizer, prompts, responses)
70
- # print(scores)
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
- {"id": id, "prompt": prompt, "response": response, "score": score, "model": chat_model_name, "team_id": team_id}
 
 
 
 
 
 
 
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()