File size: 6,980 Bytes
8df9fb2
 
 
 
628f881
5162902
8df9fb2
 
 
 
 
5162902
 
 
8df9fb2
 
 
 
 
1a468e6
8df9fb2
 
9f03894
 
 
8df9fb2
 
1a468e6
 
 
9f03894
 
 
 
1a468e6
 
 
 
8df9fb2
5162902
8df9fb2
5162902
 
8df9fb2
5162902
8df9fb2
5162902
 
 
 
 
1a468e6
5162902
 
 
 
8df9fb2
628f881
5162902
1a468e6
5162902
628f881
5162902
8df9fb2
 
 
 
 
 
 
 
5162902
8df9fb2
 
f371603
8df9fb2
 
 
5162902
8df9fb2
5162902
8df9fb2
5162902
8df9fb2
628f881
5162902
1a468e6
5162902
1a468e6
8df9fb2
5162902
 
8df9fb2
1a468e6
 
 
5162902
1a468e6
5162902
1a468e6
8df9fb2
 
5162902
8df9fb2
1a468e6
 
 
 
 
 
 
 
 
5162902
1a468e6
 
 
 
 
 
 
 
5162902
 
 
 
1a468e6
 
5162902
1a468e6
5162902
 
 
 
1a468e6
 
 
 
 
 
 
 
5162902
 
1a468e6
 
 
 
8df9fb2
5162902
 
 
 
 
 
 
1a468e6
 
 
5162902
1a468e6
 
 
5162902
 
 
 
 
 
1a468e6
8df9fb2
 
5162902
 
1a468e6
8df9fb2
 
 
5162902
 
 
 
 
 
 
 
8df9fb2
5162902
8df9fb2
 
1a468e6
 
 
 
 
 
 
8df9fb2
5162902
 
 
 
 
8df9fb2
 
5162902
 
 
 
 
 
8df9fb2
5162902
1a468e6
5162902
f371603
8df9fb2
 
 
 
5162902
 
1a468e6
8df9fb2
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import spaces
from monitoring import PerformanceMonitor, measure_time

# Model configurations
BASE_MODEL = "HuggingFaceTB/SmolLM2-1.7B-Instruct"  # Base model
ADAPTER_MODEL = "Joash2024/Math-SmolLM2-1.7B"       # Our LoRA adapter

# Initialize performance monitor
monitor = PerformanceMonitor()

print("Loading tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
tokenizer.pad_token = tokenizer.eos_token

print("Loading base model...")
base_model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    device_map="auto",
    torch_dtype=torch.float16,
    low_cpu_mem_usage=True,
    use_safetensors=True
)

print("Loading fine-tuned model...")
finetuned_model = PeftModel.from_pretrained(
    base_model, 
    ADAPTER_MODEL,
    torch_dtype=torch.float16,
    device_map="auto"
)

# Set models to eval mode
base_model.eval()
finetuned_model.eval()

def format_prompt(problem: str, problem_type: str) -> str:
    """Format input prompt for the model"""
    if problem_type == "Derivative":
        return f"""Given a mathematical function, find its derivative.

Function: {problem}
The derivative of this function is:"""
    elif problem_type == "Addition":
        return f"""Solve this addition problem.

Problem: {problem}
The solution is:"""
    else:  # Roots
        return f"""Find the roots of this equation.

Equation: {problem}
The roots are:"""

@spaces.GPU
@measure_time
def get_model_response(problem: str, problem_type: str, model) -> str:
    """Generate response from model"""
    # Format prompt
    prompt = format_prompt(problem, problem_type)
    
    # Tokenize
    inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    
    # Generate
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_length=100,
            num_return_sequences=1,
            temperature=0.1,
            do_sample=False,  # Deterministic generation
            pad_token_id=tokenizer.eos_token_id
        )
    
    # Decode and extract response
    generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
    response = generated[len(prompt):].strip()
    
    return response

@spaces.GPU
def solve_problem(problem: str, problem_type: str) -> tuple:
    """Solve math problem with both models"""
    if not problem:
        return "Please enter a problem", "Please enter a problem", None
    
    # Record problem type
    monitor.record_problem_type(problem_type)
    
    # Get responses from both models with timing
    base_response, base_time = get_model_response(problem, problem_type, base_model)
    finetuned_response, finetuned_time = get_model_response(problem, problem_type, finetuned_model)
    
    # Format outputs with steps
    if problem_type == "Derivative":
        base_output = f"""Generated derivative: {base_response}

Let's verify this step by step:
1. Starting with f(x) = {problem}
2. Applying differentiation rules
3. We get f'(x) = {base_response}"""

        finetuned_output = f"""Generated derivative: {finetuned_response}

Let's verify this step by step:
1. Starting with f(x) = {problem}
2. Applying differentiation rules
3. We get f'(x) = {finetuned_response}"""

    elif problem_type == "Addition":
        base_output = f"""Solution: {base_response}

Let's verify this step by step:
1. Starting with: {problem}
2. Adding the numbers
3. We get: {base_response}"""

        finetuned_output = f"""Solution: {finetuned_response}

Let's verify this step by step:
1. Starting with: {problem}
2. Adding the numbers
3. We get: {finetuned_response}"""

    else:  # Roots
        base_output = f"""Found roots: {base_response}

Let's verify this step by step:
1. Starting with equation: {problem}
2. Solving for x
3. Roots are: {base_response}"""

        finetuned_output = f"""Found roots: {finetuned_response}

Let's verify this step by step:
1. Starting with equation: {problem}
2. Solving for x
3. Roots are: {finetuned_response}"""
    
    # Record metrics
    monitor.record_response_time("base", base_time)
    monitor.record_response_time("finetuned", finetuned_time)
    monitor.record_success("base", not base_response.startswith("Error"))
    monitor.record_success("finetuned", not finetuned_response.startswith("Error"))
    
    # Get updated statistics
    stats = monitor.get_statistics()
    
    # Format statistics for display
    stats_display = f"""
### Performance Metrics

#### Response Times (seconds)
- Base Model: {stats.get('base_avg_response_time', 0):.2f} avg
- Fine-tuned Model: {stats.get('finetuned_avg_response_time', 0):.2f} avg

#### Success Rates
- Base Model: {stats.get('base_success_rate', 0):.1f}%
- Fine-tuned Model: {stats.get('finetuned_success_rate', 0):.1f}%

#### Problem Types Used
"""
    for ptype, percentage in stats.get('problem_type_distribution', {}).items():
        stats_display += f"- {ptype}: {percentage:.1f}%\n"
    
    return base_output, finetuned_output, stats_display

# Create Gradio interface
with gr.Blocks(title="Mathematics Problem Solver") as demo:
    gr.Markdown("# Mathematics Problem Solver")
    gr.Markdown("Compare solutions between base and fine-tuned models")
    
    with gr.Row():
        with gr.Column():
            problem_type = gr.Dropdown(
                choices=["Derivative", "Addition", "Roots"],
                value="Derivative",
                label="Problem Type"
            )
            problem_input = gr.Textbox(
                label="Enter your problem",
                placeholder="Example: x^2 + 3x"
            )
            solve_btn = gr.Button("Solve", variant="primary")
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("### Base Model")
            base_output = gr.Textbox(label="Base Model Solution", lines=6)
        
        with gr.Column():
            gr.Markdown("### Fine-tuned Model")
            finetuned_output = gr.Textbox(label="Fine-tuned Model Solution", lines=6)
    
    # Performance metrics display
    with gr.Row():
        metrics_display = gr.Markdown("### Performance Metrics\n*Solve a problem to see metrics*")
    
    # Example problems
    gr.Examples(
        examples=[
            ["x^2 + 3x", "Derivative"],
            ["235 + 567", "Addition"],
            ["x^2 - 4", "Roots"],
            ["\\sin{\\left(x\\right)}", "Derivative"],
            ["e^x", "Derivative"],
            ["\\frac{1}{x}", "Derivative"]
        ],
        inputs=[problem_input, problem_type],
        outputs=[base_output, finetuned_output, metrics_display],
        fn=solve_problem,
        cache_examples=False  # Disable caching
    )
    
    # Connect the interface
    solve_btn.click(
        fn=solve_problem,
        inputs=[problem_input, problem_type],
        outputs=[base_output, finetuned_output, metrics_display]
    )

if __name__ == "__main__":
    demo.launch()