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