Files changed (3) hide show
  1. README.md +1 -1
  2. app.py +93 -243
  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,286 +1,132 @@
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
  )
@@ -288,14 +134,18 @@ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
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
  )
 
 
 
1
  import os
 
2
  import time
3
+ from typing import List, Dict
 
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", "tlhv/osb-minier")
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
 
20
 
21
  def _to_messages(policy: str, user_prompt: str) -> List[Dict[str, str]]:
22
+ """Combine policy (as system), static system prompt, and user prompt into a chat-like structure."""
23
+ messages: List[Dict[str, str]] = []
24
+ # The user-provided policy guides the model as a system message
25
+ if policy and policy.strip():
26
+ messages.append({"role": "system", "content": policy.strip()})
27
+ # if STATIC_PROMPT:
28
+ # messages.append({"role": "system", "content": STATIC_PROMPT})
29
+ messages.append({"role": "user", "content": user_prompt})
30
+ return messages
31
 
32
 
 
 
 
 
33
  @spaces.GPU(duration=ZGPU_DURATION)
34
+ def generate_long_prompt(
35
+ policy: str,
36
+ prompt: str,
37
+ max_new_tokens: int,
38
+ temperature: float,
39
+ top_p: float,
40
+ repetition_penalty: float,
41
+ ):
42
+ global _pipe
43
  start = time.time()
44
 
45
+ if _pipe is None:
46
+ _pipe = pipeline(
47
+ "text-generation",
48
+ model=MODEL_ID,
49
+ torch_dtype="auto",
50
+ device_map="auto",
51
+ )
52
 
53
+ messages = _to_messages(policy, prompt)
 
 
 
 
54
 
55
+ outputs = _pipe(
56
  messages,
 
 
 
 
 
 
 
 
57
  max_new_tokens=max_new_tokens,
58
+ do_sample=True,
59
+ temperature=temperature,
60
  top_p=top_p,
61
+ repetition_penalty=repetition_penalty,
 
 
62
  )
63
 
64
+ text = None
65
+ if isinstance(outputs, list) and outputs:
66
+ res = outputs[0]
67
+ if isinstance(res, dict):
68
+ gt = res.get("generated_text")
69
+ if isinstance(gt, list) and gt and isinstance(gt[-1], dict):
70
+ text = gt[-1].get("content") or gt[-1].get("text")
71
+ elif isinstance(gt, str):
72
+ text = gt
73
+ if text is None:
74
+ text = str(res)
75
+ else:
76
+ text = str(outputs)
 
 
 
 
 
 
 
 
 
77
 
78
+ elapsed = time.time() - start
79
+ meta = f"Model: {MODEL_ID} | Time: {elapsed:.1f}s | max_new_tokens={max_new_tokens}"
80
+ return text, meta
81
 
 
 
 
82
 
83
+ CUSTOM_CSS = "/** Simple, clean styling **/\n:root {\n --radius: 16px;\n}\n.gradio-container {\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Inter, 'Helvetica Neue', Arial, 'Apple Color Emoji', 'Segoe UI Emoji';\n}\n#header h1 {\n font-weight: 700;\n letter-spacing: -0.02em;\n}\n#header .subtitle {\n opacity: 0.75;\n font-size: 0.95rem;\n}\n.box {\n border: 1px solid rgba(0,0,0,0.08);\n border-radius: var(--radius);\n padding: 0.75rem;\n background: linear-gradient(180deg, rgba(255,255,255,0.9), rgba(250,250,250,0.9));\n}\ntextarea, .wrap textarea {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;\n}\nfooter { display:none; }\n"
84
 
85
  with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
86
+ with gr.Column(elem_id="header"):
87
  gr.Markdown("""
88
+ # Safety GPT‑OSS (ZeroGPU)
89
+ <div class="subtitle">Guide responses with a **Policy**, provide a **Prompt**, get the **Output** – simple and clean.</div>
 
 
90
  """)
91
 
92
  with gr.Row():
93
  with gr.Column(scale=1, min_width=380):
94
+ with gr.Group():
95
+ policy = gr.Textbox(
96
+ label="Policy (system)",
97
+ lines=22, # bigger than prompt
98
+ placeholder=(
99
+ "Describe the rules, tone, and constraints.\n"
100
+ "e.g., 'Be concise, follow safety policy X, refuse Y, cite sources when applicable.'"
101
+ ),
102
+ elem_id="wrap",
103
+ container=True,
104
+ )
105
+ with gr.Group():
106
+ prompt = gr.Textbox(
107
+ label="Prompt (user)",
108
+ lines=12,
109
+ placeholder="Enter your task/question here…",
110
+ elem_id="wrap",
111
+ container=True,
112
+ )
113
  with gr.Accordion("Advanced settings", open=False):
114
  max_new_tokens = gr.Slider(16, 4096, value=DEFAULT_MAX_NEW_TOKENS, step=8, label="max_new_tokens")
115
  temperature = gr.Slider(0.0, 1.5, value=DEFAULT_TEMPERATURE, step=0.05, label="temperature")
116
  top_p = gr.Slider(0.0, 1.0, value=DEFAULT_TOP_P, step=0.01, label="top_p")
117
  repetition_penalty = gr.Slider(0.8, 2.0, value=DEFAULT_REPETITION_PENALTY, step=0.05, label="repetition_penalty")
118
  with gr.Row():
119
+ generate = gr.Button("Generate", variant="primary", scale=1)
120
+ clear = gr.Button("Clear", variant="secondary", scale=0)
121
  with gr.Column(scale=1, min_width=380):
122
+ with gr.Group():
123
+ output = gr.Textbox(label="Output", lines=24)
124
  meta = gr.Markdown()
125
 
126
+ generate.click(
127
+ fn=generate_long_prompt,
128
  inputs=[policy, prompt, max_new_tokens, temperature, top_p, repetition_penalty],
129
+ outputs=[output, meta],
130
  concurrency_limit=1,
131
  api_name="generate",
132
  )
 
134
  def _clear():
135
  return "", "", "", ""
136
 
137
+ clear.click(_clear, outputs=[policy, prompt, output, meta])
138
 
139
  gr.Examples(
140
  examples=[
141
+ [
142
+ "You are a careful assistant. Refuse unsafe requests, be concise, and provide step-by-step reasoning internally only.",
143
+ "Summarize the following 3 pages of notes into a crisp plan of action…",
144
+ ],
145
+ [
146
+ "Be a friendly teacher. Explain concepts simply, give one illustrative example, and end with 3 bullet key takeaways.",
147
+ "Explain transformers and attention to a curious developer (about 300 words).",
148
+ ],
149
  ],
150
  inputs=[policy, prompt],
151
  )
requirements.txt CHANGED
@@ -1,4 +1,2 @@
1
  transformers
2
- accelerate
3
- triton
4
- kernels
 
1
  transformers
2
+ accelerate