SixOpen commited on
Commit
7e77ec2
·
verified ·
1 Parent(s): 2671c5a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ from transformers import TextIteratorStreamer, AutoModelForCausalLM, AutoTokenizer
3
+ from threading import Thread
4
+ import gradio as gr
5
+ import re
6
+ from openai_harmony import (
7
+ load_harmony_encoding,
8
+ HarmonyEncodingName,
9
+ Role,
10
+ Message,
11
+ Conversation,
12
+ SystemContent,
13
+ DeveloperContent,
14
+ ReasoningEffort,
15
+ )
16
+
17
+ RE_REASONING = re.compile(r'(?i)Reasoning:\s*(low|medium|high)')
18
+ RE_FINAL_MARKER = re.compile(r'(?i)assistantfinal')
19
+ RE_ANALYSIS_PREFIX = re.compile(r'(?i)^analysis\s*')
20
+
21
+ def parse_reasoning_and_instructions(system_prompt: str):
22
+ instructions = system_prompt or "You are a helpful assistant."
23
+ match = RE_REASONING.search(instructions)
24
+ effort_key = match.group(1).lower() if match else 'medium'
25
+ effort = {
26
+ 'low': ReasoningEffort.LOW,
27
+ 'medium': ReasoningEffort.MEDIUM,
28
+ 'high': ReasoningEffort.HIGH,
29
+ }.get(effort_key, ReasoningEffort.MEDIUM)
30
+ cleaned_instructions = RE_REASONING.sub('', instructions).strip()
31
+ return effort, cleaned_instructions
32
+
33
+ model_id = "ArliAI/gpt-oss-20b-Derestricted"
34
+
35
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
36
+ model = AutoModelForCausalLM.from_pretrained(
37
+ model_id,
38
+ torch_dtype="auto",
39
+ trust_remote_code=True,
40
+ device_map=None,
41
+ )
42
+
43
+ enc = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
44
+
45
+ def format_conversation_history(chat_history):
46
+ """Handle legacy/new format"""
47
+ messages = []
48
+ for item in chat_history:
49
+ if isinstance(item, dict):
50
+ role = item.get("role", "user")
51
+ content = item.get("content", "")
52
+ if isinstance(content, list):
53
+ content = content[0].get("text", str(content)) if content else ""
54
+ messages.append({"role": role, "content": content})
55
+ elif isinstance(item, (list, tuple)):
56
+ if item[0]:
57
+ messages.append({"role": "user", "content": item[0]})
58
+ if len(item) > 1 and item[1]:
59
+ messages.append({"role": "assistant", "content": item[1]})
60
+ return messages
61
+
62
+ @spaces.GPU(duration=120)
63
+ def generate_response(input_data, chat_history, max_new_tokens, system_prompt, temperature, top_p, top_k, repetition_penalty):
64
+ model.to('cuda')
65
+
66
+ new_message = {"role": "user", "content": input_data}
67
+ processed_history = format_conversation_history(chat_history)
68
+ effort, instructions = parse_reasoning_and_instructions(system_prompt)
69
+ system_content = SystemContent.new().with_reasoning_effort(effort)
70
+ developer_content = DeveloperContent.new().with_instructions(instructions)
71
+ harmony_messages = [
72
+ Message.from_role_and_content(Role.SYSTEM, system_content),
73
+ Message.from_role_and_content(Role.DEVELOPER, developer_content),
74
+ ]
75
+
76
+ for m in processed_history + [new_message]:
77
+ role = Role.USER if m["role"] == "user" else Role.ASSISTANT
78
+ harmony_messages.append(Message.from_role_and_content(role, m["content"]))
79
+ conversation = Conversation.from_messages(harmony_messages)
80
+ prompt_tokens = enc.render_conversation_for_completion(conversation, Role.ASSISTANT)
81
+ prompt_text = tokenizer.decode(prompt_tokens, skip_special_tokens=False)
82
+
83
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
84
+
85
+ inputs = tokenizer(prompt_text, return_tensors="pt").to('cuda')
86
+
87
+ generation_kwargs = {
88
+ "input_ids": inputs["input_ids"],
89
+ "attention_mask": inputs["attention_mask"],
90
+ "max_new_tokens": max_new_tokens,
91
+ "do_sample": True,
92
+ "temperature": temperature,
93
+ "top_p": top_p,
94
+ "top_k": top_k,
95
+ "repetition_penalty": repetition_penalty,
96
+ "streamer": streamer,
97
+ }
98
+
99
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
100
+ thread.start()
101
+
102
+ thinking = ""
103
+ final = ""
104
+ started_final = False
105
+ for chunk in streamer:
106
+ if not started_final:
107
+ parts = RE_FINAL_MARKER.split(chunk, maxsplit=1)
108
+ thinking += parts[0]
109
+ if len(parts) > 1:
110
+ final += parts[-1]
111
+ started_final = True
112
+ else:
113
+ final += chunk
114
+ clean_thinking = RE_ANALYSIS_PREFIX.sub('', thinking).strip()
115
+ clean_final = final.strip()
116
+ formatted = f"<details open><summary>Click to view Thinking Process</summary>\n\n{clean_thinking}\n\n</details>\n\n{clean_final}"
117
+ yield formatted
118
+
119
+ thread.join()
120
+
121
+ demo = gr.ChatInterface(
122
+ fn=generate_response,
123
+ additional_inputs=[
124
+ gr.Slider(label="Max new tokens", minimum=64, maximum=4096, step=1, value=2048),
125
+ gr.Textbox(
126
+ label="System Prompt",
127
+ value="You are a helpful assistant. Reasoning: medium",
128
+ lines=4,
129
+ placeholder="Change system prompt"
130
+ ),
131
+ gr.Slider(label="Temperature", minimum=0.1, maximum=2.0, step=0.1, value=0.7),
132
+ gr.Slider(label="Top-p", minimum=0.05, maximum=1.0, step=0.05, value=0.9),
133
+ gr.Slider(label="Top-k", minimum=1, maximum=100, step=1, value=50),
134
+ gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.0)
135
+ ],
136
+ examples=[
137
+ ["Explain Newton's laws clearly and concisely"],
138
+ ["What are the benefits of open weight AI models"],
139
+ ["Write a Python function to calculate the Fibonacci sequence"],
140
+ ],
141
+ cache_examples=False,
142
+ description="""# GPT-OSS 20B Derestricted.""",
143
+ fill_height=True,
144
+ stop_btn="Stop Generation",
145
+ )
146
+
147
+ if __name__ == "__main__":
148
+ demo.launch()