From 20f525ae0fdcd7c6d61911f2552efae5196c1cd0 Mon Sep 17 00:00:00 2001 From: Aaditya Pratap Date: Sun, 22 Nov 2026 14:59:40 +0530 Subject: [PATCH] fix(metrics): exclude boolean flags from sum/coordinates and standardize fitness ranking in workers - safe_numeric_sum: explicitly exclude boolean flags and NaNs - get_fitness_score: guard combined_score against boolean false positives and convert NaNs to -inf - format_feature_coordinates: format boolean coordinates as boolean literals rather than floats - Evaluator._passes_threshold: guard combined_score against booleans and NaNs - PromptSampler._format_evolution_history: exclude boolean flags from numeric comparisons and format as boolean literals - ProcessParallelController: standardize island program sorting with get_fitness_score and safeguard target_score/early_stopping - Add comprehensive docstrings, inline explanatory comments, and test suite --- openevolve/evaluator.py | 15 +- openevolve/process_parallel.py | 43 +++-- openevolve/prompt/sampler.py | 48 +++-- openevolve/utils/metrics_utils.py | 67 +++++-- tests/test_boolean_metrics_extended.py | 234 +++++++++++++++++++++++++ 5 files changed, 360 insertions(+), 47 deletions(-) create mode 100644 tests/test_boolean_metrics_extended.py diff --git a/openevolve/evaluator.py b/openevolve/evaluator.py index f2504c84d..1a5f42129 100644 --- a/openevolve/evaluator.py +++ b/openevolve/evaluator.py @@ -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 diff --git a/openevolve/process_parallel.py b/openevolve/process_parallel.py index b19a435a3..ff9537311 100644 --- a/openevolve/process_parallel.py +++ b/openevolve/process_parallel.py @@ -4,6 +4,7 @@ import asyncio import logging +import math import multiprocessing as mp import pickle import random @@ -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__) @@ -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, ) @@ -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}" @@ -1040,8 +1053,13 @@ 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( @@ -1049,8 +1067,13 @@ async def run_evolution( ) 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: diff --git a/openevolve/prompt/sampler.py b/openevolve/prompt/sampler.py index 23a8e27e5..f493074a5 100644 --- a/openevolve/prompt/sampler.py +++ b/openevolve/prompt/sampler.py @@ -3,6 +3,7 @@ """ import logging +import math import random from typing import Any, Dict, List, Optional, Tuple, Union @@ -10,9 +11,9 @@ 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__) @@ -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): @@ -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): diff --git a/openevolve/utils/metrics_utils.py b/openevolve/utils/metrics_utils.py index 852f3606d..52e37deb0 100644 --- a/openevolve/utils/metrics_utils.py +++ b/openevolve/utils/metrics_utils.py @@ -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 @@ -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 @@ -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 @@ -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 [] @@ -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 @@ -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: diff --git a/tests/test_boolean_metrics_extended.py b/tests/test_boolean_metrics_extended.py new file mode 100644 index 000000000..9bf21de8c --- /dev/null +++ b/tests/test_boolean_metrics_extended.py @@ -0,0 +1,234 @@ +""" +Unit tests for extended boolean metric handling and fitness score ranking. + +Validates that: +- safe_numeric_sum ignores boolean flags and non-finite values. +- get_fitness_score safely handles boolean combined_score flags and NaNs. +- format_feature_coordinates renders boolean coordinates as literals. +- Evaluator._passes_threshold guards against boolean flags and NaNs. +- PromptSampler._format_evolution_history renders boolean flags as literals + and excludes them from numeric metric improvement comparisons. +- ProcessParallelController island program ranking handles NaNs and MAP-Elites + feature dimension exclusions consistently with database selection. +""" + +import math +import os +import unittest + +os.environ.setdefault("OPENAI_API_KEY", "test") + +from openevolve.config import PromptConfig +from openevolve.database import Program +from openevolve.evaluator import Evaluator +from openevolve.prompt.sampler import PromptSampler +from openevolve.utils.metrics_utils import ( + format_feature_coordinates, + get_fitness_score, + safe_numeric_average, + safe_numeric_sum, +) + + +class TestSafeNumericSum(unittest.TestCase): + """Tests for safe_numeric_sum utility function.""" + + def test_bool_excluded_from_numeric_sum(self): + """Boolean flags (True/False) should not be counted as 1.0 or 0.0 in numeric sum.""" + metrics = {"score1": 10.0, "score2": 5.0, "valid": True, "timeout": False} + self.assertAlmostEqual(safe_numeric_sum(metrics), 15.0) + + def test_all_booleans_sum_to_zero(self): + """A dictionary containing only boolean flags should sum to 0.0.""" + metrics = {"valid": True, "timeout": False, "passed": True} + self.assertEqual(safe_numeric_sum(metrics), 0.0) + + def test_empty_metrics_sum_to_zero(self): + """An empty metrics dictionary should sum to 0.0.""" + self.assertEqual(safe_numeric_sum({}), 0.0) + + def test_nan_and_invalid_values_skipped(self): + """NaN floats and string metric values should be safely skipped.""" + metrics = {"score": 7.5, "bad": float("nan"), "str_metric": "error"} + self.assertAlmostEqual(safe_numeric_sum(metrics), 7.5) + + +class TestGetFitnessScoreExtended(unittest.TestCase): + """Tests for get_fitness_score with boolean flags, NaNs, and feature dimensions.""" + + def test_boolean_combined_score_ignored(self): + """ + Boolean combined_score must not be converted to 0.0 or 1.0. + + When evaluation fails, evaluators may emit {"combined_score": False, "error": ...}. + If cast to float, 0.0 would improperly outscore programs with valid negative scores. + """ + metrics_failed = {"combined_score": False, "score": -10.0} + self.assertAlmostEqual(get_fitness_score(metrics_failed), -10.0) + + metrics_true = {"combined_score": True, "accuracy": 0.8} + self.assertAlmostEqual(get_fitness_score(metrics_true), 0.8) + + def test_nan_combined_score_returns_neg_inf(self): + """A NaN combined_score must return -inf so invalid programs rank at the bottom.""" + metrics = {"combined_score": float("nan"), "score": 100.0} + self.assertEqual(get_fitness_score(metrics), float("-inf")) + + def test_feature_dimensions_excluded_when_no_combined_score(self): + """MAP-Elites feature dimensions must not inflate fitness when combined_score is absent.""" + metrics = {"reward": 5.0, "complexity": 999.0} + score = get_fitness_score(metrics, feature_dimensions=["complexity"]) + self.assertAlmostEqual(score, 5.0) + + +class TestFormatFeatureCoordinates(unittest.TestCase): + """Tests for formatting MAP-Elites feature coordinates for prompt display.""" + + def test_boolean_coordinates_formatted_as_bool(self): + """Boolean coordinates should display as True/False rather than 1.00/0.00.""" + metrics = {"valid": True, "deterministic": False, "runtime": 0.1234} + dims = ["valid", "deterministic", "runtime"] + formatted = format_feature_coordinates(metrics, dims) + self.assertIn("valid=True", formatted) + self.assertIn("deterministic=False", formatted) + self.assertIn("runtime=0.12", formatted) + + def test_empty_coordinates(self): + """Empty metrics or dimensions should return an empty string.""" + self.assertEqual(format_feature_coordinates({}, ["dim1"]), "") + + def test_missing_and_nan_coordinates(self): + """Missing dimensions should be omitted, and NaN dimensions preserved as nan.""" + metrics = {"dim1": float("nan"), "dim2": 2.5} + formatted = format_feature_coordinates(metrics, ["dim1", "dim2", "dim3"]) + self.assertIn("dim1=nan", formatted) + self.assertIn("dim2=2.50", formatted) + self.assertNotIn("dim3", formatted) + + +class TestEvaluatorThresholdCheck(unittest.TestCase): + """Tests for cascade threshold checks in Evaluator.""" + + def setUp(self): + self.evaluator = Evaluator.__new__(Evaluator) + + def test_boolean_combined_score_does_not_pass_threshold(self): + """A boolean combined_score flag (False) must not pass threshold 0.0 via float conversion.""" + self.assertFalse( + self.evaluator._passes_threshold(metrics={"combined_score": False}, threshold=0.0) + ) + + def test_nan_combined_score_does_not_pass_threshold(self): + """A NaN combined_score must not pass threshold evaluation.""" + self.assertFalse( + self.evaluator._passes_threshold( + metrics={"combined_score": float("nan")}, threshold=0.0 + ) + ) + + def test_valid_combined_score_passes_threshold(self): + """Valid numeric combined_score meeting or exceeding threshold should pass.""" + self.assertTrue( + self.evaluator._passes_threshold(metrics={"combined_score": 0.8}, threshold=0.5) + ) + + +class TestPromptSamplerHistoryBooleanHandling(unittest.TestCase): + """Tests for evolution history prompt formatting and metric comparison.""" + + def test_boolean_flag_flip_not_treated_as_numeric_improvement(self): + """ + Verify boolean flag flipping False -> True is not counted as a numeric metric improvement. + + If a program's numeric score regresses from 10.0 to 5.0, flipping a flag to True + must not cause the prompt outcome to report 'All metrics improved'. + """ + config = PromptConfig() + sampler = PromptSampler(config) + + # Parent and child where only a boolean flag flipped and real numeric metric regressed + program = { + "id": "p2", + "metrics": {"score": 5.0, "valid": True}, + "parent_id": "p1", + "changes_description": "Fix bug", + "metadata": { + "parent_metrics": {"score": 10.0, "valid": False}, + }, + } + + history_str = sampler._format_evolution_history( + previous_programs=[program], + top_programs=[], + inspirations=[], + language="python", + ) + + # Boolean metric should be rendered as boolean literal, not float + self.assertIn("valid: True", history_str) + self.assertNotIn("valid: 1.0000", history_str) + + # Since score regressed (5.0 < 10.0), outcome should NOT report all metrics improved! + self.assertNotIn("All metrics improved", history_str) + + +class TestProcessParallelProgramRanking(unittest.TestCase): + """Tests for program ranking in parallel workers.""" + + def test_program_ranking_handles_nan_and_feature_dimensions(self): + """ + Verify sorting island programs by get_fitness_score(p.metrics, feature_dims) + correctly handles NaN values, negative scores, and excludes MAP-Elites feature dimensions. + """ + p_normal = Program( + id="p1", + code="code1", + metrics={"combined_score": 10.0}, + ) + p_nan = Program( + id="p2", + code="code2", + metrics={"combined_score": float("nan")}, + ) + p_negative = Program( + id="p3", + code="code3", + metrics={"combined_score": -100.0}, + ) + p_no_combined_high_feature = Program( + id="p4", + code="code4", + metrics={"score": 2.0, "complexity": 10000.0}, + ) + p_no_combined_better_score = Program( + id="p5", + code="code5", + metrics={"score": 8.0, "complexity": 10.0}, + ) + + programs = [ + p_nan, + p_negative, + p_normal, + p_no_combined_high_feature, + p_no_combined_better_score, + ] + feature_dims = ["complexity"] + + programs.sort( + key=lambda p: get_fitness_score(p.metrics, feature_dims), + reverse=True, + ) + + # Expected ranking order: + # p_normal (10.0) > p_no_combined_better_score (8.0) > p_no_combined_high_feature (2.0) + # > p_negative (-100.0) > p_nan (-inf) + self.assertEqual(programs[0].id, "p1") + self.assertEqual(programs[1].id, "p5") + self.assertEqual(programs[2].id, "p4") + self.assertEqual(programs[3].id, "p3") + self.assertEqual(programs[4].id, "p2") # NaN ranked at the very bottom + + +if __name__ == "__main__": + unittest.main()