---
title: 'MadEvolve: LLM Evolutionary Code Optimizer'
url: https://www.emergentmind.com/topics/madevolve
type: topic
---

# MadEvolve: LLM Evolutionary Code Optimizer

MadEvolve is a general-purpose, LLM-driven evolutionary framework for optimizing algorithms as executable code. It begins from a baseline human algorithm implementation, mutates marked code regions, evaluates each candidate with a task-specific automated fitness, and retains high-performing variants in a diverse population. In the cosmology formulation, the framework emphasizes explicit free-parameter handling, nested optimization of structure and parameters, and automated scientific reporting; a later study adapts the same machinery to algorithmic trading, where the mutable code spans execution logic, target computation, limit-order placement, and feature pipelines [2602.15951] [2605.23007].

## 1. Scope, lineage, and defining characteristics

MadEvolve was introduced as a framework for LLM-driven discovery and optimization of scientific algorithms and was applied to three problems in computational cosmology: reconstruction of cosmological initial conditions, 21cm foreground contamination reconstruction, and effective baryonic physics in N-body simulations. The cosmology paper describes it as similar to Google’s AlphaEvolve, but with a stronger emphasis on free parameters and their optimization. The same framework was subsequently adapted to optimize algorithmic trading strategies and alpha-generation pipelines for Bitcoin minute bars [2602.15951] [2605.23007].

The defining design choice is to treat an algorithm as a program subject to iterative mutation, while a domain evaluator provides a verifiable reward signal. In the cosmology setting, this reward is a deterministic physics metric; in the trading setting, it is primarily impact-adjusted PnL on a held-out validation year, with a separate forecasting run scored by a weighted combination of $R^2$, IC, and ICIR. This yields a closed-loop propose–evaluate–refine system in which surrounding infrastructure is preserved and only explicitly marked code regions are evolved [2602.15951] [2605.23007].

| Domain | Representative tasks | Reported emphasis |
|---|---|---|
| Computational cosmology | BAO/IC reconstruction, 21 cm tidal reconstruction, LDL/tSZ prediction | Free-parameter optimization, autodiff, automated scientific reports |
| Quantitative finance | Target logic, order placement, joint strategy, feature evolution | Impact-adjusted backtesting, parameter budgets, p-hacking evaluation |

A plausible implication is that MadEvolve’s identity is best understood at the framework level rather than as a single domain-specific optimizer: the same population machinery, mutation loop, and evaluator-centered search are reused across substantially different scientific and engineering problems.

## 2. Evolutionary program architecture

MadEvolve starts from a baseline human algorithm implementation, designated as a seed program. The region subject to mutation is marked with `EVOLVE-BLOCK-START/END`, while the surrounding I/O and evaluation hooks are preserved. Parent selection draws from a hybrid population comprising islands, MAP-Elites, and a global elite archive. Inspiration retrieval then fetches exemplars such as the global best, recent top performers, and diverse neighbors; these are injected into a domain-specific prompt together with the parent code, metrics, and weaknesses [2602.15951].

Candidate generation supports three modes: diff patches for incremental refinement, full rewrites for broader exploration, and synthesis from multiple references. The cosmology paper states that the proportions are configurable and defaults favor diffs at approximately 70%; the trading paper likewise reports roughly 70% patches and roughly 30% rewrites. Invalid or non-executable proposals are rejected after syntactic or runtime validation in a sandboxed evaluator, and tracebacks are logged [2602.15951] [2605.23007].

Population management is explicitly diversity-preserving. MAP-Elites retains the best program per cell, indexed by code complexity, diversity via embeddings, and performance in the trading paper, and by feature bin in the cosmology paper. A five-island model with ring migration every five generations at 10% transfer is reported for trading; the cosmology paper likewise uses islands, migration, and an elite archive, and reports global run statistics over four runs and 2,126 generations [2605.23007] [2602.15951].

MadEvolve also includes automated reporting. The cosmology paper specifies a three-stage pipeline: lineage extraction, comparative analysis, and synthesis. The generated report compares evolved and baseline algorithms, identifies innovations, lists free parameters and their meanings and values, includes code excerpts and metrics, and can contain full code for the baseline and best algorithm [2602.15951].

## 3. Nested optimization, model routing, and evaluation

A central feature of MadEvolve is explicit free-parameter handling. Newly introduced tunable parameters are declared in code via a configuration block, with initial values, bounds, and an optimization method. The framework then optimizes those parameters before final fitness scoring, so algorithmic ideas are not judged at arbitrary defaults. In the cosmology formulation this is described as nested optimization: an outer evolutionary loop searches structural code changes, while an inner loop tunes continuous parameters by reverse-mode autodiff when possible, or by budgeted derivative-free search otherwise [2602.15951].

For differentiable pipelines, MadEvolve uses JAX for BAO and 21 cm tasks and `vmad` for LDL/tSZ. The reported inner-loop optimizer is Adam for 10–50 iterations with $\eta=0.1$, $\beta_1=0.9$, $\beta_2=0.999$, and early stopping when $\|\nabla\|<10^{-5}$. When operations are non-differentiable, newly introduced parameters are tuned once under a strict evaluation budget by grid search, Latin hypercube sampling, or Gaussian-process Bayesian optimization, then frozen in code unless the LLM later removes and reintroduces them [2602.15951].

The general objective is to maximize a task-dependent fitness $S(A_\theta)$. For BAO, the paper gives a negated-plus-penalty objective
$$
J_{\mathrm{BAO}}(\theta)= -\bar r_{\mathrm{BAO}}(\theta) + \lambda \cdot \max_{k\in K_{\mathrm{LS}}}\left[r_{\mathrm{base}}(k)-r_\theta(k),0\right],
$$
with $K_{\mathrm{LS}}=\{k\le 0.2\ h\ \mathrm{Mpc}^{-1}\}$ and $\lambda=10$ [2602.15951].

Model selection within the LLM ensemble is handled by a UCB1-style bandit:
$$
UCB_i=\left(\bar r_i + c_t \sqrt{\ln N / n_i}\right) w_i,\qquad c_t=c_0\gamma^N.
$$
Here, $\bar r_i$ is the average fitness improvement from model $M_i$, $n_i$ is its usage count, $N$ is the total number of queries, and $w_i$ is a prior weight. This mechanism is reported in the cosmology paper; the trading paper similarly uses an LLM ensemble with routing across Gemini 3 Pro/Flash, GPT-5.2, o4-mini, and Claude Opus 4.6, and analyzes model-specific improvement rates and lineage contributions [2602.15951] [2605.23007].

In the trading adaptation, evaluation is backtester-centered rather than autodiff-centered. Fitness for strategy runs is impact-adjusted PnL on the 2024 validation year, not Sharpe, because Sharpe can be inflated by trading too selectively. The primary per-minute definition is
$$
PnL_t^{\mathrm{adj}} = PnL_t - I_t,
$$
where $I_t$ is the interval impact charge from a propagator impact model. The forecasting-only run instead optimizes a composite score over validation $R^2$, IC, and ICIR, with weights $0.4$, $0.3$, and $0.3$ respectively, after clamping each metric to bounded ranges [2605.23007].

## 4. Cosmological instantiations

The cosmology paper evaluates MadEvolve on three tasks with deterministic metrics and fixed simulation pipelines: BAO/initial-condition reconstruction on Quijote simulations, 21 cm tidal reconstruction on degraded Quijote boxes, and LDL/tSZ prediction on CAMELS paired DM–hydro boxes [2602.15951].

For BAO/IC reconstruction, the primary metric is the Fourier-space cross-correlation coefficient
$$
r(k)=\frac{\langle \delta_{\mathrm{rec}}(k)\delta^*_{\mathrm{IC}}(k)\rangle}{\sqrt{\langle |\delta_{\mathrm{rec}}(k)|^2\rangle \langle |\delta_{\mathrm{IC}}(k)|^2\rangle}},
$$
averaged over $k\in[0.01,0.5]\ h\ \mathrm{Mpc}^{-1}$, together with a large-scale safeguard that penalizes degradation for $k\le 0.2\ h\ \mathrm{Mpc}^{-1}$. Starting from a standard Zel’dovich baseline, the reported best evolved algorithm improves $\bar r_{\mathrm{BAO}}$ from $0.752$ to $0.924$ $(+22.8\%)$. Starting from an iterative reconstruction baseline, the best evolved algorithm improves $\bar r_{\mathrm{BAO}}$ from $0.933$ to $0.959$ $(+2.8\%)$, with a modest runtime increase of approximately $+13.4\%$ [2602.15951].

The discovered BAO innovations are described as tensor-invariant augmentation, spectral “de-warping,” and coherence-gated fusion in the standard-baseline setting, and as guided anisotropic diffusion, residual advection, a 2LPT source, and an EFT-like counterterm with a hard spectral gate in the iterative-baseline setting. The paper also notes that the stronger algorithm evolved from standard reconstruction is approximately $8\times$ slower than baseline because of FFT-heavy invariants and multi-pass filtering [2602.15951].

For 21 cm tidal reconstruction, the degraded field is constructed with a foreground high-pass along the line of sight, a shortest-baseline cutoff, and thermal noise. The metric is the cylindrical correlation coefficient
$$
r_{2D}(k_\perp,k_\parallel)=\frac{\langle \delta_{\mathrm{rec}}\delta^*_{\mathrm{true}}\rangle}{\sqrt{\langle |\delta_{\mathrm{rec}}|^2\rangle \langle |\delta_{\mathrm{true}}|^2\rangle}},
$$
averaged over designated wedge bins. The reported best evolved algorithm improves $\bar r_{2D}$ from $0.743$ to $0.971$ $(+30.7\%)$; a compact 9-parameter variant reaches $0.970$, or $99.8\%$ of the 64-parameter best, and runs approximately $3\times$ faster [2602.15951].

For LDL/tSZ prediction, the baseline uses three displacement-field layers followed by a scalar mapping from the third density field to a tSZ proxy. Evolution uses mean $r(k)$ across validation realizations as fitness, while also monitoring the transfer function
$$
T(k)=\sqrt{P_{\mathrm{pred}}/P_{\mathrm{true}}}.
$$
The best evolved model reduces test $L1$ loss from $0.613$ to $0.230$ $(-63\%)$, improves $\bar r(k)$ from $0.943$ to $0.969$ $(+2.8\%)$, and reduces mean amplitude-calibration error $|T-1|$ from $222\%$ to $90\%$ [2602.15951].

| Task | Baseline to evolved outcome | Noted innovations |
|---|---|---|
| BAO/IC reconstruction | $\bar r_{\mathrm{BAO}}: 0.752 \rightarrow 0.924$; iterative $0.933 \rightarrow 0.959$ | Tensor-invariant augmentation, spectral “de-warping,” coherence-gated fusion |
| 21 cm tidal reconstruction | $\bar r_{2D}: 0.743 \rightarrow 0.971$ | Anisotropic filtering, generalized anisotropic potential, split-weight tensor projection |
| LDL/tSZ prediction | $L1: 0.613 \rightarrow 0.230$; $\bar r(k): 0.943 \rightarrow 0.969$ | Hybrid thermo-virial factorization, screened virial temperature, gated “shock” temperature |

These results are paired with explicit generalization protocols: one training realization for evolution and nine held-out test simulations for the Quijote tasks, and a single CAMELS training realization with separate validation and six held-out test realizations for tSZ. This suggests that MadEvolve is being evaluated not only as a generator of high in-sample programs but as a search process whose outputs are expected to transfer across simulation instances [2602.15951].

## 5. Trading adaptation

The trading paper applies MadEvolve to Bitcoin trading on exchange-aggregated Polygon BTCUSD 1-minute OHLCV candles, with train data from 2022–2023 for forecaster fitting, validation data from 2024 for evolutionary fitness, and an out-of-sample test window from 2025-01-01 to 2025-10-10. The execution model uses passive limit orders, one-minute decision cadence, a stale-information correction, one resting order at a time, and cancel/replace each minute. Fees are fixed at 15 bps of notional, and market impact is modeled by a propagator with defaults $V=\$2B$, $\alpha_{\mathrm{perm}}=0.005$, $\alpha_{\mathrm{trans}}=0.010$, $\tau_0=300\,\mathrm{s}$, $\beta=0.5$, and $\delta=0.5$ [2605.23007].

The mutable program regions differ by run. Run 1 evolves `set_target()`, Run 2 evolves `set_limit_order()`, Run 3 evolves `set_passive_order_data()`, Run 4 evolves `default_calcset()` for the feature pipeline, and Run 5 jointly evolves the feature pipeline together with the strategy. The baseline forecaster is ridge regression on three EMA features with halflives of 1, 5, and 10 minutes; evolved calcsets expand to multi-scale momentum, mean-reversion state, volume and order-flow proxies, volatility regime context, candle-shape derivatives, VWAP deviations, Donchian/Bollinger/RSI/MACD variants, and time-of-day periodics [2605.23007].

The common baseline across Runs 1–3 and 5 is reported as validation Sharpe $4.81$, impact-adjusted PnL $\$83$K, and volume $\$502$M; test Sharpe $3.82$, impact-adjusted PnL $\$47$K, and win rate $60.1\%$. Against this baseline, Run 2, which evolves order placement alone, produces the largest absolute PnL: validation impact-adjusted PnL of $\$2.238$M and test impact-adjusted PnL of $\$1.205$M, with test Sharpe $5.12$ $(+1.29)$. Run 5, which jointly evolves features and strategy, yields the highest risk-adjusted performance: validation impact-adjusted PnL of $\$1.855$M, validation Sharpe $8.85$, test impact-adjusted PnL of $\$724$K, and test Sharpe $5.65$ $(+1.83)$ [2605.23007].

| Run | Evolved component | Reported test outcome |
|---|---|---|
| Run 1 | Target only | PnL $\$271$K; Sharpe $4.45$ |
| Run 2 | Order only | PnL $\$1.205$M; Sharpe $5.12$ |
| Run 3 | Joint strategy | PnL $\$473$K; Sharpe $5.11$ |
| Run 5 | Joint features + strategy | PnL $\$724$K; Sharpe $5.65$ |

The forecasting-only run reports that an evolved 77-feature calcset improves the validation combined score by $51\%$ from $0.0848$ to $0.1281$, doubles 10-minute-horizon validation $R^2$ from $0.0021$ to $0.0043$, and improves IC from $0.0736$ to $0.1100$ and ICIR from $1.03$ to $1.56$. Out of sample, $R^2$ doubles from $0.0017$ to $0.0034$, IC rises from $0.0592$ to $0.0989$, and ICIR improves from $0.99$ to $1.35$ [2605.23007].

The paper explicitly distinguishes sizing from algorithmic improvement. A counterfactual sized baseline under the same impact model shows that evolved PnL exceeds pure rescaling by $1.2$–$2.9\times$ on test and $1.4$–$4.1\times$ on validation, while out-of-sample Sharpe improves by $+0.62$, $+1.29$, $+1.29$, and $+1.83$ across Runs 1–3 and 5. It also reports a comparison with Claude Code: that approach attains strong feature-evolution results and, after Optuna recalibration, test impact-adjusted PnL of $\$235$K and Sharpe $5.27$, but the MadEvolve trading study argues that structured population search, parameter budgets, and IS-to-OOS retention analysis are central in the high-noise setting of finance [2605.23007].

## 6. Reproducibility, limitations, and naming

MadEvolve is accompanied by explicit reproducibility infrastructure. The cosmology paper describes a program database that stores source code, diffs, parameter specifications and values, `metrics.json`, LLM model used, generation mode, MAP-Elites cell, island id, and timestamps for each generation. Deterministic evaluators, explicit seeds, and full code snapshots in reports are intended to facilitate reproducibility. The reported cosmology environment includes Ubuntu 20.04, CUDA 11.4, Python 3.12, and PyTorch 2.3, with runs performed on a workstation containing a 24-core CPU, 256 GB RAM, and 2×RTX 3090. Public resources include `madevolve.org`, the framework repository, and the cosmology-task repository [2602.15951].

The trading paper likewise gives concrete reproduction guidance: use Polygon BTCUSD minute bars with the stated train/validation/test splits; implement the Appendix backtester with the specified fee and impact parameters; mark the same EVOLVE-BLOCKs; configure MAP-Elites, islands, migration, and the LLM ensemble; optimize on validation and evaluate the best program unchanged on test. Reported trading runs span 743–1,059 candidates over approximately 8.5–19 hours, depending on the run [2605.23007].

Limitations are explicit in both domains. In cosmology, failure modes include syntactic and type errors, increasing difficulty with non-differentiable operations, reward hacking without task-aware penalties, interpretability problems arising from patchworks of sensible but eclectic components, and generalization limits from simulation-only evaluation. Proposed future directions include an automated repair agent, reference mining, Pareto optimization such as NSGA-III, cross-task transfer, interactive steering, and faster operator libraries. In trading, the reported risks include overfitting to passive limit-only fill assumptions, fee and impact misspecification, aggregated Polygon data, latency and lookahead artifacts, regime shifts, and venue-specific deviations in live microstructure. Recommended best practices are to hold out an independent test split, limit free parameters, prefer impact-adjusted PnL over Sharpe as the search objective, recalibrate execution when alpha scale changes, and use ensembles for mutation diversity [2602.15951] [2605.23007].

A recurrent source of confusion is the name itself. A separate multi-agent-systems paper explicitly states that it does not mention a system named “MadEvolve”; that work introduces Meta-Team for collaborative self-evolution of LLM-based multi-agent systems and is relevant only by analogy, not by nomenclature. Accordingly, in the literature represented here, “MadEvolve” refers to the executable-code evolutionary optimization framework instantiated in cosmology and trading, rather than to a multi-agent self-evolution framework [2605.29790].

Source: https://www.emergentmind.com/topics/madevolve