From cb3cbcb8cc0c7ed1a75a5c19937d669e91106929 Mon Sep 17 00:00:00 2001 From: Bas van Stein Date: Tue, 1 Dec 2026 13:20:06 +0100 Subject: [PATCH 1/6] EoH follows the run seed; ReEvo gets its per-call temperatures EoH calls random.seed(2024) on Python's global random module when it starts, so its parent selection was identical for every run seed, and in parallel runs it reset the random state of other methods. EoH's modules now use a per-run random.Random seeded from BLADE's run seed (or the new `seed` option), and EoH's reseed is ignored. ReEvo asks for temperature + 0.3 for its initial population; BLADE's adapter dropped it. LLM.query_at_temperature passes a per-call temperature to providers that accept one (LLM.accepts_temperature), and ReEvo's base temperature is now the LLM's own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HiY2guDd9wWLKRWPoa16yy --- CHANGELOG.md | 15 +++ iohblade/llm.py | 52 ++++++++ iohblade/methods/eoh.py | 62 +++++++++- iohblade/methods/reevo.py | 18 ++- tests/unit/test_method_randomness.py | 175 +++++++++++++++++++++++++++ 5 files changed, 318 insertions(+), 4 deletions(-) create mode 100644 tests/unit/test_method_randomness.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0376bc9..8a133db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,21 @@ evaluator now moves the centres around the origin, reduces the angles modulo 60 degrees (the score is invariant to both), and rejects a hexagon whose computed sides are not 1. +- **EoH follows the run seed.** EoH calls `random.seed(2024)` on Python's + global `random` when it starts, so its parent selection was the same for + every run seed, and with parallel runs it also reset the random state of + the other methods. BLADE now gives each EoH run its own random generator, + seeded from the run seed, and ignores EoH's reseed. The new `seed` option + fixes EoH's choices (`seed: 2024` reproduces EoH's own behaviour). +- **ReEvo's initial population gets its higher temperature.** ReEvo asks + for the LLM's temperature + 0.3 for its initial population, but BLADE's + adapter ignored per-call temperatures. It now passes them on, and uses + the LLM's own temperature as ReEvo's base. +- **Per-call temperatures:** `LLM.query_at_temperature(session, + temperature)` passes a temperature to providers that accept one + (OpenAI-compatible, DeepSeek, Gemini, Ollama; see + `LLM.accepts_temperature`); other providers use their own setting, with + a warning. ## v1.2.2 (2026-11-26) diff --git a/iohblade/llm.py b/iohblade/llm.py index a9141aa..bc2df04 100644 --- a/iohblade/llm.py +++ b/iohblade/llm.py @@ -4,6 +4,7 @@ import copy import importlib +import inspect import logging import random import re @@ -364,6 +365,54 @@ def query(self, session: list, **kwargs): return message + def accepts_temperature(self) -> bool: + """Whether ``query`` can pass a per-call ``temperature`` to the provider. + + True when the provider's ``_query`` takes a ``temperature`` argument + or arbitrary keyword arguments (OpenAI-compatible, DeepSeek, Gemini, + Ollama); for a ``Multi_LLM`` only when all its LLMs do. + + Returns: + bool: True if a per-call temperature reaches the provider. + """ + try: + params = inspect.signature(self._query).parameters.values() + except (TypeError, ValueError): + return False + return any( + p.name == "temperature" or p.kind is inspect.Parameter.VAR_KEYWORD + for p in params + ) + + def query_at_temperature(self, session: list, temperature: float | None): + """Query with a per-call sampling temperature, where supported. + + Methods such as ReEvo and ShinkaEvolve ask for a different temperature + for some calls. The temperature is passed on when the provider accepts + it (see :meth:`accepts_temperature`); otherwise the LLM's own setting + is used and a warning is given once. + + Args: + session: The messages to send. + temperature: The temperature for this call, or None for the + LLM's own setting. + + Returns: + str: The text of the response. + """ + if temperature is None or temperature == getattr(self, "temperature", None): + return self.query(session) + if not self.accepts_temperature(): + if not getattr(self, "_warned_temperature", False): + self._warned_temperature = True + warnings.warn( + f"{type(self).__name__} does not take a per-call " + f"temperature; requested {temperature} is ignored.", + stacklevel=2, + ) + return self.query(session) + return self.query(session, temperature=temperature) + def _log_call(self, session: list, message: str | None): """Log the prompt and the response of one call with tokens and cost. @@ -613,6 +662,9 @@ def _query(self, session_messages, **kwargs): finally: self.last_usage = getattr(llm, "last_usage", None) + def accepts_temperature(self) -> bool: + return all(llm.accepts_temperature() for llm in self.llms) + def get_config(self) -> list[dict[str, Any]]: config_data = [] for llm in self.llms: diff --git a/iohblade/methods/eoh.py b/iohblade/methods/eoh.py index 73d8e03..5884362 100644 --- a/iohblade/methods/eoh.py +++ b/iohblade/methods/eoh.py @@ -1,9 +1,11 @@ import ast import contextlib +import importlib import json import logging import math import os +import random import re import tempfile import textwrap @@ -102,6 +104,39 @@ def get_other_inf(self): # the run in the current thread from here. _EOH_RUN = threading.local() + +class _RunRandom: + """Stand-in for the ``random`` module inside EoH. + + EoH calls ``random.seed(2024)`` on the global ``random`` module when it + starts, so every run made the same parent choices whatever BLADE's run + seed, and with parallel runs it also reset the random state of the + other methods. EoH's modules get this object as their ``random`` + instead: ``seed`` does nothing, and every other function uses the + current thread's run generator (``_EOH_RUN.rng``), which BLADE seeds + per run. Outside an EoH run it falls back to the ``random`` module. + """ + + def seed(self, *args, **kwargs) -> None: + """Ignore EoH's fixed reseed (the run generator is seeded by BLADE).""" + + def __getattr__(self, name: str): + rng = getattr(_EOH_RUN, "rng", None) + return getattr(rng if rng is not None else random, name) + + +_RUN_RANDOM = _RunRandom() +# EoH modules that use ``random`` (the fixed reseed is in the first two). +_EOH_RANDOM_MODULES = ( + "eoh.eoh", + "eoh.methods.eoh.eoh", + "eoh.methods.selection.prob_rank", + "eoh.methods.selection.roulette_wheel", + "eoh.methods.selection.tournament", + "eoh.methods.selection.equal", + "eoh.methods.management.ls_sa", +) + _DESC_BRACES = re.compile(r"\{(.*?)\}", re.DOTALL) _DESC_LINE = re.compile(r"#\s*Description\s*:\s*(.*)", re.IGNORECASE) _CODE_START = re.compile(r"^(?:import|from|class|def|@)\b", re.MULTILINE) @@ -251,6 +286,13 @@ def _install_eoh_patches() -> None: eoh_interface_EC.jsonlines = _JsonlinesToRunFolder( eoh_interface_EC.jsonlines ) + for module_name in _EOH_RANDOM_MODULES: + try: + module = importlib.import_module(module_name) + except ImportError: + continue + if getattr(module, "random", None) is random: + module.random = _RUN_RANDOM # Evaluations EoH makes, read from the installed ``eoh`` package @@ -360,7 +402,19 @@ def __init__(self, llm: LLM, budget: int, name="EoH", **kwargs): llm (LLM): The LLM instance to use for solution generation. budget (int): The maximum number of evaluations. name (str): The name of the method. - kwargs: Additional arguments for configuring EoH. + kwargs: Additional arguments for configuring EoH: + + * ``pop_size`` (default 4): EoH's population size. EoH's + library default is 5 and the paper used 10-20 with larger + budgets; 4 leaves 12 generations of 4 operators x 4 + offspring after the 8 initial evaluations of a budget of + 200 (see ``_eoh_schedule``). + * ``timeout`` (default 600): EoH's own evaluation timeout in + seconds; the problem's timeout applies as well. + * ``seed`` (default None): seed of EoH's random choices + (parent selection). By default they follow BLADE's run + seed; EoH itself always reseeds with 2024, which BLADE + disables (use ``seed: 2024`` to reproduce that). """ super().__init__(llm, budget, name) self.kwargs = kwargs @@ -385,6 +439,12 @@ def __call__(self, problem: Problem): output_dir = self._output_dir(problem, stack) _EOH_RUN.llm = self.llm _EOH_RUN.output_dir = output_dir + # A random stream of its own per run: from the ``seed`` option, + # else drawn from the global generator BLADE seeded for this run. + seed = self.kwargs.get("seed") + _EOH_RUN.rng = random.Random( + random.getrandbits(64) if seed is None else seed + ) stack.callback(_EOH_RUN.__dict__.clear) requested_pop_size = self.kwargs.get("pop_size", 4) paras = Paras() diff --git a/iohblade/methods/reevo.py b/iohblade/methods/reevo.py index c08af2a..00db610 100644 --- a/iohblade/methods/reevo.py +++ b/iohblade/methods/reevo.py @@ -146,9 +146,19 @@ def _func_desc(problem: Problem, class_name: str) -> str: class _BladeReEvoClient(BaseClient): - """Adapter that exposes the interface expected by ReEvo.""" + """Adapter that exposes the interface expected by ReEvo. - def __init__(self, llm: LLM, temperature: float = 1.0) -> None: + ReEvo asks for its own temperatures: the LLM's temperature, plus 0.3 for + the initial population. The base is the BLADE LLM's own temperature + (1.0 if it has none), and a requested temperature reaches the provider + when it accepts one (:meth:`LLM.query_at_temperature`). + """ + + def __init__(self, llm: LLM, temperature: float | None = None) -> None: + if temperature is None: + temperature = getattr(llm, "temperature", None) + if not isinstance(temperature, (int, float)): + temperature = 1.0 super().__init__(model=llm.model, temperature=temperature) self.llm = llm @@ -157,7 +167,9 @@ def _chat_completion_api( ): responses = [] for _ in range(n): - content = self.llm.query(messages) + # The base temperature is the LLM's own: no per-call override. + requested = None if temperature == self.temperature else temperature + content = self.llm.query_at_temperature(messages, requested) responses.append({"message": {"role": "assistant", "content": content}}) return responses diff --git a/tests/unit/test_method_randomness.py b/tests/unit/test_method_randomness.py new file mode 100644 index 0000000..7e9ba56 --- /dev/null +++ b/tests/unit/test_method_randomness.py @@ -0,0 +1,175 @@ +"""Per-run randomness and per-call temperatures of the wrapped methods. + +* EoH reseeded Python's global ``random`` with 2024 when it started, so its + parent choices were the same for every run seed (and reset the random + state of other runs in the same process). +* ReEvo asks for a higher temperature for its initial population; BLADE's + adapter dropped it. + +The tests use fake LLMs and problems (no API calls). +""" + +import random +import types +import warnings + +import pytest + +from iohblade.llm import LLM, Multi_LLM +from iohblade.solution import Solution + +try: + import eoh.methods.eoh.eoh_interface_EC as eoh_interface_ec +except Exception: # pragma: no cover - optional dependency + eoh_interface_ec = None + + +# region Fakes. +class PlainLLM(LLM): + """A provider whose ``_query`` takes no keyword arguments.""" + + def __init__(self): + super().__init__("", "plain", None) + self.calls = [] + + def _query(self, session_messages): + self.calls.append(None) + return "ok" + + def get_config(self): + return {} + + +class TemperatureLLM(LLM): + """A provider that takes a per-call ``temperature``.""" + + def __init__(self, temperature=1.0): + super().__init__("", "temp", None) + self.temperature = temperature + self.calls = [] + + def _query(self, session_messages, temperature=None): + self.calls.append(temperature) + return "ok" + + def get_config(self): + return {} + + +class KwargsLLM(PlainLLM): + """A provider that passes any keyword arguments on (Gemini, Ollama).""" + + def _query(self, session_messages, **kwargs): + self.calls.append(kwargs.get("temperature")) + return "ok" + + +# endregion + + +# region LLM.query_at_temperature. +def test_accepts_temperature(): + assert not PlainLLM().accepts_temperature() + assert TemperatureLLM().accepts_temperature() + assert KwargsLLM().accepts_temperature() + assert Multi_LLM([TemperatureLLM(), KwargsLLM()]).accepts_temperature() + assert not Multi_LLM([TemperatureLLM(), PlainLLM()]).accepts_temperature() + + +def test_query_at_temperature_passes_it_on(): + llm = TemperatureLLM(temperature=1.0) + llm.query_at_temperature([{"role": "user", "content": "x"}], 1.3) + llm.query_at_temperature([{"role": "user", "content": "x"}], None) + llm.query_at_temperature([{"role": "user", "content": "x"}], 1.0) + assert llm.calls == [1.3, None, None] + kw = KwargsLLM() + kw.query_at_temperature([{"role": "user", "content": "x"}], 0.5) + assert kw.calls == [0.5] + + +def test_query_at_temperature_warns_once_when_unsupported(): + llm = PlainLLM() + with pytest.warns(UserWarning, match="per-call temperature"): + llm.query_at_temperature([{"role": "user", "content": "x"}], 1.3) + with warnings.catch_warnings(): + warnings.simplefilter("error") + llm.query_at_temperature([{"role": "user", "content": "x"}], 1.3) + assert llm.calls == [None, None] + + +# endregion + + +# region ReEvo. +def test_reevo_client_uses_the_llm_temperature_and_extra_heat(): + pytest.importorskip("reevo") + from iohblade.methods.reevo import _BladeReEvoClient + + llm = TemperatureLLM(temperature=0.7) + client = _BladeReEvoClient(llm) + assert client.temperature == 0.7 + messages = [{"role": "user", "content": "x"}] + # ReEvo's initial population: temperature + 0.3. + client.multi_chat_completion([messages], 2, temperature=client.temperature + 0.3) + # Other calls: the LLM's own temperature, no per-call override. + client.multi_chat_completion([messages], 1) + assert llm.calls == [pytest.approx(1.0), pytest.approx(1.0), None] + + +def test_reevo_client_without_llm_temperature_defaults_to_one(): + pytest.importorskip("reevo") + from iohblade.methods.reevo import _BladeReEvoClient + + assert _BladeReEvoClient(PlainLLM()).temperature == 1.0 + + +# endregion + + +# region EoH. +def _run_eoh(monkeypatch, tmp_path, run_seed, **kwargs): + from iohblade.methods.eoh import EoH + + if eoh_interface_ec is None: # pragma: no cover - optional dependency + pytest.skip("eoh is not installed") + monkeypatch.setattr( + eoh_interface_ec, + "time", + types.SimpleNamespace(sleep=lambda s: None, time=lambda: 0.0), + ) + monkeypatch.chdir(tmp_path) + from .test_method_budgets import RecordingProblem, TourLLM + + random.seed(run_seed) # what BLADE does before every run + llm = TourLLM() + out = tmp_path / f"run-{run_seed}-{len(list(tmp_path.iterdir()))}" + # RecordingProblem scores with the global ``random`` (seeded above). + EoH(llm, 24, pop_size=3, output_path=str(out), **kwargs)(RecordingProblem()) + return llm.prompts + + +def test_eoh_follows_the_run_seed(monkeypatch, tmp_path): + a = _run_eoh(monkeypatch, tmp_path, 1) + b = _run_eoh(monkeypatch, tmp_path, 1) + c = _run_eoh(monkeypatch, tmp_path, 2) + assert a == b # same run seed: same choices + assert a != c # EoH's fixed random.seed(2024) made these equal + + +def test_eoh_does_not_reseed_the_global_random(monkeypatch, tmp_path): + from iohblade.methods import eoh as eoh_wrapper + + _run_eoh(monkeypatch, tmp_path, 3) + random.seed(5) + expected = random.Random(5).random() + eoh_wrapper._RUN_RANDOM.seed(2024) # what EoH calls; must not reseed + assert random.random() == expected + + +def test_eoh_seed_option_fixes_the_choices(monkeypatch, tmp_path): + a = _run_eoh(monkeypatch, tmp_path, 1, seed=2024) + b = _run_eoh(monkeypatch, tmp_path, 1, seed=2024) + assert a == b and len(a) == 18 # 2*3 initial + one generation of 4*3 + + +# endregion From 3deab99198b81d02e5c1f2a30240e8ec60b2c090 Mon Sep 17 00:00:00 2001 From: Bas van Stein Date: Tue, 1 Dec 2026 16:05:34 +0100 Subject: [PATCH 2/6] Align MCTS-AHD and LHNS with the reference implementations MCTS-AHD: - Progressive widening as in the paper (Eq. 4) and the reference: every node on the selection path with int(N ** alpha) > #children gets a new child (e1 at the root, e2 elsewhere). The dead is_fully_expanded helper is removed; the root starts with 0 visits; max_children is an optional cap (default none). - Selection stops at max_depth (10); a node there is expanded again. - Exploration: lambda = lambda_0 * (1 - t / budget) (Eq. 7) and the bonus sqrt(ln(N_parent + 1) / N). - An LLM failure while generating a node uses one evaluation, is logged as a failed candidate, and the search continues. Failed candidates are discarded from the tree and the operator retried (max 3 tries), as in the reference. Nodes are evaluated and back-propagated one at a time, in the reference's operator order; s1 is skipped at depth 1. - 4 initial nodes (initial_node_count), as in the paper. LHNS: - Use the evaluated candidate returned by the problem (the current solution never moved before). - Temperature cools: T = cooling_rate * (1 - (t - 1) / budget); relative worsening in the acceptance probability. - Adaptive VNS destruction ratio (ini_ratio, reset on accept, +0.1 per reject, wrap after 1.0); ceil(r * n) lines drawn with replacement and deleted by index (trailing-whitespace lines were never deleted); def/class/import lines kept, comments dropped. - ILS/TS destroy with ini_ratio and perturb after 10 non-improving iterations in a row (ILS from the best so far, TS merging a tabu entry). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HiY2guDd9wWLKRWPoa16yy --- CHANGELOG.md | 52 +++ docs/methods_overview.rst | 9 +- iohblade/mcts_node.py | 19 - iohblade/methods/lhns/lhns.py | 534 +++++++++++++++------------- iohblade/methods/lhns/prompt.py | 2 +- iohblade/methods/mcts_ahd/mcts.py | 422 +++++++++++++--------- tests/unit/test_lhns.py | 559 ++++++++++++------------------ tests/unit/test_mcts_ahd.py | 513 +++++++++++++++------------ tests/unit/test_method_budgets.py | 46 ++- 9 files changed, 1153 insertions(+), 1003 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a133db..dc74997 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,58 @@ (OpenAI-compatible, DeepSeek, Gemini, Ollama; see `LLM.accepts_temperature`); other providers use their own setting, with a warning. +- **MCTS-AHD: progressive widening never happened.** It was decided by a + helper (dead code in the reference implementation) that treated the root + and every expanded node as "fully expanded", so the root kept its + initial children for the whole run and `alpha` had no effect. Every node + on the selection path now gets a new child when `int(N ** alpha)` exceeds + its number of children (paper Eq. 4): by e1 at the root, by e2 + elsewhere. The root starts with 0 visits, as in the reference. + `max_children` now defaults to no cap (it is an optional extra limit). +- **MCTS-AHD: `max_depth` was not used.** The selection now stops at depth + 10 (`max_depth`), and a node there is expanded again even if it has + children, as in the reference. This also bounds the s1 prompt, which + holds the whole path, to 10 algorithms. +- **MCTS-AHD: wrong exploration term.** The exploration constant was + `lambda_0 * evaluations left` (about 20 at the start of a 200-evaluation + run, against an exploitation term in [0, 1]), and the bonus divided by + `N` instead of `sqrt(N)`. It is now `lambda_0 * (1 - t / budget)` + (paper Eq. 7), decaying from 0.1 to 0, with the bonus + `sqrt(ln(N_parent + 1) / N)`. +- **MCTS-AHD: one LLM failure ended the run.** An LLM error while + generating a node (for example an empty answer to a too-long s1 prompt) + left the method and the run stopped early (two runs ended at 99 of 200 + evaluations). Such a failure now uses one evaluation, is logged as a + failed candidate, and the search continues. Failed candidates are no + longer added to the tree: as in the reference, they are discarded and + the operator is tried again (at most 3 tries, each one evaluation). + Before, an all-failing run grew one ever-deeper chain of failed nodes. + Each node is now evaluated and back-propagated as soon as it is + generated, and expansion uses the reference's order (e2, m1 x k, + m2 x k, s1; s1 is skipped at depth 1). +- **MCTS-AHD starts with 4 nodes** (one i1, three e1), as in the paper and + the reference, instead of 3 (`initial_node_count`). +- **LHNS never moved away from its first solution.** It compared the + candidate object it had sent to the evaluation, not the evaluated one + that came back, so every candidate looked unevaluated and was rejected; + all destroy-repair steps started from the initial code. It now uses the + evaluated candidate. +- **LHNS: the temperature rose instead of cooling.** It was + `cooling_rate * t / budget`; it is now `cooling_rate * (1 - (t - 1) / + budget)`, as in the reference. A worse candidate is accepted with + probability `exp(-delta / T)` with the relative worsening + `delta = |f_new - f_cur| / (|f_cur| + 1e-10)`, so acceptance no longer + depends on the scale of the fitness. +- **LHNS: destruction did not follow the reference.** The VNS ratio cycled + with the iteration number (every 10th step deleted all code); it now + starts at `ini_ratio` (0.1), is reset on acceptance and grows by 0.1 per + rejection up to 1.0, then starts again. Lines are deleted by index, so + lines with trailing whitespace are deleted too (they never were). + `ceil(r * n)` lines are drawn with replacement, `def`, `class` and import + lines are kept and comment lines are always removed. ILS and TS destroy + with `ini_ratio` and perturb after 10 iterations in a row without + improvement (ILS asks to modify the best solution so far, TS merges in a + tabu-table entry), instead of every 10th iteration. ## v1.2.2 (2026-11-26) diff --git a/docs/methods_overview.rst b/docs/methods_overview.rst index 15952eb..525cf1d 100644 --- a/docs/methods_overview.rst +++ b/docs/methods_overview.rst @@ -48,14 +48,17 @@ fairly. `paper `__ * - **LHNS** - ``lhns`` - - LLM-driven heuristic neighbourhood search: destroy and repair parts - of the best code, accepted by simulated annealing. + - LLM-driven heuristic neighbourhood search: delete lines of the + current code and let the LLM repair it; simulated annealing + accepts the result. Variants ``vns`` (the share of deleted lines + grows while candidates are rejected), ``ils`` and ``ts``. - `code `__, `paper `__ * - **MCTS-AHD** - ``mcts_ahd`` - Monte Carlo tree search over algorithms, so that weaker branches - can still be explored. + can still be explored; progressive widening adds new branches as + nodes are visited more often. - `code `__, `paper `__ * - **MoEH** diff --git a/iohblade/mcts_node.py b/iohblade/mcts_node.py index da4db71..804135a 100644 --- a/iohblade/mcts_node.py +++ b/iohblade/mcts_node.py @@ -126,22 +126,3 @@ def is_less_fit_than(self, other: MCTS_Node, maximisation: bool = True): if self.Q is None or other.Q is None: return False return self.Q < other.Q if maximisation else self.Q > other.Q - - def is_fully_expanded(self, max_children: int, maximisation: bool = True) -> bool: - """ - Check for completion of progressive Widening (Page 3: https://arxiv.org/pdf/2501.08603). - - ## Args: - `max_children: int`: User defined upper limit of sub-tree width. - `maximisation: bool`: The optimisation direction. - - ## Returns: - `bool`: Truth value of whether upper limit is reach or not. - """ - return ( - len(self.children) >= max_children - or any( - self.is_less_fit_than(child, maximisation) for child in self.children - ) - or self.is_root - ) diff --git a/iohblade/methods/lhns/lhns.py b/iohblade/methods/lhns/lhns.py index d7d4b3f..86b41f5 100644 --- a/iohblade/methods/lhns/lhns.py +++ b/iohblade/methods/lhns/lhns.py @@ -1,6 +1,5 @@ import math import random -import re from typing import Any from iohblade.fitness import is_better @@ -13,6 +12,10 @@ class LHNS: + #: Consecutive non-improving iterations after which ILS and TS perturb + #: (``ils_count >= 10`` in the reference implementation). + STAGNATION_LIMIT = 10 + def __init__( self, problem: Problem, @@ -22,25 +25,52 @@ def __init__( table_size: int = 10, budget=100, minimisation=False, + ini_ratio: float = 0.1, ): - """ - LHNS is a single individual based optimisation method, that destroyes current iteration of code, by deleting number of certain lines of code - and uses LLMs to repair them. More info on (https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=11043025) - - ## Args: - `problem: iohblade.Problem` instance of a problem to be solved, with prompts and evaluate function as it's members. - `llm: iohblade.LLM`: A llm object to communicate with LLMs. - `method: str`: String literal in one of 'vns', 'ils' or 'ts'. - `cooling_rate: float`: Used to guide current solution update decision, higher cooling_rate leads to more random selection of next iteration earlier. - `table_size: int`: Max table size for storing taboo table elements. - `minimisation: bool`: Optimisation direction of the problem. + """LLM-driven heuristic neighbourhood search (LHNS). + + A single-solution method: it deletes lines of the current code + (destruction) and asks the LLM to repair it. A candidate replaces + the current solution by simulated annealing. Follows the reference + implementation (https://github.com/Acquent0/LHNS); paper: + https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=11043025. + + - Temperature: ``T = cooling_rate * (1 - (t - 1) / budget)`` at + iteration ``t``, so it cools linearly to almost 0. + - A worse candidate is accepted with probability + ``exp(-delta / T)``, where ``delta = |f_new - f_cur| / + (|f_cur| + 1e-10)`` is the relative worsening. + - Destruction: ``ceil(r * n)`` of the ``n`` content lines are + drawn with replacement and deleted; ``def`` and import lines + (and ``class`` lines) are kept and comment lines always removed. + - VNS: ``r`` starts at ``ini_ratio``, is reset to it when a + candidate is accepted and grows by 0.1 per rejection up to 1.0, + after which it starts again at ``ini_ratio``. + - ILS and TS destroy with ``r = ini_ratio``. After + ``STAGNATION_LIMIT`` (10) iterations in a row without improving + the current solution, ILS asks the LLM to modify the best + solution so far and TS merges in features of a tabu-table entry. + + Args: + problem: The problem to solve, with its prompts and evaluation. + llm: The LLM that generates and repairs code. + method: One of ``"vns"``, ``"ils"`` or ``"ts"``. + cooling_rate: Initial temperature of the simulated annealing + (0.1 in the reference implementation). + table_size: Size of the tabu table (TS only). + budget: Number of evaluations: the initial solution plus + ``budget - 1`` iterations. + minimisation: Optimisation direction of the problem. + ini_ratio: Initial (and, for ILS and TS, fixed) destruction + ratio ``r`` (0.1 in the reference implementation). + + Raises: + ValueError: If ``method`` is not one of the three variants. """ self.problem: Problem = problem self.llm: LLM = llm self.table_size: int = table_size - try: - assert method in ["vns", "ils", "ts"] - except: + if method not in ["vns", "ils", "ts"]: raise ValueError( f"Expected method parameter to be one of 'vns', 'ils', 'ts', got {method}" ) @@ -55,6 +85,11 @@ def __init__( self.alpha = cooling_rate self.budget = budget self.minimisation = minimisation + self.ini_ratio = ini_ratio + # Destruction ratio r, adapted by VNS (fixed for ILS and TS). + self.ratio = ini_ratio + # Iterations in a row without improving the current solution. + self.stagnation_count = 0 self.current_solution = Solution() self.best_solution = Solution() @@ -68,50 +103,81 @@ def _log_best_solution(self, next: Solution): ): self.best_solution = next - def simulated_annealing(self, next_solution: Solution, iteration_number: int): + def temperature(self, iteration_number: int) -> float: + """Temperature of the simulated annealing at an iteration. + + ``T = cooling_rate * (1 - (t - 1) / budget)``: it starts at + ``cooling_rate`` and cools linearly towards 0, as in the reference + implementation. + + Args: + iteration_number: The iteration ``t`` (1 for the first). + + Returns: + The temperature, never below 0. """ - Selects the replacement of `self.current_solution` with next solution with probability $P(r) = e^{-|f_1-f_2|/T$, - where $T = \alpha iteration_number/budget$. + return max(self.alpha * (1 - (iteration_number - 1) / self.budget), 0.0) - ## Args: - `next_solution: Solution`: Next repaired solution which is potentially going to replace the current individual. - `iteration_number: int`: Current iteration number. + def simulated_annealing( + self, next_solution: Solution, iteration_number: int + ) -> tuple[bool, bool]: + """Decide whether ``next_solution`` replaces the current solution. - ## Returns: - `None`: Will replace self.current_solution with aforementioned probability. + A better candidate is always accepted. A candidate that is not + better is accepted with probability ``exp(-delta / T)``, where + ``delta = |f_new - f_cur| / (|f_cur| + 1e-10)`` is the relative + worsening and ``T`` is :meth:`temperature`. A failed candidate + (non-finite fitness) is never accepted over a valid current + solution. + + Args: + next_solution: The evaluated candidate. + iteration_number: The current iteration ``t`` (1 for the first). + + Returns: + ``(accepted, improved)``: whether the candidate became the + current solution, and whether it was strictly better than it. """ print("Simulated Annealing....") - if math.isnan(self.current_solution.fitness) or math.isinf( - self.current_solution.fitness + current = self.current_solution + current_valid = current.fitness_is_valid() + next_valid = next_solution.fitness_is_valid() + if not next_valid: + if not current_valid: + self.current_solution = random.choice([current, next_solution]) + return self.current_solution is next_solution, False + return False, False + if not current_valid or is_better( + next_solution.fitness, current.fitness, self.minimisation ): - if math.isnan(next_solution.fitness) or math.isinf(next_solution.fitness): - self.current_solution = random.choice( - [self.current_solution, next_solution] - ) - else: - self.current_solution = next_solution - return - if math.isnan(next_solution.fitness) or math.isinf(next_solution.fitness): - return - - temperature = self.alpha * iteration_number / self.budget - - if self.minimisation: - if next_solution.fitness < self.current_solution.fitness: - self.current_solution = next_solution - else: - delta = abs(next_solution.fitness - self.current_solution.fitness) - p = math.e ** (-1 * delta / temperature) - if random.random() <= p: - self.current_solution = next_solution + self.current_solution = next_solution + return True, True + + temperature = self.temperature(iteration_number) + delta = abs(next_solution.fitness - current.fitness) / ( + abs(current.fitness) + 1e-10 + ) + p = math.exp(-delta / temperature) if temperature > 0 else 0.0 + if random.random() < p: + self.current_solution = next_solution + return True, False + return False, False + + def update_ratio(self, accepted: bool): + """Adapt the VNS destruction ratio after an iteration. + + Reset to ``ini_ratio`` on acceptance; otherwise grow by 0.1 up to + 1.0, and start again from ``ini_ratio`` after 1.0. + + Args: + accepted: Whether the iteration's candidate was accepted. + """ + if accepted: + self.ratio = self.ini_ratio + elif self.ratio < 1.0: + self.ratio = round(self.ratio + 0.1, 1) else: - if next_solution.fitness > self.current_solution.fitness: - self.current_solution = next_solution - else: - delta = abs(next_solution.fitness - self.current_solution.fitness) - p = math.e ** (-1 * delta / temperature) - if random.random() <= p: - self.current_solution = next_solution + self.ratio = self.ini_ratio def initialise(self): """ @@ -125,22 +191,36 @@ def initialise(self): """ print("Initialise....") initialisation_prompt = self.prompt_generator.get_prompt_i1() - solution = None + self.current_solution = self._sample(initialisation_prompt) + + def _sample(self, prompt: str) -> Solution: + """Ask the LLM for a solution, trying up to 5 times. + + Args: + prompt: The prompt to send. + + Returns: + The solution the LLM generated. + + Raises: + Exception: The LLM's error, if all 5 tries fail. + """ for i in range(5): try: - solution = self.llm.sample_solution( - [{"role": "user", "content": initialisation_prompt}] - ) - self.current_solution = solution - break # One successful (paid) LLM call is enough. + return self.llm.sample_solution([{"role": "user", "content": prompt}]) except Exception as e: if i == 4: raise e + print("LHNS: Failed to communicate with LLM, retrying...") def evaluate(self, solution: Solution) -> Solution: """ Evaluates the solution with `problem()` function, and returns if it returns, else returns solution un-mutated. + The problem may return another object than ``solution`` (it does + when the evaluation runs in a subprocess), so callers must use the + returned solution. + ## Args: `solution: Solution`: A solution object that needs to be evaluated. @@ -155,217 +235,161 @@ def evaluate(self, solution: Solution) -> Solution: return evaluated_solution return solution + @staticmethod + def _is_kept_line(stripped: str) -> bool: + """Whether a (stripped) line is never deleted: blank, ``def`` or + import lines as in the reference, and ``class`` lines (BLADE's + problems ask for classes, the reference for a function).""" + return ( + stripped == "" + or stripped.startswith(("def ", "async def ", "class ")) + or stripped.startswith("import") + or (stripped.startswith("from ") and " import " in stripped) + ) + def _extract_executable_lines_with_indices( self, code: str ) -> list[tuple[int, str]]: - """ - Return list of (line_number, line_text) for lines that are executable, - excluding class/def declarations, comments and blank lines. + """Return the content lines that destruction may delete. - ## Args; + As in the reference implementation (``delete_lines`` in + ``lhns_prompt.py``), every line that is not blank, not a + ``def``/import line and not a comment is a content line + (docstring lines included). ``class`` lines are kept as well. + + ## Args: `code: str`: A python code string, that is going through destruction phase. ## Returns: - `(line_number, str)`: line_number is 0 indexed line number corresponding to the text, representing executable code. + `[(line_number, str)]`: 0-indexed line numbers and the lines as written. """ - doc_pat = re.compile(r'(?s)(""".*?"""|\'\'\'.*?\'\'\')') - - def _preserve_lines(m): - matched = m.group(0) - lines = matched.count("\n") - return "\n" * lines - - code_preserve_lines = doc_pat.sub(_preserve_lines, code) - - lines = code_preserve_lines.splitlines() - - pattern = re.compile(r"^(?!\s*(?:class\s+\w+|def\s+\w+|#))\s*\S.*$") - result = [] - for i, line in enumerate(lines): - if pattern.match(line): - result.append((i, line.rstrip())) + for i, line in enumerate(code.split("\n")): + stripped = line.strip() + if self._is_kept_line(stripped) or stripped.startswith("#"): + continue + result.append((i, line)) return result - def get_destroyed_code(self, r: float, solution: Solution) -> str: - """ - Destroy repair mutation, takes `self.current_solution`, deletes `r * 100`% of the code. And uses LLM to repair that code\ - fragment into a new code, from that destroyed code. + def destroy_code(self, r: float, solution: Solution) -> tuple[str, int]: + """Delete lines of ``solution.code`` (the destruction step). + + As in the reference implementation: ``k = ceil(r * n)`` of the + ``n`` content lines are drawn with replacement (so ``r = 1.0`` + deletes about 63% of distinct lines) and deleted by index, and all + comment lines are removed. ``def``, import and ``class`` lines are + kept. + ## Args: - `r: float`: Ratio of executable lines that needs to be destroyed. - `solution: Solution`: An instance of the current_individual, that needs to be mutated. + `r: float`: Destruction ratio in (0, 1]. + `solution: Solution`: The solution whose code is destroyed. ## Returns: - `code_fragment: str`: A destroyed code with r * number of executable lines in code, removed. - """ - code = solution.code - code_lines = code.split("\n") - destructable_code = self._extract_executable_lines_with_indices(code) - delete_count = 0 - # select deletable lines: - lines_to_delete = [] - for _ in range(int(r * len(destructable_code))): - delete_line = random.choice(destructable_code) - lines_to_delete.append(delete_line) - destructable_code.remove(delete_line) - - lines_to_delete.sort(key=lambda line_to_delete: line_to_delete[0], reverse=True) - # delete r * len(destructable_code) lines. - for lc, line_to_delete in lines_to_delete: - if code_lines[lc] == line_to_delete: - code_lines.pop(lc) - delete_count += 1 - print(f"\t\tDeleted {delete_count} lines.") - return "\n".join(code_lines) - - def mutate_lhns_vns(self, iteration_number: int) -> Solution: + `(destroyed_code, k)`: The code without the deleted lines, and + the number ``k`` of drawn lines, reported to the LLM as the + number of removed lines (as the reference does). """ - Apply LHNS VNS from work (https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=11043025), the initial r value is not stated, - so it will be randomly generated. + lines = solution.code.split("\n") + comment_lines = { + i for i, line in enumerate(lines) if line.strip().startswith("#") + } + content = [ + i for i, _ in self._extract_executable_lines_with_indices(solution.code) + ] + k = min(math.ceil(r * len(content)), len(content)) + deleted = set(random.choices(content, k=k)) if k > 0 else set() + to_delete = comment_lines | deleted + print(f"\t\tDeleted {len(deleted)} distinct lines (k = {k}).") + return ( + "\n".join(line for i, line in enumerate(lines) if i not in to_delete), + k, + ) - ## Args: - `iteration_number: int`: Current iteration of the algorithm. + def get_destroyed_code(self, r: float, solution: Solution) -> str: + """Destroyed code only; see :meth:`destroy_code`.""" + return self.destroy_code(r, solution)[0] + + def _strip_comment_lines(self, code: str) -> str: + """The code without its comment lines (TS perturbation, as the + reference's ``ts_merge_features``).""" + return "\n".join( + line for line in code.split("\n") if not line.strip().startswith("#") + ) + + def _destroy_repair(self, r: float) -> Solution: + """Destroy ``r`` of the current code and ask the LLM to repair it.""" + current = self.current_solution + destroyed_code, deleted_count = self.destroy_code(r, current) + prompt = self.prompt_generator.get_prompt_destroy_repair( + current, destroyed_code, deleted_count + ) + return self._sample(prompt) + + def _perturbation_due(self) -> bool: + """Whether ILS/TS perturb in this iteration; resets the counter.""" + if self.stagnation_count >= self.STAGNATION_LIMIT: + self.stagnation_count = 0 + return True + return False + + def mutate_lhns_vns(self) -> Solution: + """One VNS step: destroy-repair with the adaptive ratio ``self.ratio``. ## Returns - `Solution`: An instance of solution generated from LHNS-VNS mapping onto the self.current_solution. + `Solution`: The repaired candidate. ## Raises: - If the LLM is not following the contract, or if you run out of tokens, the Errors are reaised respectively. + The LLM's error if it fails 5 times in a row. """ print("VNS Mutations....") - current = self.current_solution - r = 0.1 * (1 + (iteration_number % 10)) + return self._destroy_repair(self.ratio) - destroyed_code = self.get_destroyed_code(r, current) - destruction_count = len(current.code.split("\n")) - len( - destroyed_code.split("\n") - ) - destruction_repair_prompt = self.prompt_generator.get_prompt_destroy_repair( - current, destroyed_code, destruction_count - ) + def mutate_lhns_ils(self) -> Solution: + """One ILS step. - for i in range(5): - try: - new = self.llm.sample_solution( - [{"role": "user", "content": destruction_repair_prompt}] - ) - return new - except Exception as e: - if i == 4: - raise e - return current - - def mutate_lhns_ils(self, iteration_number: int) -> Solution: - """ - Apply LHNS INS from work (https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=11043025), the value of r is set constant to - 0.5, and this mutation eiter generarates a new code with 50% repaired code, or a complete new initialisation (rewrite of the code.) - - ## Args: - `iteration_number: int`: Current iteration of the algorithm. + Normally destroy-repair of the current solution with + ``r = ini_ratio``. After ``STAGNATION_LIMIT`` non-improving + iterations in a row, the perturbation of the reference (``p1``): + the LLM is asked to modify the best solution found so far. ## Returns - `Solution`: An instance of solution generated from LHNS-ILS mapping onto the self.current_solution, provided LLM generated - a solution. + `Solution`: The new candidate. ## Raises: - If the LLM is not following the contract, or if you run out of tokens, the Errors are reaised respectively. + The LLM's error if it fails 5 times in a row. """ print("ILS Mutation....") - if iteration_number % 10 == 9: - initialisation_prompt = self.prompt_generator.get_prompt_i1() - for i in range(5): - try: - new = self.llm.sample_solution( - [{"role": "user", "content": initialisation_prompt}] - ) - return new - except Exception as e: - if i == 4: - raise e - else: - print( - "mutate_lhns_ils: Failed to communicate with LLM, retrying..." - ) - else: - current = self.current_solution - destroyed_code = self.get_destroyed_code(0.5, current) - destruction_count = len(current.code.split("\n")) - len( - destroyed_code.split("\n") - ) - ils_prompt = self.prompt_generator.get_prompt_destroy_repair( - current, destroyed_code, destruction_count - ) - for i in range(5): - try: - new = self.llm.sample_solution( - [{"role": "user", "content": ils_prompt}] - ) - return new - except Exception as e: - if i == 4: - raise e - else: - print( - "mutate_lhns_ils: Failed to communicate with LLM, retrying..." - ) - return self.current_solution - - def mutate_lhns_ts(self, iteration_number: int) -> Solution: - """ - Apply LHNS TS from work (https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=11043025), the value of r is set constant to - 0.5, if applying taboo search, (once every 10 iterations) else apply VNS mutation for rest of the cases. - ## Args: - `iteration_number: int`: Current iteration of the algorithm. + if self._perturbation_due(): + prompt = self.prompt_generator.get_prompt_o_index(self.best_solution) + return self._sample(prompt) + return self._destroy_repair(self.ratio) + + def mutate_lhns_ts(self) -> Solution: + """One TS step. + + Normally destroy-repair of the current solution with + ``r = ini_ratio``. After ``STAGNATION_LIMIT`` non-improving + iterations in a row, the perturbation of the reference (``p2``): + the current code (without comments) and the features of a tabu-table + entry with other code are merged by the LLM. Without such an entry, + a destroy-repair step is made instead. ## Returns - `Optional[Solution]`: An instance of solution generated from LHNS-TS mapping onto the self.current_solution, provided LLM generated - a valid solution. + `Solution`: The new candidate. + + ## Raises: + The LLM's error if it fails 5 times in a row. """ print("TS Mutation....") current = self.current_solution - if iteration_number % 10 == 9: - destroyed_code = self.get_destroyed_code(0.5, current) + if self._perturbation_due(): taboo_element = self.taboo_table.get_distinct_entry(current) - destruction_count = len(current.code.split("\n")) - len( - destroyed_code.split("\n") - ) if taboo_element: prompt = self.prompt_generator.get_prompt_taboo_search( - current, destroyed_code, taboo_element + current, self._strip_comment_lines(current.code), taboo_element ) - else: - prompt = self.prompt_generator.get_prompt_destroy_repair( - current, destroyed_code, destruction_count - ) - # Send whichever prompt was built (taboo or destroy-repair). - for i in range(5): - try: - new = self.llm.sample_solution( - [{"role": "user", "content": prompt}] - ) - return new - except Exception as e: - if i == 4: - raise e - else: - current = self.current_solution - destroyed_code = self.get_destroyed_code(0.5, current) - destruction_count = len(current.code.split("\n")) - len( - destroyed_code.split("\n") - ) - ils_prompt = self.prompt_generator.get_prompt_destroy_repair( - current, destroyed_code, destruction_count - ) - for i in range(5): - try: - new = self.llm.sample_solution( - [{"role": "user", "content": ils_prompt}] - ) - return new - except Exception as e: - if i == 4: - raise e - return current + return self._sample(prompt) + return self._destroy_repair(self.ratio) def run(self) -> Solution: """ @@ -377,30 +401,36 @@ def run(self) -> Solution: self.initialise() current = self.evaluate(self.current_solution) self.current_solution = current + self.ratio = self.ini_ratio + self.stagnation_count = 0 # The initial evaluation above uses one unit of the budget. for iteration_number in range(1, self.budget): + current = self.current_solution print( - f"Gen {iteration_number}: Current: ({current.id}, {current.fitness}, {current.feedback}); Best: ({self.best_solution.id}, {self.best_solution.fitness}, {self.best_solution.feedback})" + f"Gen {iteration_number}: Current: ({current.id}, {current.fitness}, {current.feedback}); Best: ({self.best_solution.id}, {self.best_solution.fitness}, {self.best_solution.feedback}); r = {self.ratio}" ) if self.method == "ts": print(f"\tTT: {self.taboo_table.get_fitness_series()}") match self.method: case "vns": - next = self.mutate_lhns_vns(iteration_number) - self.evaluate(next) + next = self.mutate_lhns_vns() case "ils": - next = self.mutate_lhns_ils(iteration_number) - self.evaluate(next) + next = self.mutate_lhns_ils() case "ts": - current = self.current_solution - next = self.mutate_lhns_ts(iteration_number) - self.evaluate(next) - self.taboo_table.update_taboo_search_table(current, next) + next = self.mutate_lhns_ts() case _: raise ValueError( f"Expected method to be in ['vns', 'ils', 'ts'], got {self.method}" ) - self.simulated_annealing(next, iteration_number) + # Use the returned solution: an evaluation in a subprocess + # returns a new object and leaves `next` unevaluated. + next = self.evaluate(next) + if self.method == "ts": + self.taboo_table.update_taboo_search_table(current, next) + accepted, improved = self.simulated_annealing(next, iteration_number) + self.stagnation_count = 0 if improved else self.stagnation_count + 1 + if self.method == "vns": + self.update_ratio(accepted) return self.best_solution @@ -414,27 +444,33 @@ def __init__( table_size: int = 10, name="LHNS", minimisation=True, + ini_ratio: float = 0.1, ): """ - Initializes the LLaMEA algorithm within the benchmarking framework. + Initializes LHNS within the benchmarking framework. ## Args: - `problem: Problem`: The problem instance to optimize. `llm: LLM`: The LLM instance to use for solution generation. `budget: int`: The maximum number of evaluations. - `name: str`: The name of the method. `method: str` The method to be used in lhns, a string literal in ['vns', 'ils', 'ts'] + `cooling_rate: float`: Initial temperature of the simulated + annealing; it cools linearly to 0 over the budget. + `table_size: int`: Size of the tabu table (TS only). + `name: str`: The name of the method. `minimisation: bool`: Objective direction, minimisation if true, maximisation if false. + `ini_ratio: float`: Initial destruction ratio (VNS adapts it; + ILS and TS keep it), 0.1 as in the reference implementation. """ super().__init__(llm, budget, f"{name}:{method}") self.method = method self.minimisation = minimisation self.table_size = table_size self.cooling_rate = cooling_rate + self.ini_ratio = ini_ratio def __call__(self, problem: Problem): """ - Executes the evolutionary search process via LLaMEA. + Executes the LHNS search on the problem. Returns: Solution: The best solution found. @@ -452,6 +488,7 @@ def __call__(self, problem: Problem): table_size=self.table_size, budget=self.budget, minimisation=self.minimisation, + ini_ratio=self.ini_ratio, ) return self.lhns_instance.run() @@ -465,7 +502,13 @@ def to_dict(self): return { "method_name": self.name if self.name != None else "LHNS", "budget": self.budget, - "kwargs": {"method": self.method, "minimisation": self.minimisation}, + "kwargs": { + "method": self.method, + "minimisation": self.minimisation, + "cooling_rate": self.cooling_rate, + "table_size": self.table_size, + "ini_ratio": self.ini_ratio, + }, } def get_config(self) -> dict[str, Any]: @@ -474,6 +517,7 @@ def get_config(self) -> dict[str, Any]: "taboo_table_size": self.table_size, "evaluation_budget": self.budget, "cooling_rate": self.cooling_rate, + "ini_ratio": self.ini_ratio, } return { "name": "LHNS", diff --git a/iohblade/methods/lhns/prompt.py b/iohblade/methods/lhns/prompt.py index 0cd05ec..842efd3 100644 --- a/iohblade/methods/lhns/prompt.py +++ b/iohblade/methods/lhns/prompt.py @@ -17,7 +17,7 @@ def get_prompt_i1(self) -> str: def get_prompt_o_index(self, individual: Solution) -> str: return f"""I have one algorithm with its code as follows.\\ -Algorithm description: " + {individual.description}\\ +Algorithm description: {individual.description}\\ Code:\n {individual.code}\\ Modify the provided algorithm to improve its performance, where you can determine the degree of modification needed.\\ diff --git a/iohblade/methods/mcts_ahd/mcts.py b/iohblade/methods/mcts_ahd/mcts.py index fbdc890..41dfd7e 100644 --- a/iohblade/methods/mcts_ahd/mcts.py +++ b/iohblade/methods/mcts_ahd/mcts.py @@ -3,6 +3,7 @@ import math import random import traceback +import warnings from typing import Any, Iterable, Optional from iohblade.fitness import is_better @@ -40,42 +41,72 @@ def __init__( lambda_0: float = 0.1, alpha: float = 0.5, maximisation: bool = True, - max_children: int = 10, + max_children: int | None = None, expansion_factor: int = 2, # Referred to as k in (https://arxiv.org/pdf/2501.08603) algorithm 1. + max_depth: int = 10, + initial_node_count: int = 4, + max_tries: int = 3, ): """ - MCTS method for solving a given `Problem` using LLMs. + MCTS-AHD (https://arxiv.org/abs/2501.08603) for solving a given + `Problem` using LLMs, following the reference implementation + (https://github.com/zz1358m/MCTS-AHD-master). + + - Initialisation: `initial_node_count` (N_I = 4) valid root + children, one from i1 and the others from e1. + - Selection descends from the root to the child with the highest + UCT, `(Q - q_min) / (q_max - q_min) + lambda * sqrt(ln(N_parent + + 1) / N_child)`, with `lambda = lambda_0 * (1 - t / budget)` + after `t` evaluations (Eq. 7), while the node has children and + its depth is below `max_depth`. + - Progressive widening (Eq. 4): every node passed in the selection + with `int(N ** alpha) > #children` gets a new child, by e1 at the + root and e2 elsewhere. + - Expansion of the selected node: e2 once, m1 and m2 + `expansion_factor` (k) times each, and s1 once (2k + 2 nodes; s1 + is skipped at depth 1, where the path holds a single algorithm). + A node at the depth limit is expanded again even if it already + has children. + - Each new node is evaluated and back-propagated at once. A + candidate that fails (non-finite fitness, or an LLM error) is + discarded from the tree, as in the reference, and the operator is + retried up to `max_tries` times; every try costs one evaluation. ## Args: `llm:iohblade.LLM` Any LLM model from `iohblade.llm.py`.\\ `problem: iohblade.Problem`: An iohblade problem instance with appropriate prompts, and evaluation function for solving the problem.\\ `buget: int`: Number of evaluations allowed for the method.\\ - `lambda_0: float`: A constant λ_0 used in UCT calculation.\\ - `alpha: float`: Intended as the progressive-widening coefficient of - the paper. **Currently unused**: it is stored and logged, but - progressive widening is decided by `MCTS_Node.is_fully_expanded` - (`max_children` and the children's Q values), not by `alpha`.\\ + `lambda_0: float`: The initial exploration constant λ_0 of the UCT (0.1).\\ + `alpha: float`: Progressive-widening exponent α (0.5).\\ `maximisation: bool`: The direction of optimisation, setting it to false will lead to arg max(f), else arg min(f).\\ - `max_children: int`: A limit to maximum number of children any given node can have.\\ - `expansion_factor: int` Number of m1 and m2 mutations allowed during the expansion phase. + `max_children: int | None`: Optional cap on the number of children + progressive widening may give a node; `None` (default, as in the + paper) means no cap.\\ + `expansion_factor: int` Number of m1 and m2 mutations allowed during the expansion phase.\\ + `max_depth: int`: Depth limit of the selection (10).\\ + `initial_node_count: int`: Number of initial root children N_I (4).\\ + `max_tries: int`: Tries per operator application before it is given + up (3 in the reference). ## Budget: `run()` makes at most `budget` calls to `problem(...)`: no node is generated (LLM call) or simulated once the remaining budget is used. + An LLM failure while generating a node also uses one evaluation + (it is logged as a failed candidate), so the search always ends. """ self.llm = llm self.problem = problem self.maximisation = maximisation self.lambda_0 = lambda_0 - # Not used by the search (see docstring); kept for configs and logs. self.alpha = alpha self.expansion_factor = expansion_factor self.eval_remain = budget self.budget = budget - # Prefedined parameters. - self.max_depth = 10 + self.max_depth = max_depth + self.initial_node_count = initial_node_count + self.max_tries = max_tries self.epsilon = 1e-10 self.discount_factor = 1 self.q_min = None @@ -83,10 +114,13 @@ def __init__( self.rank_list = [] self.e2_candidates: list[MCTS_Node] = [] self.max_children = max_children + # Nodes whose generation failed (LLM error); not part of the tree. + self.failed_generations = 0 - # Instantiate the root node, with empty solution. + # Instantiate the root node, with empty solution. The root starts + # with 0 visits (every other node with 1), as in the reference. solution = Solution() - self.root = MCTS_Node(solution, approach="root") + self.root = MCTS_Node(solution, approach="root", visit=0) if maximisation: self.root.fitness = float("-inf") else: @@ -296,25 +330,105 @@ def _get_e2_nodes(self, as_child_of_node: MCTS_Node) -> list[MCTS_Node]: # endregion # region MCTS Methods. - def initialise(self, initial_node_count: int = 3): + def _relevant_nodes(self, approach: str, parent: MCTS_Node) -> list[MCTS_Node]: + """The nodes the prompt of `approach` needs for a child of `parent`.""" + match approach: + case "i1": + return [] + case "e1": + return self._get_e1_nodes(parent) + case "e2": + return self._get_e2_nodes(parent) + case "m1": + return self._get_m1_nodes(parent) + case "m2": + return self._get_m2_nodes(parent) + case "s1": + return self._get_s1_nodes(parent) + raise ValueError(f"Unknown approach {approach}.") + + def _record_failed_generation( + self, approach: str, parent: MCTS_Node, error: Exception + ): + """Charge one evaluation for a node the LLM failed to generate. + + The failure is logged as a failed candidate (worst fitness) when + the problem has a logger, so the log holds one entry per + evaluation of the budget. """ - Initialises the algorithm, by appending predefined number of nodes to the root node. - Generate 1 i1 node, and n - 1 e1 node based on + self.eval_remain -= 1 + self.failed_generations += 1 + message = f"LLM failure while generating a {approach} node: {error!r}" + print(f"\t{message}") + failed = Solution(code="", operator=approach) + failed.parent_ids = [] if parent.is_root else [parent.id] + failed.set_scores(self.problem.failure_fitness(), message, message) + logger = getattr(self.problem, "logger", None) + if logger is not None: + logger.log_individual(failed) + + def grow( + self, parent: MCTS_Node, approach: str, max_tries: int | None = None + ) -> MCTS_Node | None: + """Generate, evaluate and add one child of `parent` by `approach`. + + As in the reference (`evolve_algorithm`), a candidate that fails is + discarded and the operator is tried again, at most `max_tries` times + (`self.max_tries` when None). Every try uses one evaluation, also + when the LLM fails to produce the node. A valid child is added to + the tree and back-propagated at once. ## Args: - `initial_node_count: int = 3` Number of initial nodes to be added to the tree. + `parent: MCTS_Node`: The node that gets the child. + `approach: str`: One of i1, e1, e2, m1, m2, s1. + `max_tries: int | None`: Maximum number of tries. ## Returns: - `None`: Inline algorithm, changes the data-structure, but returns nothing. + `MCTS_Node | None`: The new child, or None when all tries failed + or the budget is used. + """ + max_tries = self.max_tries if max_tries is None else max_tries + for _ in range(max_tries): + if self.eval_remain <= 0: + return None + relevant_nodes = self._relevant_nodes(approach, parent) + try: + node = self._get_new_node( + approach, relevant_nodes, depth=parent.depth + 1 + ) + except Exception as e: + self._record_failed_generation(approach, parent, e) + continue + node.parent_ids = [] if parent.is_root else [parent.id] + node = self.simulate(node) + print(f"\t{approach} node {node.id}: fitness {node.fitness}") + if node.Q is None: + continue # Failed candidate: not added to the tree. + parent.add_child(node) + self.backpropogate(node) + return node + return None + + def initialise(self, initial_node_count: int | None = None): """ - if initial_node_count < 1: - return - initial_node = self._get_new_node("i1", [], depth=1) - self.root.add_child(initial_node) + Initialises the tree with `initial_node_count` valid root children: + the first from i1, the others from e1 on the children so far. - for _ in range(1, initial_node_count): - node = self._get_new_node("e1", [initial_node], depth=1) - self.root.add_child(node) + As in the reference (`get_algorithm`), a failed candidate is + replaced until the count is reached or the budget is used. + + ## Args: + `initial_node_count: int | None` Number of initial nodes; + `self.initial_node_count` (4) when None. + + ## Returns: + `None`: Inline algorithm, changes the data-structure, but returns nothing. + """ + if initial_node_count is None: + initial_node_count = self.initial_node_count + while len(self.root.children) < initial_node_count and self.eval_remain > 0: + approach = "e1" if self.root.children else "i1" + self.grow(self.root, approach, max_tries=1) def simulate(self, node: MCTS_Node): """ @@ -324,7 +438,7 @@ def simulate(self, node: MCTS_Node): `node: MCTS_Node`: A node that is being simulated; to evaluate the performance. ## Returns: - `MCTS_Node`: Inline algorithm, changes the data-structure, but returns nothing. + `MCTS_Node`: The evaluated node; `Q` is None if it failed. """ if self.eval_remain <= 0: @@ -360,82 +474,77 @@ def simulate(self, node: MCTS_Node): self.best_solution = new_node return new_node - def selection( - self, max_new_nodes: int | None = None - ) -> tuple[list[MCTS_Node], MCTS_Node]: - """ - Iteratively pick fittest child from root node, to the leaf node, while adhering to progressive widening. + def needs_widening(self, node: MCTS_Node) -> bool: + """Progressive widening criterion (paper Eq. 4, reference code): + `int(N(node) ** alpha) > #children`, within `max_children` if set.""" + if self.max_children is not None and len(node.children) >= self.max_children: + return False + return int(node.visit**self.alpha) > len(node.children) - ## Args: - `max_new_nodes: int | None`: At most this many progressive - widening nodes are generated (each one costs an evaluation); - `None` means no limit. + def selection(self) -> tuple[list[MCTS_Node], MCTS_Node]: + """ + Descend from the root to the child with the highest UCT while the + node has children and its depth is below `max_depth`, widening + every node on the path that meets the progressive widening + criterion (e1 at the root, e2 elsewhere). As in the reference, the + child to descend to is chosen before the node is widened. ## Returns: - The function returns a tuple of [NCTS_Node], and NCTS_Node, which is to be interpreted as:\\ - `expanded_node : [MCTS_Node]`: A list of nodes added to tree adhering to `Progressive Widening`.\\ - `selected_node : MCTS_Node`: A leaf node that is selected for expansion. + The function returns a tuple of [MCTS_Node], and MCTS_Node, which is to be interpreted as:\\ + `expanded_node : [MCTS_Node]`: The valid nodes added by progressive widening.\\ + `selected_node : MCTS_Node`: The node selected for expansion. """ current = self.root expanded_nodes = [] - while not current.is_leaf: - # Expand node. - if ( - max_new_nodes is None or len(expanded_nodes) < max_new_nodes - ) and not current.is_fully_expanded( - self.max_children, maximisation=self.maximisation - ): - if current.is_root: - relevant_nodes = self._get_e1_nodes(current) - node = self._get_new_node("e1", relevant_nodes, depth=1) - else: - relevant_nodes = self._get_e2_nodes(current) - node = self._get_new_node( - "e2", relevant_nodes, depth=current.depth + 1 - ) - current.add_child(node) - expanded_nodes.append(node) - - # Find best child: uct() is higher-is-better in both directions. + while current.children and current.depth < self.max_depth: + # uct() is higher-is-better in both directions. best_child = max(current.children, key=self.uct) - + if self.eval_remain > 0 and self.needs_widening(current): + approach = "e1" if current.is_root else "e2" + node = self.grow(current, approach) + if node is not None: + expanded_nodes.append(node) current = best_child return expanded_nodes, current - def expansion(self, on_node: MCTS_Node, max_nodes: int | None = None): + def expansion(self, on_node: MCTS_Node) -> list[MCTS_Node]: """ - Impelements the expansion phase of the MCTS_AHD. "Apply expansion e2, s1, m1 (k times), m2 (k times), a total of 2k+2 new nodes added. - Only implemented on leaf nodes, that is not root. + Expansion phase of MCTS-AHD: apply e2 once, m1 and m2 k times each + and s1 once (2k + 2 operators, in the reference's order). s1 is + skipped when the path from the root holds a single algorithm, as + in the reference. Each node is evaluated and back-propagated + before the next one is generated; the expansion stops when the + budget is used. ## Args: - `on_node: MCTS_Node`: A MCTS_Node instance that is a leaf node, (non root) on which expansion is to be performed. - `max_nodes: int | None`: Generate at most this many nodes (each one - costs an evaluation), in the order m1, m2 (k times), s1, e2; `None` - generates all 2k+2. + `on_node: MCTS_Node`: A non-root node to expand (a leaf, or a node + at the depth limit). ## Returns: - `None`: Inline implementation that updates underlying Data Structure. Nothing to return. + `list[MCTS_Node]`: The valid children added. ## Raises: - ValueError: if `on_node` is not leaf node or is a root node. - """ - if (not on_node.is_leaf) or on_node.is_root: - print(f"self.is_root {on_node.is_root}, self.is_leaf {on_node.is_leaf}") - raise ValueError("Expansion only works on non-root leaf node.") - - approaches = ["m1", "m2"] * self.expansion_factor + ["s1", "e2"] - if max_nodes is not None: - approaches = approaches[: max(max_nodes, 0)] - node_getters = { - "m1": self._get_m1_nodes, - "m2": self._get_m2_nodes, - "s1": self._get_s1_nodes, - "e2": self._get_e2_nodes, - } + ValueError: if `on_node` is the root node. + """ + if on_node.is_root: + raise ValueError("Expansion does not work on the root node.") + + approaches = ( + ["e2"] + + ["m1"] * self.expansion_factor + + ["m2"] * self.expansion_factor + + ["s1"] + ) + added = [] for approach in approaches: - relevant_nodes = node_getters[approach](on_node) - node = self._get_new_node(approach, relevant_nodes, on_node.depth + 1) - on_node.add_child(node) + if self.eval_remain <= 0: + break + if approach == "s1" and len(self._get_s1_nodes(on_node)) < 2: + continue + node = self.grow(on_node, approach) + if node is not None: + added.append(node) + return added def backpropogate(self, node: MCTS_Node): """ @@ -470,21 +579,27 @@ def backpropogate(self, node: MCTS_Node): # endregion # region UCT + def exploration_constant(self) -> float: + """lambda = lambda_0 * (1 - t / budget) after t evaluations (Eq. 7): + decays linearly from lambda_0 to 0 over the budget.""" + if self.budget <= 0: + return 0.0 + return self.lambda_0 * max(self.eval_remain, 0) / self.budget + def uct(self, node: MCTS_Node) -> float: """ - Scores the provided node with a score, determining how likely it is to better optima on visiting current - node again. + UCT score of a node (paper Eq. 3/5 with Eq. 7): + `(Q - q_min) / (q_max - q_min) + lambda * sqrt(ln(N_parent + 1) / N_node)`. + For minimisation the normalised term is `(q_max - Q) / (q_max - q_min)`. ## Args: - `node: MCTS_Node`: A non-root node that needs to be scored.\\ - `eval_remains: int`: Number of evaluation remaining for current optimisation process. + `node: MCTS_Node`: A non-root node that needs to be scored. ## Returns: `float`: The UCT score; higher is more promising in both optimisation directions (``-inf`` for nodes without a valid Q). """ uct = 0 - exploration_constant = self.lambda_0 * max(self.eval_remain, 0) if node.Q is None or self.q_max is None or self.q_min is None: # Unevaluated or failed nodes are the least attractive; the # selection always takes the highest UCT. @@ -497,15 +612,12 @@ def uct(self, node: MCTS_Node) -> float: else: uct = (self.q_max - node.Q) / (self.q_max - self.q_min) if node.parent: - return uct + ( - exploration_constant - * (math.log(node.parent.visit + 1) ** 0.5) - / node.visit + return uct + self.exploration_constant() * math.sqrt( + math.log(node.parent.visit + 1) / max(node.visit, 1) ) return 0 # endregion - # region Tree Printer. def print_tree( self, @@ -534,24 +646,10 @@ def print_tree( def run(self): print("Started MCTS-AHD solver.") - # Never generate more initial nodes than can be evaluated. - self.initialise(min(3, self.eval_remain)) + self.initialise() print(f"Initialised with {len(self.root.children)} nodes.") - for i, child in enumerate(self.root.children): - print(f"\tEvaluating {child.id} node.") - - child = self.simulate(child) - child.parent = self.root - self.root.children[i] = child - - print(f"\t\tFitness {child.fitness}") - print(f"\t\tFeedback {child.feedback}") - - for child in self.root.children: - self.backpropogate(child) - iteration = 1 while self.eval_remain > 0: print(f"Q_min = {self.q_min}, Q_max = {self.q_max}.") @@ -559,61 +657,20 @@ def run(self): print(f"Iteratrion # {iteration}.") - # Every generated node is evaluated once, so the number of new - # nodes is capped at the remaining budget. - progressive_widening_nodes, selected_node = self.selection( - max_new_nodes=self.eval_remain - ) - + progressive_widening_nodes, selected_node = self.selection() print(f"Selected Node: {selected_node}") - - remaining = self.eval_remain - len(progressive_widening_nodes) - if remaining > 0: - self.expansion(selected_node, max_nodes=remaining) - expanded_nodes = selected_node.children + if self.eval_remain <= 0: + break + if selected_node.is_root: + # No valid root child yet (cannot happen after a complete + # initialisation): keep initialising. + self.initialise() + continue + expanded_nodes = self.expansion(selected_node) print( - f"Generating {len(progressive_widening_nodes)} progressive widening nodes, {len(expanded_nodes)} leaf nodes." + f"Added {len(progressive_widening_nodes)} progressive widening nodes, {len(expanded_nodes)} expansion nodes." ) - - node_lists = [progressive_widening_nodes, expanded_nodes] - for nodes in node_lists: - for i, node in enumerate(nodes): - print(f"\tEvaluating {node.id} node.") - - new_node = self.simulate(node) - - # update the list we're iterating - if new_node is not node: - nodes[i] = new_node - - # keep parent pointers consistent too - if node.parent is not None: - p = node.parent - try: - idx = p.children.index(node) - except ValueError: - # in case it was already replaced earlier - idx = ( - p.children.index(nodes[i]) - if nodes[i] in p.children - else None - ) - - if idx is not None: - p.children[idx] = new_node - new_node.parent = p - - print(f"\t\tFitness {nodes[i].fitness}.") - print(f"\t\tFeedback {nodes[i].feedback}") - - for node in ( - expanded_nodes + progressive_widening_nodes - ): # Make sure progressive widening nodes are handeled after expanded nodes. - print(f"\tBackpropogating from node #{node.id}.") - - self.backpropogate(node) - print(f"\tBudget remaining {self.eval_remain}.") iteration += 1 @@ -636,21 +693,30 @@ def __init__( lambda_0: float = 0.1, alpha: float = 0.5, maximisation: bool = True, - max_children: int = 5, + max_children: int | None = None, expansion_factor: int = 2, + max_depth: int = 10, + initial_node_count: int = 4, + max_tries: int = 3, ): """ - MCTS method wrapper for adding it to iohblade/methods. + MCTS-AHD method wrapper for adding it to iohblade/methods; see + `MCTS` for the search. ## Args: `llm:iohblade.LLM` Any LLM model from `iohblade.llm.py`.\\ `buget: int`: Number of evaluations allowed for the method.\\ - `lambda_0: float`: A constant λ_0 used in UCT calculation.\\ - `alpha: float`: Intended progressive-widening coefficient; currently - unused (see `MCTS`), kept for configuration compatibility.\\ - `maximisation: bool`: The direction of optimisation, setting it to false will lead to arg max(f), else arg min(f).\\ - `max_children: int`: A limit to maximum number of children any given node can have.\\ - `expansion_factor: int` Number of m1 and m2 mutations allowed during the expansion phase. + `lambda_0: float`: The initial exploration constant λ_0 of the UCT; + it decays linearly to 0 over the budget.\\ + `alpha: float`: Progressive-widening exponent α.\\ + `maximisation: bool`: The direction of optimisation; set from the + problem when the method runs.\\ + `max_children: int | None`: Optional cap on progressive widening; + None (default) means no cap, as in the paper.\\ + `expansion_factor: int` Number of m1 and m2 mutations allowed during the expansion phase.\\ + `max_depth: int`: Depth limit of the selection.\\ + `initial_node_count: int`: Number of initial root children N_I.\\ + `max_tries: int`: Tries per operator application. """ super().__init__(llm, budget, name="MCTS_AHD") self.lambda_0 = lambda_0 @@ -658,6 +724,9 @@ def __init__( self.maximisation = maximisation self.max_children = max_children self.expansion_factor = expansion_factor + self.max_depth = max_depth + self.initial_node_count = initial_node_count + self.max_tries = max_tries sig = inspect.signature(self.__init__) self.init_params = { k: getattr(self, k) @@ -686,12 +755,20 @@ def __call__(self, problem: Problem): self.maximisation, self.max_children, self.expansion_factor, + max_depth=self.max_depth, + initial_node_count=self.initial_node_count, + max_tries=self.max_tries, ) try: return self.mcts_instance.run() except Exception as e: - print("Some error occured, best solution till now V") - print(traceback.print_exc(), e, "-----------", sep="\n") + # LLM failures are handled per node; anything else is a bug. + # Return the best so far, but do not end the run silently. + traceback.print_exc() + used = self.budget - self.mcts_instance.eval_remain + warnings.warn( + f"MCTS-AHD stopped after {used}/{self.budget} evaluations: {e!r}" + ) return self.mcts_instance.best_solution def to_dict(self): @@ -717,6 +794,9 @@ def get_config(self) -> dict[str, Any]: "alpha": self.alpha, "max_children": self.max_children, "expansion_factor": self.expansion_factor, + "max_depth": self.max_depth, + "initial_node_count": self.initial_node_count, + "max_tries": self.max_tries, "budget": self.budget, "minimisation": not self.maximisation, } diff --git a/tests/unit/test_lhns.py b/tests/unit/test_lhns.py index 27941fb..d91837a 100644 --- a/tests/unit/test_lhns.py +++ b/tests/unit/test_lhns.py @@ -502,46 +502,6 @@ def test_simulated_annealing_picks_optimal_solution(): assert old_id != lhns.current_solution.id -def test_simulated_annealing_accepts_with_probability(monkeypatch): - lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "ts", cooling_rate=2) - monkeypatch.setattr(lhns_module.random, "random", lambda: 0.1) - lhns.current_solution.set_scores(100) - - next_solution = Solution() - next_solution.set_scores(98) - current_solution = lhns.current_solution - - iteration = 50 - temperature = lhns.alpha * iteration / lhns.budget - delta = abs(next_solution.fitness - lhns.current_solution.fitness) - p = math.e ** (-1 * delta / temperature) - - lhns.simulated_annealing(next_solution, iteration_number=iteration) - if 0.1 <= p: - assert lhns.current_solution != current_solution - else: - assert lhns.current_solution == next_solution - - lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "ts", minimisation=True, cooling_rate=2) - monkeypatch.setattr(lhns_module.random, "random", lambda: 0.1) - lhns.current_solution.set_scores(80) - - next_solution = Solution() - next_solution.set_scores(82) - current_solution = lhns.current_solution - - iteration = 50 - temperature = lhns.alpha * iteration / lhns.budget - delta = abs(next_solution.fitness - lhns.current_solution.fitness) - p = math.e ** (-1 * delta / temperature) - - lhns.simulated_annealing(next_solution, iteration_number=iteration) - if 0.1 <= p: - assert lhns.current_solution != current_solution - else: - assert lhns.current_solution == next_solution - - def test_initialise_stops_execution_on_5x_failure(monkeypatch): def failure_of_a_sample_solution(): raise TypeError @@ -609,216 +569,204 @@ def evaluate(solution: Solution): assert solution == new_solution -def test_extract_executable_lines(): +# region Behaviour of the reference implementation. +QUADRATIC = '''import math +from numpy import sqrt - code = ''' -def get_roots_of_quadratic_with_parameters(a: float, b: float, c: float) -> list[float]: - """Given a, b, c for ax^2 + bx + c = 0, equation, returns the root of the solution: - - ## Args: - `a: float`: Coefficient of x^2. - `b: float`: Coefficient of x. - `c: float`: Final Constant. - - ## Returns: - `roots: [float]`: Returns a list of roots for the solution, may be of length 0, 1 or 2. - """ - - determinant = (b ** 2) - 4*a*c - if determinant < 0: - return [] - elif determinant == 0: - return [-b/(2 * a)] - else: - return [(-b - (determinant) ** 0.5)/(2 * a), (-b + (determinant) ** 0.5)/(2 * a)] +class Roots: + """Roots of a quadratic.""" + + def __call__(self, a, b, c): + # the discriminant + determinant = (b ** 2) - 4*a*c + if determinant < 0: + return [] + return [(-b - math.sqrt(determinant)) / (2 * a)] ''' - lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns") - data = lhns._extract_executable_lines_with_indices(code) - - expected_data = [ - (13, " determinant = (b ** 2) - 4*a*c"), - (14, " if determinant < 0:"), - (15, " return []"), - (16, " elif determinant == 0:"), - (17, " return [-b/(2 * a)]"), - (18, " else:"), - ( - 19, - " return [(-b - (determinant) ** 0.5)/(2 * a), (-b + (determinant) ** 0.5)/(2 * a)]", - ), - ] - assert data == expected_data +class NewObjectProblem(DummyProblem): + """Returns a new evaluated object, like an evaluation in a subprocess, + with the fitness values from ``fitnesses`` in turn.""" + def __init__(self, fitnesses): + super().__init__() + self.fitnesses = list(fitnesses) + self.calls = 0 -def test_get_destroyed_code_only_destroys_executable_non_defs(): - code = ''' -def get_roots_of_quadratic_with_parameters(a: float, b: float, c: float) -> list[float]: - """Given a, b, c for ax^2 + bx + c = 0, equation, returns the root of the solution: + def __call__(self, solution: Solution): + fitness = self.fitnesses[self.calls % len(self.fitnesses)] + self.calls += 1 + evaluated = Solution(solution.code, solution.name, solution.description) + evaluated.id = solution.id + evaluated.set_scores(fitness, f"Fitness {fitness}") + return evaluated + + +class CodeLLM(Dummy_LLM): + """Returns a new solution (with its own code) per call; records prompts.""" + + def __init__(self): + super().__init__() + self.prompts = [] + + def sample_solution(self, messages, *args, **kwargs): + self.prompts.append(messages[-1]["content"]) + n = len(self.prompts) + return Solution(f"x = {n}\ny = x * 2\n", f"S{n}", f"desc {n}") + + +def test_temperature_cools_linearly_to_zero(): + lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns", cooling_rate=0.1, budget=100) + temperatures = [lhns.temperature(t) for t in range(1, 100)] + assert temperatures[0] == pytest.approx(0.1) + assert all(a > b for a, b in zip(temperatures, temperatures[1:])) + assert temperatures[-1] == pytest.approx(0.1 * 2 / 100) + assert lhns.temperature(101) == 0 + + +@pytest.mark.parametrize("minimisation", [True, False]) +def test_simulated_annealing_uses_relative_worsening(monkeypatch, minimisation): + lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns", minimisation=minimisation, budget=10) + current = Solution().set_scores(-200.0) + worse = Solution().set_scores(-198.0 if minimisation else -202.0) + lhns.current_solution = current + t = 3 + delta = 2.0 / 200.0 # relative to |f_cur|, independent of the scale + p = math.exp(-delta / lhns.temperature(t)) + + monkeypatch.setattr(lhns_module.random, "random", lambda: p - 1e-9) + assert lhns.simulated_annealing(worse, t) == (True, False) + assert lhns.current_solution is worse + + lhns.current_solution = current + monkeypatch.setattr(lhns_module.random, "random", lambda: p + 1e-9) + assert lhns.simulated_annealing(worse, t) == (False, False) + assert lhns.current_solution is current + + better = Solution().set_scores(-300.0 if minimisation else -100.0) + assert lhns.simulated_annealing(better, t) == (True, True) + assert lhns.current_solution is better + + +def test_vns_ratio_adapts_on_accept_and_reject(): + lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns", ini_ratio=0.1) + assert lhns.ratio == 0.1 + for expected in [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 0.1, 0.2]: + lhns.update_ratio(accepted=False) + assert lhns.ratio == expected + lhns.update_ratio(accepted=True) + assert lhns.ratio == 0.1 + + +def test_vns_run_uses_the_adaptive_ratio(monkeypatch): + # Fitness (maximisation): 10, then never better and too much worse to + # be accepted, then better: r = 0.1, 0.2, 0.3, back to 0.1. + problem = NewObjectProblem([10.0, -1e9, -1e9, 20.0, -1e9]) + lhns = LHNS(problem, CodeLLM(), "vns", budget=6, minimisation=False) + ratios = [] + original = lhns.destroy_code + + def recording(r, solution): + ratios.append(r) + return original(r, solution) + + monkeypatch.setattr(lhns, "destroy_code", recording) + lhns.run() + assert ratios == [0.1, 0.2, 0.3, 0.1, 0.2] + + +def test_run_uses_the_evaluated_solution(): + # Problems that evaluate in a subprocess return a new object; the + # current solution must move to the evaluated (better) candidate. + problem = NewObjectProblem([1.0, 2.0, 3.0, 4.0]) + llm = CodeLLM() + lhns = LHNS(problem, llm, "vns", budget=4, minimisation=False) + best = lhns.run() + assert lhns.current_solution.fitness == 4.0 + assert best.fitness == 4.0 + # Each destroy-repair prompt starts from the previous candidate. + assert "desc 1" in llm.prompts[1] and "desc 3" in llm.prompts[3] - ## Args: - `a: float`: Coefficient of x^2. - `b: float`: Coefficient of x. - `c: float`: Final Constant. - ## Returns: - `roots: [float]`: Returns a list of roots for the solution, may be of length 0, 1 or 2. - """ +def test_extract_executable_lines(): + lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns") + data = lhns._extract_executable_lines_with_indices(QUADRATIC) + lines = QUADRATIC.split("\n") + # Content lines: not blank, def/class/import or comment lines. + assert [i for i, _ in data] == [4, 8, 9, 10, 11] + # Lines are returned as written (trailing whitespace included). + assert data[2] == (9, lines[9]) + assert lines[9].endswith(" ") - determinant = (b ** 2) - 4*a*c - if determinant < 0: - return [] - elif determinant == 0: - return [-b/(2 * a)] - else: - return [(-b - (determinant) ** 0.5)/(2 * a), (-b + (determinant) ** 0.5)/(2 * a)] -''' - expected_output = ''' -def get_roots_of_quadratic_with_parameters(a: float, b: float, c: float) -> list[float]: - """Given a, b, c for ax^2 + bx + c = 0, equation, returns the root of the solution: +@pytest.mark.parametrize("r", [0.1, 0.3, 0.5, 1.0]) +def test_destroy_code_draws_ceil_r_n_lines(monkeypatch, r): + lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns") + drawn = {} + original = lhns_module.random.choices - ## Args: - `a: float`: Coefficient of x^2. - `b: float`: Coefficient of x. - `c: float`: Final Constant. + def recording(population, k): + drawn["k"], drawn["n"] = k, len(population) + return original(population, k=k) - ## Returns: - `roots: [float]`: Returns a list of roots for the solution, may be of length 0, 1 or 2. - """ + monkeypatch.setattr(lhns_module.random, "choices", recording) + _, k = lhns.destroy_code(r, Solution(code=QUADRATIC)) + assert drawn["n"] == 5 + assert k == drawn["k"] == math.ceil(r * 5) -''' +def test_destroy_code_deletes_by_index_and_keeps_structure(monkeypatch): lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns") - soln = Solution(code=code) - output = lhns.get_destroyed_code(1.0, soln) - print("----------------------------Acutal Output----------------------------") - for index, line in enumerate(output.split("\n")): - print(index + 1, ":", line, "|") - print("----------------------------Expected Output----------------------------") - for index, line in enumerate(expected_output.split("\n")): - print(index + 1, ":", line, "|") - assert expected_output == output - - -def test_mutate_lhns_vns_calls_methods_properly(monkeypatch): - - destruction_ratio = [] - destroyed_code_arr = [] - destruction_prompt = [] - - def fake_destroy_code(r, current): - destruction_ratio.append(r) - code = f"destroyed code r={r}" - destroyed_code_arr.append(code) - return code - - def fake_destruction_prompt( - individual: Solution, destroyed_code: str, deleted_line_count: int - ) -> str: - proompt = f"destruction prompt with code {destroyed_code}." - destruction_prompt.append(proompt) - return proompt - - problem = DummyProblem() - llm = Dummy_LLM() - lhns_instance = LHNS(problem, llm, "vns", budget=10) - monkeypatch.setattr(lhns_instance, "get_destroyed_code", fake_destroy_code) + # Draw every content line once (with replacement in general). monkeypatch.setattr( - lhns_instance.prompt_generator, - "get_prompt_destroy_repair", - fake_destruction_prompt, + lhns_module.random, "choices", lambda population, k: list(population) ) - _ = lhns_instance.run() - # The initial solution uses one evaluation, so there are budget - 1 - # destroy-repair iterations (issue #206). - assert len(destruction_ratio) == lhns_instance.budget - 1 - for index in range(lhns_instance.budget - 1): - assert f"{destruction_ratio[index]:2}" == f"{0.1 * (1 + ((index + 1) % 10)):2}" - assert ( - destroyed_code_arr[index] - == f"destroyed code r={0.1 * (1 + ((index + 1) % 10))}" - ) - assert ( - destruction_prompt[index] - == f"destruction prompt with code {destroyed_code_arr[index]}." - ) - - -def test_lhns_vns_raises_after_5x_tries(monkeypatch): - counter = 0 - - def fake_sample_solution(message): - nonlocal counter - counter += 1 - raise NoCodeException - - problem = DummyProblem() - llm = Dummy_LLM() - lhns_instance = LHNS(problem, llm, "vns", budget=10) - monkeypatch.setattr(lhns_instance.llm, "sample_solution", fake_sample_solution) - - with pytest.raises(NoCodeException): - lhns_instance.mutate_lhns_vns(4) - assert counter == 5 - - -def test_mutate_lhns_ils_calls_methods_properly(monkeypatch): - - destruction_ratio = [] - destroyed_code_arr = [] - destruction_prompt = [] - - def fake_destroy_code(r, current): - destruction_ratio.append(r) - code = f"destroyed code r={r}" - destroyed_code_arr.append(code) - return code - - def fake_destruction_prompt( - individual: Solution, destroyed_code: str, deleted_line_count: int - ) -> str: - proompt = f"destruction prompt with code {destroyed_code}." - destruction_prompt.append(proompt) - return proompt - - def fake_initialisation_prompt(): - destruction_ratio.append(None) - destroyed_code_arr.append(None) - destruction_prompt.append("hi") - return "hi" - - problem = DummyProblem() - llm = Dummy_LLM() - lhns_instance = LHNS(problem, llm, "ils", budget=10) - monkeypatch.setattr(lhns_instance, "get_destroyed_code", fake_destroy_code) + destroyed, k = lhns.destroy_code(1.0, Solution(code=QUADRATIC)) + assert k == 5 + remaining = destroyed.split("\n") + # The line with trailing whitespace is deleted too. + assert " if determinant < 0: " not in remaining + # def, class and import lines are kept; comments are always dropped. + for kept in [ + "import math", + "from numpy import sqrt", + "class Roots:", + " def __call__(self, a, b, c):", + ]: + assert kept in remaining + assert " # the discriminant" not in remaining + assert not any(line.strip() and "=" in line for line in remaining) + + +def test_destroy_code_draws_with_replacement(): + random.seed(1) + lhns = LHNS(BBOB_SBOX(), Dummy_LLM(), "vns") + code = "\n".join(f"x{i} = {i}" for i in range(200)) + destroyed, k = lhns.destroy_code(1.0, Solution(code=code)) + assert k == 200 + # About 1 - 1/e = 63% of the distinct lines are deleted, not all. + left = len([line for line in destroyed.split("\n") if line]) + assert 40 < left < 110 + + +def test_mutate_lhns_vns_reports_drawn_count(monkeypatch): + lhns = LHNS(BBOB_SBOX(), CodeLLM(), "vns") + lhns.current_solution = Solution(code=QUADRATIC, description="roots") + lhns.ratio = 0.5 + prompts = [] monkeypatch.setattr( - lhns_instance.prompt_generator, + lhns.prompt_generator, "get_prompt_destroy_repair", - fake_destruction_prompt, + lambda individual, code, count: prompts.append(count) or "P", ) - monkeypatch.setattr( - lhns_instance.prompt_generator, "get_prompt_i1", fake_initialisation_prompt - ) - _ = lhns_instance.run() - - for index in range(lhns_instance.budget): - print( - f"{index}| {destruction_ratio[index]} | {destruction_prompt[index]} | {destroyed_code_arr[index]} | {destruction_ratio[index]}" - ) - if destruction_ratio[index] is not None: - assert destroyed_code_arr[index] == "destroyed code r=0.5" - assert ( - destruction_prompt[index] - == "destruction prompt with code destroyed code r=0.5." - ) - else: - assert destroyed_code_arr[index] is None - assert destruction_prompt[index] == "hi" + new = lhns.mutate_lhns_vns() + assert prompts == [3] # ceil(0.5 * 5) + assert new.code.startswith("x = 1") -def test_lhns_ils_raises_after_5x_tries(monkeypatch): +@pytest.mark.parametrize("method", ["vns", "ils", "ts"]) +def test_mutations_raise_after_5x_tries(monkeypatch, method): counter = 0 def fake_sample_solution(message): @@ -826,123 +774,62 @@ def fake_sample_solution(message): counter += 1 raise NoCodeException - problem = DummyProblem() - llm = Dummy_LLM() - lhns_instance = LHNS(problem, llm, "ils", budget=10) - monkeypatch.setattr(lhns_instance.llm, "sample_solution", fake_sample_solution) - + lhns = LHNS(DummyProblem(), Dummy_LLM(), method, budget=10) + lhns.current_solution = Solution(code=QUADRATIC) + monkeypatch.setattr(lhns.llm, "sample_solution", fake_sample_solution) with pytest.raises(NoCodeException): - lhns_instance.mutate_lhns_ils(4) + getattr(lhns, f"mutate_lhns_{method}")() assert counter == 5 -def test_taboo_search_calls_functions_appripriately(monkeypatch): - destruction_ratio = [] - destroyed_code_arr = [] # No padding. - taboo_elements = [] # padding. - prompt = [] # No padding. - - def fake_destroy_code(r, current): - destruction_ratio.append(r) - code = f"destroyed code r={r}" - return code - - def fake_destruction_prompt( - individual: Solution, destroyed_code: str, deleted_line_count: int - ) -> str: - proompt = f"destruction prompt with code {destroyed_code}." - destroyed_code_arr.append(proompt) - taboo_elements.append(None) - prompt.append(proompt) - return proompt - - def fake_taboo_prompt( - individual: Solution, destroyed_code: str, taboo_element - ) -> str: - proompt = ( - f"taboo prompt with code {destroyed_code}. Taboo Element {taboo_element}" - ) - destroyed_code_arr.append(destroyed_code) - taboo_elements.append(taboo_element) - prompt.append(proompt) - return proompt - - def fake_get_distinct_entry(for_individual): - taboo_element = TabooElement( - "taboo desc", "taboo_element", random.random(), ["feature."] - ) - return taboo_element - - def fake_initialisation_prompt(): - destruction_ratio.append(None) - destroyed_code_arr.append(None) - taboo_elements.append(None) - prompt.append("Init") - return "Init" - - problem = DummyProblem() - llm = Dummy_LLM() - lhns_instance = LHNS(problem, llm, "ts", budget=10) - +def _stagnating_run(method, monkeypatch, budget=25): + """Run where every candidate is much worse than the first solution, + so it is never accepted and never improves.""" + problem = NewObjectProblem([100.0] + [-1e9] * (budget - 1)) + llm = CodeLLM() + lhns = LHNS(problem, llm, method, budget=budget, minimisation=False) + ratios = [] + original = lhns.destroy_code monkeypatch.setattr( - lhns_instance.prompt_generator, "get_prompt_i1", fake_initialisation_prompt + lhns, "destroy_code", lambda r, s: ratios.append(r) or original(r, s) ) - monkeypatch.setattr(lhns_instance, "get_destroyed_code", fake_destroy_code) + return lhns, llm, ratios + + +def test_ils_restarts_from_best_after_10_non_improving(monkeypatch): + lhns, llm, ratios = _stagnating_run("ils", monkeypatch) + o_index = [] monkeypatch.setattr( - lhns_instance.taboo_table, "get_distinct_entry", fake_get_distinct_entry + lhns.prompt_generator, + "get_prompt_o_index", + lambda individual: o_index.append(individual.fitness) or "O INDEX", ) + lhns.run() + # Iterations 1-10 do not improve, so iteration 11 perturbs; the + # perturbation counts as the first of the next 10 (reference). + perturbed = [i + 1 for i, p in enumerate(llm.prompts[1:]) if p == "O INDEX"] + assert perturbed == [11, 21] + assert o_index == [100.0, 100.0] # the best solution so far + # ILS destroys with the fixed initial ratio. + assert set(ratios) == {0.1} + + +def test_ts_merges_taboo_features_after_10_non_improving(monkeypatch): + lhns, llm, ratios = _stagnating_run("ts", monkeypatch) + element = TabooElement("taboo desc", "other code", 0.5, ["feature"]) + monkeypatch.setattr(lhns.taboo_table, "get_distinct_entry", lambda s: element) + codes = [] monkeypatch.setattr( - lhns_instance.prompt_generator, "get_prompt_taboo_search", fake_taboo_prompt + lhns.prompt_generator, + "get_prompt_taboo_search", + lambda individual, code, taboo_element: codes.append(code) or "TABOO", ) - monkeypatch.setattr( - lhns_instance.prompt_generator, - "get_prompt_destroy_repair", - fake_destruction_prompt, - ) - - _ = lhns_instance.run() + lhns.run() + perturbed = [i + 1 for i, p in enumerate(llm.prompts[1:]) if p == "TABOO"] + assert perturbed == [11, 21] + # The current code is merged without destruction (reference p2). + assert codes[0] == lhns.current_solution.code + assert set(ratios) == {0.1} - print( - f"Length of destruction ratio={len(destruction_ratio)}, destroyed code={len(destroyed_code_arr)}, taboo elements={len(taboo_elements)}, prompt={len(prompt)}" - ) - for index in range(lhns_instance.budget): - print( - f"{index}| {destruction_ratio[index]} | {prompt[index]} | {destroyed_code_arr[index]} | {taboo_elements[index]}" - ) - if destruction_ratio[index] is not None: - # Every 10th iteration (index % 10 == 9) uses the taboo prompt. - expected = ( - "destruction prompt with code destroyed code r=0.5." - if index % 10 != 9 - else "taboo prompt with code destroyed code r=0.5." - ) - assert prompt[index].startswith(expected) - else: - # Initialisation step - assert destroyed_code_arr[index] is None - assert prompt[index] == "Init" - - -def test_lhns_ts_raises_after_5x_tries(monkeypatch): - counter = 0 - - def fake_sample_solution(message): - nonlocal counter - counter += 1 - raise NoCodeException - - problem = DummyProblem() - llm = Dummy_LLM() - lhns_instance = LHNS(problem, llm, "ts", budget=10) - monkeypatch.setattr(lhns_instance.llm, "sample_solution", fake_sample_solution) - - with pytest.raises(NoCodeException): - lhns_instance.mutate_lhns_ts(4) - - assert counter == 5 - - counter = 0 - with pytest.raises(NoCodeException): - lhns_instance.mutate_lhns_ts(9) - assert counter == 5 +# endregion diff --git a/tests/unit/test_mcts_ahd.py b/tests/unit/test_mcts_ahd.py index 79863e9..dbcd713 100644 --- a/tests/unit/test_mcts_ahd.py +++ b/tests/unit/test_mcts_ahd.py @@ -1,3 +1,4 @@ +import math import random from typing import Any @@ -191,48 +192,48 @@ def test_mcts_node_adds_child_correctly(): assert b.children == [] -def test_mcts_nodes_is_fully_expanded(): - grandparent = MCTS_Node(Solution(), "root") - parent = MCTS_Node(Solution(), "i1") +class ValidProblem(DummyProblem): + """Every evaluation succeeds, with a random fitness in [0, 100).""" - child1 = MCTS_Node(Solution(), "e2") - parent.Q = 10 - child1.Q = 8 - grandparent.add_child(parent) - parent.add_child(child1) - assert parent.is_fully_expanded(5) == False + def evaluate(self, solution): + self.count += 1 + solution.fitness = random.random() * 100 + return solution - child2 = MCTS_Node(Solution(), "s2") - child2.Q = 5 - parent.add_child(child2) - assert parent.is_fully_expanded(5) == False - child3 = MCTS_Node(Solution(), "s2") - child3.Q = 4 - parent.add_child(child3) - assert parent.is_fully_expanded(5) == False - assert parent.is_fully_expanded(3) == True - child3.Q = 12 - assert parent.is_fully_expanded(5) == True - assert grandparent.is_fully_expanded(100) == True +class FailingProblem(DummyProblem): + """Every evaluation after the first ``valid`` ones fails.""" + def __init__(self, valid: int = 0, maximise: bool = True): + super().__init__(maximise) + self.valid = valid -def test_expansion_on_non_leaf_node_is_refuted(): - llm = DummyLLM() - problem = DummyProblem() + def evaluate(self, solution): + self.count += 1 + if self.count <= self.valid: + solution.fitness = random.random() * 100 + else: + solution.fitness = float("-inf") if self.maximise else float("inf") + return solution - mcts_instance = MCTS(llm, problem, 10) + +def test_expansion_on_root_is_refuted(): + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 10) # raise on root expansion. Only initialise is applicable on root. with pytest.raises(ValueError): mcts_instance.expansion(mcts_instance.root) - mcts_instance.initialise() - n1 = MCTS_Node(Solution(), "e2", depth=2) - mcts_instance.root.children[0].add_child(n1) - # raises on non-leaf, non-root, only selection can expand on non leaf nodes. - with pytest.raises(ValueError): - child = mcts_instance.root.children[0] - mcts_instance.expansion(child) + +def test_expansion_of_a_node_with_children_adds_more(): + # A node at the depth limit is selected although it has children, and + # is expanded again (reference implementation). + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 100) + mcts_instance.initialise(1) + child = mcts_instance.root.children[0] + mcts_instance.expansion(child) + first = len(child.children) + mcts_instance.expansion(child) + assert len(child.children) == 2 * first def test_Q_comparison(): @@ -281,69 +282,24 @@ def test_initialise_works_correctly(): assert e1_count == 4 -def test_expansion_generates_2kp2_nodes(): +@pytest.mark.parametrize("k", [2, 6]) +def test_expansion_generates_2kp2_nodes(k): """ - Each expansion must generate 2 (expantion factor) + 2 nodes. - expansion factor number of nodes in m1, m2. - 1 s1 node. - 1 e2 node. + An expansion applies e2 once, m1 and m2 k (expansion factor) times + each and s1 once: 2k + 2 nodes, in the reference's order. At depth 1 + the s1 path holds one algorithm and s1 is skipped (reference). """ - llm = DummyLLM() - problem = DummyProblem() + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 1000, expansion_factor=k) + mcts_instance.initialise(2) + depth_1 = mcts_instance.root.children[0] + added = mcts_instance.expansion(depth_1) + assert [c.approach for c in added] == ["e2"] + ["m1"] * k + ["m2"] * k - mcts_instance = MCTS(llm, problem, budget=10, expansion_factor=2) - mcts_instance.initialise(5) - for child in mcts_instance.root.children: - mcts_instance.expansion(child) - - for intitalised_nodes in mcts_instance.root.children: - m1_nodes = m2_nodes = e2_nodes = s1_nodes = 0 - assert len(intitalised_nodes.children) == 6 - for child in intitalised_nodes.children: - match child.approach: - case "m1": - m1_nodes += 1 - case "m2": - m2_nodes += 1 - case "s1": - s1_nodes += 1 - case "e2": - e2_nodes += 1 - case x: - raise ValueError( - f"Got approach {x}, which is not in m1, m2, s1, e2." - ) - assert m1_nodes == mcts_instance.expansion_factor - assert m2_nodes == mcts_instance.expansion_factor - assert s1_nodes == 1 - assert e2_nodes == 1 - - mcts_instance = MCTS(llm, problem, budget=10, expansion_factor=6) - mcts_instance.initialise(5) - for child in mcts_instance.root.children: - mcts_instance.expansion(child) - - for intitalised_nodes in mcts_instance.root.children: - m1_nodes = m2_nodes = e2_nodes = s1_nodes = 0 - assert len(intitalised_nodes.children) == 14 - for child in intitalised_nodes.children: - match child.approach: - case "m1": - m1_nodes += 1 - case "m2": - m2_nodes += 1 - case "s1": - s1_nodes += 1 - case "e2": - e2_nodes += 1 - case x: - raise ValueError( - f"Got approach {x}, which is not in m1, m2, s1, e2." - ) - assert m1_nodes == mcts_instance.expansion_factor - assert m2_nodes == mcts_instance.expansion_factor - assert s1_nodes == 1 - assert e2_nodes == 1 + depth_2 = depth_1.children[0] + added = mcts_instance.expansion(depth_2) + assert len(added) == 2 * k + 2 + assert [c.approach for c in added] == (["e2"] + ["m1"] * k + ["m2"] * k + ["s1"]) + assert all(c.parent is depth_2 and c.depth == 3 for c in added) def test_get_node_raises_error_for_wrong_node_type(): @@ -529,147 +485,119 @@ def test_e2_node_generator_raises_when_expected_parent_is_root(): # endregion +def _node(approach="m1", code="x = 1"): + return MCTS_Node(Solution(code=code), approach) + + def test_simulate_updates_eval_remaining(): - llm = DummyLLM() - problem = DummyProblem() - mcts_instance = MCTS(llm, problem, 10) + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 10) assert mcts_instance.eval_remain == 10 - - mcts_instance.initialise() - for index, node in enumerate(mcts_instance.root.children): - mcts_instance.simulate(node) + for index in range(3): + mcts_instance.simulate(_node()) assert mcts_instance.eval_remain == 9 - index -def test_simulate_updates_Q_val_appropriately(monkeypatch): - llm = DummyLLM() - problem = DummyProblem() - mcts_instance = MCTS(llm, problem, 10) - mcts_instance.initialise() +@pytest.mark.parametrize("failure", [float("inf"), float("-inf"), float("nan")]) +def test_simulate_updates_Q_val_appropriately(monkeypatch, failure): + problem = ValidProblem() + mcts_instance = MCTS(DummyLLM(), problem, 10) def invalid_evaluator(node: MCTS_Node): - node.fitness = float("inf") - return node - - def invalid_evaluator_minus(node: MCTS_Node): - node.fitness = float("-inf") + node.fitness = failure return node monkeypatch.setattr(problem, "evaluate", invalid_evaluator) - for node in mcts_instance.root.children: - mcts_instance.simulate(node) - assert node.fitness == float("inf") - assert node.Q is None - assert mcts_instance.q_max is None - assert mcts_instance.q_min is None - - mcts_instance = MCTS(llm, problem, 10) - monkeypatch.setattr(problem, "evaluate", invalid_evaluator_minus) - mcts_instance.initialise() - for node in mcts_instance.root.children: - mcts_instance.simulate(node) - assert node.fitness == float("-inf") + for _ in range(3): + node = mcts_instance.simulate(_node()) assert node.Q is None assert mcts_instance.q_max is None assert mcts_instance.q_min is None -def test_simulate_updates_best_fitness_values_correctly(): - llm = DummyLLM() - problem = DummyProblem() # maximisation problem. - - mcts_instance_maximisation = MCTS(llm, problem, 10) - mcts_instance_maximisation.initialise(10) - q_min = None - q_max = None - for node in mcts_instance_maximisation.root.children: - mcts_instance_maximisation.simulate(node) - q_min = safe_min([q_min, node.Q]) - q_max = safe_max([q_max, node.Q]) - assert q_min == mcts_instance_maximisation.q_min - assert q_max == mcts_instance_maximisation.q_max - assert mcts_instance_maximisation.best_solution.fitness == q_max - - llm = DummyLLM() - problem = DummyProblem(maximise=False) # Minimisation problem. - - mcts_instance_minimisation = MCTS(llm, problem, 10, maximisation=False) - mcts_instance_minimisation.initialise(10) +@pytest.mark.parametrize("maximise", [True, False]) +def test_simulate_updates_best_fitness_values_correctly(maximise): + mcts_instance = MCTS( + DummyLLM(), DummyProblem(maximise=maximise), 10, maximisation=maximise + ) q_min = None q_max = None - for node in mcts_instance_minimisation.root.children: - mcts_instance_minimisation.simulate(node) + for _ in range(10): + node = mcts_instance.simulate(_node()) q_min = safe_min([q_min, node.Q]) q_max = safe_max([q_max, node.Q]) - print(f"\tNode(id:{node.id}, fitness:{node.fitness}, method:{node.approach})") - assert q_min == mcts_instance_minimisation.q_min - assert q_max == mcts_instance_minimisation.q_max - print( - f"MCTS Best solution: Node(id:{mcts_instance_minimisation.best_solution.id}, fitness:{mcts_instance_minimisation.best_solution.fitness}, method:{mcts_instance_minimisation.best_solution.approach})" - ) - assert mcts_instance_minimisation.best_solution.fitness == q_min - - -def test_selection_exapnds_root_nodes(monkeypatch): - llm = DummyLLM() - problem = DummyProblem() + assert q_min == mcts_instance.q_min + assert q_max == mcts_instance.q_max + expected = q_max if maximise else q_min + assert mcts_instance.best_solution.fitness == expected - def is_never_fully_expanded(max_children: int, *args, **kwargs): - return False - mcts_instance = MCTS(llm, problem, 10) +def test_selection_widens_root_with_e1(): + """Progressive widening at the root: int(N ** alpha) > #children.""" + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 100) mcts_instance.initialise() - for node in mcts_instance.root.children: - mcts_instance.simulate(node) - - monkeypatch.setattr( - mcts_instance.root, "is_fully_expanded", is_never_fully_expanded - ) - - expanded_node, selected_node = mcts_instance.selection() - assert len(expanded_node) == 1 - assert selected_node == mcts_instance.best_solution - assert expanded_node[0].parent == mcts_instance.root - - -def test_selection_exapnds_non_root(monkeypatch): - llm = DummyLLM() - problem = DummyProblem() - - def is_never_fully_expanded(max_children: int, *args, **kwargs): - return False - - def is_always_fully_expanded(max_children: int, *args, **kwargs): - return True - - mcts_instance = MCTS(llm, problem, 40) - n1 = MCTS_Node(Solution(), "i1", 1) - mcts_instance.root.add_child(n1) - - n2 = MCTS_Node(Solution(), "m1", 2) - n1.add_child(n2) - - n3 = MCTS_Node(Solution(), "m2", 3) - n2.add_child(n3) - - for node in [n1, n2, n3]: - mcts_instance.simulate(node) - - mcts_instance.backpropogate(n3) - - monkeypatch.setattr( - mcts_instance.root, "is_fully_expanded", is_always_fully_expanded - ) - monkeypatch.setattr(n1, "is_fully_expanded", is_always_fully_expanded) - monkeypatch.setattr(n2, "is_fully_expanded", is_never_fully_expanded) - monkeypatch.setattr(n3, "is_fully_expanded", is_always_fully_expanded) - - expanded, _ = mcts_instance.selection() - - assert len(expanded) == 1 - assert expanded[0].approach == "e2" - assert expanded[0].parent == n2 + root = mcts_instance.root + assert len(root.children) == 4 + assert root.visit == 4 # 0 at the start, +1 per valid child. + + root.visit = 24 # int(24 ** 0.5) = 4, not > 4 children. + widened, _ = mcts_instance.selection() + assert widened == [] and len(root.children) == 4 + + root.visit = 25 # int(25 ** 0.5) = 5 > 4 children. + widened, selected = mcts_instance.selection() + assert len(widened) == 1 + assert widened[0].approach == "e1" + assert widened[0].parent is root + assert len(root.children) == 5 + # The child to descend to is chosen before widening (reference). + assert selected is not widened[0] + + +def test_selection_widens_inner_node_with_e2(): + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 100) + mcts_instance.initialise(1) + n1 = mcts_instance.root.children[0] + mcts_instance.expansion(n1) # 5 children (s1 is skipped at depth 1). + assert len(n1.children) == 5 + root_children = len(mcts_instance.root.children) + mcts_instance.root.visit = 1 # int(1) = 1, not > 1: no root widening. + + n1.visit = 35 # int(35 ** 0.5) = 5, not > 5. + widened, _ = mcts_instance.selection() + assert widened == [] + + n1.visit = 36 # int(36 ** 0.5) = 6 > 5. + mcts_instance.root.visit = 1 # int(1) = 1, not > 1: no root widening. + widened, selected = mcts_instance.selection() + assert [w.approach for w in widened] == ["e2"] + assert widened[0].parent is n1 + assert len(mcts_instance.root.children) == root_children + assert selected.parent is n1 + + +def test_selection_respects_max_children_cap(): + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 100, max_children=4) + mcts_instance.initialise() + mcts_instance.root.visit = 100 + widened, _ = mcts_instance.selection() + assert widened == [] + + +def test_selection_stops_at_max_depth(): + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 100, max_depth=3) + parent = mcts_instance.root + chain = [] + for depth in range(1, 7): + node = MCTS_Node(Solution(), "m1", depth=depth, Q=1.0) + parent.add_child(node) + chain.append(node) + parent = node + mcts_instance.q_min = mcts_instance.q_max = 1.0 + mcts_instance.eval_remain = 0 # no widening + _, selected = mcts_instance.selection() + assert selected is chain[2] + assert selected.depth == 3 and not selected.is_leaf def test_selection_always_picks_better_child(): @@ -698,13 +626,8 @@ def test_selection_always_picks_better_child(): def test_back_propagation_logs_rank_list_properly(): - llm = DummyLLM() - problem = DummyProblem() - - mcts_instance = MCTS(llm, problem, 100) + mcts_instance = MCTS(DummyLLM(), DummyProblem(), 100) mcts_instance.initialise(10) - [mcts_instance.simulate(node) for node in mcts_instance.root.children] - [mcts_instance.backpropogate(node) for node in mcts_instance.root.children] assert None not in mcts_instance.rank_list assert len(mcts_instance.rank_list) == len( set([node.Q for node in mcts_instance.root.children if node.Q is not None]) @@ -739,3 +662,161 @@ def test_backpropagate_logs_e2_elements(): assert n2 in mcts_instance.e2_candidates assert n3 not in mcts_instance.e2_candidates assert n4 not in mcts_instance.e2_candidates + + +# region Behaviour of the reference implementation. +class RecordingLogger: + def __init__(self): + self.logged = [] + + def log_individual(self, individual): + self.logged.append(individual) + + +class FlakyLLM(DummyLLM): + """Fails (every try) for the calls in ``fail_calls``; counts calls.""" + + def __init__(self, fail_calls=()): + super().__init__() + self.calls = 0 + self.fail_calls = set(fail_calls) + + def sample_solution(self, session_messages, *args, **kwargs): + self.calls += 1 + if self.calls in self.fail_calls: + raise RuntimeError("empty response") + return super().sample_solution(session_messages) + + +def _all_nodes(node): + for child in node.children: + yield child + yield from _all_nodes(child) + + +def test_default_initial_node_count_is_4(): + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 100) + mcts_instance.initialise() + assert [c.approach for c in mcts_instance.root.children] == [ + "i1", + "e1", + "e1", + "e1", + ] + + +def test_initialise_replaces_failed_candidates(): + # Evaluations 5, 15, ... fail; the failed one is not added. + problem = DummyProblem() + mcts_instance = MCTS(DummyLLM(), problem, 100) + mcts_instance.initialise(5) + assert len(mcts_instance.root.children) == 5 + assert problem.count == 6 + assert all(c.Q is not None for c in mcts_instance.root.children) + + +def test_exploration_constant_decays_to_zero(): + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 200, lambda_0=0.1) + assert mcts_instance.exploration_constant() == pytest.approx(0.1) + mcts_instance.eval_remain = 100 + assert mcts_instance.exploration_constant() == pytest.approx(0.05) + mcts_instance.eval_remain = 0 + assert mcts_instance.exploration_constant() == 0 + + +def test_uct_bonus_is_sqrt_of_log_over_visits(): + mcts_instance = MCTS(DummyLLM(), ValidProblem(), 200, lambda_0=0.1) + mcts_instance.eval_remain = 100 + mcts_instance.q_min, mcts_instance.q_max = 0.0, 10.0 + parent = mcts_instance.root + parent.visit = 8 + node = MCTS_Node(Solution(), "e1", depth=1, visit=4, Q=5.0) + parent.add_child(node) + expected = 0.5 + 0.05 * math.sqrt(math.log(9) / 4) + assert mcts_instance.uct(node) == pytest.approx(expected) + mcts_instance.maximisation = False + assert mcts_instance.uct(node) == pytest.approx(expected) + + +def test_failed_candidates_are_not_added_to_the_tree(): + problem = DummyProblem() # evaluations 5, 15, 25, ... fail + mcts_instance = MCTS(DummyLLM(), problem, 60) + mcts_instance.run() + assert problem.count == 60 + nodes = list(_all_nodes(mcts_instance.root)) + assert nodes and all(n.Q is not None for n in nodes) + assert len(nodes) == 60 - 6 + + +def test_llm_failure_does_not_end_the_run(): + # Calls 20-29 fail: each of the 5 tries of two nodes fails. + llm = FlakyLLM(fail_calls=range(20, 30)) + problem = ValidProblem() + logger = RecordingLogger() + problem.logger = logger + mcts_instance = MCTS(llm, problem, 50) + mcts_instance.run() + assert mcts_instance.failed_generations == 2 + assert problem.count == 48 + assert mcts_instance.eval_remain == 0 + # The failed generations are logged as failed candidates. + failed = [s for s in logger.logged if s.code == ""] + assert len(failed) == 2 + assert all(math.isinf(s.fitness) for s in failed) + + +def test_llm_always_failing_uses_budget_and_ends(): + llm = FlakyLLM(fail_calls=range(1, 10_000)) + problem = ValidProblem() + mcts_instance = MCTS(llm, problem, 20) + mcts_instance.run() + assert mcts_instance.eval_remain == 0 + assert mcts_instance.failed_generations == 20 + assert problem.count == 0 + assert mcts_instance.root.children == [] + + +@pytest.mark.parametrize("valid", [0, 4, 10]) +def test_all_failing_candidates_use_the_full_budget(valid): + problem = FailingProblem(valid=valid) + mcts_instance = MCTS(DummyLLM(), problem, 200) + mcts_instance.run() + assert problem.count == 200 + assert mcts_instance.eval_remain == 0 + nodes = list(_all_nodes(mcts_instance.root)) + assert len(nodes) == valid # failed candidates are discarded + + +def test_run_depth_is_bounded_by_max_depth(monkeypatch): + max_depth = 3 + problem = ValidProblem() + mcts_instance = MCTS(DummyLLM(), problem, 300, max_depth=max_depth) + s1_paths = [] + original = mcts_instance._get_s1_nodes + + def recording_s1_nodes(node): + path = original(node) + s1_paths.append(len(path)) + return path + + monkeypatch.setattr(mcts_instance, "_get_s1_nodes", recording_s1_nodes) + mcts_instance.run() + assert problem.count == 300 + depths = [n.depth for n in _all_nodes(mcts_instance.root)] + # Selection stops at max_depth; that node's children are one deeper. + assert max(depths) == max_depth + 1 + assert max(s1_paths) <= max_depth + + +def test_method_wrapper_logs_new_parameters(): + from iohblade.methods.mcts_ahd.mcts import MCTS_Method + + method = MCTS_Method(DummyLLM(), 10) + config = method.get_config()["config"] + assert config["max_depth"] == 10 + assert config["initial_node_count"] == 4 + assert config["max_children"] is None + assert method.to_dict()["kwargs"]["max_tries"] == 3 + + +# endregion diff --git a/tests/unit/test_method_budgets.py b/tests/unit/test_method_budgets.py index 495c086..af3629a 100644 --- a/tests/unit/test_method_budgets.py +++ b/tests/unit/test_method_budgets.py @@ -152,16 +152,24 @@ def test_lhns_ts_sends_taboo_prompt(monkeypatch): lambda individual, destroyed_code, taboo_element: "TABOO PROMPT", ) - new = lhns.mutate_lhns_ts(9) + lhns.stagnation_count = 10 # 10 iterations without improvement + new = lhns.mutate_lhns_ts() assert llm.prompts[-1] == "TABOO PROMPT" assert new is not current -def test_lhns_ts_run_sends_taboo_prompt_once_every_10(monkeypatch): - problem = CountingProblem() +def test_lhns_ts_run_sends_taboo_prompt_after_10_non_improving(monkeypatch): + # The first solution is the best: no iteration improves on it. + class Stagnating(CountingProblem): + def __call__(self, solution, logger=None): + self.calls += 1 + fitness = 1.0 if self.calls == 1 else -1e9 + return solution.set_scores(fitness, "ok") + + problem = Stagnating() llm = FakeLLM() - lhns = LHNS(problem, llm, "ts", budget=10) + lhns = LHNS(problem, llm, "ts", budget=12) element = TabooElement("taboo desc", "taboo code", 0.5, ["feature"]) monkeypatch.setattr(lhns.taboo_table, "get_distinct_entry", lambda s: element) monkeypatch.setattr( @@ -170,9 +178,10 @@ def test_lhns_ts_run_sends_taboo_prompt_once_every_10(monkeypatch): lambda individual, destroyed_code, taboo_element: "TABOO PROMPT", ) lhns.run() - # Iterations 1..9: iteration 9 is the taboo iteration. + # Iterations 1..10 do not improve: iteration 11 is the taboo iteration. assert llm.prompts.count("TABOO PROMPT") == 1 - assert problem.calls == 10 + assert llm.prompts.index("TABOO PROMPT") == 11 + assert problem.calls == 12 # endregion @@ -196,18 +205,31 @@ def test_mcts_simulate_does_not_evaluate_beyond_budget(): problem = CountingProblem() mcts = MCTS(FakeLLM(), problem, 2) mcts.initialise(3) - for child in mcts.root.children: - mcts.simulate(child) assert problem.calls == 2 + assert len(mcts.root.children) == 2 assert mcts.eval_remain == 0 -def test_mcts_expansion_respects_max_nodes(): - mcts = MCTS(FakeLLM(), CountingProblem(), 100, expansion_factor=2) +def test_mcts_expansion_stops_at_the_budget(): + problem = CountingProblem() + mcts = MCTS(FakeLLM(), problem, 4, expansion_factor=2) mcts.initialise(1) child = mcts.root.children[0] - mcts.expansion(child, max_nodes=3) - assert [c.approach for c in child.children] == ["m1", "m2", "m1"] + mcts.expansion(child) + assert [c.approach for c in child.children] == ["e2", "m1", "m1"] + assert problem.calls == 4 + + +@pytest.mark.parametrize("budget", [7, 30]) +def test_mcts_llm_failures_count_against_the_budget(budget): + # Every node fails 5 tries once (calls 1-5), then the LLM works. + problem = CountingProblem(fail_every=4) + llm = FakeLLM(fail_first=5) + mcts = MCTS(llm, problem, budget) + mcts.run() + assert mcts.failed_generations == 1 + assert problem.calls == budget - 1 + assert mcts.eval_remain == 0 # endregion From d5e18f1c7a34229fd6cf03d970bddf28f19af092 Mon Sep 17 00:00:00 2001 From: Bas van Stein Date: Tue, 1 Dec 2026 17:22:07 +0100 Subject: [PATCH 3/6] MoEH: use the installed Python grammar for syntax match tree-sitter-language-pack 1.x downloads grammars at first use; on a Windows CI runner the download returned invalid JSON and test_moeh_evaluates_exactly_budget failed. Pass the grammar of the tree-sitter-python dependency to codebleu instead (same scores, no network access needed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HiY2guDd9wWLKRWPoa16yy --- iohblade/methods/moeh_method/population.py | 16 +++++++++++++--- tests/unit/test_moeh.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/iohblade/methods/moeh_method/population.py b/iohblade/methods/moeh_method/population.py index 0eb2719..bd2f705 100644 --- a/iohblade/methods/moeh_method/population.py +++ b/iohblade/methods/moeh_method/population.py @@ -1,10 +1,17 @@ import numpy as np -from codebleu.syntax_match import calc_syntax_match +import tree_sitter_python +from codebleu.syntax_match import corpus_syntax_match from pymoo.util.nds.non_dominated_sorting import NonDominatedSorting +from tree_sitter import Language from iohblade.fitness import Fitness from iohblade.solution import Solution +# The installed Python grammar. Without it, codebleu asks +# tree-sitter-language-pack, which downloads the grammar at first use (and +# fails without network access). +_PYTHON = Language(tree_sitter_python.language()) + class Population: def __init__(self, size, minimisation: bool) -> None: @@ -38,8 +45,11 @@ def _get_delta_domination_matrix(self) -> np.ndarray: for i in range(N): for j in range(N): if i != j: - S[i, j] = -calc_syntax_match( - self._population[i].code, self._population[j].code, "python" + S[i, j] = -corpus_syntax_match( + [self._population[i].code], + [self._population[j].code], + "python", + tree_sitter_language=_PYTHON, ) if ( diff --git a/tests/unit/test_moeh.py b/tests/unit/test_moeh.py index 6f50ca9..46caf35 100644 --- a/tests/unit/test_moeh.py +++ b/tests/unit/test_moeh.py @@ -443,6 +443,24 @@ def test_population_matrix_returns_appropriate_array(): assert expected[i][j] == cell +def test_population_matrix_uses_the_installed_grammar(monkeypatch): + """No grammar download: tree-sitter-language-pack fetches grammars at + first use, which failed on CI runners without (working) network.""" + import codebleu.syntax_match + + def no_download(lang): + raise AssertionError("downloaded grammar requested") + + monkeypatch.setattr(codebleu.syntax_match, "get_tree_sitter_language", no_download) + p = Population(2, True) + for code, f in [("ABC", 1), ("ACD", 2)]: + s = Solution(code) + s.set_scores(f, "test") + p.append(s) + m = p._get_delta_domination_matrix() + assert m.shape == (2, 2) and m[0, 1] < 0 and m[1, 0] == 0 + + def test_parent_selection_gracefully_exits_selection_on_empty(): p = Population(10, True) assert p.parent_selection(4) == [] From 29f90e8a8cd0fdaa7fade69730642acbb3085f4d Mon Sep 17 00:00:00 2001 From: Bas van Stein Date: Tue, 1 Dec 2026 17:22:59 +0100 Subject: [PATCH 4/6] MoEH: compare whole programs in the syntax match codebleu expects a list of references per candidate. Given a bare code string it iterated over its characters, so MoEH's code similarity was about 0 for every pair of real programs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HiY2guDd9wWLKRWPoa16yy --- CHANGELOG.md | 7 +++++++ iohblade/methods/moeh_method/population.py | 4 +++- tests/unit/test_moeh.py | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc74997..548e2c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -111,6 +111,13 @@ with `ini_ratio` and perturb after 10 iterations in a row without improvement (ILS asks to modify the best solution so far, TS merges in a tabu-table entry), instead of every 10th iteration. +- **MoEH: code similarity compared characters, not programs.** The + code was passed to codebleu's syntax match as a bare string, where a list + of references is expected, so single characters were compared and the + similarity of real programs was about 0. Programs are now compared as a + whole, which changes MoEH's parent selection. The syntax match also uses + the installed `tree-sitter-python` grammar instead of downloading one at + first use (that failed without network access). ## v1.2.2 (2026-11-26) diff --git a/iohblade/methods/moeh_method/population.py b/iohblade/methods/moeh_method/population.py index bd2f705..69f9b86 100644 --- a/iohblade/methods/moeh_method/population.py +++ b/iohblade/methods/moeh_method/population.py @@ -45,8 +45,10 @@ def _get_delta_domination_matrix(self) -> np.ndarray: for i in range(N): for j in range(N): if i != j: + # One candidate (j) with one reference (i): a list of + # reference lists, or codebleu iterates the characters. S[i, j] = -corpus_syntax_match( - [self._population[i].code], + [[self._population[i].code]], [self._population[j].code], "python", tree_sitter_language=_PYTHON, diff --git a/tests/unit/test_moeh.py b/tests/unit/test_moeh.py index 46caf35..31ca79b 100644 --- a/tests/unit/test_moeh.py +++ b/tests/unit/test_moeh.py @@ -461,6 +461,23 @@ def no_download(lang): assert m.shape == (2, 2) and m[0, 1] < 0 and m[1, 0] == 0 +def test_population_matrix_compares_whole_programs(): + """codebleu wants a list of references per candidate; given a bare + string it compared single characters, so every pair scored about 0.""" + p = Population(3, True) + same_shape_a = "def f(x):\n y = x + 1\n return y * 2\n" + same_shape_b = "def f(x):\n y = x + 3\n return y * 2\n" + other = "import numpy as np\n\nclass A:\n def __call__(self, f):\n return np.zeros(3)\n" + for code, f in [(same_shape_a, 1), (same_shape_b, 2), (other, 3)]: + s = Solution(code) + s.set_scores(f, "test") + p.append(s) + m = p._get_delta_domination_matrix() + assert m[0, 1] == -1.0 # same syntax tree + assert m[0, 2] == 0.0 # no shared subtree + assert m[1, 0] == 0.0 # dominated + + def test_parent_selection_gracefully_exits_selection_on_empty(): p = Population(10, True) assert p.parent_selection(4) == [] From 99b263b0736868e26a8f0693f97c434c659e20fb Mon Sep 17 00:00:00 2001 From: Bas van Stein Date: Tue, 1 Dec 2026 17:26:50 +0100 Subject: [PATCH 5/6] MCTS-AHD e1/e2 parents and LHNS LLM failures as in the reference - MCTS-AHD e2: one rank-weighted node of the elite set (10 best distinct nodes) followed by the parent, as the e2 prompt text already assumed. - MCTS-AHD e1: one random node per root-child subtree, then randint(2, 5) of those with replacement. - LHNS: an LLM failure costs one evaluation, is logged as a failed candidate and rejected; the search continues. A failed initial generation is retried within the budget. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HiY2guDd9wWLKRWPoa16yy --- CHANGELOG.md | 12 ++ iohblade/methods/lhns/lhns.py | 86 ++++++++++--- iohblade/methods/mcts_ahd/mcts.py | 112 ++++++++++++---- tests/unit/test_lhns.py | 76 +++++++++++ tests/unit/test_mcts_ahd.py | 207 +++++++++++++++--------------- 5 files changed, 342 insertions(+), 151 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e2c2..d5b6a2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,11 +90,23 @@ m2 x k, s1; s1 is skipped at depth 1). - **MCTS-AHD starts with 4 nodes** (one i1, three e1), as in the paper and the reference, instead of 3 (`initial_node_count`). +- **MCTS-AHD: e1 and e2 prompts use the reference's algorithms.** e2 showed + up to 5 nodes sampled from depth 1-2 and the best solution, without the + parent; it now shows one node of the elite set (the `elite_size` = 10 + best nodes with distinct fitness, rank-weighted) followed by the parent, + as its prompt text already assumed. e1 during progressive widening + showed all root children; it now draws one random node from each root + child's subtree, then 2 to `e1_max_parents` (5) of those. - **LHNS never moved away from its first solution.** It compared the candidate object it had sent to the evaluation, not the evaluated one that came back, so every candidate looked unevaluated and was rejected; all destroy-repair steps started from the initial code. It now uses the evaluated candidate. +- **LHNS: one LLM failure ended the run.** After 5 failed tries the + error left the method. Such a step now uses one evaluation, is logged as + a failed candidate and is rejected (a non-improving step), and the + search continues, as in the reference. A failed initial generation is + tried again within the budget. - **LHNS: the temperature rose instead of cooling.** It was `cooling_rate * t / budget`; it is now `cooling_rate * (1 - (t - 1) / budget)`, as in the reference. A worse candidate is accepted with diff --git a/iohblade/methods/lhns/lhns.py b/iohblade/methods/lhns/lhns.py index 86b41f5..8911816 100644 --- a/iohblade/methods/lhns/lhns.py +++ b/iohblade/methods/lhns/lhns.py @@ -213,6 +213,32 @@ def _sample(self, prompt: str) -> Solution: raise e print("LHNS: Failed to communicate with LLM, retrying...") + def _record_failed_generation( + self, operator: str, parent: Solution | None, error: Exception + ) -> Solution: + """A candidate the LLM failed to generate, charged as one + evaluation: it gets the problem's failure fitness and is logged as + a failed candidate when the problem has a logger. + + Args: + operator: The LHNS step (i1, vns, ils or ts). + parent: The solution the step started from, if any. + error: The LLM's error. + + Returns: + The failed candidate. + """ + message = f"LLM failure in LHNS step {operator}: {error!r}" + print(f"\t{message}") + failed = Solution(code="", operator=operator) + failed.parent_ids = [] if parent is None else [parent.id] + failed.set_scores(self.problem.failure_fitness(), message, message) + logger = getattr(self.problem, "logger", None) + if logger is not None: + logger.log_individual(failed) + self._log_best_solution(failed) + return failed + def evaluate(self, solution: Solution) -> Solution: """ Evaluates the solution with `problem()` function, and returns if it returns, else returns solution un-mutated. @@ -397,36 +423,54 @@ def run(self) -> Solution: Makes exactly `budget` evaluations: the initial solution plus `budget - 1` destroy-repair iterations. + + When the LLM fails (5 tries in a row), the step costs one + evaluation and its candidate counts as failed: it is rejected and + the search continues, as in the reference (where a failed + candidate has objective None). A failed initial generation is + tried again. """ - self.initialise() - current = self.evaluate(self.current_solution) - self.current_solution = current + used = 0 + initial = None + while initial is None and used < self.budget: + used += 1 + try: + self.initialise() + except Exception as error: + self._record_failed_generation("i1", None, error) + continue + initial = self.evaluate(self.current_solution) + if initial is None: + return self.best_solution + self.current_solution = initial self.ratio = self.ini_ratio self.stagnation_count = 0 - # The initial evaluation above uses one unit of the budget. - for iteration_number in range(1, self.budget): + for iteration_number in range(used, self.budget): current = self.current_solution print( f"Gen {iteration_number}: Current: ({current.id}, {current.fitness}, {current.feedback}); Best: ({self.best_solution.id}, {self.best_solution.fitness}, {self.best_solution.feedback}); r = {self.ratio}" ) if self.method == "ts": print(f"\tTT: {self.taboo_table.get_fitness_series()}") - match self.method: - case "vns": - next = self.mutate_lhns_vns() - case "ils": - next = self.mutate_lhns_ils() - case "ts": - next = self.mutate_lhns_ts() - case _: - raise ValueError( - f"Expected method to be in ['vns', 'ils', 'ts'], got {self.method}" - ) - # Use the returned solution: an evaluation in a subprocess - # returns a new object and leaves `next` unevaluated. - next = self.evaluate(next) - if self.method == "ts": - self.taboo_table.update_taboo_search_table(current, next) + mutate = { + "vns": self.mutate_lhns_vns, + "ils": self.mutate_lhns_ils, + "ts": self.mutate_lhns_ts, + }.get(self.method) + if mutate is None: + raise ValueError( + f"Expected method to be in ['vns', 'ils', 'ts'], got {self.method}" + ) + try: + next = mutate() + except Exception as error: + next = self._record_failed_generation(self.method, current, error) + else: + # Use the returned solution: an evaluation in a subprocess + # returns a new object and leaves `next` unevaluated. + next = self.evaluate(next) + if self.method == "ts": + self.taboo_table.update_taboo_search_table(current, next) accepted, improved = self.simulated_annealing(next, iteration_number) self.stagnation_count = 0 if improved else self.stagnation_count + 1 if self.method == "vns": diff --git a/iohblade/methods/mcts_ahd/mcts.py b/iohblade/methods/mcts_ahd/mcts.py index 41dfd7e..c113958 100644 --- a/iohblade/methods/mcts_ahd/mcts.py +++ b/iohblade/methods/mcts_ahd/mcts.py @@ -1,4 +1,5 @@ import copy +import functools import inspect import math import random @@ -46,6 +47,8 @@ def __init__( max_depth: int = 10, initial_node_count: int = 4, max_tries: int = 3, + elite_size: int = 10, + e1_max_parents: int = 5, ): """ MCTS-AHD (https://arxiv.org/abs/2501.08603) for solving a given @@ -62,6 +65,10 @@ def __init__( - Progressive widening (Eq. 4): every node passed in the selection with `int(N ** alpha) > #children` gets a new child, by e1 at the root and e2 elsewhere. + - e1 draws one random node from the subtree of each root child, + then 2 to `e1_max_parents` of those (with replacement). e2 gets + the parent and one node of the elite set (the `elite_size` best + nodes with distinct fitness, rank-weighted), as in the reference. - Expansion of the selected node: e2 once, m1 and m2 `expansion_factor` (k) times each, and s1 once (2k + 2 nodes; s1 is skipped at depth 1, where the path holds a single algorithm). @@ -86,7 +93,9 @@ def __init__( `max_depth: int`: Depth limit of the selection (10).\\ `initial_node_count: int`: Number of initial root children N_I (4).\\ `max_tries: int`: Tries per operator application before it is given - up (3 in the reference). + up (3 in the reference).\\ + `elite_size: int`: Size of the elite set E that e2 draws from (10).\\ + `e1_max_parents: int`: Most algorithms in an e1 prompt (5). ## Budget: `run()` makes at most `budget` calls to `problem(...)`: no node is @@ -112,7 +121,8 @@ def __init__( self.q_min = None self.q_max = None self.rank_list = [] - self.e2_candidates: list[MCTS_Node] = [] + self.elite_size = elite_size + self.e1_max_parents = e1_max_parents self.max_children = max_children # Nodes whose generation failed (LLM error); not part of the tree. self.failed_generations = 0 @@ -126,9 +136,7 @@ def __init__( else: self.root.fitness = float("inf") - self.best_solution: MCTS_Node = ( - self.root - ) # Best solution node used as reference for e2 expansion. + self.best_solution: MCTS_Node = self.root # Best solution found so far. # region Node Generators. @@ -285,14 +293,17 @@ def _get_s1_nodes(self, as_child_of_node: MCTS_Node) -> list[MCTS_Node]: def _get_e1_nodes(self, as_child_of_node: MCTS_Node) -> list[MCTS_Node]: """ - Return relevant nodes for e1 mutation, adheres to returning list[MCTS_Node]. The `for_node` must be a child of root node. - Returns the sibling of the `for_node`. + The algorithms of an e1 prompt (reference `expand` and + `get_offspring`): one random node from the subtree of each root + child (the child and its descendants), then `randint(2, + e1_max_parents)` of those, drawn with replacement (at most as many + as there are root children). ## Args: `as_child_of_node: MCTS_Node`: Always the root node. ## Returns: - `list[MCTS_Node]`: Children of the root node, which are going to be sibling to the node being generated. + `list[MCTS_Node]`: The algorithms to show in the prompt. ## Raises: ValueError: If `as_child_of_node != root`. """ @@ -300,32 +311,77 @@ def _get_e1_nodes(self, as_child_of_node: MCTS_Node) -> list[MCTS_Node]: raise ValueError( "E1 Mutation is only applicable on depth = 1, i.e. for root node." ) - return as_child_of_node.children + pool = [ + random.choice(self._subtree(child)) for child in as_child_of_node.children + ] + if not pool: + return [] + count = min(random.randint(2, max(2, self.e1_max_parents)), len(pool)) + return random.choices(pool, k=count) def _get_e2_nodes(self, as_child_of_node: MCTS_Node) -> list[MCTS_Node]: """ - Return relevant nodes for adding E2 mutation node as child to `as_child_of_node`, where `for_node` is a MCTS_Node with min depth = 1. - If there is no best solution yet (due to evaluation errors), reverts back to M1. + The algorithms of an e2 prompt for a child of `as_child_of_node` + (reference `get_offspring`): one node of the elite set other than + the parent, drawn with weight `1 / (rank + 1 + n)` (rank 0 = best), + followed by the parent. The prompt asks for an algorithm similar to + the last one (the parent) and inspired by the first. ## Args: - `as_child_of_node: MCTS_Node`: MCTS_Node in the tree at a minimum depth of 1. + `as_child_of_node: MCTS_Node`: The parent, a non-root node. ## Returns: - `[MCTS_Node]`: Relevant nodes for e2 mutation child if best_solution is exists: [as_child_of_node, best_solution], else returns [as_child_of_node]. + `[MCTS_Node]`: `[elite, parent]`, or `[parent]` while the elite set + holds no other node. ## Raises: - `ValueError`: If `for_node` is below depth 2. + `ValueError`: If `as_child_of_node` is the root. """ if as_child_of_node.is_root: raise ValueError("E2 cannot be used to generate child of root node.") - choice_pool = list( - set( - self.e2_candidates - + ([self.best_solution] if not self.best_solution.is_root else []) - ) - ) - relevant_nodes = random.sample(choice_pool, k=min(5, len(choice_pool))) - return relevant_nodes + others = [node for node in self.elite() if node is not as_child_of_node] + if not others: + return [as_child_of_node] + n = len(others) + weights = [1 / (rank + 1 + n) for rank in range(n)] + return random.choices(others, weights=weights, k=1) + [as_child_of_node] + + def _subtree(self, node: MCTS_Node) -> list[MCTS_Node]: + """`node` and all its descendants.""" + nodes, stack = [], [node] + while stack: + current = stack.pop() + nodes.append(current) + stack.extend(current.children) + return nodes + + def elite(self) -> list[MCTS_Node]: + """The elite set E of the reference (`population_management`): the + `elite_size` best nodes of the tree with distinct fitness values, + best first. Failed candidates are not in the tree.""" + minimisation = not self.maximisation + + def compare(a: MCTS_Node, b: MCTS_Node) -> int: + if is_better(a.fitness, b.fitness, minimisation): + return -1 + if is_better(b.fitness, a.fitness, minimisation): + return 1 + return 0 + + nodes = [ + node + for child in self.root.children + for node in self._subtree(child) + if node.fitness_is_valid() + ] + nodes.sort(key=functools.cmp_to_key(compare)) + elite: list[MCTS_Node] = [] + for node in nodes: + if all(node.fitness != other.fitness for other in elite): + elite.append(node) + if len(elite) == self.elite_size: + break + return elite # endregion @@ -572,8 +628,6 @@ def backpropogate(self, node: MCTS_Node): + best_child_Q * self.discount_factor ) parent.visit += 1 - if node.depth in [1, 2]: - self.e2_candidates.append(node) parent = parent.parent # endregion @@ -698,6 +752,8 @@ def __init__( max_depth: int = 10, initial_node_count: int = 4, max_tries: int = 3, + elite_size: int = 10, + e1_max_parents: int = 5, ): """ MCTS-AHD method wrapper for adding it to iohblade/methods; see @@ -716,7 +772,9 @@ def __init__( `expansion_factor: int` Number of m1 and m2 mutations allowed during the expansion phase.\\ `max_depth: int`: Depth limit of the selection.\\ `initial_node_count: int`: Number of initial root children N_I.\\ - `max_tries: int`: Tries per operator application. + `max_tries: int`: Tries per operator application.\\ + `elite_size: int`: Size of the elite set that e2 draws from.\\ + `e1_max_parents: int`: Most algorithms in an e1 prompt. """ super().__init__(llm, budget, name="MCTS_AHD") self.lambda_0 = lambda_0 @@ -727,6 +785,8 @@ def __init__( self.max_depth = max_depth self.initial_node_count = initial_node_count self.max_tries = max_tries + self.elite_size = elite_size + self.e1_max_parents = e1_max_parents sig = inspect.signature(self.__init__) self.init_params = { k: getattr(self, k) @@ -758,6 +818,8 @@ def __call__(self, problem: Problem): max_depth=self.max_depth, initial_node_count=self.initial_node_count, max_tries=self.max_tries, + elite_size=self.elite_size, + e1_max_parents=self.e1_max_parents, ) try: return self.mcts_instance.run() diff --git a/tests/unit/test_lhns.py b/tests/unit/test_lhns.py index d91837a..16e9af4 100644 --- a/tests/unit/test_lhns.py +++ b/tests/unit/test_lhns.py @@ -833,3 +833,79 @@ def test_ts_merges_taboo_features_after_10_non_improving(monkeypatch): # endregion + + +class FlakyLLM(CodeLLM): + """CodeLLM whose calls with the given (1-based) numbers raise.""" + + def __init__(self, failing_calls): + super().__init__() + self.failing_calls = set(failing_calls) + self.attempts = 0 + + def sample_solution(self, messages, *args, **kwargs): + self.attempts += 1 + if self.attempts in self.failing_calls: + raise NoCodeException + return super().sample_solution(messages, *args, **kwargs) + + +class RecordingLogger: + def __init__(self): + self.logged = [] + + def log_individual(self, solution): + self.logged.append(solution) + + +@pytest.mark.parametrize("method", ["vns", "ils", "ts"]) +def test_llm_failure_costs_one_evaluation_and_the_run_goes_on(method): + """Reference: a failed candidate (objective None) is rejected and the + search continues. Calls 2-6 are the 5 tries of the first step.""" + problem = NewObjectProblem([1.0, 2.0, 3.0, 4.0, 5.0]) + problem.logger = RecordingLogger() + llm = FlakyLLM(failing_calls=range(2, 7)) + lhns = LHNS(problem, llm, method, budget=5, minimisation=False) + best = lhns.run() + assert problem.calls == 4 # initial + 3 steps; 1 step failed + failed = [s for s in problem.logger.logged if s.code == ""] + assert len(failed) == 1 and failed[0].fitness == float("-inf") + assert "LLM failure" in failed[0].feedback + assert best.fitness == 4.0 # the search went on after the failure + + +def test_llm_failure_is_a_rejection_for_vns(monkeypatch): + problem = NewObjectProblem([10.0, -1e9]) + llm = FlakyLLM(failing_calls=range(2, 7)) + lhns = LHNS(problem, llm, "vns", budget=3, minimisation=False) + ratios = [] + original = lhns.destroy_code + + def recording(r, solution): + ratios.append(r) + return original(r, solution) + + monkeypatch.setattr(lhns, "destroy_code", recording) + lhns.run() + # Failed step at r = 0.1 (rejected), then r = 0.2. + assert ratios == [0.1, 0.2] + assert lhns.current_solution.fitness == 10.0 + + +def test_failed_initial_generation_is_retried_within_budget(): + problem = NewObjectProblem([1.0, 2.0]) + llm = FlakyLLM(failing_calls=range(1, 6)) # the first i1 fails 5 times + lhns = LHNS(problem, llm, "vns", budget=3, minimisation=False) + best = lhns.run() + assert problem.calls == 2 # one evaluation went to the failed i1 + assert best.fitness == 2.0 + + +def test_all_failing_llm_ends_after_budget(): + problem = NewObjectProblem([1.0]) + llm = FlakyLLM(failing_calls=range(1, 1000)) + lhns = LHNS(problem, llm, "vns", budget=4, minimisation=False) + best = lhns.run() + assert problem.calls == 0 + assert llm.attempts == 4 * 5 + assert not best.fitness_is_valid() diff --git a/tests/unit/test_mcts_ahd.py b/tests/unit/test_mcts_ahd.py index dbcd713..82eae3c 100644 --- a/tests/unit/test_mcts_ahd.py +++ b/tests/unit/test_mcts_ahd.py @@ -7,6 +7,7 @@ from iohblade.llm import LLM from iohblade.mcts_node import MCTS_Node from iohblade.methods.mcts_ahd.mcts import MCTS, safe_max, safe_min +from iohblade.methods.mcts_ahd.prompts import MCTS_Prompts from iohblade.problem import Problem from iohblade.solution import Solution @@ -361,82 +362,108 @@ def test_get_s1_nodes_returns_correct_trace(): assert trace == [n1, n2, n3] -def test_get_e1_node_returns_siblings(): - llm = DummyLLM() - problem = DummyProblem() - mcts_instance = MCTS(llm, problem, 10) - i1 = MCTS_Node(Solution(), "i1", 1) - e1 = MCTS_Node(Solution(), "e1", 1) - e11 = MCTS_Node(Solution(), "e1", 1) - e2 = MCTS_Node(Solution(), "e2", 2) - mcts_instance.root.add_child(i1) - mcts_instance.root.add_child(e1) - mcts_instance.root.add_child(e11) - e1.add_child(e2) - - relevant_nodes = mcts_instance._get_e1_nodes(mcts_instance.root) - assert i1 in relevant_nodes - assert e1 in relevant_nodes - assert e11 in relevant_nodes - assert e2 not in relevant_nodes - - -def test_get_e2_nodes_returns_random_sample_from_best_solutions(monkeypatch): - - llm = DummyLLM() - problem = DummyProblem() - mcts_instance = MCTS(llm, problem, 10) - n1 = MCTS_Node(Solution(), "i1", 1) - - mcts_instance.root.add_child(n1) - assert mcts_instance._get_e2_nodes(as_child_of_node=n1) == [] - - # Add candidates progressively - f1 = MCTS_Node(Solution(), "e2", 2) - mcts_instance.e2_candidates.append(f1) - result = mcts_instance._get_e2_nodes(as_child_of_node=n1) - assert result == [f1] - - f2 = MCTS_Node(Solution(), "s1", 2) - mcts_instance.e2_candidates.append(f2) - result = mcts_instance._get_e2_nodes(as_child_of_node=n1) - assert set(result) == {f1, f2} - assert len(result) == 2 - - f3 = MCTS_Node(Solution(), "m1", 3) - mcts_instance.e2_candidates.append(f3) - result = mcts_instance._get_e2_nodes(as_child_of_node=n1) - assert set(result) <= {f1, f2, f3} - assert 1 <= len(result) <= 3 - - f4 = MCTS_Node(Solution(), "m2", 4) - mcts_instance.e2_candidates.append(f4) - result = mcts_instance._get_e2_nodes(as_child_of_node=n1) - assert all(x in mcts_instance.e2_candidates for x in result) - assert len(result) <= 5 # sample up to 5 - - f5 = MCTS_Node(Solution(), "m2", 2) - mcts_instance.e2_candidates.append(f5) - - mcts_instance.best_solution = f5 - result = mcts_instance._get_e2_nodes(as_child_of_node=n1) - - # Verify all results are from the deduplicated candidate pool - expected_pool = list( - dict.fromkeys( - mcts_instance.e2_candidates - + ( - [mcts_instance.best_solution] - if not mcts_instance.best_solution.is_root - else [] - ) - ) +def _scored(approach, depth, fitness): + node = MCTS_Node(Solution(), approach, depth) + node.fitness = fitness + return node + + +def test_get_e1_nodes_draws_one_node_per_root_subtree(monkeypatch): + """Reference `expand`: one random node from each root child's + subtree, then randint(2, m) of those with replacement.""" + mcts_instance = MCTS(DummyLLM(), DummyProblem(), 10) + i1 = _scored("i1", 1, 1.0) + e1 = _scored("e1", 1, 2.0) + e11 = _scored("e1", 1, 3.0) + deep = _scored("e2", 2, 4.0) + for child in (i1, e1, e11): + mcts_instance.root.add_child(child) + e1.add_child(deep) + + # Pick the last node of each subtree; take the largest count. + monkeypatch.setattr(random, "choice", lambda seq: seq[-1]) + monkeypatch.setattr(random, "randint", lambda a, b: b) + drawn = [] + monkeypatch.setattr( + random, "choices", lambda pool, k: drawn.append((list(pool), k)) or pool[:k] ) - - assert all(x in expected_pool for x in result) - assert len(result) <= min(5, len(expected_pool)) - # Ensure no duplicate references - assert len(result) == len(set(map(id, result))) + result = mcts_instance._get_e1_nodes(mcts_instance.root) + pool, k = drawn[0] + assert pool == [i1, deep, e11] # a descendant stands in for e1 + assert k == 3 # min(randint(2, 5), number of root children) + assert result == [i1, deep, e11] + + +def test_get_e1_nodes_count_is_between_two_and_max(monkeypatch): + mcts_instance = MCTS(DummyLLM(), DummyProblem(), 10, e1_max_parents=4) + for f in range(8): + mcts_instance.root.add_child(_scored("e1", 1, float(f))) + for seed in range(30): + random.seed(seed) + nodes = mcts_instance._get_e1_nodes(mcts_instance.root) + assert 2 <= len(nodes) <= 4 + assert all(n in mcts_instance.root.children for n in nodes) + # A single root child (initialisation): just that one. + single = MCTS(DummyLLM(), DummyProblem(), 10) + only = _scored("i1", 1, 1.0) + single.root.add_child(only) + assert single._get_e1_nodes(single.root) == [only] + + +def test_elite_is_best_distinct_and_capped(): + mcts_instance = MCTS(DummyLLM(), DummyProblem(), 10, elite_size=3) + a, b, c = _scored("i1", 1, 1.0), _scored("e1", 1, 5.0), _scored("m1", 2, 5.0) + d, bad = _scored("m2", 3, 3.0), _scored("m2", 2, float("-inf")) + e = _scored("s1", 2, 4.0) + mcts_instance.root.add_child(a) + mcts_instance.root.add_child(b) + b.add_child(c) + c.add_child(d) + a.add_child(bad) + a.add_child(e) + elite = mcts_instance.elite() + assert [n.fitness for n in elite] == [5.0, 4.0, 3.0] # maximisation + assert bad not in elite + mcts_instance.maximisation = False + assert [n.fitness for n in mcts_instance.elite()] == [1.0, 3.0, 4.0] + + +def test_get_e2_nodes_is_one_elite_then_the_parent(monkeypatch): + """Reference `get_offspring` (e2): one rank-weighted node of the elite + set other than the parent, followed by the parent.""" + mcts_instance = MCTS(DummyLLM(), DummyProblem(), 10) + parent = _scored("i1", 1, 1.0) + mcts_instance.root.add_child(parent) + assert mcts_instance._get_e2_nodes(as_child_of_node=parent) == [parent] + + best, second = _scored("e1", 1, 9.0), _scored("m1", 2, 7.0) + mcts_instance.root.add_child(best) + best.add_child(second) + seen = [] + + def fake_choices(pool, weights, k): + seen.append((list(pool), list(weights), k)) + return [pool[0]] + + monkeypatch.setattr(random, "choices", fake_choices) + result = mcts_instance._get_e2_nodes(as_child_of_node=parent) + pool, weights, k = seen[0] + assert pool == [best, second] # the parent is left out of the pool + assert weights == pytest.approx([1 / 3, 1 / 4]) # 1 / (rank + 1 + n) + assert k == 1 + assert result == [best, parent] + + +def test_e2_prompt_names_the_parent_last(): + mcts_instance = MCTS(DummyLLM(), DummyProblem(), 10) + parent, elite = _scored("i1", 1, 1.0), _scored("e1", 1, 2.0) + parent.code, elite.code = "PARENT_CODE", "ELITE_CODE" + mcts_instance.root.add_child(parent) + mcts_instance.root.add_child(elite) + nodes = mcts_instance._get_e2_nodes(as_child_of_node=parent) + prompt = MCTS_Prompts.get_prompt_e2("task", "", "", nodes) + assert prompt.index("ELITE_CODE") < prompt.index("PARENT_CODE") + assert "similar form to the No.2 algorithm" in prompt # region Test get node function raises appropriate errors: @@ -634,36 +661,6 @@ def test_back_propagation_logs_rank_list_properly(): ) -def test_backpropagate_logs_e2_elements(): - llm = DummyLLM() - problem = DummyProblem() - - mcts_instance = MCTS(llm, problem, 100) - n1 = MCTS_Node(Solution(), "i1", 1) - n2 = MCTS_Node(Solution(), "e2", 2) - n3 = MCTS_Node(Solution(), "m1", 3) - n4 = MCTS_Node(Solution(), "m2", 4) - - mcts_instance.root.add_child(n1) - n1.add_child(n2) - n2.add_child(n3) - n3.add_child(n4) - - mcts_instance.simulate(n1) - mcts_instance.backpropogate(n1) - mcts_instance.simulate(n2) - mcts_instance.backpropogate(n2) - mcts_instance.simulate(n3) - mcts_instance.backpropogate(n3) - mcts_instance.simulate(n4) - mcts_instance.backpropogate(n4) - - assert n1 in mcts_instance.e2_candidates - assert n2 in mcts_instance.e2_candidates - assert n3 not in mcts_instance.e2_candidates - assert n4 not in mcts_instance.e2_candidates - - # region Behaviour of the reference implementation. class RecordingLogger: def __init__(self): From 91774268c8308932c91cac19c7de5d965bf4fe5f Mon Sep 17 00:00:00 2001 From: Bas van Stein Date: Tue, 1 Dec 2026 18:25:33 +0100 Subject: [PATCH 6/6] LLaMEA-HPO: ask the LLM for the configuration space LLaMEA adds its request for a SMAC configuration space to the output format only when it is given no format prompt, and BLADE always passes the problem's. With variant hpo or HPO: true the LLM was never asked for a space, so no solution had one and nothing was tuned. Append the request (in the format LLM.extract_configspace parses) to the problem's format prompt when the method uses HPO. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HiY2guDd9wWLKRWPoa16yy --- CHANGELOG.md | 6 +++ iohblade/methods/llamea.py | 21 ++++++++- tests/unit/test_hpo.py | 93 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0dc249..9d26cc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,12 @@ ### Bug fixes +- **LLaMEA-HPO never tuned anything.** LLaMEA asks for the configuration + space only when it gets no output format prompt, and BLADE always passes + the problem's. So with `variant: hpo` or `HPO: true` the LLM was never + asked for a space, no solution had one, and SMAC never ran. The request + (`HPO_FORMAT_PROMPT`, in the format BLADE parses) is now added to the + problem's format prompt when the method uses HPO. - **Auto-correlation inequalities 1-3: tiny functions no longer score too well.** A function with values around 1e-162 made `f * f` underflow, and auto-correlation 1 scored 1.0 (best known 1.5053). The evaluators now diff --git a/iohblade/methods/llamea.py b/iohblade/methods/llamea.py index 495b778..9519db2 100644 --- a/iohblade/methods/llamea.py +++ b/iohblade/methods/llamea.py @@ -35,6 +35,22 @@ """) +# LLaMEA adds its own request for a configuration space to the output format +# only when it is given no format prompt; BLADE always passes the problem's, +# so the request is added here. The format matches LLM.extract_configspace. +HPO_FORMAT_PROMPT = textwrap.dedent(""" + Also give the hyperparameters of the algorithm as a SMAC3 configuration + space (a Python dictionary): numeric ranges as (lower, upper) tuples and + options as lists. Each hyperparameter must be a keyword argument of + `__init__` with a default value; the tuned values are passed there. + Give the space after the code, in the format: + Space: + ```python + {"name_of_float_parameter": (0.1, 0.9), "name_of_int_parameter": (2, 20), "name_of_option": ["a", "b"]} + ``` + """) + + def _tag_values(problem) -> set[str]: try: tags = problem.get_config().get("tags", []) @@ -344,6 +360,9 @@ def __call__(self, problem: Problem): raise ValueError(reason) configure_bo([self], [problem]) # no-op if already prepared task_prompt = task_prompt.rstrip() + "\n" + BO_PROMPT + format_prompt = problem.format_prompt + if self.uses_hpo: + format_prompt = format_prompt.rstrip() + "\n" + HPO_FORMAT_PROMPT # The plain algorithm through the module-level name, so tests can patch it. algorithm = LLAMEA_Algorithm if self.variant == "llamea" else self._variant_cls @@ -353,7 +372,7 @@ def __call__(self, problem: Problem): role_prompt="You are an excellent Python programmer.", # not needed, it is part of the task prompt. task_prompt=task_prompt, example_prompt=problem.example_prompt, - output_format_prompt=problem.format_prompt, + output_format_prompt=format_prompt, log=None, # We do not use the LLaMEA native logger, we use the experiment logger instead which is attached on problem level. budget=self.budget, max_workers=1, # We do not use parallelization, as it is not supported in combination with the BLADE parrallelization. diff --git a/tests/unit/test_hpo.py b/tests/unit/test_hpo.py index 6de66b1..1d79618 100644 --- a/tests/unit/test_hpo.py +++ b/tests/unit/test_hpo.py @@ -495,3 +495,96 @@ def test_plan_enables_hpo_for_check(tmp_path, automl_module): assert problem.hpo is True assert all(dep in problem.dependencies for dep in HPO_DEPENDENCIES) assert len(plan.notes) == 1 and plan.warnings == [] + + +# --------------------------------------------- LLaMEA asks for the space --- + +_HPO_ANSWER = """# Description: Random search with a step size. +# Code: +```python +class Tunable: + def __init__(self, budget=10, dim=2, step=0.5, pool=4, mode="a"): + self.budget = budget + + def __call__(self, func): + return 0.0, None +``` +Space: +```python +{"step": (0.1, 0.9), "pool": (2, 20), "mode": ["a", "b"]} +``` +""" + + +class _SpaceLLM: + """An iohblade LLM answering with code and a configuration space.""" + + def __new__(cls): + from iohblade.llm import LLM + + class SpaceLLM(LLM): + def __init__(self): + super().__init__("", "space", None) + self.prompts = [] + + def _query(self, session_messages, **kwargs): + self.prompts.append(session_messages[-1]["content"]) + return _HPO_ANSWER + + def get_config(self): + return {} + + return SpaceLLM() + + +class _RecordingTunableProblem(_TunableProblem): + def __init__(self): + super().__init__(name="t") + self.task_prompt = "Write an optimiser." + self.example_prompt = "" + self.format_prompt = "Give the code in a python block." + self.spaces = [] + + def __call__(self, solution, logger=None): + self.spaces.append(getattr(solution, "configspace", None)) + solution.set_scores(1.0, "ok") + return solution + + +@pytest.mark.parametrize("params", [{"variant": "hpo"}, {"HPO": True}]) +def test_llamea_hpo_asks_for_and_passes_on_the_configspace(params): + """LLaMEA adds its space request only without a format prompt; BLADE + passes the problem's, so without HPO_FORMAT_PROMPT the LLM was never + asked for a space and nothing was tuned.""" + from iohblade.methods import LLaMEA + from iohblade.methods.llamea import HPO_FORMAT_PROMPT + + llm = _SpaceLLM() + problem = _RecordingTunableProblem() + LLaMEA(llm, budget=2, n_parents=1, n_offspring=1, **params)(problem) + assert llm.prompts and all(HPO_FORMAT_PROMPT in p for p in llm.prompts) + assert all("Give the code in a python block." in p for p in llm.prompts) + spaces = [s for s in problem.spaces if s is not None] + assert len(spaces) == len(problem.spaces) == 2 + assert set(spaces[0].keys()) == {"step", "pool", "mode"} + + +def test_llamea_without_hpo_does_not_ask_for_a_space(): + from iohblade.methods import LLaMEA + from iohblade.methods.llamea import HPO_FORMAT_PROMPT + + llm = _SpaceLLM() + LLaMEA(llm, budget=1, n_parents=1, n_offspring=1)(_RecordingTunableProblem()) + assert llm.prompts and HPO_FORMAT_PROMPT not in llm.prompts[0] + + +def test_hpo_format_prompt_example_parses(): + import re + + from iohblade.llm import _DEFAULT_CS_PATTERN + from iohblade.methods.llamea import HPO_FORMAT_PROMPT + + m = re.search(_DEFAULT_CS_PATTERN, HPO_FORMAT_PROMPT, re.DOTALL | re.IGNORECASE) + assert m is not None + space = ConfigurationSpace(eval(m.group(1), {"__builtins__": {}})) + assert len(list(space.keys())) == 3