33 """Run the fixed-archive, callback-based variant of QD-LLM.
35 :param archive: Empty parentless best-only Grid or CVTGrid.
36 :param initial_embedding: Finite 2D array with one vector per soft token.
37 :param sigma: Gaussian exploration scale per embedding coordinate.
38 :param probe_step: Length of updates along random unit probe directions.
39 :param probe_directions: Maximum number of paired probes per targeted update.
40 :param targeted_probability: Probability of selecting targeted variation.
41 :param crossover_probability: Probability of interpolating two prompts.
42 :param seed: Private seed for embedding search and decoder calls.
45 def __init__(self, archive, initial_embedding, *, sigma=.1, probe_step=.1, probe_directions=4,
46 targeted_probability=.35, crossover_probability=.3, seed=0):
47 _validate_grid(archive)
48 initial = np.array(initial_embedding, dtype=np.float64, order=
"C", copy=
True)
49 if initial.ndim != 2
or not initial.size
or not np.isfinite(initial).all():
50 raise ValueError(
"Supply a finite nonempty token-by-embedding array.")
51 if (
not np.isfinite(sigma)
or sigma <= 0.
or not np.isfinite(probe_step)
or probe_step <= 0.
52 or min(targeted_probability, crossover_probability) < 0.
53 or not 0. <= targeted_probability + crossover_probability <= 1.):
54 raise ValueError(
"Use positive finite steps and variation probabilities totalling at most one.")
55 lower, upper = np.asarray(archive.features_domain, dtype=float).T
57 if not np.all(np.isfinite(spans) & (spans > 0.)):
58 raise ValueError(
"Soft-prompt search needs finite increasing descriptor domains.")
59 self.
_directions = _positive_int(probe_directions,
"probe_directions")
60 if archive.fitness_weights
is None:
61 archive._set_fitness_weights((1.,))
67 search_seed, decode_seed = np.random.SeedSequence(seed).spawn(2)
68 self.
_rng, self.
_decode = np.random.default_rng(search_seed), np.random.default_rng(decode_seed)
73 """Return cumulative decoding and archive work."""
78 """Return a fresh array for an elite from this search. Its text is elite[0]."""
79 return np.frombuffer(elite[1], dtype=np.float64).reshape(self.
_initial.shape).copy()
82 return int(self.
_decode.integers(2**63, dtype=np.uint64))
84 def _evaluate(self, prompt, generate, evaluate, *, seed, probe=False):
85 prompt = np.ascontiguousarray(prompt, dtype=np.float64)
86 if not np.isfinite(prompt).all():
87 raise ValueError(
"Variation produced a nonfinite prompt. Reduce the step sizes.")
90 text = generate(prompt.copy(), seed)
93 if not isinstance(text, str):
94 raise TypeError(
"The generator must return text or None.")
96 result = evaluate(text)
99 fitness, descriptor = result
100 genome = (text, prompt.tobytes())
101 measurement = _measurement(self.
archive, ((fitness,), descriptor), genome)
102 previous = self.
archive.nb_added
103 _offer(self.
archive, measurement)
105 candidate, cell = measurement
106 return np.asarray(candidate.features.values)
if cell
is not None else None
109 choices = tuple(cell
for cell, occupants
in self.
archive.solutions.items()
if not occupants)
111 choices = tuple(self.
archive.solutions)
112 cell = choices[int(self.
_rng.integers(len(choices)))]
113 if isinstance(self.
archive, CVTGrid):
114 return self.
archive.cluster_centers[cell[0]]
117 def _guided(self, parent, directions, generate, evaluate):
119 gradient = np.zeros_like(parent)
120 for _
in range(directions):
121 direction = self.
_rng.normal(size=parent.shape)
122 direction /= np.linalg.norm(direction)
124 plus = self.
_evaluate(parent + self.
_probe_step * direction, generate, evaluate, seed=seed, probe=
True)
125 minus = self.
_evaluate(parent - self.
_probe_step * direction, generate, evaluate, seed=seed, probe=
True)
126 if plus
is not None and minus
is not None:
127 toward = (target - minus) / self.
_span
128 away = (target - plus) / self.
_span
129 gradient += (np.dot(toward, toward) - np.dot(away, away)) * direction
130 length = np.linalg.norm(gradient)
132 return parent + self.
_sigma * np.sqrt(parent.size) * gradient / length
135 def _gaussian(self, parent):
136 return parent + self.
_rng.normal(scale=self.
_sigma, size=parent.shape)
138 def _offspring(self, mode, remaining, generate, evaluate):
145 if mode ==
"targeted":
146 choice = self.
_rng.random()
148 other_slot = int(self.
_rng.integers(len(self.
archive) - 1))
150 weight = self.
_rng.uniform(.3, .7)
151 return weight * parent + (1 - weight) * other
152 directions = min(self.
_directions, (remaining - 1) // 2)
154 return self.
_guided(parent, directions, generate, evaluate)
158 def run(self, generate, evaluate, *, budget, mode="targeted"):
159 """Fill the archive using frozen decoding and independent output assessment.
161 generate(embedding, seed) returns text or None. evaluate(text)
162 returns (scalar fitness, descriptor vector) or None. Paired
163 probes receive the same seed and can enter the archive.
164 Choose "gaussian" for a mutation control or "fixed" to decode
165 repeatedly from the initial embedding.
167 if not callable(generate)
or not callable(evaluate):
168 raise TypeError(
"Supply generation and evaluation callbacks.")
169 if mode
not in (
"targeted",
"gaussian",
"fixed"):
170 raise ValueError(
"mode must be targeted, gaussian or fixed.")
171 stop = self.
_generations + _positive_int(budget,
"budget")