Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -12,16 +12,6 @@ device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
|
12 |
phi4_model = AutoModelForCausalLM.from_pretrained(phi4_model_path, device_map="auto", torch_dtype="auto")
|
13 |
phi4_tokenizer = AutoTokenizer.from_pretrained(phi4_model_path)
|
14 |
|
15 |
-
# Function to process LaTeX in the output
|
16 |
-
def process_latex(text):
|
17 |
-
"""
|
18 |
-
Process LaTeX equations in text:
|
19 |
-
- Inline equations: $...$
|
20 |
-
- Block equations: $$...$$
|
21 |
-
"""
|
22 |
-
# No special processing needed as Gradio's markdown component supports LaTeX
|
23 |
-
return text
|
24 |
-
|
25 |
@spaces.GPU(duration=120)
|
26 |
def generate_response(user_message, max_tokens, temperature, top_k, top_p, repetition_penalty, history_state):
|
27 |
if not user_message.strip():
|
@@ -34,8 +24,19 @@ def generate_response(user_message, max_tokens, temperature, top_k, top_p, repet
|
|
34 |
sep_tag = "<|im_sep|>"
|
35 |
end_tag = "<|im_end|>"
|
36 |
|
37 |
-
#
|
38 |
-
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
prompt = f"{start_tag}system{sep_tag}{system_message}{end_tag}"
|
40 |
for message in history_state:
|
41 |
if message["role"] == "user":
|
@@ -46,8 +47,6 @@ def generate_response(user_message, max_tokens, temperature, top_k, top_p, repet
|
|
46 |
|
47 |
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
48 |
|
49 |
-
do_sample = not (temperature == 1.0 and top_k >= 100 and top_p == 1.0)
|
50 |
-
|
51 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
|
52 |
|
53 |
# sampling techniques
|
@@ -56,10 +55,10 @@ def generate_response(user_message, max_tokens, temperature, top_k, top_p, repet
|
|
56 |
"attention_mask": inputs["attention_mask"],
|
57 |
"max_new_tokens": int(max_tokens),
|
58 |
"do_sample": True,
|
59 |
-
"temperature":
|
60 |
"top_k": int(top_k),
|
61 |
-
"top_p":
|
62 |
-
"repetition_penalty": repetition_penalty,
|
63 |
"streamer": streamer,
|
64 |
}
|
65 |
|
@@ -72,39 +71,28 @@ def generate_response(user_message, max_tokens, temperature, top_k, top_p, repet
|
|
72 |
{"role": "user", "content": user_message},
|
73 |
{"role": "assistant", "content": ""}
|
74 |
]
|
|
|
75 |
for new_token in streamer:
|
76 |
cleaned_token = new_token.replace("<|im_start|>", "").replace("<|im_sep|>", "").replace("<|im_end|>", "")
|
77 |
assistant_response += cleaned_token
|
78 |
-
|
79 |
-
processed_response = process_latex(assistant_response.strip())
|
80 |
-
new_history[-1]["content"] = processed_response
|
81 |
yield new_history, new_history
|
82 |
|
83 |
yield new_history, new_history
|
84 |
|
|
|
85 |
example_messages = {
|
86 |
"Math reasoning": "If a rectangular prism has a length of 6 cm, a width of 4 cm, and a height of 5 cm, what is the length of the longest line segment that can be drawn from one vertex to another?",
|
87 |
"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?",
|
88 |
"Physics problem": "A ball is thrown upward with an initial velocity of 15 m/s from a height of 2 meters above the ground. Assuming the acceleration due to gravity is 9.8 m/s², determine: 1) The maximum height the ball reaches. 2) The total time the ball is in the air before hitting the ground. 3) The velocity with which the ball hits the ground.",
|
89 |
-
"
|
90 |
-
}
|
91 |
-
|
92 |
-
# Customize the Gradio CSS to enhance the LaTeX rendering
|
93 |
-
css = """
|
94 |
-
.math-container .katex {
|
95 |
-
font-size: 1.2em;
|
96 |
-
}
|
97 |
-
.math-block .katex {
|
98 |
-
font-size: 1.5em;
|
99 |
-
display: block;
|
100 |
-
margin: 1em 0;
|
101 |
}
|
102 |
-
"""
|
103 |
|
104 |
-
with gr.Blocks(theme=gr.themes.Soft()
|
105 |
gr.Markdown(
|
106 |
"""
|
107 |
-
#
|
|
|
108 |
"""
|
109 |
)
|
110 |
|
@@ -148,14 +136,14 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
|
148 |
)
|
149 |
|
150 |
with gr.Column(scale=4):
|
151 |
-
# Use
|
152 |
chatbot = gr.Chatbot(
|
153 |
label="Chat",
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
)
|
160 |
with gr.Row():
|
161 |
user_input = gr.Textbox(
|
@@ -170,7 +158,49 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
|
170 |
example1_button = gr.Button("Math reasoning")
|
171 |
example2_button = gr.Button("Logic puzzle")
|
172 |
example3_button = gr.Button("Physics problem")
|
173 |
-
example4_button = gr.Button("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
|
175 |
submit_button.click(
|
176 |
fn=generate_response,
|
@@ -204,7 +234,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
|
204 |
outputs=user_input
|
205 |
)
|
206 |
example4_button.click(
|
207 |
-
fn=lambda: gr.update(value=example_messages["
|
208 |
inputs=None,
|
209 |
outputs=user_input
|
210 |
)
|
|
|
12 |
phi4_model = AutoModelForCausalLM.from_pretrained(phi4_model_path, device_map="auto", torch_dtype="auto")
|
13 |
phi4_tokenizer = AutoTokenizer.from_pretrained(phi4_model_path)
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
@spaces.GPU(duration=120)
|
16 |
def generate_response(user_message, max_tokens, temperature, top_k, top_p, repetition_penalty, history_state):
|
17 |
if not user_message.strip():
|
|
|
24 |
sep_tag = "<|im_sep|>"
|
25 |
end_tag = "<|im_end|>"
|
26 |
|
27 |
+
# Add a prompt to encourage LaTeX usage for mathematical expressions
|
28 |
+
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.
|
29 |
+
|
30 |
+
Please structure your response into two main sections: Thought and Solution using the specified format: <think> {Thought section} </think> {Solution section}.
|
31 |
+
|
32 |
+
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.
|
33 |
+
|
34 |
+
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.
|
35 |
+
|
36 |
+
IMPORTANT: When expressing mathematical formulas or equations, always use LaTeX format. Use single dollar signs for inline equations (e.g., $x^2$) and double dollar signs for block equations (e.g., $$\\frac{a}{b}$$). Ensure all mathematical symbols, fractions, square roots, and complex expressions are properly formatted in LaTeX.
|
37 |
+
|
38 |
+
Now, try to solve the following question through the above guidelines:"""
|
39 |
+
|
40 |
prompt = f"{start_tag}system{sep_tag}{system_message}{end_tag}"
|
41 |
for message in history_state:
|
42 |
if message["role"] == "user":
|
|
|
47 |
|
48 |
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
49 |
|
|
|
|
|
50 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
|
51 |
|
52 |
# sampling techniques
|
|
|
55 |
"attention_mask": inputs["attention_mask"],
|
56 |
"max_new_tokens": int(max_tokens),
|
57 |
"do_sample": True,
|
58 |
+
"temperature": float(temperature),
|
59 |
"top_k": int(top_k),
|
60 |
+
"top_p": float(top_p),
|
61 |
+
"repetition_penalty": float(repetition_penalty),
|
62 |
"streamer": streamer,
|
63 |
}
|
64 |
|
|
|
71 |
{"role": "user", "content": user_message},
|
72 |
{"role": "assistant", "content": ""}
|
73 |
]
|
74 |
+
|
75 |
for new_token in streamer:
|
76 |
cleaned_token = new_token.replace("<|im_start|>", "").replace("<|im_sep|>", "").replace("<|im_end|>", "")
|
77 |
assistant_response += cleaned_token
|
78 |
+
new_history[-1]["content"] = assistant_response.strip()
|
|
|
|
|
79 |
yield new_history, new_history
|
80 |
|
81 |
yield new_history, new_history
|
82 |
|
83 |
+
# Add an example that explicitly shows LaTeX formatting
|
84 |
example_messages = {
|
85 |
"Math reasoning": "If a rectangular prism has a length of 6 cm, a width of 4 cm, and a height of 5 cm, what is the length of the longest line segment that can be drawn from one vertex to another?",
|
86 |
"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?",
|
87 |
"Physics problem": "A ball is thrown upward with an initial velocity of 15 m/s from a height of 2 meters above the ground. Assuming the acceleration due to gravity is 9.8 m/s², determine: 1) The maximum height the ball reaches. 2) The total time the ball is in the air before hitting the ground. 3) The velocity with which the ball hits the ground.",
|
88 |
+
"LaTeX example": "Solve the quadratic equation ax^2 + bx + c = 0 and explain the solution. Then calculate the roots of 2x^2 - 5x + 3 = 0."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
}
|
|
|
90 |
|
91 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
92 |
gr.Markdown(
|
93 |
"""
|
94 |
+
# Problem Solving with LaTeX Math Support
|
95 |
+
This application uses advanced reasoning to solve complex problems with LaTeX formatting for mathematical expressions.
|
96 |
"""
|
97 |
)
|
98 |
|
|
|
136 |
)
|
137 |
|
138 |
with gr.Column(scale=4):
|
139 |
+
# Use the markdown flag to ensure proper rendering of LaTeX
|
140 |
chatbot = gr.Chatbot(
|
141 |
label="Chat",
|
142 |
+
render_markdown=True,
|
143 |
+
elem_id="chatbot",
|
144 |
+
show_copy_button=True,
|
145 |
+
bubble_full_width=False,
|
146 |
+
avatar_images=(None, None)
|
147 |
)
|
148 |
with gr.Row():
|
149 |
user_input = gr.Textbox(
|
|
|
158 |
example1_button = gr.Button("Math reasoning")
|
159 |
example2_button = gr.Button("Logic puzzle")
|
160 |
example3_button = gr.Button("Physics problem")
|
161 |
+
example4_button = gr.Button("LaTeX example")
|
162 |
+
|
163 |
+
# Add custom JavaScript to ensure LaTeX rendering
|
164 |
+
demo.load(None, None, None, _js="""
|
165 |
+
function() {
|
166 |
+
// Check if MathJax is available
|
167 |
+
if (typeof window.MathJax === 'undefined') {
|
168 |
+
// Load MathJax if not available
|
169 |
+
const script = document.createElement('script');
|
170 |
+
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML';
|
171 |
+
script.async = true;
|
172 |
+
document.head.appendChild(script);
|
173 |
+
|
174 |
+
// Configure MathJax
|
175 |
+
window.MathJax = {
|
176 |
+
tex2jax: {
|
177 |
+
inlineMath: [['$', '$']],
|
178 |
+
displayMath: [['$$', '$$']],
|
179 |
+
processEscapes: true
|
180 |
+
},
|
181 |
+
showProcessingMessages: false,
|
182 |
+
messageStyle: 'none'
|
183 |
+
};
|
184 |
+
}
|
185 |
+
|
186 |
+
// Function to render LaTeX in the chatbot
|
187 |
+
function renderMathInChatbot() {
|
188 |
+
if (window.MathJax && window.MathJax.Hub) {
|
189 |
+
window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, document.getElementById('chatbot')]);
|
190 |
+
}
|
191 |
+
}
|
192 |
+
|
193 |
+
// Set up a mutation observer to detect changes in the chatbot
|
194 |
+
const observer = new MutationObserver(renderMathInChatbot);
|
195 |
+
const chatbot = document.getElementById('chatbot');
|
196 |
+
if (chatbot) {
|
197 |
+
observer.observe(chatbot, { childList: true, subtree: true });
|
198 |
+
}
|
199 |
+
|
200 |
+
// Initial render
|
201 |
+
renderMathInChatbot();
|
202 |
+
}
|
203 |
+
""")
|
204 |
|
205 |
submit_button.click(
|
206 |
fn=generate_response,
|
|
|
234 |
outputs=user_input
|
235 |
)
|
236 |
example4_button.click(
|
237 |
+
fn=lambda: gr.update(value=example_messages["LaTeX example"]),
|
238 |
inputs=None,
|
239 |
outputs=user_input
|
240 |
)
|