chegde commited on
Commit
9e21282
·
verified ·
1 Parent(s): e5f147f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -161
app.py CHANGED
@@ -8,173 +8,68 @@ veri_model_path = "nyu-dice-lab/VeriThoughts-Reasoning-7B"
8
 
9
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
10
 
11
- veri_model = AutoModelForCausalLM.from_pretrained(veri_model_path, device_map="auto", torch_dtype="auto")
12
- veri_tokenizer = AutoTokenizer.from_pretrained(veri_model_path)
 
 
 
 
 
 
13
 
14
  @spaces.GPU(duration=60)
15
- def generate_response(user_message, max_tokens, temperature, top_k, top_p, repetition_penalty, history_state):
 
 
 
16
  if not user_message.strip():
17
- return history_state, history_state
18
 
19
- # model settings
20
- model = veri_model
21
- tokenizer = veri_tokenizer
22
- start_tag = "<|im_start|>"
23
- sep_tag = "<|im_sep|>"
24
- end_tag = "<|im_end|>"
25
-
26
- # Recommended prompt settings by Qwen
27
- system_message = "Your role as an assistant involves thoroughly exploring questions through a systematic thinking process before providing the final precise and accurate solutions. This requires engaging in a comprehensive cycle of analysis, summarizing, exploration, reassessment, reflection, backtracing, and iteration to develop well-considered thinking process. Please structure your response into two main sections: Thought and Solution using the specified format: <think> {Thought section} </think> {Solution section}. In the Thought section, detail your reasoning process in steps. Each step should include detailed considerations such as analysing questions, summarizing relevant findings, brainstorming new ideas, verifying the accuracy of the current steps, refining any errors, and revisiting previous steps. In the Solution section, based on various attempts, explorations, and reflections from the Thought section, systematically present the final solution that you deem correct. The Solution section should be logical, accurate, and concise and detail necessary steps needed to reach the conclusion. Now, try to solve the following question through the above guidelines:"
28
- prompt = f"{start_tag}system{sep_tag}{system_message}{end_tag}"
29
- for message in history_state:
30
- if message["role"] == "user":
31
- prompt += f"{start_tag}user{sep_tag}{message['content']}{end_tag}"
32
- elif message["role"] == "assistant" and message["content"]:
33
- prompt += f"{start_tag}assistant{sep_tag}{message['content']}{end_tag}"
34
- prompt += f"{start_tag}user{sep_tag}{user_message}{end_tag}{start_tag}assistant{sep_tag}"
35
-
36
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
37
-
38
- do_sample = not (temperature == 1.0 and top_k >= 100 and top_p == 1.0)
39
-
40
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
41
-
42
- # sampling techniques
43
- generation_kwargs = {
44
- "input_ids": inputs["input_ids"],
45
- "attention_mask": inputs["attention_mask"],
46
- "max_new_tokens": int(max_tokens),
47
- "do_sample": True,
48
- "temperature": 0.8,
49
- "top_k": int(top_k),
50
- "top_p": 0.95,
51
- "repetition_penalty": repetition_penalty,
52
- "streamer": streamer,
53
- }
54
-
55
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
56
- thread.start()
57
-
58
- # Stream the response
59
- assistant_response = ""
60
- new_history = history_state + [
61
- {"role": "user", "content": user_message},
62
- {"role": "assistant", "content": ""}
63
- ]
64
- for new_token in streamer:
65
- cleaned_token = new_token.replace("<|im_start|>", "").replace("<|im_sep|>", "").replace("<|im_end|>", "")
66
- assistant_response += cleaned_token
67
- new_history[-1]["content"] = assistant_response.strip()
68
- yield new_history, new_history
69
-
70
- yield new_history, new_history
71
-
72
- # Fixed: Match the keys with your button labels
73
- example_messages = {
74
- "Math reasoning": "Calculate the sum of the first 10 prime numbers and explain your reasoning step by step.",
75
- "Logic puzzle": "Four people (Alex, Blake, Casey, and Dana) each have a different favorite color (red, blue, green, yellow) and a different favorite fruit (apple, banana, cherry, date). Given the following clues: 1) The person who likes red doesn't like dates. 2) Alex likes yellow. 3) The person who likes blue likes cherries. 4) Blake doesn't like apples or bananas. 5) Casey doesn't like yellow or green. Who likes what color and what fruit?",
76
- "Verilog example": "Design a 4-bit adder circuit in Verilog with proper test benches."
77
- }
78
-
79
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
80
- gr.Markdown(
81
- """
82
- # VeriThoughts-7B Chatbot
83
- Welcome to VeriThoughts-7B! This is a reasoning model for Verilog code generation.
84
-
85
- The model will provide responses with two sections:
86
- 1. **<think>**: A detailed step-by-step reasoning process showing its work
87
- 2. **Solution**: A concise, accurate final answer based on the reasoning
88
-
89
- """
90
- )
91
 
92
- history_state = gr.State([])
93
-
94
- with gr.Row():
95
- with gr.Column(scale=1):
96
- gr.Markdown("### Settings")
97
- max_tokens_slider = gr.Slider(
98
- minimum=64,
99
- maximum=32768,
100
- step=1024,
101
- value=4096,
102
- label="Max Tokens"
103
- )
104
- with gr.Accordion("Advanced Settings", open=False):
105
- temperature_slider = gr.Slider(
106
- minimum=0.1,
107
- maximum=2.0,
108
- value=0.8,
109
- label="Temperature"
110
- )
111
- top_k_slider = gr.Slider(
112
- minimum=1,
113
- maximum=100,
114
- step=1,
115
- value=50,
116
- label="Top-k"
117
- )
118
- top_p_slider = gr.Slider(
119
- minimum=0.1,
120
- maximum=1.0,
121
- value=0.95,
122
- label="Top-p"
123
- )
124
- repetition_penalty_slider = gr.Slider(
125
- minimum=1.0,
126
- maximum=2.0,
127
- value=1.0,
128
- label="Repetition Penalty"
129
- )
130
-
131
- with gr.Column(scale=4):
132
- chatbot = gr.Chatbot(label="Chat", type="messages")
133
- with gr.Row():
134
- user_input = gr.Textbox(
135
- label="Your message",
136
- placeholder="Type your message here...",
137
- scale=3
138
- )
139
- submit_button = gr.Button("Send", variant="primary", scale=1)
140
- clear_button = gr.Button("Clear", scale=1)
141
- gr.Markdown("**Try these examples:**")
142
- with gr.Row():
143
- example1_button = gr.Button("Math reasoning")
144
- example2_button = gr.Button("Logic puzzle")
145
- example3_button = gr.Button("Verilog example")
146
 
147
- submit_button.click(
148
- fn=generate_response,
149
- inputs=[user_input, max_tokens_slider, temperature_slider, top_k_slider, top_p_slider, repetition_penalty_slider, history_state],
150
- outputs=[chatbot, history_state]
 
 
 
 
 
 
 
 
 
151
  ).then(
152
- fn=lambda: gr.update(value=""),
153
- inputs=None,
154
- outputs=user_input
155
- )
156
-
157
- clear_button.click(
158
- fn=lambda: ([], []),
159
- inputs=None,
160
- outputs=[chatbot, history_state]
161
- )
162
-
163
- # Fixed: Now these will work without KeyError
164
- example1_button.click(
165
- fn=lambda: gr.update(value=example_messages["Math reasoning"]),
166
- inputs=None,
167
- outputs=user_input
168
- )
169
- example2_button.click(
170
- fn=lambda: gr.update(value=example_messages["Logic puzzle"]),
171
- inputs=None,
172
- outputs=user_input
173
- )
174
- example3_button.click(
175
- fn=lambda: gr.update(value=example_messages["Verilog example"]),
176
- inputs=None,
177
- outputs=user_input
178
  )
 
 
179
 
180
- demo.launch(ssr_mode=False, share=True)
 
 
8
 
9
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
10
 
11
+ # Try loading the model with explicit error handling
12
+ try:
13
+ veri_model = AutoModelForCausalLM.from_pretrained(veri_model_path, device_map="auto", torch_dtype="auto")
14
+ veri_tokenizer = AutoTokenizer.from_pretrained(veri_model_path)
15
+ except Exception as e:
16
+ print(f"Model loading error: {e}")
17
+ veri_model = None
18
+ veri_tokenizer = None
19
 
20
  @spaces.GPU(duration=60)
21
+ def generate_response(user_message, history):
22
+ if not veri_model or not veri_tokenizer:
23
+ return history + [["Error", "Model not loaded properly"]]
24
+
25
  if not user_message.strip():
26
+ return history
27
 
28
+ # Simple generation without streaming first
29
+ system_message = "You are a helpful assistant that thinks step by step."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # Create conversation history
32
+ conversation = f"System: {system_message}\n"
33
+ for h in history:
34
+ conversation += f"User: {h[0]}\nAssistant: {h[1]}\n"
35
+ conversation += f"User: {user_message}\nAssistant:"
36
+
37
+ inputs = veri_tokenizer(conversation, return_tensors="pt", truncation=True, max_length=2048).to(device)
38
+
39
+ with torch.no_grad():
40
+ outputs = veri_model.generate(
41
+ **inputs,
42
+ max_new_tokens=512,
43
+ temperature=0.8,
44
+ do_sample=True,
45
+ pad_token_id=veri_tokenizer.eos_token_id
46
+ )
47
+
48
+ response = veri_tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
49
+
50
+ # Return updated history
51
+ return history + [[user_message, response.strip()]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ # Create minimal interface
54
+ with gr.Blocks(title="VeriThoughts-7B Chatbot") as demo:
55
+ gr.Markdown("# VeriThoughts-7B Chatbot")
56
+
57
+ chatbot = gr.Chatbot(value=[], label="Chat")
58
+ msg = gr.Textbox(label="Your message", placeholder="Type here...")
59
+ clear = gr.Button("Clear")
60
+
61
+ # Simple event handling
62
+ msg.submit(
63
+ fn=generate_response,
64
+ inputs=[msg, chatbot],
65
+ outputs=chatbot
66
  ).then(
67
+ lambda: "",
68
+ inputs=None,
69
+ outputs=msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  )
71
+
72
+ clear.click(lambda: [], outputs=chatbot)
73
 
74
+ # Launch without ssr_mode parameter which might cause issues
75
+ demo.launch()