Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions openevolve/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,11 +811,20 @@ def _passes_threshold(self, metrics: Dict[str, float], threshold: float) -> bool
if not metrics:
return False

# Use combined_score if available - this is what evolution uses
# Use combined_score if available - this is what evolution uses.
# Ensure combined_score is genuine numeric data rather than a boolean failure flag
# (e.g. {"combined_score": False}), and verify it is not NaN.
if "combined_score" in metrics:
score = metrics.get("combined_score")
if isinstance(score, (int, float)):
return float(score) >= threshold
# In Python, bool is a subclass of int. A boolean flag (e.g., False)
# must not be cast to 0.0, which could incorrectly pass a threshold <= 0.0.
if isinstance(score, (int, float)) and not isinstance(score, bool):
try:
float_score = float(score)
if not math.isnan(float_score):
return float_score >= threshold
except (TypeError, ValueError, OverflowError):
pass

# Fallback: average all numeric metrics except 'error'
# This maintains backward compatibility
Expand Down
43 changes: 33 additions & 10 deletions openevolve/process_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import asyncio
import logging
import math
import multiprocessing as mp
import pickle
import random
Expand All @@ -21,7 +22,7 @@
from openevolve.database import Program, ProgramDatabase
from openevolve.llm.ensemble import add_usage, take_usage
from openevolve.selection import IslandSelectionContext, IslandSelector, IslandState
from openevolve.utils.metrics_utils import safe_numeric_average
from openevolve.utils.metrics_utils import get_fitness_score, safe_numeric_average

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -255,9 +256,16 @@ def _run_iteration(
programs[pid] for pid in db_snapshot["islands"][parent_island] if pid in programs
]

# Sort by metrics for top programs
# Sort island programs by fitness score to determine top performers for prompt context.
# Use get_fitness_score() rather than raw combined_score or safe_numeric_average():
# 1. NaN combined_scores map to -inf so invalid programs rank at the bottom (preventing
# Timsort comparison failures and incorrect promotion to LLM prompt context).
# 2. When combined_score is absent, feature_dimensions (e.g., complexity or diversity)
# are excluded so high-complexity solutions do not crowd out genuinely high-performing solutions.
# 3. Boolean flags (which subclass int in Python) are excluded from scoring.
feature_dims = db_snapshot.get("feature_dimensions", [])
island_programs.sort(
key=lambda p: p.metrics.get("combined_score", safe_numeric_average(p.metrics)),
key=lambda p: get_fitness_score(p.metrics, feature_dims),
reverse=True,
)

Expand Down Expand Up @@ -1003,11 +1011,16 @@ async def run_evolution(
completed_iteration, checkpoint_callback, is_new_best=is_new_best
)

# Check target score
# Check target score: verify combined_score is genuine numeric data
# (avoid treating boolean flags like True as 1.0 or NaN as meeting targets).
if target_score is not None and child_program.metrics:
target_metric_val = child_program.metrics.get("combined_score")
if (
"combined_score" in child_program.metrics
and child_program.metrics["combined_score"] >= target_score
target_metric_val is not None
and isinstance(target_metric_val, (int, float))
and not isinstance(target_metric_val, bool)
and not math.isnan(float(target_metric_val))
and float(target_metric_val) >= target_score
):
logger.info(
f"Target score {target_score} reached at iteration {completed_iteration}"
Expand Down Expand Up @@ -1040,17 +1053,27 @@ async def run_evolution(
self.config.early_stopping_metric
]
elif self.config.early_stopping_metric == "combined_score":
# Default metric not found, use safe average (standard pattern)
current_score = safe_numeric_average(child_program.metrics)
# Default metric not found: calculate fitness score excluding
# MAP-Elites feature dimensions (complexity, diversity) so they
# do not skew convergence detection.
current_score = get_fitness_score(
child_program.metrics,
self.config.database.feature_dimensions,
)
else:
# User specified a custom metric that doesn't exist
logger.warning(
f"Early stopping metric '{self.config.early_stopping_metric}' not found, using safe numeric average"
)
current_score = safe_numeric_average(child_program.metrics)

if current_score is not None and isinstance(
current_score, (int, float)
# Verify score is numeric: exclude boolean flags and NaNs from
# improvement calculations to prevent corrupted convergence tracking.
if (
current_score is not None
and isinstance(current_score, (int, float))
and not isinstance(current_score, bool)
and not math.isnan(current_score)
):
# Check for improvement
if self.config.early_stopping_patience > 0:
Expand Down
48 changes: 33 additions & 15 deletions openevolve/prompt/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@
"""

import logging
import math
import random
from typing import Any, Dict, List, Optional, Tuple, Union

from openevolve.config import PromptConfig
from openevolve.prompt.templates import TemplateManager
from openevolve.utils.format_utils import format_metrics_safe
from openevolve.utils.metrics_utils import (
safe_numeric_average,
get_fitness_score,
format_feature_coordinates,
get_fitness_score,
safe_numeric_average,
)

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -283,10 +284,14 @@ def _format_evolution_history(
"changes", self.template_manager.get_fragment("attempt_unknown_changes")
)

# Format performance metrics using safe formatting
# Format performance metrics using safe formatting:
# Booleans are flags, not numeric scores; format as literal 'True' / 'False'
# rather than floating point numbers (e.g., avoid 'valid: 1.0000').
performance_parts = []
for name, value in program.get("metrics", {}).items():
if isinstance(value, (int, float)):
if isinstance(value, bool):
performance_parts.append(f"{name}: {value}")
elif isinstance(value, (int, float)):
try:
performance_parts.append(f"{name}: {value:.4f}")
except (ValueError, TypeError):
Expand All @@ -310,17 +315,30 @@ def _format_evolution_history(
prog_value = program_metrics.get(m, 0)
parent_value = parent_metrics.get(m, 0)

# Only compare if both values are numeric
if isinstance(prog_value, (int, float)) and isinstance(parent_value, (int, float)):
if prog_value > parent_value:
numeric_comparisons_improved.append(True)
else:
numeric_comparisons_improved.append(False)

if prog_value < parent_value:
numeric_comparisons_regressed.append(True)
else:
numeric_comparisons_regressed.append(False)
# Only compare genuine numeric metrics. Boolean flags (which subclass int
# in Python) such as valid=False -> valid=True must not be treated as
# numeric improvements (+1.0), and NaN values must not distort comparisons.
if (
isinstance(prog_value, (int, float))
and not isinstance(prog_value, bool)
and isinstance(parent_value, (int, float))
and not isinstance(parent_value, bool)
):
try:
prog_float = float(prog_value)
parent_float = float(parent_value)
if not math.isnan(prog_float) and not math.isnan(parent_float):
if prog_float > parent_float:
numeric_comparisons_improved.append(True)
else:
numeric_comparisons_improved.append(False)

if prog_float < parent_float:
numeric_comparisons_regressed.append(True)
else:
numeric_comparisons_regressed.append(False)
except (ValueError, TypeError, OverflowError):
continue

# Determine outcome based on numeric comparisons
if numeric_comparisons_improved and all(numeric_comparisons_improved):
Expand Down
67 changes: 48 additions & 19 deletions openevolve/utils/metrics_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,12 @@ def safe_numeric_average(metrics: Dict[str, Any]) -> float:
def safe_numeric_sum(metrics: Dict[str, Any]) -> float:
"""
Calculate the sum of numeric values in a metrics dictionary,
safely ignoring non-numeric values like strings.
safely ignoring non-numeric values like strings and boolean flags.

In Python, `bool` is a subclass of `int` (`isinstance(True, int)` is True).
Treating boolean flags (such as `{"timeout": True}` or `{"valid": True}`) as
numeric scores would corrupt calculations (e.g., adding 1.0 or 0.0 to sums).
Therefore, boolean values are explicitly excluded.

Args:
metrics: Dictionary of metric names to values
Expand All @@ -63,14 +68,17 @@ def safe_numeric_sum(metrics: Dict[str, Any]) -> float:

numeric_sum = 0.0
for value in metrics.values():
if isinstance(value, (int, float)):
# In Python, bool subclasses int, but boolean flags (e.g., {"timeout": True})
# represent status metadata rather than numeric scores. Explicitly skip booleans
# to avoid inflating numeric sums by 1.0 or 0.0.
if isinstance(value, (int, float)) and not isinstance(value, bool):
try:
# Convert to float and check if it's a valid number
# Convert to float and verify it is not NaN (NaN values are skipped)
float_val = float(value)
if not (float_val != float_val): # Check for NaN (NaN != NaN is True)
if not math.isnan(float_val):
numeric_sum += float_val
except (ValueError, TypeError, OverflowError):
# Skip invalid numeric values
# Skip invalid or overflowing numeric values
continue

return numeric_sum
Expand All @@ -80,10 +88,18 @@ def get_fitness_score(
metrics: Dict[str, Any], feature_dimensions: Optional[List[str]] = None
) -> float:
"""
Calculate fitness score, excluding MAP-Elites feature dimensions
Calculate fitness score, excluding MAP-Elites feature dimensions.

This ensures that MAP-Elites features (like code complexity or diversity)
do not pollute the fitness calculation when combined_score is not available.

This ensures that MAP-Elites features don't pollute the fitness calculation
when combined_score is not available.
Special cases:
- Boolean `combined_score` values (e.g. `False` on evaluation failure) are
treated as non-numeric flags to prevent `float(False)` from becoming 0.0
and falsely beating programs with valid negative scores.
- A NaN `combined_score` yields -inf so that invalid programs rank below
every other program.
- If `combined_score` is absent, averages only non-feature numeric metrics.

Args:
metrics: All metrics from evaluation
Expand All @@ -96,14 +112,21 @@ def get_fitness_score(
if not metrics:
return 0.0

# Always prefer combined_score if available
# Always prefer combined_score if available and genuinely numeric
if "combined_score" in metrics:
try:
combined_score = float(metrics["combined_score"])
# Every comparison with NaN is False, so a NaN score would never be beaten. Rank it last
return float("-inf") if math.isnan(combined_score) else combined_score
except (ValueError, TypeError):
pass
score_val = metrics["combined_score"]
# Booleans are flags, not scores. For example, evaluators may return
# {"combined_score": False, "error": "timeout"} on failure.
# If treated as numeric, float(False) becomes 0.0, improperly outscoring
# programs that received negative fitness scores (e.g., loss = -5.0).
if not isinstance(score_val, bool):
try:
combined_score = float(score_val)
# Every comparison with NaN is False in IEEE 754, which breaks sorting.
# Assign -inf so that NaN scores rank at the absolute bottom.
return float("-inf") if math.isnan(combined_score) else combined_score
except (ValueError, TypeError, OverflowError):
pass

# Otherwise, average only non-feature metrics
feature_dimensions = feature_dimensions or []
Expand All @@ -116,7 +139,7 @@ def get_fitness_score(
if isinstance(value, (int, float)) and not isinstance(value, bool):
try:
float_val = float(value)
if not (float_val != float_val): # Check for NaN
if not math.isnan(float_val):
fitness_metrics[key] = float_val
except (ValueError, TypeError, OverflowError):
continue
Expand All @@ -137,17 +160,23 @@ def format_feature_coordinates(metrics: Dict[str, Any], feature_dimensions: List
feature_dimensions: List of MAP-Elites feature dimensions

Returns:
Formatted string showing feature coordinates
Formatted string showing feature coordinates (e.g. 'valid=True, complexity=12.50')
"""
feature_values = []
for dim in feature_dimensions:
if dim in metrics:
value = metrics[dim]
if isinstance(value, (int, float)):
# In Python, bool subclasses int. Formatting boolean feature flags as floats
# (e.g., 'valid=1.00') is misleading in LLM prompts. Output boolean literals.
if isinstance(value, bool):
feature_values.append(f"{dim}={value}")
elif isinstance(value, (int, float)):
try:
float_val = float(value)
if not (float_val != float_val): # Check for NaN
if not math.isnan(float_val):
feature_values.append(f"{dim}={float_val:.2f}")
else:
feature_values.append(f"{dim}={value}")
except (ValueError, TypeError, OverflowError):
feature_values.append(f"{dim}={value}")
else:
Expand Down
Loading
Loading