QDpy
Loading...
Searching...
No Matches
llmatic.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Search architectures with typed proposal requests and measured prompt feedback."""
7
8from dataclasses import dataclass
9from typing import Hashable
10
11import numpy as np
12
13from ._population import _attempt_budget
14from .modern import _positive_int
15from .task_search import _measurement, _offer, _validate_grid
16
17__all__ = ["LLMaticRequest", "LLMaticResult", "llmatic"]
18
19
20
21@dataclass(frozen=True, slots=True)
23 """Mutation has one parent, while crossover starts from nearby elites."""
24
25 parents: tuple[Hashable, ...]
26 prompt: str
27 temperature: float
28 crossover: bool
29
30
31
32@dataclass(frozen=True)
34 """Keep callback counts, unique architecture evaluations and prompt feedback."""
35
36 architectures: object
37 prompts: object
38 proposals: int
39 evaluations: int
40 invalid: int
41 duplicates: int
42 mutations: int
43 crossovers: int
44 admissions: int
45 prompt_curiosity: tuple[float, ...]
46 prompt_credits: tuple[int, ...]
47
48
49def _network_offer(archive, candidate):
50 before = archive.nb_added
51 _offer(archive, candidate)
52 return archive.nb_added - before
53
54
55def _neighbors(elites, anchor, count, domain):
56 features = np.asarray([tuple(elite.features) for elite in elites])
57 bounds = np.asarray(domain)
58 with np.errstate(over="ignore", invalid="ignore"):
59 spans = bounds[:, 1] - bounds[:, 0]
60 spans = np.where(np.isfinite(spans) & (spans > 0), spans, np.maximum(1., abs(features).max(axis=0)))
61 scaled = features / spans
62 distance = np.linalg.norm(scaled - scaled[anchor], axis=1)
63 distance[anchor] = np.inf
64 return np.argsort(distance, kind="stable")[:count]
65
66
67
85def llmatic(archive, prompt_archive, *, initial, prompts, generate, evaluate, proposal_budget,
86 evaluation_budget, batch_size=8, crossover_probability=.3, crossover_prompt="Combine the parents.",
87 crossover_neighbors=2, prompt_exploration=.2, initial_temperature=.6, temperature_step=.1, seed=0):
88 """Reward prompts that produce good measured architectures.
89
90 Curiosity is tracked per template. A new archive entry earns one point,
91 rejection costs half a point, and a failed mutation costs one point.
92 Only measured models can earn credit for exceeding the previous batch's
93 best architecture. The prompt grid stores cumulative credits and uses
94 normalized template index and temperature as descriptors. The network
95 grid stores measured validation quality.
96
97 The evaluator is assumed stationary and deterministic for an immutable
98 architecture (including rejected ones). Each payload is measured at most
99 once. The initial architecture supplies a parent without using a
100 measurement call. It can enter the archive if a generator proposes it.
101 """
102 _validate_grid(archive)
103 _validate_grid(prompt_archive)
104 if archive is prompt_archive or any(grid.fitness_weights not in (None, (1.,))
105 for grid in (archive, prompt_archive)):
106 raise ValueError("Supply distinct maximization archives.")
107 if len(prompt_archive.features_domain) != 2 or any(low > 0 or high < 1
108 for low, high in prompt_archive.features_domain):
109 raise ValueError("The prompt archive must cover [0, 1] for both descriptors.")
110 if not (prompt_archive.fitness_domain[0][0] <= 0 <= prompt_archive.fitness_domain[0][1]):
111 raise ValueError("The prompt archive fitness domain must include zero.")
112 if isinstance(prompts, str):
113 raise TypeError("Supply a sequence of prompt strings.")
114 prompts = tuple(prompts)
115 if (not prompts or any(not isinstance(item, str) or not item.strip() for item in prompts)
116 or len(set(prompts)) != len(prompts)):
117 raise ValueError("Supply distinct nonempty prompt strings.")
118 if not isinstance(crossover_prompt, str) or not crossover_prompt.strip():
119 raise ValueError("Supply a nonempty crossover instruction.")
120 if not callable(generate) or not callable(evaluate):
121 raise TypeError("Supply callable architecture generation and evaluation.")
122 if initial is None:
123 raise ValueError("Supply an immutable initial architecture.")
124 hash(initial)
125 if not all(0 <= value <= 1 for value in (crossover_probability, prompt_exploration,
126 initial_temperature, temperature_step)):
127 raise ValueError("Probabilities and temperature controls must be in [0, 1].")
128 proposal_budget, evaluation_budget = _attempt_budget(proposal_budget), _attempt_budget(evaluation_budget)
129 batch_size = _positive_int(batch_size, "batch_size")
130 crossover_neighbors = _positive_int(crossover_neighbors, "crossover_neighbors")
131 for grid in (archive, prompt_archive):
132 grid._set_fitness_weights((1.,))
133 rng = np.random.default_rng(seed)
134 curiosity = np.zeros(len(prompts))
135 credits = [0] * len(prompts)
136 known = set()
137 proposals = evaluations = invalid = duplicates = crossovers = admissions = 0
138 while proposals < proposal_budget and evaluations < evaluation_budget:
139 elites, prompt_elites = tuple(archive), tuple(prompt_archive)
140 previous_best = max((row.fitness.values[0] for row in elites), default=-np.inf)
141 pending = []
142 for _ in range(min(batch_size, proposal_budget - proposals)):
143 if evaluations == evaluation_budget:
144 break
145 anchor = int(rng.integers(len(elites))) if elites else None
146 parent = initial if anchor is None else elites[anchor][0]
147 if len(elites) > 1 and rng.random() < crossover_probability:
148 neighbors = _neighbors(elites, anchor, min(len(elites) - 1, crossover_neighbors), archive.features_domain)
149 parents = (parent, *(elites[i][0] for i in neighbors))
150 request = LLMaticRequest(parents, crossover_prompt, initial_temperature, True)
151 prompt_id = None
152 crossovers += 1
153 else:
154 if prompt_elites and rng.random() >= prompt_exploration:
155 scores = np.asarray([curiosity[row[0]] for row in prompt_elites])
156 row = prompt_elites[rng.choice(np.flatnonzero(scores == scores.max()))]
157 prompt_id, temperature = row[:2]
158 else:
159 prompt_id, temperature = int(rng.integers(len(prompts))), initial_temperature
160 if temperature_step and rng.random() < .5:
161 temperature += rng.uniform(-temperature_step, temperature_step)
162 request = LLMaticRequest((parent,), prompts[prompt_id], float(np.clip(temperature, 0., 1.)), False)
163 proposals += 1
164 payload = generate(request, rng)
165 candidate = None
166 penalty = -1.
167 if payload is None:
168 invalid += 1
169 elif payload in known:
170 duplicates += 1
171 penalty = -.5
172 else:
173 known.add(payload)
174 evaluations += 1
175 measured = evaluate(payload)
176 if measured is None:
177 invalid += 1
178 else:
179 quality, descriptor = measured
180 candidate = _measurement(archive, ((quality,), descriptor), (payload,))
181 pending.append((prompt_id, request.temperature, candidate, penalty))
182 for prompt_id, temperature, candidate, penalty in pending:
183 admitted = _network_offer(archive, candidate) if candidate is not None else 0
184 admissions += admitted
185 if prompt_id is None:
186 continue
187 curiosity[prompt_id] += (1. if admitted else -.5) if candidate is not None else penalty
188 if candidate is not None:
189 improved = candidate[0].fitness.values[0] > previous_best
190 credits[prompt_id] += int(improved)
191 temperature = float(np.clip(temperature + (1 if improved else -1) * temperature_step / 2, 0., 1.))
192 descriptor = (prompt_id / max(1, len(prompts) - 1), temperature)
193 measurement = ((credits[prompt_id],), descriptor)
194 prompt = _measurement(prompt_archive, measurement, (prompt_id, temperature, credits[prompt_id]))
195 _offer(prompt_archive, prompt)
196 return LLMaticResult(archive, prompt_archive, proposals, evaluations, invalid, duplicates,
197 proposals - crossovers, crossovers, admissions, tuple(map(float, curiosity)), tuple(credits))
One typed architecture proposal, with explicit parents and generation controls.
Definition llmatic.py:22
Coupled archives and the distinct costs of generation and measurement.
Definition llmatic.py:33