TuringsSolutions commited on
Commit
0715009
·
verified ·
1 Parent(s): 1de0a44

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +302 -0
app.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import random
5
+ import time
6
+ from huggingface_hub import InferenceClient
7
+ import google.generativeai as genai
8
+
9
+ # --- Helper Functions ---
10
+
11
+ def log_message(message, type='info'):
12
+ """Helper to format log messages with a timestamp."""
13
+ timestamp = time.strftime("%H:%M:%S")
14
+ return f"[{timestamp}] {message}"
15
+
16
+ # --- Core GEPA Functions (Python Implementation) ---
17
+
18
+ def run_huggingface_rollout(client, model_id, prompt, input_text):
19
+ """
20
+ Calls the Hugging Face Inference API for the target model (e.g., Gemma).
21
+ This function performs a "rollout" for a given prompt and input.
22
+ """
23
+ full_prompt = f"<start_of_turn>user\n{prompt}\n\nText: \"{input_text}\"<end_of_turn>\n<start_of_turn>model\n"
24
+ try:
25
+ response = client.text_generation(
26
+ model=model_id,
27
+ prompt=full_prompt,
28
+ max_new_tokens=100,
29
+ do_sample=True,
30
+ temperature=0.7,
31
+ top_p=0.95
32
+ )
33
+ return response
34
+ except Exception as e:
35
+ # Provide a more specific error message for common issues
36
+ if "authorization" in str(e).lower():
37
+ raise gr.Error("Hugging Face API Error: Authorization failed. Please check your HF Token.")
38
+ if "not found" in str(e).lower():
39
+ raise gr.Error(f"Hugging Face API Error: Model '{model_id}' not found or requires a Pro subscription.")
40
+ raise gr.Error(f"Hugging Face API Error: {str(e)}")
41
+
42
+
43
+ def evaluation_and_feedback_function(output, task):
44
+ """
45
+ The evaluation function (μ_f in the paper).
46
+ This function scores the model's output and provides textual feedback.
47
+ IMPORTANT: This is the most critical part to customize for a specific task.
48
+ """
49
+ # --- CUSTOMIZE THIS FUNCTION ---
50
+ # This example checks for keyword presence. For a real task, you might use
51
+ # regex, semantic similarity, code compilation, etc.
52
+ score = 0.0
53
+ feedback = ""
54
+ found_keywords = 0
55
+ expected_keywords = task.get("expected_keywords", [])
56
+
57
+ if not expected_keywords:
58
+ return {
59
+ "score": 0.0,
60
+ "feedback": "No evaluation criteria (expected_keywords) found in training data for this task."
61
+ }
62
+
63
+ for keyword in expected_keywords:
64
+ if keyword.lower() in output.lower():
65
+ found_keywords += 1
66
+ feedback += f"SUCCESS: Output correctly contained the keyword '{keyword}'.\n"
67
+ else:
68
+ feedback += f"FAILURE: Output was missing the required keyword '{keyword}'.\n"
69
+
70
+ score = found_keywords / len(expected_keywords)
71
+ feedback += f"Final Score for this task: {score:.2f}"
72
+ return {"score": score, "feedback": feedback}
73
+ # --- END CUSTOMIZATION ---
74
+
75
+
76
+ def reflect_and_propose_new_prompt(gemini_model, current_prompt, examples):
77
+ """
78
+ Performs the Reflective Prompt Mutation step using a powerful LLM (Gemini).
79
+ """
80
+ reflection_prompt = f"""You are an expert prompt engineer. Your task is to refine a prompt to improve its performance based on feedback from previous attempts.
81
+
82
+ Here is the current prompt that needs improvement:
83
+ --- CURRENT PROMPT ---
84
+ {currentPrompt}
85
+ --------------------
86
+
87
+ Here are examples of how the prompt performed on a few tasks, along with feedback on what went wrong or right:
88
+ --- EXAMPLES & FEEDBACK ---
89
+ {'---'.join(f'Task Input: "{e["input"]}"\nGenerated Output: "{e["output"]}"\nFeedback:\n{e["feedback"]}\n\n' for e in examples)}
90
+ -------------------------
91
+
92
+ Based on this analysis, your task is to write a new, improved prompt. The new prompt should be a complete set of instructions that directly addresses the failures and incorporates the successful strategies observed in the feedback. Do not just give suggestions; provide the full, ready-to-use prompt.
93
+ Your response should ONLY contain the new prompt text, and nothing else."""
94
+
95
+ try:
96
+ response = gemini_model.generate_content(reflection_prompt)
97
+ return response.text.strip()
98
+ except Exception as e:
99
+ raise gr.Error(f"Gemini API Error: {str(e)}. Check your Gemini API Key.")
100
+
101
+
102
+ def select_candidate_for_mutation(candidate_pool, num_tasks):
103
+ """
104
+ Selects the next candidate to mutate based on the Pareto-based strategy.
105
+ This simplified version gives higher probability to candidates that are best at any single task.
106
+ """
107
+ if len(candidate_pool) == 1:
108
+ return candidate_pool[0]
109
+
110
+ best_scores_per_task = [-1] * num_tasks
111
+ for candidate in candidate_pool:
112
+ for i in range(num_tasks):
113
+ if candidate["scores"][i] > best_scores_per_task[i]:
114
+ best_scores_per_task[i] = candidate["scores"][i]
115
+
116
+ pareto_front_ids = set()
117
+ for i in range(num_tasks):
118
+ for candidate in candidate_pool:
119
+ # Use a small tolerance for float comparison
120
+ if abs(candidate["scores"][i] - best_scores_per_task[i]) < 1e-6:
121
+ pareto_front_ids.add(candidate["id"])
122
+
123
+ if not pareto_front_ids: # Fallback to best overall if pareto is empty
124
+ return max(candidate_pool, key=lambda c: c["avg_score"])
125
+
126
+ selected_id = random.choice(list(pareto_front_ids))
127
+ return next(c for c in candidate_pool if c["id"] == selected_id)
128
+
129
+
130
+ # --- Main Gradio Application Logic ---
131
+
132
+ def run_gepa_optimization(hf_token, gemini_key, model_id, seed_prompt, training_data_str, budget):
133
+ """
134
+ The main function that orchestrates the GEPA optimization process.
135
+ This is a generator function that yields updates to the Gradio UI.
136
+ """
137
+ # --- Validate Inputs ---
138
+ if not hf_token:
139
+ raise gr.Error("Hugging Face API Token is required.")
140
+ if not gemini_key:
141
+ raise gr.Error("Google Gemini API Key is required for the reflection step.")
142
+ try:
143
+ training_data = json.loads(training_data_str)
144
+ if not isinstance(training_data, list) or not all(isinstance(item, dict) for item in training_data):
145
+ raise ValueError()
146
+ except (json.JSONDecodeError, ValueError):
147
+ raise gr.Error("Training Data is not valid JSON. It should be a list of objects.")
148
+
149
+ # --- Initialization ---
150
+ log_history = []
151
+ hf_client = InferenceClient(token=hf_token)
152
+ genai.configure(api_key=gemini_key)
153
+ gemini_model = genai.GenerativeModel('gemini-1.5-flash') # Using Flash for speed/cost
154
+
155
+ rollout_count = 0
156
+ candidate_pool = []
157
+ best_candidate = None
158
+
159
+ # --- Initial Evaluation of Seed Prompt ---
160
+ log_history.append(log_message("Initializing with seed prompt..."))
161
+ yield {"log": "\n".join(log_history), "best_prompt": "Initializing...", "best_score": "0.00"}
162
+
163
+ initial_candidate = {"id": 0, "prompt": seed_prompt, "parentId": None, "scores": [0.0] * len(training_data), "avg_score": 0.0}
164
+ total_score = 0.0
165
+ for i, task in enumerate(training_data):
166
+ log_history.append(log_message(f" - Evaluating seed on task {i+1}..."))
167
+ yield {"log": "\n".join(log_history)}
168
+ output = run_huggingface_rollout(hf_client, model_id, initial_candidate["prompt"], task["input"])
169
+ eval_result = evaluation_and_feedback_function(output, task)
170
+ initial_candidate["scores"][i] = eval_result["score"]
171
+ total_score += eval_result["score"]
172
+ rollout_count += 1
173
+
174
+ initial_candidate["avg_score"] = total_score / len(training_data)
175
+ candidate_pool.append(initial_candidate)
176
+ best_candidate = initial_candidate
177
+
178
+ log_history.append(log_message(f"Seed prompt initial score: {initial_candidate['avg_score']:.2f}", 'best'))
179
+ yield {
180
+ "log": "\n".join(log_history),
181
+ "best_prompt": best_candidate["prompt"],
182
+ "best_score": f"{best_candidate['avg_score']:.2f}"
183
+ }
184
+
185
+ # --- Main Optimization Loop ---
186
+ while rollout_count < budget:
187
+ log_history.append(log_message(f"--- Iteration Start (Rollouts: {rollout_count}/{budget}) ---"))
188
+ yield {"log": "\n".join(log_history)}
189
+
190
+ # a. Select a candidate to mutate
191
+ parent_candidate = select_candidate_for_mutation(candidate_pool, len(training_data))
192
+ log_history.append(log_message(f"Selected candidate #{parent_candidate['id']} (Score: {parent_candidate['avg_score']:.2f}) for mutation."))
193
+ yield {"log": "\n".join(log_history)}
194
+
195
+ # b. Perform reflective mutation
196
+ task_index = random.randint(0, len(training_data) - 1)
197
+ reflection_task = training_data[task_index]
198
+ log_history.append(log_message(f"Performing reflective mutation using task {task_index + 1}..."))
199
+ yield {"log": "\n".join(log_history)}
200
+
201
+ rollout_output = run_huggingface_rollout(hf_client, model_id, parent_candidate["prompt"], reflection_task["input"])
202
+ rollout_count += 1
203
+ eval_result = evaluation_and_feedback_function(rollout_output, reflection_task)
204
+
205
+ new_prompt = reflect_and_propose_new_prompt(gemini_model, parent_candidate["prompt"], [{
206
+ "input": reflection_task["input"],
207
+ "output": rollout_output,
208
+ "feedback": eval_result["feedback"]
209
+ }])
210
+
211
+ new_candidate = {"id": len(candidate_pool), "prompt": new_prompt, "parentId": parent_candidate["id"], "scores": [0.0] * len(training_data), "avg_score": 0.0}
212
+ log_history.append(log_message(f"Generated new candidate prompt #{new_candidate['id']}."))
213
+ yield {"log": "\n".join(log_history)}
214
+
215
+ # c. Evaluate the new candidate
216
+ new_total_score = 0.0
217
+ for i, task in enumerate(training_data):
218
+ if rollout_count >= budget: break
219
+ output = run_huggingface_rollout(hf_client, model_id, new_candidate["prompt"], task["input"])
220
+ eval_result = evaluation_and_feedback_function(output, task)
221
+ new_candidate["scores"][i] = eval_result["score"]
222
+ new_total_score += eval_result["score"]
223
+ rollout_count += 1
224
+ new_candidate["avg_score"] = new_total_score / len(training_data) if len(training_data) > 0 else 0.0
225
+
226
+ # d. Add to pool if it's a promising candidate
227
+ if new_candidate["avg_score"] > parent_candidate["avg_score"]:
228
+ log_history.append(log_message(f"New candidate #{new_candidate['id']} improved! Score: {new_candidate['avg_score']:.2f} > {parent_candidate['avg_score']:.2f}", 'success'))
229
+ candidate_pool.push(new_candidate)
230
+ if new_candidate["avg_score"] > best_candidate["avg_score"]:
231
+ best_candidate = new_candidate
232
+ log_history.append(log_message("--- NEW BEST PROMPT FOUND! ---", 'best'))
233
+ yield {
234
+ "log": "\n".join(log_history),
235
+ "best_prompt": best_candidate["prompt"],
236
+ "best_score": f"{best_candidate['avg_score']:.2f}"
237
+ }
238
+ else:
239
+ log_history.append(log_message(f"New candidate #{new_candidate['id']} did not improve. Score: {new_candidate['avg_score']:.2f}. Discarding.", 'fail'))
240
+
241
+ yield {"log": "\n".join(log_history)}
242
+
243
+ log_history.append(log_message("Optimization budget exhausted. Finished.", 'best'))
244
+ yield {"log": "\n".join(log_history)}
245
+
246
+
247
+ # --- Gradio Interface Definition ---
248
+ with gr.Blocks(theme=gr.themes.Soft(), title="GEPA Prompt Optimizer") as demo:
249
+ gr.Markdown("""
250
+ # GEPA Prompt Optimizer for Hugging Face Models
251
+ This Space implements the **GEPA (Genetic-Pareto)** framework to automatically optimize prompts for a target model (like Gemma) hosted on Hugging Face.
252
+ It uses a powerful LLM (Gemini) for the "reflection" step to propose high-quality prompt improvements.
253
+ """)
254
+
255
+ with gr.Row():
256
+ with gr.Column(scale=1):
257
+ gr.Markdown("## 1. Configuration")
258
+ hf_token_input = gr.Textbox(label="Hugging Face API Token", type="password", info="Your HF token with write access.")
259
+ gemini_key_input = gr.Textbox(label="Google Gemini API Key", type="password", info="Get this from Google AI Studio.")
260
+ model_id_input = gr.Textbox(label="Target Model ID", value="google/gemma-2b-it", info="The Hugging Face model to optimize for.")
261
+ seed_prompt_input = gr.Textbox(label="Initial Seed Prompt", lines=5, value="You are a helpful assistant that summarizes text. Given the following text, provide a one-sentence summary.")
262
+ training_data_input = gr.Code(
263
+ label="Training Data (JSON)",
264
+ language="json",
265
+ lines=10,
266
+ value="""[
267
+ {
268
+ "input": "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It is named after the engineer Gustave Eiffel, whose company designed and built the tower.",
269
+ "expected_keywords": ["Eiffel Tower", "Paris"]
270
+ },
271
+ {
272
+ "input": "The Great Wall of China is a series of fortifications that were built across the historical northern borders of ancient Chinese states and Imperial China as protection against various nomadic groups from the Eurasian Steppe.",
273
+ "expected_keywords": ["Great Wall", "China", "fortifications"]
274
+ },
275
+ {
276
+ "input": "The Colosseum is an oval amphitheatre in the centre of the city of Rome, Italy, just east of the Roman Forum. It is the largest ancient amphitheatre ever built, and is still the largest standing amphitheatre in the world today, despite its age.",
277
+ "expected_keywords": ["Colosseum", "Rome", "amphitheatre"]
278
+ }
279
+ ]"""
280
+ )
281
+ budget_input = gr.Slider(label="Optimization Budget (Total Rollouts)", minimum=5, maximum=100, value=10, step=1)
282
+ start_button = gr.Button("Start Optimization", variant="primary")
283
+
284
+ with gr.Column(scale=1):
285
+ gr.Markdown("## 2. Results")
286
+ best_prompt_output = gr.Textbox(label="Best Prompt Found", lines=8, interactive=False)
287
+ best_score_output = gr.Textbox(label="Best Score", interactive=False)
288
+ log_output = gr.Textbox(label="Optimization Log", lines=20, interactive=False)
289
+
290
+ # Connect the button to the main function
291
+ start_button.click(
292
+ fn=run_gepa_optimization,
293
+ inputs=[hf_token_input, gemini_key_input, model_id_input, seed_prompt_input, training_data_input, budget_input],
294
+ outputs={
295
+ "log": log_output,
296
+ "best_prompt": best_prompt_output,
297
+ "best_score": best_score_output
298
+ }
299
+ )
300
+
301
+ if __name__ == "__main__":
302
+ demo.launch()