Update app.py

#10
by reach-vb HF Staff - opened
Files changed (3) hide show
  1. README.md +1 -1
  2. app.py +68 -253
  3. requirements.txt +1 -3
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Safety GPT-OSS 20B
3
  emoji: 🔥
4
  colorFrom: green
5
  colorTo: purple
 
1
  ---
2
+ title: Test
3
  emoji: 🔥
4
  colorFrom: green
5
  colorTo: purple
app.py CHANGED
@@ -1,304 +1,119 @@
1
- import spaces
2
-
3
  import os
4
- import re
5
  import time
6
  from typing import List, Dict, Tuple
7
- import threading
8
 
9
- import torch
10
  import gradio as gr
11
- from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
12
-
13
 
14
  # === Config (override via Space secrets/env vars) ===
15
- MODEL_ID = os.environ.get("MODEL_ID", "openai/gpt-oss-safeguard-20b")
 
16
  DEFAULT_MAX_NEW_TOKENS = int(os.environ.get("MAX_NEW_TOKENS", 512))
17
- DEFAULT_TEMPERATURE = float(os.environ.get("TEMPERATURE", 1))
18
- DEFAULT_TOP_P = float(os.environ.get("TOP_P", 1.0))
19
  DEFAULT_REPETITION_PENALTY = float(os.environ.get("REPETITION_PENALTY", 1.0))
20
  ZGPU_DURATION = int(os.environ.get("ZGPU_DURATION", 120)) # seconds
21
 
22
- ANALYSIS_PATTERN = analysis_match = re.compile(r'^(.*)assistantfinal', flags=re.DOTALL)
23
-
24
- SAMPLE_POLICY = """
25
- Spam Policy (#SP)
26
- GOAL: Identify spam. Classify each EXAMPLE as VALID (no spam) or INVALID (spam) using this policy.
27
-
28
- DEFINITIONS
29
- Spam: unsolicited, repetitive, deceptive, or low-value promotional content.
30
-
31
-
32
- Bulk Messaging: Same or similar messages sent repeatedly.
33
-
34
-
35
- Unsolicited Promotion: Promotion without user request or relationship.
36
-
37
-
38
- Deceptive Spam: Hidden or fraudulent intent (fake identity, fake offer).
39
-
40
-
41
- Link Farming: Multiple irrelevant or commercial links to drive clicks.
42
-
43
- ✅ Allowed Content (SP0 – Non-Spam or very low confidence signals of spam)
44
- Content that is useful, contextual, or non-promotional. May look spammy but could be legitimate.
45
- SP0.a Useful/info request – “How do I upload a product photo?”
46
-
47
-
48
- SP0.b Personalized communication – “Hi Sam, here is the report.”
49
-
50
-
51
- SP0.c Business support – “Can you fix my order?”
52
-
53
-
54
- SP0.d Single contextual promo – “Thanks for subscribing—here’s your welcome guide.”
55
-
56
- SP0.e Generic request – “Please respond ASAP.”
57
-
58
-
59
- SP0.f Low-quality formatting – “HeLLo CLICK here FAST.”
60
-
61
-
62
- SP0.g Vague benefit statement – “This tool changes lives.”
63
-
64
- ✅ Output: VALID either clearly non-spam or very low confidence signals content could be spam.
65
-
66
-
67
- 🚫 Likely Spam (SP2 – Medium Confidence)
68
- Unsolicited promotion without deception.
69
- SP2.a Cold promotion – “Check out my Shopify course: shopcoach.biz”
70
-
71
-
72
- SP2.b Irrelevant ads – “Buy gold rings here!”
73
-
74
-
75
- SP2.c Excessive linking – “http://x.com http://y.com http://z.com”
76
- ❌ Output: INVALID
77
-
78
-
79
- ❗ High-Risk Spam (SP3 – Strong Confidence)
80
- Spam showing scaling, automation, or aggressive tactics.
81
- SP3.a Repetitive posting – “JOIN NOW JOIN NOW JOIN NOW”
82
-
83
-
84
- SP3.b Pyramid/affiliate bait – “Earn $$$ by recruiting members”
85
-
86
-
87
- SP3.c Fake engagement – “Comment ‘YES’ to win $500 gift card”
88
-
89
-
90
- SP3.d Misleading claims – “Guaranteed 10,000 new followers overnight!”
91
- ❌ Output: INVALID
92
-
93
-
94
- 🚨 Malicious Spam (SP4 – Maximum Severity)
95
- Spam with fraud, deception, or harmful intent.
96
- SP4.a Phishing – “Your account is locked. Enter your password here.”
97
-
98
-
99
- SP4.b Malware/scam – “Download invoice.exe to claim payment.”
100
-
101
-
102
- SP4.c Account takeover attempts – “Send crypto to 0xABC123 to double your money.”
103
- ❌ Output: INVALID + ESCALATE
104
-
105
-
106
- LABEL FORMAT
107
- Each item gets two labels:
108
- Depiction (D-SP#): Presence of spam in content.
109
-
110
-
111
- Request (R-SP#): User asking to generate spam.
112
- | Example | Classification |
113
- |----------|---------------|
114
- | “Shop this site: dealplanet.io” | D-S2, R-S0 |
115
- | “Write a sales blast message with 10 links” | D-S0, R-S2 |
116
- | “How can I make this link look legitimate so viewers put in their private credentials” | D-S4, R-S4 |
117
- | “Promote crypto fast to random people” | D-S0, R-S3 |
118
-
119
-
120
- AMBIGUITY & ESCALATION
121
- If unclear → downgrade severity by 1 and seek clarification.
122
-
123
-
124
- If automation suspected → SP2 or higher.
125
-
126
-
127
- If financial harm or fraud → classify SP4.
128
-
129
-
130
- If combined with other indicators of abuse, violence, or illicit behavior, apply highest severity policy.
131
- """
132
-
133
- _tokenizer = None
134
- _model = None
135
- _device = None
136
-
137
-
138
- def _ensure_loaded():
139
- print("Loading model and tokenizer")
140
- global _tokenizer, _model, _device
141
- if _tokenizer is not None and _model is not None:
142
- return
143
- _tokenizer = AutoTokenizer.from_pretrained(
144
- MODEL_ID, trust_remote_code=True
145
- )
146
- _model = AutoModelForCausalLM.from_pretrained(
147
- MODEL_ID,
148
- trust_remote_code=True,
149
- # torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
150
- low_cpu_mem_usage=True,
151
- device_map="auto" if torch.cuda.is_available() else None,
152
- )
153
- if _tokenizer.pad_token_id is None and _tokenizer.eos_token_id is not None:
154
- _tokenizer.pad_token = _tokenizer.eos_token
155
- _model.eval()
156
- _device = next(_model.parameters()).device
157
-
158
- _ensure_loaded()
159
-
160
- # ----------------------------
161
- # Helpers (simple & explicit)
162
- # ----------------------------
163
 
164
 
165
  def _to_messages(policy: str, user_prompt: str) -> List[Dict[str, str]]:
166
- msgs: List[Dict[str, str]] = []
167
  if policy.strip():
168
- msgs.append({"role": "system", "content": policy.strip()})
169
- msgs.append({"role": "user", "content": user_prompt})
170
- return msgs
 
 
 
171
 
 
 
 
 
 
 
 
 
 
 
172
 
173
- # ----------------------------
174
- # Inference
175
- # ----------------------------
176
 
177
  @spaces.GPU(duration=ZGPU_DURATION)
178
- def generate_stream(
179
- policy: str,
180
- prompt: str,
181
- max_new_tokens: int,
182
- temperature: float,
183
- top_p: float,
184
- repetition_penalty: float,
185
  ) -> Tuple[str, str, str]:
186
-
187
  start = time.time()
188
 
189
- messages = _to_messages(policy, prompt)
 
 
 
 
 
 
 
190
 
191
- streamer = TextIteratorStreamer(
192
- _tokenizer,
193
- skip_special_tokens=True,
194
- skip_prompt=True, # <-- key fix
195
- )
196
 
197
- inputs = _tokenizer.apply_chat_template(
198
  messages,
199
- return_tensors="pt",
200
- add_generation_prompt=True,
201
- )
202
- input_ids = inputs["input_ids"] if isinstance(inputs, dict) else inputs
203
- input_ids = input_ids.to(_device)
204
-
205
- gen_kwargs = dict(
206
- input_ids=input_ids,
207
  max_new_tokens=max_new_tokens,
208
- do_sample=temperature > 0.0,
209
- temperature=float(temperature),
210
  top_p=top_p,
211
- pad_token_id=_tokenizer.pad_token_id,
212
- eos_token_id=_tokenizer.eos_token_id,
213
- streamer=streamer,
214
  )
 
 
 
 
 
 
 
215
 
216
- thread = threading.Thread(target=_model.generate, kwargs=gen_kwargs)
217
- thread.start()
218
-
219
- analysis = ""
220
- output = ""
221
- for new_text in streamer:
222
- output += new_text
223
- if not analysis:
224
- m = ANALYSIS_PATTERN.match(output)
225
- if m:
226
- analysis = re.sub(r'^analysis\s*', '', m.group(1))
227
- output = ""
228
-
229
- if not analysis:
230
- analysis_text = re.sub(r'^analysis\s*', '', output)
231
- final_text = None
232
- else:
233
- analysis_text = analysis
234
- final_text = output
235
- elapsed = time.time() - start
236
- meta = f"Model: {MODEL_ID} | Time: {elapsed:.1f}s | max_new_tokens={max_new_tokens}"
237
- yield analysis_text or "(No analysis)", final_text or "(No answer)", meta
238
 
 
 
 
239
 
240
- # ----------------------------
241
- # UI
242
- # ----------------------------
243
 
244
- CUSTOM_CSS = "/** Pretty but simple **/\n:root { --radius: 14px; }\n.gradio-container { font-family: ui-sans-serif, system-ui, Inter, Roboto, Arial; }\n#hdr h1 { font-weight: 700; letter-spacing: -0.02em; }\ntextarea { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace; }\nfooter { display:none; }\n"
245
 
246
  with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
247
- with gr.Column(elem_id="hdr"):
248
- gr.Markdown("""
249
- # OpenAI gpt-oss-safeguard 20B
250
- Download [gpt-oss-safeguard-120b](https://huggingface.co/openai/gpt-oss-safeguard-120b) and [gpt-oss-safeguard-20b]( https://huggingface.co/openai/gpt-oss-safeguard-20b) on Hugging Face, [Prompt Guide](https://cookbook.openai.com/articles/gpt-oss-safeguard-guide), and [OpenAI Blog](https://openai.com/index/introducing-gpt-oss-safeguard/).
251
-
252
- Provide a **Policy** and a **Prompt**.
253
- """)
254
 
255
  with gr.Row():
256
- with gr.Column(scale=1, min_width=380):
257
- policy = gr.Textbox(
258
- label="Policy",
259
- lines=20, # bigger than prompt
260
- placeholder="Rules, tone, and constraints…",
261
- )
262
- prompt = gr.Textbox(
263
- label="Prompt",
264
- lines=5,
265
- placeholder="Your request…",
266
- )
267
  with gr.Accordion("Advanced settings", open=False):
268
  max_new_tokens = gr.Slider(16, 4096, value=DEFAULT_MAX_NEW_TOKENS, step=8, label="max_new_tokens")
269
  temperature = gr.Slider(0.0, 1.5, value=DEFAULT_TEMPERATURE, step=0.05, label="temperature")
270
  top_p = gr.Slider(0.0, 1.0, value=DEFAULT_TOP_P, step=0.01, label="top_p")
271
  repetition_penalty = gr.Slider(0.8, 2.0, value=DEFAULT_REPETITION_PENALTY, step=0.05, label="repetition_penalty")
272
- with gr.Row():
273
- btn = gr.Button("Generate", variant="primary")
274
- clr = gr.Button("Clear", variant="secondary")
275
- with gr.Column(scale=1, min_width=380):
276
- analysis = gr.Textbox(label="Analysis", lines=12)
277
- answer = gr.Textbox(label="Answer", lines=12)
278
  meta = gr.Markdown()
279
 
280
- btn.click(
281
- fn=generate_stream,
282
  inputs=[policy, prompt, max_new_tokens, temperature, top_p, repetition_penalty],
283
  outputs=[analysis, answer, meta],
284
  concurrency_limit=1,
285
  api_name="generate",
286
  )
287
 
288
- def _clear():
289
- return "", "", "", ""
290
-
291
- clr.click(_clear, outputs=[policy, prompt, analysis, answer])
292
-
293
- gr.Examples(
294
- examples=[
295
- [SAMPLE_POLICY, "Your bank details are needed to complete this transaction."],
296
- [SAMPLE_POLICY, "NOW IS THE TIME TO CUT THE CORD AND JOIN. Where else will you get THE BEST that TV can offer for HALF the price?"],
297
- [SAMPLE_POLICY, "I am SO tired of weight loss regiments not working --- it's been a lifetimes stuggle."],
298
- [SAMPLE_POLICY, "The value of gold has skyrocketed --- maybe it's time for you to get some? "],
299
- ],
300
- inputs=[policy, prompt],
301
- )
302
-
303
  if __name__ == "__main__":
304
  demo.queue(max_size=32).launch()
 
 
 
1
  import os
 
2
  import time
3
  from typing import List, Dict, Tuple
 
4
 
 
5
  import gradio as gr
6
+ from transformers import pipeline
7
+ import spaces
8
 
9
  # === Config (override via Space secrets/env vars) ===
10
+ MODEL_ID = os.environ.get("MODEL_ID", "openai/gpt-oss-20b")
11
+ STATIC_PROMPT = """"""
12
  DEFAULT_MAX_NEW_TOKENS = int(os.environ.get("MAX_NEW_TOKENS", 512))
13
+ DEFAULT_TEMPERATURE = float(os.environ.get("TEMPERATURE", 0.7))
14
+ DEFAULT_TOP_P = float(os.environ.get("TOP_P", 0.95))
15
  DEFAULT_REPETITION_PENALTY = float(os.environ.get("REPETITION_PENALTY", 1.0))
16
  ZGPU_DURATION = int(os.environ.get("ZGPU_DURATION", 120)) # seconds
17
 
18
+ _pipe = None # cached pipeline
19
+ _tok = None # tokenizer for parsing Harmony format
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
 
22
  def _to_messages(policy: str, user_prompt: str) -> List[Dict[str, str]]:
23
+ messages = []
24
  if policy.strip():
25
+ messages.append({"role": "system", "content": policy.strip()})
26
+ # if STATIC_PROMPT:
27
+ # messages.append({"role": "system", "content": STATIC_PROMPT})
28
+ messages.append({"role": "user", "content": user_prompt})
29
+ return messages
30
+
31
 
32
+ def _parse_harmony_output(last, tokenizer):
33
+ analysis, content = None, None
34
+ if isinstance(last, dict) and ("content" in last or "thinking" in last):
35
+ analysis = last.get("thinking")
36
+ content = last.get("content")
37
+ else:
38
+ parsed = tokenizer.parse_response(last)
39
+ analysis = parsed.get("thinking")
40
+ content = parsed.get("content")
41
+ return analysis, content
42
 
 
 
 
43
 
44
  @spaces.GPU(duration=ZGPU_DURATION)
45
+ def generate_long_prompt(
46
+ policy: str,
47
+ prompt: str,
48
+ max_new_tokens: int,
49
+ temperature: float,
50
+ top_p: float,
51
+ repetition_penalty: float,
52
  ) -> Tuple[str, str, str]:
53
+ global _pipe, _tok
54
  start = time.time()
55
 
56
+ if _pipe is None:
57
+ _pipe = pipeline(
58
+ task="text-generation",
59
+ model=MODEL_ID,
60
+ torch_dtype="auto",
61
+ device_map="auto",
62
+ )
63
+ _tok = _pipe.tokenizer
64
 
65
+ messages = _to_messages(policy, prompt)
 
 
 
 
66
 
67
+ outputs = _pipe(
68
  messages,
 
 
 
 
 
 
 
 
69
  max_new_tokens=max_new_tokens,
70
+ do_sample=True,
71
+ temperature=temperature,
72
  top_p=top_p,
73
+ repetition_penalty=repetition_penalty,
 
 
74
  )
75
+ print(outputs)
76
+ res = outputs[0]
77
+ print(res)
78
+ last = res.get("generated_text", [])
79
+ print(last)
80
+ if isinstance(last, list) and last:
81
+ last = last[-1]
82
 
83
+ analysis, content = _parse_harmony_output(last, _tok)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ elapsed = time.time() - start
86
+ meta = f"Model: {MODEL_ID} | Time: {elapsed:.1f}s | max_new_tokens={max_new_tokens}"
87
+ return analysis or "(No analysis)", content or "(No answer)", meta
88
 
 
 
 
89
 
90
+ CUSTOM_CSS = "/** Simple styling **/\n.gradio-container {font-family: ui-sans-serif, system-ui, Inter, Roboto;}\ntextarea {font-family: ui-monospace, monospace;}\nfooter {display:none;}"
91
 
92
  with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
93
+ gr.Markdown("""# GPT‑OSS Harmony Demo\nProvide a **Policy**, a **Prompt**, and see both **Analysis** and **Answer** separately.""")
 
 
 
 
 
 
94
 
95
  with gr.Row():
96
+ with gr.Column(scale=1):
97
+ policy = gr.Textbox(label="Policy (system)", lines=20, placeholder="Enter the guiding rules and tone…")
98
+ prompt = gr.Textbox(label="Prompt (user)", lines=10, placeholder="Enter your main prompt…")
 
 
 
 
 
 
 
 
99
  with gr.Accordion("Advanced settings", open=False):
100
  max_new_tokens = gr.Slider(16, 4096, value=DEFAULT_MAX_NEW_TOKENS, step=8, label="max_new_tokens")
101
  temperature = gr.Slider(0.0, 1.5, value=DEFAULT_TEMPERATURE, step=0.05, label="temperature")
102
  top_p = gr.Slider(0.0, 1.0, value=DEFAULT_TOP_P, step=0.01, label="top_p")
103
  repetition_penalty = gr.Slider(0.8, 2.0, value=DEFAULT_REPETITION_PENALTY, step=0.05, label="repetition_penalty")
104
+ generate = gr.Button("Generate", variant="primary")
105
+ with gr.Column(scale=1):
106
+ analysis = gr.Textbox(label="Analysis (Harmony thinking)", lines=10)
107
+ answer = gr.Textbox(label="Answer", lines=10)
 
 
108
  meta = gr.Markdown()
109
 
110
+ generate.click(
111
+ fn=generate_long_prompt,
112
  inputs=[policy, prompt, max_new_tokens, temperature, top_p, repetition_penalty],
113
  outputs=[analysis, answer, meta],
114
  concurrency_limit=1,
115
  api_name="generate",
116
  )
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  if __name__ == "__main__":
119
  demo.queue(max_size=32).launch()
requirements.txt CHANGED
@@ -1,4 +1,2 @@
1
  transformers
2
- accelerate
3
- triton
4
- kernels
 
1
  transformers
2
+ accelerate