Spaces:
Sleeping
Sleeping
File size: 24,812 Bytes
cacd4d0 74d4bea cacd4d0 c0b1bdf cacd4d0 74d4bea cacd4d0 74d4bea cacd4d0 c0b1bdf cacd4d0 | 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 | """
Pareto Front Logger - Tracks candidate comparisons and Pareto front updates
"""
from typing import Dict, List, Optional
from collections import defaultdict
import logging
logger = logging.getLogger(__name__)
class ParetoLogger:
"""Tracks evaluations and Pareto front updates"""
def __init__(self):
self.candidates_evaluated = [] # List of (prompt, score, type, dataset)
self.pareto_front = [] # Current Pareto front (prompt, score, type)
self.baseline_score = None
def log_candidate_evaluation(self, prompt: str, score: float, candidate_type: str, dataset_type: str):
"""Log a candidate evaluation"""
self.candidates_evaluated.append({
'prompt': prompt,
'score': score,
'type': candidate_type,
'dataset': dataset_type
})
# If evaluated on Dpareto, check against Pareto front
if dataset_type == 'dpareto':
self._check_pareto_update(prompt, score, candidate_type)
def _check_pareto_update(self, prompt: str, score: float, candidate_type: str):
"""Check if candidate should be added to Pareto front
π₯ CRITICAL RULE: Candidate must be better than baseline (f(Sβ)) to enter Pareto front
Exception: Seed prompt (Sβ) itself is always added as baseline
"""
# Get notation for candidate with better mapping
if candidate_type == 'gepa_reflection':
cand_notation = 'Sα΅£'
elif candidate_type == 'llego_crossover' or candidate_type == 'llego_crossover1' or candidate_type == 'llego_crossover2':
cand_notation = 'Oββ'
elif candidate_type == 'llego_mutation' or candidate_type == 'llego_mutation1' or candidate_type == 'llego_mutation2':
cand_notation = 'Oβα΅€β'
elif candidate_type == 'seed':
cand_notation = 'Sβ'
elif candidate_type == 'unknown' or not candidate_type:
cand_notation = 'S' # Default for unknown
else:
# For any other type, use base notation
cand_notation = 'S'
logger.info("\n" + "β" * 80)
logger.info(f"π PARETO FRONT P ANALYSIS - Evaluating {cand_notation}")
logger.info("β" * 80)
logger.info(f"\n π Evaluating: {cand_notation} with f({cand_notation}) = {score:.4f}")
# π₯ CRITICAL BASELINE CHECK: Candidate must be better than baseline (unless it's the seed itself)
# Rule: Only candidates with f(candidate) > f(Sβ) can enter Pareto front
# Exception: Seed prompt (Sβ) itself is always added as the baseline
if candidate_type == 'seed':
# π₯ FIX: Check if seed prompt is already in Pareto front to prevent duplicates
normalized_prompt = prompt.strip().strip('"\'')
for existing_cand in self.pareto_front:
existing_prompt = existing_cand.get('prompt', '').strip().strip('"\'')
if existing_prompt == normalized_prompt and existing_cand.get('type') == 'seed':
logger.info(f"\n β οΈ {cand_notation} is already in Pareto Front P (duplicate detected)")
logger.info(f" Skipping duplicate seed prompt addition")
front_notations = [c.get('notation', 'S') for c in self.pareto_front]
logger.info(f" P = {{{', '.join(front_notations)}}}")
return # Skip adding duplicate
logger.info(f"\n β
{cand_notation} is seed prompt - always added as baseline")
# Set baseline if not already set (safety check - adapter should have done this)
if self.baseline_score is None:
self.baseline_score = score
logger.info(f" π‘ Setting baseline: f(Sβ) = {score:.4f}")
# Add seed to Pareto front immediately (no dominance check needed)
self.pareto_front.append({
'prompt': prompt,
'score': score,
'type': candidate_type,
'notation': cand_notation
})
self.pareto_front.sort(key=lambda x: x['score'], reverse=True)
# Display Pareto front with seed
front_notations = [c.get('notation', 'S') for c in self.pareto_front]
logger.info(f"\n β
ADDED to Pareto Front P (baseline)")
logger.info(f" P = {{{', '.join(front_notations)}}}")
self._display_pareto_front()
return # Seed is always added - skip dominance check
else:
# For non-seed candidates, must be better than baseline to proceed
if self.baseline_score is not None:
if score > self.baseline_score:
logger.info(f"\n β
{cand_notation} meets baseline requirement:")
logger.info(f" f(Sβ) = {self.baseline_score:.4f} (baseline)")
logger.info(f" f({cand_notation}) = {score:.4f}")
logger.info(f" f({cand_notation}) > f(Sβ) β Can be added to Pareto front")
logger.info(f" Improvement over baseline: +{score - self.baseline_score:.4f}")
else:
logger.info(f"\n β {cand_notation} does NOT meet baseline requirement:")
logger.info(f" f(Sβ) = {self.baseline_score:.4f} (baseline)")
logger.info(f" f({cand_notation}) = {score:.4f}")
logger.info(f" f({cand_notation}) β€ f(Sβ) β NOT ADDED to Pareto front")
logger.info(f" π‘ Only candidates better than baseline can enter Pareto front")
logger.info(f" π‘ Difference: {score - self.baseline_score:.4f} (needs to be > 0)")
return # Skip Pareto front update - candidate is not better than baseline
else:
# CRITICAL: Baseline must be set before evaluating any non-seed candidates
logger.error(f"\n β CRITICAL ERROR: Baseline score not set!")
logger.error(f" Cannot evaluate {cand_notation} without baseline f(Sβ)")
logger.error(f" π‘ Seed prompt must be evaluated on Dpareto first")
logger.error(f" π‘ Rejecting candidate to maintain correctness")
# Debug logging removed - not needed in production
return # Reject candidate - baseline is required
# Check if this candidate dominates any in current front
dominated = []
for i, front_candidate in enumerate(self.pareto_front):
front_score = front_candidate['score']
front_notation = front_candidate.get('notation', 'S')
# Simple dominance: higher score dominates
if score > front_score:
dominated.append(i)
logger.info(f"\n β
{cand_notation} DOMINATES P{i+1}:")
logger.info(f" f(P{i+1}) = {front_score:.4f}")
logger.info(f" f({cand_notation}) = {score:.4f}")
logger.info(f" f({cand_notation}) > f({front_notation}) β DOMINANCE")
logger.info(f" Improvement: +{score - front_score:.4f}")
if dominated:
# Remove dominated candidates
for i in reversed(dominated):
removed = self.pareto_front.pop(i)
removed_notation = removed.get('notation', 'S')
logger.info(f" β‘οΈ Removing {removed_notation} from Pareto front P (dominated by {cand_notation})")
# Add new candidate
self.pareto_front.append({
'prompt': prompt,
'score': score,
'type': candidate_type,
'notation': cand_notation
})
# Sort by score
self.pareto_front.sort(key=lambda x: x['score'], reverse=True)
# Display Pareto front with candidate notations
front_notations = [c.get('notation', 'S') for c in self.pareto_front]
logger.info(f"\n β
ADDED to Pareto Front P")
logger.info(f" P = {{{', '.join(front_notations)}}}")
else:
# Check if any in front dominates this candidate
is_dominated = False
for i, front_candidate in enumerate(self.pareto_front):
if front_candidate['score'] > score:
front_notation = front_candidate.get('notation', 'S')
logger.info(f"\n β {cand_notation} is DOMINATED by {front_notation}:")
logger.info(f" f({front_notation}) = {front_candidate['score']:.4f}")
logger.info(f" f({cand_notation}) = {score:.4f}")
logger.info(f" f({front_notation}) > f({cand_notation}) β DOMINATED")
logger.info(f" Difference: {score - front_candidate['score']:.4f}")
is_dominated = True
break
if not is_dominated:
# Check for equal scores (for single-objective, we can add if non-dominated)
equal_candidates = [c.get('notation', 'S') for c in self.pareto_front if abs(c['score'] - score) < 1e-6]
# Non-dominated: add to front
self.pareto_front.append({
'prompt': prompt,
'score': score,
'type': candidate_type,
'notation': cand_notation
})
self.pareto_front.sort(key=lambda x: x['score'], reverse=True)
# Display Pareto front with candidate notations
front_notations = [c.get('notation', 'S') for c in self.pareto_front]
if equal_candidates:
logger.info(f"\n β
ADDED to Pareto Front P (non-dominated)")
logger.info(f" f({cand_notation}) = {score:.4f} (same score as {', '.join(equal_candidates)})")
logger.info(f" P = {{{', '.join(front_notations)}}}")
else:
logger.info(f"\n β
ADDED to Pareto Front P (non-dominated)")
logger.info(f" {cand_notation} is non-dominated β kept in P")
logger.info(f" P = {{{', '.join(front_notations)}}}")
else:
# Show all dominating candidates with their notations
dominating_list = [(c.get('notation', 'S'), c['score']) for c in self.pareto_front if c['score'] > score]
if dominating_list:
for dom_notation, dom_score in dominating_list:
logger.info(f"\n β {cand_notation} is DOMINATED by {dom_notation}:")
logger.info(f" f({dom_notation}) = {dom_score:.4f}")
logger.info(f" f({cand_notation}) = {score:.4f}")
logger.info(f" f({dom_notation}) > f({cand_notation}) β DOMINATED")
logger.info(f"\n β NOT ADDED to Pareto Front P (dominated)")
self._display_pareto_front()
def _display_pareto_front(self):
"""Display current Pareto front with candidate notation"""
logger.info(f"\nπ CURRENT PARETO FRONT P (Size: |P| = {len(self.pareto_front)}):")
logger.info("β" * 80)
if not self.pareto_front:
logger.info(" P = {} (Empty - no candidates added yet)")
logger.info(" π‘ NOTATION: P = Pareto front (non-dominated solutions)")
return
# Display Pareto front using candidate notations instead of P1, P2, etc.
front_notations = [c.get('notation', 'S') for c in self.pareto_front]
logger.info(f" P = {{{', '.join(front_notations)}}}")
for candidate in self.pareto_front:
notation = candidate.get('notation', 'S')
# Enhanced type labels with full notation
type_labels = {
'seed': ('π± Seed Prompt', 'Sβ'),
'gepa_reflection': ('π GEPA Reflection Candidate', 'Sα΅£'),
'llego_crossover': ('π LLEGO Crossover Offspring', 'Oββ'),
'llego_mutation': ('π² LLEGO Mutation Offspring', 'Oβα΅€β'),
'unknown': ('π Unknown Candidate', 'S')
}
cand_type = candidate.get('type', 'unknown')
type_label, type_notation = type_labels.get(cand_type, (f'π {cand_type}', notation))
# Use the notation from the candidate if available, otherwise use type notation
display_notation = notation if notation != 'S' else type_notation
logger.info(f"\n {display_notation}: {type_label}")
logger.info(f" f({display_notation}) = {candidate['score']:.4f}")
prompt_preview = candidate['prompt'][:150] if len(candidate['prompt']) > 150 else candidate['prompt']
logger.info(f" Prompt ({len(candidate['prompt'])} chars): {prompt_preview}{'...' if len(candidate['prompt']) > 150 else ''}")
logger.info(f"\n π‘ NOTATION EXPLANATION:")
logger.info(f" P = Pareto front (set of non-dominated solutions)")
logger.info(f" Sβ = Seed prompt (baseline)")
logger.info(f" Sα΅£ = GEPA Reflection candidate")
logger.info(f" Oββ = LLEGO Crossover offspring (combines parents)")
logger.info(f" Oβα΅€β = LLEGO Mutation offspring (explores variations)")
logger.info(f" f({', '.join(front_notations[:3])}) = Fitness scores of candidates in Pareto front")
logger.info("β" * 80)
def set_baseline(self, score: float):
"""Set baseline score for comparison"""
self.baseline_score = score
# Add seed to Pareto front if we have it
if self.pareto_front:
seed_candidate = self.pareto_front[0] # First is usually seed
seed_candidate['baseline_score'] = score
def batch_update_pareto_front(self, candidates_with_scores: List[Dict]) -> List[Dict]:
"""
π₯ BATCH PARETO FRONT UPDATE
Efficiently update Pareto front with multiple candidates in one operation.
Steps:
1. Filter by baseline (score > baseline_score)
2. Find non-dominated among filtered candidates
3. Compare with current Pareto front
4. Update Pareto front (remove dominated, add non-dominated)
Args:
candidates_with_scores: List of dicts with keys:
- 'prompt': str
- 'score': float
- 'type': str (candidate_type)
- 'notation': str (optional, will be generated if missing)
Returns:
List of candidates that were added to Pareto front
"""
if not candidates_with_scores:
return []
logger.info("\n" + "β" * 80)
logger.info(f"π₯ BATCH PARETO FRONT UPDATE - Processing {len(candidates_with_scores)} candidates")
logger.info("β" * 80)
# Step 0: Deduplicate input candidates by prompt text
seen_prompts = set()
deduplicated_candidates = []
for cand in candidates_with_scores:
normalized_prompt = cand.get('prompt', '').strip().strip('"\'')
if normalized_prompt not in seen_prompts:
seen_prompts.add(normalized_prompt)
deduplicated_candidates.append(cand)
else:
logger.info(f" β οΈ Skipping duplicate candidate: {cand.get('notation', 'S')} (prompt already in batch)")
if len(deduplicated_candidates) < len(candidates_with_scores):
logger.info(f" π Deduplicated: {len(candidates_with_scores)} β {len(deduplicated_candidates)} candidates")
candidates_with_scores = deduplicated_candidates
# Step 1: Filter by baseline (score > baseline_score)
if self.baseline_score is None:
logger.error("β Baseline score not set - cannot perform batch update")
logger.error(" π‘ Seed prompt must be evaluated on Dpareto first")
return []
baseline = self.baseline_score
filtered = []
for cand in candidates_with_scores:
score = cand.get('score', 0.0)
cand_type = cand.get('type', 'unknown')
# Seed is always included (it's the baseline)
if cand_type == 'seed':
# π₯ FIX: Check if seed is already in Pareto front
normalized_prompt = cand.get('prompt', '').strip().strip('"\'')
already_in_front = False
for existing_cand in self.pareto_front:
existing_prompt = existing_cand.get('prompt', '').strip().strip('"\'')
if existing_prompt == normalized_prompt and existing_cand.get('type') == 'seed':
already_in_front = True
logger.info(f" β οΈ Seed prompt already in Pareto front - skipping duplicate")
break
if not already_in_front:
filtered.append(cand)
continue
# Non-seed candidates must be better than baseline
if score > baseline:
filtered.append(cand)
logger.info(f" β
{cand.get('notation', 'S')} passes baseline: f={score:.4f} > f(Sβ)={baseline:.4f}")
else:
notation = cand.get('notation', 'S')
logger.info(f" β {notation} fails baseline: f={score:.4f} β€ f(Sβ)={baseline:.4f}")
if not filtered:
logger.info(f"\n β No candidates pass baseline filter (baseline: {baseline:.4f})")
logger.info(" π‘ All candidates are worse than or equal to seed prompt")
return []
logger.info(f"\n π After baseline filter: {len(filtered)}/{len(candidates_with_scores)} candidates remain")
# Step 2: Find non-dominated among filtered candidates
# Sort by score (descending) for easier dominance checking
filtered_sorted = sorted(filtered, key=lambda x: x.get('score', 0.0), reverse=True)
non_dominated_batch = []
for i, cand in enumerate(filtered_sorted):
cand_score = cand.get('score', 0.0)
cand_notation = cand.get('notation', 'S')
is_dominated = False
# Check if dominated by any other candidate in batch
for other in filtered_sorted[:i]: # Only check candidates with higher scores
other_score = other.get('score', 0.0)
if other_score > cand_score:
other_notation = other.get('notation', 'S')
logger.info(f" β {cand_notation} dominated by {other_notation} in batch: f({other_notation})={other_score:.4f} > f({cand_notation})={cand_score:.4f}")
is_dominated = True
break
if not is_dominated:
non_dominated_batch.append(cand)
logger.info(f" β
{cand_notation} is non-dominated in batch: f={cand_score:.4f}")
logger.info(f"\n π After batch dominance check: {len(non_dominated_batch)}/{len(filtered)} non-dominated candidates")
if not non_dominated_batch:
logger.info(" β No non-dominated candidates in batch")
return []
# Step 3: Compare with current Pareto front and update
added_to_front = []
candidates_to_remove = []
# First, check which current front candidates are dominated by new batch
for front_cand in self.pareto_front:
front_score = front_cand.get('score', 0.0)
front_notation = front_cand.get('notation', 'S')
# Check if any new candidate dominates this front candidate
for new_cand in non_dominated_batch:
new_score = new_cand.get('score', 0.0)
new_notation = new_cand.get('notation', 'S')
if new_score > front_score:
candidates_to_remove.append(front_cand)
logger.info(f" β‘οΈ {front_notation} will be removed (dominated by {new_notation}): f({front_notation})={front_score:.4f} < f({new_notation})={new_score:.4f}")
break
# Remove dominated candidates from front
for cand_to_remove in candidates_to_remove:
if cand_to_remove in self.pareto_front:
self.pareto_front.remove(cand_to_remove)
# Now add non-dominated new candidates (check they're not dominated by remaining front)
for new_cand in non_dominated_batch:
new_score = new_cand.get('score', 0.0)
new_notation = new_cand.get('notation', 'S')
new_type = new_cand.get('type', 'unknown')
new_prompt = new_cand.get('prompt', '')
# Check if dominated by any remaining front candidate
is_dominated_by_front = False
for front_cand in self.pareto_front:
front_score = front_cand.get('score', 0.0)
if front_score > new_score:
front_notation = front_cand.get('notation', 'S')
logger.info(f" β {new_notation} dominated by existing {front_notation}: f({front_notation})={front_score:.4f} > f({new_notation})={new_score:.4f}")
is_dominated_by_front = True
break
if not is_dominated_by_front:
# Generate notation if missing
if 'notation' not in new_cand:
if new_type == 'gepa_reflection':
new_notation = 'Sα΅£'
elif new_type.startswith('llego_crossover'):
new_notation = 'Oββ'
elif new_type.startswith('llego_mutation'):
new_notation = 'Oβα΅€β'
elif new_type == 'seed':
new_notation = 'Sβ'
else:
new_notation = 'S'
# Add to Pareto front
front_entry = {
'prompt': new_prompt,
'score': new_score,
'type': new_type,
'notation': new_notation
}
self.pareto_front.append(front_entry)
added_to_front.append(new_cand)
# Also log to candidates_evaluated for tracking
self.candidates_evaluated.append({
'prompt': new_prompt,
'score': new_score,
'type': new_type,
'dataset': 'dpareto'
})
logger.info(f" β
{new_notation} ADDED to Pareto front: f={new_score:.4f}")
# Sort Pareto front by score
self.pareto_front.sort(key=lambda x: x.get('score', 0.0), reverse=True)
# Display updated Pareto front
logger.info(f"\n{'β'*80}")
logger.info(f"β
BATCH UPDATE COMPLETE")
logger.info(f" Added: {len(added_to_front)} candidates")
logger.info(f" Removed: {len(candidates_to_remove)} dominated candidates")
logger.info(f" Pareto front size: |P| = {len(self.pareto_front)}")
front_notations = [c.get('notation', 'S') for c in self.pareto_front]
logger.info(f" P = {{{', '.join(front_notations)}}}")
self._display_pareto_front()
logger.info("β" * 80 + "\n")
return added_to_front
# Global instance
_pareto_logger = ParetoLogger()
def get_pareto_logger() -> ParetoLogger:
"""Get global Pareto logger instance"""
return _pareto_logger
def reset_pareto_logger() -> ParetoLogger:
"""Reset global Pareto logger instance (for new runs)"""
global _pareto_logger
_pareto_logger = ParetoLogger()
# Debug logging removed - not needed in production
return _pareto_logger
|