File size: 13,306 Bytes
ea8c728 | 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 | # OpenEvolve Examples
This directory contains a collection of examples demonstrating how to use OpenEvolve for various tasks including optimization, algorithm discovery, and code evolution. Each example showcases different aspects of OpenEvolve's capabilities and provides templates for creating your own evolutionary coding projects.
## Quick Start Template
To create your own OpenEvolve example, you need three essential components:
### 1. Initial Program (`initial_program.py`)
Your initial program must contain exactly **one** `EVOLVE-BLOCK`:
```python
# EVOLVE-BLOCK-START
def your_function():
# Your initial implementation here
# This is the only section OpenEvolve will modify
pass
# EVOLVE-BLOCK-END
# Helper functions and other code outside the evolve block
def helper_function():
# This code won't be modified by OpenEvolve
pass
```
**Critical Requirements:**
- โ
**Exactly one EVOLVE-BLOCK** (not multiple blocks)
- โ
Use `# EVOLVE-BLOCK-START` and `# EVOLVE-BLOCK-END` markers
- โ
Put only the code you want evolved inside the block
- โ
Helper functions and imports go outside the block
### 2. Evaluator (`evaluator.py`)
Your evaluator can return either a **dictionary** or an **`EvaluationResult`** object:
```python
def evaluate(program_path: str) -> Dict:
"""
Evaluate the program and return metrics.
Can return either a dict or EvaluationResult object.
Use EvaluationResult if you want to include artifacts for debugging.
"""
try:
# Import and run your program
# Calculate metrics
return {
'combined_score': 0.8, # PRIMARY METRIC for evolution (required)
'accuracy': 0.9, # Your custom metrics
'speed': 0.7,
'robustness': 0.6,
# Add any other metrics you want to track
}
except Exception as e:
return {
'combined_score': 0.0, # Always return combined_score, even on error
'error': str(e)
}
# Or use EvaluationResult for artifacts support:
from openevolve.evaluation_result import EvaluationResult
def evaluate(program_path: str) -> EvaluationResult:
return EvaluationResult(
metrics={'combined_score': 0.8, 'accuracy': 0.9},
artifacts={'debug_info': 'useful debugging data'}
)
```
**Critical Requirements:**
- โ
**Return a dictionary or `EvaluationResult`** - both are supported
- โ
**Must include `'combined_score'`** - this is the primary metric OpenEvolve uses
- โ
Higher `combined_score` values should indicate better programs
- โ
Handle exceptions and return `combined_score: 0.0` on failure
- โ
Use `EvaluationResult` with artifacts for richer debugging feedback
### 3. Configuration (`config.yaml`)
Essential configuration structure:
```yaml
# Evolution settings
max_iterations: 100
checkpoint_interval: 10
parallel_evaluations: 1
# LLM configuration
llm:
api_base: "https://api.openai.com/v1" # Or your LLM provider
models:
- name: "gpt-4"
weight: 1.0
temperature: 0.7
max_tokens: 4000
timeout: 120
# Database configuration (MAP-Elites algorithm)
database:
population_size: 50
num_islands: 3
migration_interval: 10
feature_dimensions: # MUST be a list, not an integer
- "score"
- "complexity"
# Evaluation settings
evaluator:
timeout: 60
max_retries: 3
# Prompt configuration
prompt:
system_message: |
You are an expert programmer. Your goal is to improve the code
in the EVOLVE-BLOCK to achieve better performance on the task.
Focus on algorithmic improvements and code optimization.
num_top_programs: 3
num_diverse_programs: 2
# Logging
log_level: "INFO"
```
**Critical Requirements:**
- โ
**`feature_dimensions` must be a list** (e.g., `["score", "complexity"]`), not an integer
- โ
Set appropriate timeouts for your use case
- โ
Configure LLM settings for your provider
- โ
Use meaningful `system_message` to guide evolution
## Common Configuration Mistakes
โ **Wrong:** `feature_dimensions: 2`
โ
**Correct:** `feature_dimensions: ["score", "complexity"]`
โ **Wrong:** Using `'total_score'` metric name
โ
**Correct:** Using `'combined_score'` metric name
โ **Wrong:** Multiple EVOLVE-BLOCK sections
โ
**Correct:** Exactly one EVOLVE-BLOCK section
๐ก **Tip:** Both `{'combined_score': 0.8, ...}` dict and `EvaluationResult(metrics={...}, artifacts={...})` are valid return types
## MAP-Elites Feature Dimensions Best Practices
When using custom feature dimensions, your evaluator must return **raw continuous values**, not pre-computed bin indices:
### โ
Correct: Return Raw Values
```python
def evaluate(program_path: str) -> Dict:
# Calculate actual measurements
prompt_length = len(generated_prompt) # Actual character count
execution_time = measure_runtime() # Time in seconds
memory_usage = get_peak_memory() # Bytes used
return {
"combined_score": accuracy_score,
"prompt_length": prompt_length, # Raw count, not bin index
"execution_time": execution_time, # Raw seconds, not bin index
"memory_usage": memory_usage # Raw bytes, not bin index
}
```
### โ Wrong: Return Bin Indices
```python
def evaluate(program_path: str) -> Dict:
prompt_length = len(generated_prompt)
# DON'T DO THIS - pre-computing bins
if prompt_length < 100:
length_bin = 0
elif prompt_length < 500:
length_bin = 1
# ... more binning logic
return {
"combined_score": accuracy_score,
"prompt_length": length_bin, # โ This is a bin index, not raw value
}
```
### Why This Matters
- OpenEvolve uses min-max scaling internally
- Bin indices get incorrectly scaled as if they were raw values
- Grid positions become unstable as new programs change the min/max range
- This violates MAP-Elites principles and leads to poor evolution
### Examples of Good Feature Dimensions
- **Counts**: Token count, line count, character count
- **Performance**: Execution time, memory usage, throughput
- **Quality**: Accuracy, precision, recall, F1 score
- **Complexity**: Cyclomatic complexity, nesting depth, function count
## Running Your Example
```bash
# Basic run
python openevolve-run.py path/to/initial_program.py path/to/evaluator.py --config path/to/config.yaml --iterations 100
# Resume from checkpoint
python openevolve-run.py path/to/initial_program.py path/to/evaluator.py \
--config path/to/config.yaml \
--checkpoint path/to/checkpoint_directory \
--iterations 50
# View results
python scripts/visualizer.py --path path/to/openevolve_output/checkpoints/checkpoint_100/
```
## Advanced Configuration Options
### LLM Ensemble (Multiple Models)
```yaml
llm:
models:
- name: "gpt-4"
weight: 0.7
- name: "claude-3-sonnet"
weight: 0.3
```
### Island Evolution (Population Diversity)
```yaml
database:
num_islands: 5 # More islands = more diversity
migration_interval: 15 # How often islands exchange programs
population_size: 100 # Larger population = more exploration
```
### Cascade Evaluation (Multi-Stage Testing)
```yaml
evaluator:
cascade_stages:
- stage1_timeout: 30 # Quick validation
- stage2_timeout: 120 # Full evaluation
```
## Example Directory
### ๐งฎ Mathematical Optimization
#### [Function Minimization](function_minimization/)
**Task:** Find global minimum of complex non-convex function
**Achievement:** Evolved from random search to sophisticated simulated annealing
**Key Lesson:** Shows automatic discovery of optimization algorithms
```bash
cd examples/function_minimization
python ../../openevolve-run.py initial_program.py evaluator.py --config config.yaml
```
#### [Circle Packing](circle_packing/)
**Task:** Pack 26 circles in unit square to maximize sum of radii
**Achievement:** Matched AlphaEvolve paper results (2.634/2.635)
**Key Lesson:** Demonstrates evolution from geometric heuristics to mathematical optimization
```bash
cd examples/circle_packing
python ../../openevolve-run.py initial_program.py evaluator.py --config config_phase_1.yaml
```
### ๐ง Algorithm Discovery
#### [Signal Processing](signal_processing/)
**Task:** Design digital filters for audio processing
**Achievement:** Discovered novel filter designs with superior characteristics
**Key Lesson:** Shows evolution of domain-specific algorithms
```bash
cd examples/signal_processing
python ../../openevolve-run.py initial_program.py evaluator.py --config config.yaml
```
#### [Rust Adaptive Sort](rust_adaptive_sort/)
**Task:** Create sorting algorithm that adapts to data patterns
**Achievement:** Evolved sorting strategies beyond traditional algorithms
**Key Lesson:** Multi-language support (Rust) and algorithm adaptation
```bash
cd examples/rust_adaptive_sort
python ../../openevolve-run.py initial_program.rs evaluator.py --config config.yaml
```
### ๐ Performance Optimization
#### [MLX Metal Kernel Optimization](mlx_metal_kernel_opt/)
**Task:** Optimize attention mechanisms for Apple Silicon
**Achievement:** 2-3x speedup over baseline implementation
**Key Lesson:** Hardware-specific optimization and performance tuning
```bash
cd examples/mlx_metal_kernel_opt
python ../../openevolve-run.py initial_program.py evaluator.py --config config.yaml
```
### ๐ Web and Data Processing
#### [Web Scraper with optillm](web_scraper_optillm/)
**Task:** Extract API documentation from HTML pages
**Achievement:** Demonstrates optillm integration with readurls and MoA
**Key Lesson:** Shows integration with LLM proxy systems and test-time compute
```bash
cd examples/web_scraper_optillm
python ../../openevolve-run.py initial_program.py evaluator.py --config config.yaml
```
### ๐ป Programming Challenges
#### [Online Judge Programming](online_judge_programming/)
**Task:** Solve competitive programming problems
**Achievement:** Automated solution generation and submission
**Key Lesson:** Integration with external evaluation systems
```bash
cd examples/online_judge_programming
python ../../openevolve-run.py initial_program.py evaluator.py --config config.yaml
```
### ๐ Machine Learning and AI
#### [LLM Prompt Optimization](llm_prompt_optimization/)
**Task:** Evolve prompts for better LLM performance
**Achievement:** Discovered effective prompt engineering techniques
**Key Lesson:** Self-improving AI systems and prompt evolution
```bash
cd examples/llm_prompt_optimazation
python ../../openevolve-run.py initial_prompt.txt evaluator.py --config config.yaml
```
#### [LM-Eval Integration](lm_eval/)
**Task:** Integrate with language model evaluation harness
**Achievement:** Automated benchmark improvement
**Key Lesson:** Integration with standard ML evaluation frameworks
#### [Symbolic Regression](symbolic_regression/)
**Task:** Discover mathematical expressions from data
**Achievement:** Automated discovery of scientific equations
**Key Lesson:** Scientific discovery and mathematical modeling
### ๐ฌ Scientific Computing
#### [R Robust Regression](r_robust_regression/)
**Task:** Develop robust statistical regression methods
**Achievement:** Novel statistical algorithms resistant to outliers
**Key Lesson:** Multi-language support (R) and statistical algorithm evolution
```bash
cd examples/r_robust_regression
python ../../openevolve-run.py initial_program.r evaluator.py --config config.yaml
```
### ๐ฏ Advanced Features
#### [Circle Packing with Artifacts](circle_packing_with_artifacts/)
**Task:** Circle packing with detailed execution feedback
**Achievement:** Advanced debugging and artifact collection
**Key Lesson:** Using OpenEvolve's artifact system for detailed analysis
```bash
cd examples/circle_packing_with_artifacts
python ../../openevolve-run.py initial_program.py evaluator.py --config config_phase_1.yaml
```
## Best Practices
### ๐ฏ Design Effective Evaluators
- Use meaningful metrics that reflect your goals
- Include both quality and efficiency measures
- Handle edge cases and errors gracefully
- Provide informative feedback for debugging
### ๐ง Configuration Tuning
- Start with smaller populations and fewer iterations for testing
- Increase `num_islands` for more diverse exploration
- Adjust `temperature` based on how creative you want the LLM to be
- Set appropriate timeouts for your compute environment
### ๐ Evolution Strategy
- Use multiple phases with different configurations
- Begin with exploration, then focus on exploitation
- Consider cascade evaluation for expensive tests
- Monitor progress and adjust configuration as needed
### ๐ Debugging
- Check logs in `openevolve_output/logs/`
- Examine failed programs in checkpoint directories
- Use artifacts to understand program behavior
- Test your evaluator independently before evolution
## Getting Help
- ๐ See individual example READMEs for detailed walkthroughs
- ๐ Check the main [OpenEvolve documentation](../README.md)
- ๐ฌ Open issues on the [GitHub repository](https://github.com/codelion/openevolve)
Each example is self-contained and includes all necessary files to get started. Pick an example similar to your use case and adapt it to your specific problem!
|