llamea 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llamea/__init__.py +3 -0
- llamea/llamea.py +292 -0
- llamea/loggers.py +66 -0
- llamea/utils.py +116 -0
- llamea-0.1.0.dist-info/LICENSE +21 -0
- llamea-0.1.0.dist-info/METADATA +134 -0
- llamea-0.1.0.dist-info/RECORD +8 -0
- llamea-0.1.0.dist-info/WHEEL +4 -0
llamea/__init__.py
ADDED
llamea/llamea.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""LLaMEA - LLM powered Evolutionary Algorithm for code optimization
|
|
2
|
+
This module integrates OpenAI's language models to generate and evolve
|
|
3
|
+
algorithms to automatically evaluate (for example metaheuristics evaluated on BBOB).
|
|
4
|
+
"""
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from openai import OpenAI
|
|
9
|
+
|
|
10
|
+
from .loggers import ExperimentLogger
|
|
11
|
+
from .utils import NoCodeException
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LLaMEA:
|
|
15
|
+
"""
|
|
16
|
+
A class that represents the Language Model powered Evolutionary Algorithm (LLaMEA).
|
|
17
|
+
This class handles the initialization, evolution, and interaction with a language model
|
|
18
|
+
to generate and refine algorithms.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
f,
|
|
24
|
+
api_key,
|
|
25
|
+
role_prompt="",
|
|
26
|
+
task_prompt="",
|
|
27
|
+
experiment_name="",
|
|
28
|
+
elitism=False,
|
|
29
|
+
feedback_prompt="",
|
|
30
|
+
budget=100,
|
|
31
|
+
model="gpt-4-turbo",
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initializes the LLaMEA instance with provided parameters.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
f (callable): The evaluation function to measure the fitness of algorithms.
|
|
38
|
+
api_key (str): The API key for accessing OpenAI's services.
|
|
39
|
+
role_prompt (str): A prompt that defines the role of the language model in the optimization task.
|
|
40
|
+
task_prompt (str): A prompt describing the task for the language model to generate optimization algorithms.
|
|
41
|
+
experiment_name (str): The name of the experiment for logging purposes.
|
|
42
|
+
elitism (bool): Flag to decide if elitism should be used in the evolutionary process.
|
|
43
|
+
feedback_prompt (str): Prompt to guide the model on how to provide feedback on the generated algorithms.
|
|
44
|
+
budget (int): The number of generations to run the evolutionary algorithm.
|
|
45
|
+
model (str): The model identifier from OpenAI to be used.
|
|
46
|
+
"""
|
|
47
|
+
self.client = OpenAI(api_key=api_key)
|
|
48
|
+
self.api_key = api_key
|
|
49
|
+
self.model = model
|
|
50
|
+
self.f = f # evaluation function, provides a string as feedback, a numerical value (higher is better), and a possible error string.
|
|
51
|
+
self.role_prompt = role_prompt
|
|
52
|
+
if role_prompt == "":
|
|
53
|
+
self.role_prompt = "You are a highly skilled computer scientist in the field of natural computing. Your task is to design novel metaheuristic algorithms to solve black box optimization problems. Do not use hyped nature-inspired algorithms such as Harmony Search, Grey Wolf, Firefly, Whale optimizer etc. since these are generally not well performing."
|
|
54
|
+
if task_prompt == "":
|
|
55
|
+
self.task_prompt = """
|
|
56
|
+
The optimization algorithm should handle a wide range of tasks, which is evaluated on the BBOB test suite of 24 noiseless functions. Your task is to write the optimization algorithm in Python code. The code should contain an `__init__(self, budget)` function and the function `def __call__(self, func)`, which should optimize the black box function `func` using `self.budget` function evaluations.
|
|
57
|
+
The func() can only be called as many times as the budget allows, not more. Each of the optimization functions has a search space between -5.0 (lower bound) and 5.0 (upper bound). The dimensionality is set to 5.
|
|
58
|
+
An example of such code (a simple random search), is as follows:
|
|
59
|
+
```
|
|
60
|
+
class RandomSearch:
|
|
61
|
+
def __init__(self, budget=10000):
|
|
62
|
+
self.budget = 10000
|
|
63
|
+
self.dim = len(func.bounds.lb)
|
|
64
|
+
|
|
65
|
+
def __call__(self, func):
|
|
66
|
+
self.f_opt = np.Inf
|
|
67
|
+
self.x_opt = None
|
|
68
|
+
for i in range(self.budget):
|
|
69
|
+
x = np.random.uniform(func.bounds.lb, func.bounds.ub)
|
|
70
|
+
|
|
71
|
+
f = func(x)
|
|
72
|
+
if f < self.f_opt:
|
|
73
|
+
self.f_opt = f
|
|
74
|
+
self.x_opt = x
|
|
75
|
+
|
|
76
|
+
return self.f_opt, self.x_opt
|
|
77
|
+
```
|
|
78
|
+
Give an excellent and novel heuristic algorithm to solve this task and also give it a name. Give the response in the format:
|
|
79
|
+
# Name: <classname>
|
|
80
|
+
# Code: <code>
|
|
81
|
+
"""
|
|
82
|
+
else:
|
|
83
|
+
self.task_prompt = task_prompt
|
|
84
|
+
self.feedback_prompt = feedback_prompt
|
|
85
|
+
if feedback_prompt == "":
|
|
86
|
+
self.feedback_prompt = (
|
|
87
|
+
f"Either refine or redesign to improve the solution. Give the response in the format:\n"
|
|
88
|
+
f"# Name: <classname>\n"
|
|
89
|
+
f"# Code: <code>"
|
|
90
|
+
)
|
|
91
|
+
self.budget = budget
|
|
92
|
+
self.elitism = elitism
|
|
93
|
+
self.generation = 0
|
|
94
|
+
self.best_solution = None
|
|
95
|
+
self.best_fitness = -np.Inf
|
|
96
|
+
self.best_error = ""
|
|
97
|
+
self.last_error = ""
|
|
98
|
+
self.last_solution = ""
|
|
99
|
+
self.history = ""
|
|
100
|
+
self.logger = ExperimentLogger(f"{self.model}-ES {experiment_name}")
|
|
101
|
+
|
|
102
|
+
def initialize(self):
|
|
103
|
+
"""
|
|
104
|
+
Initializes the evolutionary process by generating the first parent program.
|
|
105
|
+
"""
|
|
106
|
+
self.last_error = ""
|
|
107
|
+
session_messages = [
|
|
108
|
+
{"role": "system", "content": self.role_prompt},
|
|
109
|
+
{"role": "user", "content": self.task_prompt},
|
|
110
|
+
]
|
|
111
|
+
self.logger.log_conversation(self.task_prompt)
|
|
112
|
+
try:
|
|
113
|
+
solution, name, algorithm_name_long = self.llm(session_messages)
|
|
114
|
+
self.last_solution = solution
|
|
115
|
+
(
|
|
116
|
+
self.last_feedback,
|
|
117
|
+
self.last_fitness,
|
|
118
|
+
self.last_error,
|
|
119
|
+
) = self.evaluate_fitness(solution, name, algorithm_name_long)
|
|
120
|
+
except NoCodeException:
|
|
121
|
+
self.last_fitness = -np.Inf
|
|
122
|
+
self.last_feedback = "No code was extracted."
|
|
123
|
+
except Exception as e:
|
|
124
|
+
self.last_fitness = -np.Inf
|
|
125
|
+
self.last_error = repr(e)
|
|
126
|
+
self.last_feedback = f"An exception occured: {self.last_error}."
|
|
127
|
+
# print(self.last_error)
|
|
128
|
+
self.generation += 1
|
|
129
|
+
|
|
130
|
+
self.best_solution = self.last_solution
|
|
131
|
+
self.best_fitness = self.last_fitness
|
|
132
|
+
self.best_error = self.last_error
|
|
133
|
+
self.best_feedback = self.last_feedback
|
|
134
|
+
|
|
135
|
+
def llm(self, session_messages):
|
|
136
|
+
"""
|
|
137
|
+
Interacts with a language model to generate or mutate solutions based on the provided session messages.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
session_messages (list): A list of dictionaries with keys 'role' and 'content' to simulate a conversation with the language model.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
tuple: A tuple containing the new algorithm code, its class name, and its full descriptive name.
|
|
144
|
+
|
|
145
|
+
Raises:
|
|
146
|
+
NoCodeException: If the language model fails to return any code.
|
|
147
|
+
Exception: Captures and logs any other exceptions that occur during the interaction.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
response = self.client.chat.completions.create(
|
|
151
|
+
model=self.model, messages=session_messages, temperature=0.8
|
|
152
|
+
)
|
|
153
|
+
message = response.choices[0].message.content
|
|
154
|
+
self.logger.log_conversation(message)
|
|
155
|
+
new_algorithm = self.extract_algorithm_code(message)
|
|
156
|
+
|
|
157
|
+
algorithm_name = re.findall("class\\s*(\\w*)\\:", new_algorithm, re.IGNORECASE)[
|
|
158
|
+
0
|
|
159
|
+
]
|
|
160
|
+
algorithm_name_long = self.extract_algorithm_name(message)
|
|
161
|
+
if algorithm_name_long == "":
|
|
162
|
+
algorithm_name_long = algorithm_name
|
|
163
|
+
# todo rename algorithm
|
|
164
|
+
self.last_solution = message
|
|
165
|
+
# extract algorithm name and algorithm
|
|
166
|
+
return new_algorithm, algorithm_name, algorithm_name_long
|
|
167
|
+
|
|
168
|
+
def evaluate_fitness(self, solution, name, long_name):
|
|
169
|
+
"""
|
|
170
|
+
Evaluates the fitness of the provided solution by invoking the evaluation function `f`.
|
|
171
|
+
This method handles error reporting and logs the feedback, fitness, and errors encountered.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
solution (str): The solution code to evaluate.
|
|
175
|
+
name (str): The name of the algorithm.
|
|
176
|
+
long_name (str): The full descriptive name of the algorithm.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
tuple: A tuple containing feedback (string), fitness (float), and error message (string).
|
|
180
|
+
"""
|
|
181
|
+
# Implement fitness evaluation and error handling logic.
|
|
182
|
+
self.logger.log_code(self.generation, name, solution)
|
|
183
|
+
feedback, fitness, error = self.f(solution, name, long_name)
|
|
184
|
+
self.history += f"\nYou already tried {long_name}, with score: {fitness}"
|
|
185
|
+
if error != "":
|
|
186
|
+
self.history += f" with error: {error}"
|
|
187
|
+
return feedback, fitness, error
|
|
188
|
+
|
|
189
|
+
def construct_prompt(self):
|
|
190
|
+
"""
|
|
191
|
+
Constructs a new session prompt for the language model based on the best or the latest solution,
|
|
192
|
+
depending on whether elitism is enabled.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
list: A list of dictionaries simulating a conversation with the language model for the next evolutionary step.
|
|
196
|
+
"""
|
|
197
|
+
if self.elitism:
|
|
198
|
+
solution = self.best_solution
|
|
199
|
+
feedback = self.best_feedback
|
|
200
|
+
else:
|
|
201
|
+
solution = self.last_solution
|
|
202
|
+
feedback = self.last_feedback
|
|
203
|
+
|
|
204
|
+
session_messages = [
|
|
205
|
+
{"role": "system", "content": self.role_prompt},
|
|
206
|
+
{"role": "user", "content": self.task_prompt},
|
|
207
|
+
{"role": "user", "content": self.history},
|
|
208
|
+
{"role": "assistant", "content": solution},
|
|
209
|
+
{"role": "user", "content": feedback},
|
|
210
|
+
{"role": "user", "content": self.feedback_prompt},
|
|
211
|
+
]
|
|
212
|
+
# Logic to construct the new prompt based on current evolutionary state.
|
|
213
|
+
return session_messages
|
|
214
|
+
|
|
215
|
+
def update_best(self):
|
|
216
|
+
"""
|
|
217
|
+
Updates the record of the best solution found so far if the latest solution has a higher fitness.
|
|
218
|
+
This method checks and compares the fitness of the latest solution against the best-known fitness.
|
|
219
|
+
"""
|
|
220
|
+
if self.best_fitness < self.last_fitness:
|
|
221
|
+
self.best_solution = self.last_solution
|
|
222
|
+
self.best_fitness = self.last_fitness
|
|
223
|
+
self.best_error = self.last_error
|
|
224
|
+
|
|
225
|
+
def extract_algorithm_code(self, message):
|
|
226
|
+
"""
|
|
227
|
+
Extracts algorithm code from a given message string using regular expressions.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
message (str): The message string containing the algorithm code.
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
str: Extracted algorithm code.
|
|
234
|
+
|
|
235
|
+
Raises:
|
|
236
|
+
NoCodeException: If no code block is found within the message.
|
|
237
|
+
"""
|
|
238
|
+
pattern = r"```(?:python)?\n(.*?)\n```"
|
|
239
|
+
match = re.search(pattern, message, re.DOTALL | re.IGNORECASE)
|
|
240
|
+
if match:
|
|
241
|
+
return match.group(1)
|
|
242
|
+
else:
|
|
243
|
+
print(message, "contained no ``` code block")
|
|
244
|
+
raise NoCodeException
|
|
245
|
+
|
|
246
|
+
def extract_algorithm_name(self, message):
|
|
247
|
+
"""
|
|
248
|
+
Extracts algorithm name from a given message string using regular expressions.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
message (str): The message string containing the algorithm name and code.
|
|
252
|
+
|
|
253
|
+
Returns:
|
|
254
|
+
str: Extracted algorithm name or empty string.
|
|
255
|
+
"""
|
|
256
|
+
pattern = r"`#\s*Name:\s*(\\w*)`"
|
|
257
|
+
match = re.search(pattern, message, re.IGNORECASE)
|
|
258
|
+
if match:
|
|
259
|
+
return match.group(1)
|
|
260
|
+
else:
|
|
261
|
+
return ""
|
|
262
|
+
|
|
263
|
+
def run(self):
|
|
264
|
+
"""
|
|
265
|
+
Main loop to evolve the solutions until the evolutionary budget is exhausted.
|
|
266
|
+
The method iteratively refines solutions through interaction with the language model,
|
|
267
|
+
evaluates their fitness, and updates the best solution found.
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
tuple: A tuple containing the best solution and its fitness at the end of the evolutionary process.
|
|
271
|
+
"""
|
|
272
|
+
self.initialize()
|
|
273
|
+
while self.generation < self.budget:
|
|
274
|
+
new_prompt = self.construct_prompt()
|
|
275
|
+
try:
|
|
276
|
+
self.last_solution, name, algorithm_name_long = self.llm(new_prompt)
|
|
277
|
+
(
|
|
278
|
+
self.last_feedback,
|
|
279
|
+
self.last_fitness,
|
|
280
|
+
self.last_error,
|
|
281
|
+
) = self.evaluate_fitness(self.last_solution, name, algorithm_name_long)
|
|
282
|
+
except NoCodeException:
|
|
283
|
+
print("No code was found. Continue the loop to try again.")
|
|
284
|
+
self.last_error = (
|
|
285
|
+
"The code should be encapsulated with ``` in your response."
|
|
286
|
+
)
|
|
287
|
+
self.generation = self.generation + 1
|
|
288
|
+
continue
|
|
289
|
+
self.update_best()
|
|
290
|
+
self.generation = self.generation + 1
|
|
291
|
+
|
|
292
|
+
return self.best_solution, self.best_fitness
|
llamea/loggers.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ExperimentLogger:
|
|
8
|
+
def __init__(self, name=""):
|
|
9
|
+
"""
|
|
10
|
+
Initializes an instance of the ExperimentLogger.
|
|
11
|
+
Sets up a new logging directory named with the current date and time.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
name (str): The name of the experiment.
|
|
15
|
+
"""
|
|
16
|
+
self.dirname = self.create_log_dir(name)
|
|
17
|
+
|
|
18
|
+
def create_log_dir(self, name=""):
|
|
19
|
+
"""
|
|
20
|
+
Creates a new directory for logging experiments based on the current date and time.
|
|
21
|
+
Also creates subdirectories for IOH experimenter data and code files.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
str: The name of the created directory.
|
|
25
|
+
"""
|
|
26
|
+
today = datetime.today().strftime("%m-%d_%H%M%S")
|
|
27
|
+
dirname = f"exp-{today}-{name}"
|
|
28
|
+
os.mkdir(dirname)
|
|
29
|
+
os.mkdir(f"{dirname}/ioh")
|
|
30
|
+
os.mkdir(f"{dirname}/code")
|
|
31
|
+
return dirname
|
|
32
|
+
|
|
33
|
+
def log_conversation(self, content):
|
|
34
|
+
"""
|
|
35
|
+
Logs the given conversation content into a conversation log file.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
content (str): The conversation content to be logged.
|
|
39
|
+
"""
|
|
40
|
+
with open(f"{self.dirname}/conversationlog.txt", "a") as file:
|
|
41
|
+
file.write(f"\n\n-- {datetime.now()}\n")
|
|
42
|
+
file.write(content)
|
|
43
|
+
|
|
44
|
+
def log_code(self, attempt, algorithm_name, code):
|
|
45
|
+
"""
|
|
46
|
+
Logs the provided code into a file, uniquely named based on the attempt number and algorithm name.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
attempt (int): The attempt number of the code execution.
|
|
50
|
+
algorithm_name (str): The name of the algorithm used.
|
|
51
|
+
code (str): The source code to be logged.
|
|
52
|
+
"""
|
|
53
|
+
with open(
|
|
54
|
+
f"{self.dirname}/code/try-{attempt}-{algorithm_name}.py", "w"
|
|
55
|
+
) as file:
|
|
56
|
+
file.write(code)
|
|
57
|
+
|
|
58
|
+
def log_aucs(self, attempt, aucs):
|
|
59
|
+
"""
|
|
60
|
+
Logs the given AOCCs (Area Over the Convergence Curve, named here auc) into a file, named based on the attempt number.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
attempt (int): The attempt number corresponding to the AOCCs.
|
|
64
|
+
aucs (array_like): An array of AUC scores to be saved.
|
|
65
|
+
"""
|
|
66
|
+
np.savetxt(f"{self.dirname}/try-{attempt}-aucs.txt", aucs)
|
llamea/utils.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from ioh import LogInfo, logger
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class OverBudgetException(Exception):
|
|
7
|
+
"""The algorithm tried to do more evaluations than allowed."""
|
|
8
|
+
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NoCodeException(Exception):
|
|
13
|
+
"""Could not extract generated code."""
|
|
14
|
+
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def correct_aoc(ioh_function, logger, budget):
|
|
19
|
+
"""Correct aoc values in case a run stopped before the budget was exhausted
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
ioh_function: The function in its final state (before resetting!)
|
|
23
|
+
logger: The logger in its final state, so we can ensure the settings for aoc calculation match
|
|
24
|
+
budget: The intended maximum budget
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
float: The normalized aoc of the run, corrected for stopped runs
|
|
28
|
+
"""
|
|
29
|
+
fraction = (
|
|
30
|
+
logger.transform(
|
|
31
|
+
np.clip(
|
|
32
|
+
ioh_function.state.current_best_internal.y, logger.lower, logger.upper
|
|
33
|
+
)
|
|
34
|
+
)
|
|
35
|
+
- logger.transform(logger.lower)
|
|
36
|
+
) / (logger.transform(logger.upper) - logger.transform(logger.lower))
|
|
37
|
+
aoc = (
|
|
38
|
+
logger.aoc
|
|
39
|
+
+ np.clip(budget - ioh_function.state.evaluations, 0, budget) * fraction
|
|
40
|
+
) / budget
|
|
41
|
+
|
|
42
|
+
return 1 - aoc
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class aoc_logger(logger.AbstractLogger):
|
|
46
|
+
"""aoc_logger class implementing the logging module for ioh."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
budget,
|
|
51
|
+
lower=1e-8,
|
|
52
|
+
upper=1e8,
|
|
53
|
+
scale_log=True,
|
|
54
|
+
*args,
|
|
55
|
+
**kwargs,
|
|
56
|
+
):
|
|
57
|
+
"""Initialize the logger.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
budget (int): Evaluation budget for calculating aoc.
|
|
61
|
+
"""
|
|
62
|
+
super().__init__(*args, **kwargs)
|
|
63
|
+
self.aoc = 0
|
|
64
|
+
self.lower = lower
|
|
65
|
+
self.upper = upper
|
|
66
|
+
self.budget = budget
|
|
67
|
+
self.transform = lambda x: np.log10(x) if scale_log else (lambda x: x)
|
|
68
|
+
|
|
69
|
+
def __call__(self, log_info: LogInfo):
|
|
70
|
+
"""Subscalculate the aoc.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
log_info (ioh.LogInfo): info about current values.
|
|
74
|
+
"""
|
|
75
|
+
if log_info.evaluations > self.budget:
|
|
76
|
+
raise OverBudgetException
|
|
77
|
+
if log_info.evaluations == self.budget:
|
|
78
|
+
return
|
|
79
|
+
y_value = np.clip(log_info.raw_y_best, self.lower, self.upper)
|
|
80
|
+
self.aoc += (self.transform(y_value) - self.transform(self.lower)) / (
|
|
81
|
+
self.transform(self.upper) - self.transform(self.lower)
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def reset(self, func):
|
|
85
|
+
super().reset()
|
|
86
|
+
self.aoc = 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class budget_logger(logger.AbstractLogger):
|
|
90
|
+
"""budget_logger class implementing the logging module for ioh."""
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
budget,
|
|
95
|
+
*args,
|
|
96
|
+
**kwargs,
|
|
97
|
+
):
|
|
98
|
+
"""Initialize the logger.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
budget (int): Evaluation budget for calculating aoc.
|
|
102
|
+
"""
|
|
103
|
+
super().__init__(*args, **kwargs)
|
|
104
|
+
self.budget = budget
|
|
105
|
+
|
|
106
|
+
def __call__(self, log_info: LogInfo):
|
|
107
|
+
"""Subscalculate the aoc.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
log_info (ioh.LogInfo): info about current values.
|
|
111
|
+
"""
|
|
112
|
+
if log_info.evaluations > self.budget:
|
|
113
|
+
raise OverBudgetException
|
|
114
|
+
|
|
115
|
+
def reset(self):
|
|
116
|
+
super().reset()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Niki van Stein
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: llamea
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary:
|
|
5
|
+
Home-page: https://github.com/nikivanstein/LLaMEA
|
|
6
|
+
License: MIT
|
|
7
|
+
Author: Niki van Stein
|
|
8
|
+
Author-email: n.van.stein@liacs.leidenuniv.nl
|
|
9
|
+
Requires-Python: >=3.8,<4.0
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Requires-Dist: ioh (==0.3.14)
|
|
18
|
+
Requires-Dist: jellyfish (>=1.0.3,<2.0.0)
|
|
19
|
+
Requires-Dist: levenshtein (>=0.25.1,<0.26.0)
|
|
20
|
+
Requires-Dist: numpy (==1.24.4)
|
|
21
|
+
Requires-Dist: openai (>=1.25.2,<2.0.0)
|
|
22
|
+
Requires-Dist: pandas (==2.0.3)
|
|
23
|
+
Requires-Dist: pypop7 (>=0.0.79,<0.0.80)
|
|
24
|
+
Requires-Dist: scikit-learn (==1.3.0)
|
|
25
|
+
Requires-Dist: seaborn (>=0.13.2,<0.14.0)
|
|
26
|
+
Requires-Dist: tqdm (>=4.66.4,<5.0.0)
|
|
27
|
+
Requires-Dist: zss (>=1.2.0,<2.0.0)
|
|
28
|
+
Project-URL: Repository, https://github.com/nikivanstein/LLaMEA
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
<p align="center">
|
|
32
|
+
<img src="logo.png" alt="LLaMEA Logo" width="200"/>
|
|
33
|
+
</p>
|
|
34
|
+
|
|
35
|
+
<h1 align="center">LLaMEA: Large Language Model Evolutionary Algorithm</h1>
|
|
36
|
+
|
|
37
|
+
<p align="center">
|
|
38
|
+
<a href="https://pypi.org/project/llamea/">
|
|
39
|
+
<img src="https://badge.fury.io/py/llamea.svg" alt="PyPI version" height="20">
|
|
40
|
+
</a>
|
|
41
|
+
</p>
|
|
42
|
+
|
|
43
|
+
## Introduction
|
|
44
|
+
|
|
45
|
+
LLaMEA (Large Language Model Evolutionary Algorithm) is an innovative framework that leverages the power of large language models (LLMs) such as GPT-4 for the automated generation and refinement of metaheuristic optimization algorithms. The framework utilizes a novel approach to evolve and optimize algorithms iteratively based on performance metrics and runtime evaluations without requiring extensive prior algorithmic knowledge. This makes LLaMEA an ideal tool for both research and practical applications in fields where optimization is crucial.
|
|
46
|
+
|
|
47
|
+
## Features
|
|
48
|
+
|
|
49
|
+
- **Automated Algorithm Generation**: Automatically generates and refines algorithms using GPT models.
|
|
50
|
+
- **Performance Evaluation**: Integrates with the IOHexperimenter for real-time performance feedback, guiding the evolutionary process to generate metaheuristic optimization algorithms.
|
|
51
|
+
- **Customizable Evolution Strategies**: Supports configuration of evolutionary strategies to explore algorithmic design spaces effectively.
|
|
52
|
+
- **Extensible and Modular**: Designed to be flexible, allowing users to integrate other models and evaluation tools.
|
|
53
|
+
|
|
54
|
+
## Getting Started
|
|
55
|
+
|
|
56
|
+
### Prerequisites
|
|
57
|
+
|
|
58
|
+
- Python 3.8 or later
|
|
59
|
+
- OpenAI API key for accessing GPT models
|
|
60
|
+
|
|
61
|
+
### Installation
|
|
62
|
+
|
|
63
|
+
1. Clone the repository:
|
|
64
|
+
```bash
|
|
65
|
+
git clone https://github.com/yourgithub/llamea.git
|
|
66
|
+
```
|
|
67
|
+
2. Install the required Python packages:
|
|
68
|
+
```bash
|
|
69
|
+
pip install -r requirements.txt
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Setting Up Your Environment
|
|
73
|
+
|
|
74
|
+
1. Set up an OpenAI API key:
|
|
75
|
+
- Obtain an API key from [OpenAI](https://openai.com/).
|
|
76
|
+
- Set the API key in your environment variables:
|
|
77
|
+
```bash
|
|
78
|
+
export OPENAI_API_KEY='your_api_key_here'
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
2. Running an Experiment
|
|
82
|
+
|
|
83
|
+
To run an optimization experiment using LLaMEA:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from llamea import LLaMEA
|
|
87
|
+
|
|
88
|
+
# Define your evaluation function
|
|
89
|
+
def your_evaluation_function(solution):
|
|
90
|
+
# Implementation of your function
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
# Initialize LLaMEA with your API key and other parameters
|
|
94
|
+
optimizer = LLaMEA(f=your_evaluation_function, api_key="your_api_key_here")
|
|
95
|
+
|
|
96
|
+
# Run the optimizer
|
|
97
|
+
best_solution, best_fitness = optimizer.run()
|
|
98
|
+
print(f"Best Solution: {best_solution}, Fitness: {best_fitness}")
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Contributing
|
|
102
|
+
|
|
103
|
+
Contributions to LLaMEA are welcome! Here are a few ways you can help:
|
|
104
|
+
|
|
105
|
+
- **Report Bugs**: Use [GitHub Issues](https://github.com/yourgithub/llamea/issues) to report bugs.
|
|
106
|
+
- **Feature Requests**: Suggest new features or improvements.
|
|
107
|
+
- **Pull Requests**: Submit PRs for bug fixes or feature additions.
|
|
108
|
+
|
|
109
|
+
Please refer to CONTRIBUTING.md for more details on contributing guidelines.
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
Distributed under the MIT License. See `LICENSE` for more information.
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
## Citation
|
|
117
|
+
|
|
118
|
+
If you use LLaMEA in your research, please consider citing the associated paper:
|
|
119
|
+
|
|
120
|
+
```bibtex
|
|
121
|
+
@misc{vanstein2024llamea,
|
|
122
|
+
title={LLaMEA: A Large Language Model Evolutionary Algorithm for Automatically Generating Metaheuristics},
|
|
123
|
+
author={Niki van Stein and Thomas Bäck},
|
|
124
|
+
year={2024},
|
|
125
|
+
eprint={2405.20132},
|
|
126
|
+
archivePrefix={arXiv},
|
|
127
|
+
primaryClass={cs.NE}
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
For more details, please refer to the documentation and tutorials available in the repository.
|
|
134
|
+
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
llamea/__init__.py,sha256=_h-zwA6CqAWU3dPAANHsmOam_tGKoN5C9rnjUMhBItI,146
|
|
2
|
+
llamea/llamea.py,sha256=s5bTkTxabw9KXmNCKnmFibtGc7qiuUvDnjLL1rPfxhk,12330
|
|
3
|
+
llamea/loggers.py,sha256=U6WjeGMhLieBWvZ5ikNo1IvXIYRtnOI3tqusufSpkiA,2239
|
|
4
|
+
llamea/utils.py,sha256=o0iVoAjr9QB1o5rD4ECZOqE7xX4yr4vE47upLBwzKb8,3089
|
|
5
|
+
llamea-0.1.0.dist-info/LICENSE,sha256=-fqLXExOTdhiU8Gyt39Nl1aZWCAI-Eeil_85GO0lP18,1071
|
|
6
|
+
llamea-0.1.0.dist-info/METADATA,sha256=bigsZx-p9zmirXFSgU_blQ5r72p1KCStOe4kF985URY,4644
|
|
7
|
+
llamea-0.1.0.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
|
|
8
|
+
llamea-0.1.0.dist-info/RECORD,,
|