# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Run callback-based QD workflows with deterministic or hosted model proposals. """Compare QD workflows on extractive QA and bounded scheduling problems.""" import argparse from collections import Counter from dataclasses import asdict from itertools import permutations import json import os from pathlib import Path import re import numpy as np from examples.few_shot_qd import _cases, schedule, schedule_metrics, schedule_proposal from examples.qdaif_llm import litellm_completion, openrouter_completion from qdpy.algorithms import (IDEAgent, IdeaAssessment, NeighborhoodElites, QDEvo, TaskArchiveSearch, TaskAssessment, TaskRequest, answer_entropy, idea_yield) from qdpy.containers import Grid ## @brief Adapt the existing chat clients to object responses and count usage by role. class Model: """Count attempted calls. The providers supply token totals on successful replies.""" def __init__(self, complete): self.complete = complete self.calls = Counter() self.tokens = Counter() def ask(self, role, instruction, data): """Send one request and return its parsed object, or None for an invalid reply.""" self.calls[role] += 1 response = self.complete([ {"role": "system", "content": instruction}, {"role": "user", "content": json.dumps(data)}, ]) if not isinstance(response, dict): return None usage = response.get("usage") or {} counts = tuple(usage.get(key) for key in ("prompt_tokens", "completion_tokens")) if all(type(count) is int and count >= 0 for count in counts): self.tokens["responses_with_usage"] += 1 for key in ("prompt_tokens", "completion_tokens"): count = usage.get(key) if type(count) is int and count >= 0: self.tokens[key] += count try: payload = json.loads(response["choices"][0]["message"]["content"]) except (KeyError, IndexError, TypeError, ValueError): return None return payload if isinstance(payload, dict) else None SOURCE = "Mira planted the silver birch. A blue bench stood nearby. The rain fell at noon." QUESTION = "Who planted the silver birch?" SUPPORTED = {"mira planted the silver birch": "direct", "the silver birch was planted by mira": "paraphrastic"} EDIT_TYPES = ("distractor", "reorder", "style") SUPPORT = ("direct", "paraphrastic") def sentences(text): """Split this toy task's period-delimited contexts.""" return [part.strip().casefold() for part in text.split(".") if part.strip()] def rewrite_check(parent, candidate, target): """Verify the preserved answer and the requested edit independently of the editor.""" before, after = sentences(parent), sentences(candidate) mentions = [sentence for sentence in after if "birch" in sentence] if len(mentions) != 1 or (support := SUPPORTED.get(mentions[0])) is None: return None ordered = iter(after) insertion = len(after) > len(before) and all(any(part == old for part in ordered) for old in before) reorder = before != after and Counter(before) == Counter(after) kind = "distractor" if insertion else "reorder" if reorder else "style" if kind != target[0] or before == after: return None original = set(re.findall(r"\w+", SOURCE.casefold())) rewrite = set(re.findall(r"\w+", candidate.casefold())) return (kind, support), len(original & rewrite) / len(original | rewrite) ## @brief Construct and probe a small labeled QA neighborhood. def neighborhood(model, budget, seed): """Keep the gold answer inside construction and send only context and question to the answerer.""" def edit(parent, target, rng): if model: reply = model.ask( "editor", 'Return a JSON object with a "context" field. Rewrite the parent using the requested edit. ' 'Distractor means insert one sentence without changing the others. Reorder means move whole ' 'sentences only. Style means rephrase a sentence. Use period-delimited sentences. Preserve the ' 'unique answer and refer to the birch in only one sentence. For a style edit, use "Mira planted ' 'the silver birch" for direct support, or "The silver birch was planted by Mira" for paraphrastic ' 'support. If the support is already correct, rephrase an unrelated sentence.', dict(parent=parent, question=QUESTION, answer="Mira", edit=target[0], support=target[1]), ) return (reply or {}).get("context") parts = sentences(parent) if target[0] == "distractor": parts.append(f"the clock struck {int(rng.integers(1, 13))}") elif target[0] == "reorder": parts = parts[1:] + parts[:1] else: support = next(text for text, label in SUPPORTED.items() if label == target[1]) position = next(i for i, part in enumerate(parts) if "birch" in part) parts[(position + 1) % len(parts)] = f"the bells rang {int(rng.integers(1, 13))} times" parts[position] = support return ". ".join(part.capitalize() for part in parts) + "." def predict(context): if model: reply = model.ask("answerer", 'Answer from the context. Return a JSON object with an "answer" field.', dict(context=context, question=QUESTION)) answer = (reply or {}).get("answer") if not isinstance(answer, str) or not answer.strip(): raise ValueError("The answerer must return a nonempty answer.") return answer # A deterministic stand-in that only notices evidence in the first sentence. return "Mira" if "birch" in sentences(context)[0] else "unknown" search = NeighborhoodElites(SOURCE, edits=EDIT_TYPES, support=SUPPORT, seed=seed) search.run(edit, rewrite_check, budget=budget, refinement_reserve=budget // 5) def group(text): return text.casefold().strip(" .") rng = np.random.default_rng(seed) independent = {} for _ in range(search.stats.edits): target = ("style", SUPPORT[int(rng.integers(len(SUPPORT)))]) candidate = edit(SOURCE, target, rng) if isinstance(candidate, str) and (measured := rewrite_check(SOURCE, candidate, target)) is not None: independent[candidate] = measured[0] query_count = min(len(search.entries), len(independent)) probe = search.probe(predict, group=group) answers = [predict(candidate) for candidate in list(independent)[:query_count]] return dict(targeted=dict(stats=asdict(search.stats), occupied=len(search.entries), probe=asdict(probe), matched_entropy=answer_entropy(probe.answers[:query_count], group=group), entries=[asdict(entry) for entry in search.entries]), cells=len(search.cells), independent_style=dict(editor_calls=search.stats.edits, occupied=len(set(independent.values())), valid_rewrites=len(independent), answer_calls=query_count, entropy=answer_entropy(answers, group=group))) def bounded_rule(payload): """Parse immutable priority-rule data. Scheduling uses the existing evaluator.""" rule = (payload or {}).get("rule") if (not isinstance(rule, list) or len(rule) != 3 or any(type(value) is not int for value in rule) or rule[0] not in (0, 1) or any(not 0 <= weight <= 7 for weight in rule[1:]) or not any(rule[1:])): return None return tuple(rule) RULE_PROMPT = ( 'Return JSON with a "rule" field [adaptive, duration_weight, due_weight] and a short "reflection" string. ' 'Use 0 or 1 for adaptive and integer weights from 0 to 7, with at least one nonzero weight. ' 'The scheduler chooses the job with the lowest weighted duration and due priority. ' 'The adaptive rule recomputes slack before choosing each next job. ' 'Use any parent feedback to explain a concrete weakness and propose a revision.' ) def rule_signature(rule): """Identify a mechanism by its scheduling mode and which priority term dominates.""" adaptive, duration, due = rule return f"{adaptive}/{(duration > due) - (duration < due)}" ## @brief Compare repaired lineages with the same qualification rule and independent drafting. def ideagent(model, budget, seed): """Measure scheduling rules on fixed training and held-out cases.""" rng = np.random.default_rng(seed) training, held_out = (_cases(rng, count) for count in (8, 12)) def assess(rule): cost, effort = schedule_metrics(rule, training) adaptive, duration, due = rule novelty = .48 + .17 * bool(adaptive or duration and due) + .08 * bool(adaptive and duration and due) return IdeaAssessment(rule_signature(rule), novelty, 1. - cost, 1., 1. - effort, f"training tardiness {cost:.4f}, priority work {effort:.4f}") def similarity(first, second): return float(first == second) def propose(request, rng): parent = request.parent if model: data = dict(stage=request.stage, parent=parent.idea if parent else None, feedback=parent.assessment.feedback if parent else None, active=[entry.assessment.signature for entry in request.active], historical=request.historical, rejected=request.rejected) instruction = RULE_PROMPT + " For a repair or refinement preserve the mode and the dominant priority." return bounded_rule(model.ask("ideator", instruction, data)) if parent is None: if not (request.active or request.historical or request.rejected): return (0, 3, 0) return schedule_proposal((), rng) adaptive, duration, due = parent.idea if not duration or not due: if max(duration, due) == 1: duration *= 2 due *= 2 return adaptive, max(duration, 1), max(due, 1) return adaptive, min(duration + 1, 7), min(due + 1, 7) reports = {} for label, auxiliary in (("lineages", 2), ("independent", 0)): search = IDEAgent(auxiliary_attempts=auxiliary, seed=seed) stats = search.run(propose, assess, similarity, budget=budget) reports[label] = dict(stats=asdict(stats), yield_count=idea_yield( (entry.assessment for entry in search.entries), similarity), retained=[dict(rule=entry.idea, held_out=schedule_metrics(entry.idea, held_out)) for entry in search.entries]) return reports def bounded_task(payload): """Parse a five-job instance with fixed duration and deadline bounds.""" values = tuple((payload or {}).get(key) for key in ("durations", "deadlines")) for vector, limit in zip(values, (9, 45), strict=True): if (not isinstance(vector, list) or len(vector) != 5 or any(type(value) is not int or not 1 <= value <= limit for value in vector)): return None return tuple(map(tuple, values)) ## @brief Generate scheduling benchmarks and certify each one with an exact solver. def tasks(model, budget, seed): """Archive tasks by heuristic regret and disagreement on one common case.""" def propose(request, rng): if model: return bounded_task(model.ask( "task_generator", 'Return a JSON object with "durations" and "deadlines", each a list of five integers. ' 'Durations must be 1 through 9 and deadlines 1 through 45. Invent a single-machine ' 'schedule instance that challenges shortest-job-first or earliest-deadline-first ' 'and allows moderate total tardiness. Use parents and feedback as data.', dict(parent=request.parent.task if request.parent else None, examples=[asdict(row) for row in request.examples], failed=[asdict(row) for row in request.failed[-2:]]), )) if request.parent and rng.random() < .65: values = [list(row) for row in request.parent.task] axis, job = int(rng.integers(2)), int(rng.integers(5)) values[axis][job] = int(np.clip(values[axis][job] + rng.integers(-4, 5), 1, (9, 45)[axis])) return tuple(map(tuple, values)) return tuple(map(int, rng.integers(1, 10, 5))), tuple(map(int, rng.integers(1, 46, 5))) def evaluate(task): durations, deadlines = task def tardiness(order): elapsed = total = 0 for job in order: elapsed += durations[job] total += max(0, elapsed - deadlines[job]) return total jobs = range(len(durations)) exact = min(map(tardiness, permutations(jobs))) first, second = (tardiness(sorted(jobs, key=values.__getitem__)) for values in task) scale = len(jobs) * sum(durations) regret, gap = (min(first, second) - exact) / scale, abs(first - second) / scale solved = exact / scale <= .12 return TaskAssessment(gap, (regret, gap), solved, f"optimum={exact}, shortest={first}, earliest={second}") reports = {} empty = TaskRequest(None, (), ()) for label, conditioned in (("task_archive", True), ("independent", False)): archive = Grid(shape=(12, 12), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2) search = TaskArchiveSearch(archive, seed=seed) stats = search.run(lambda request, rng: propose(request if conditioned else empty, rng), evaluate, budget=budget, review=lambda row, _: row.assessment.quality > 0) reports[label] = dict(stats=asdict(stats), solver_calls=3 * stats.evaluations, exact_orders=120 * stats.evaluations, retained=[asdict(row) for row in search.entries]) return reports ## @brief Compare QDEvo with and without supplying parent measurements to the model. def qdevo(model, budget, seed): """Use disjoint optimization, behaviour embedding, and audit schedules.""" rng = np.random.default_rng(seed) training, panel, held_out = (_cases(rng, count) for count in (8, 6, 12)) def embed(rule): return np.concatenate([np.argsort(schedule(rule, case)[0]) - 3.5 for case in panel]) reports = {} for label, reflect in (("reflection", True), ("independent", False)): def propose(entries, rng): parents = entries if reflect else () if model: return bounded_rule(model.ask("rule_generator", RULE_PROMPT, dict( parents=[dict(rule=row.heuristic, training_objectives=row.objectives) for row in parents], objectives=["minimize normalized tardiness", "minimize normalized priority computation"], ))) return schedule_proposal(parents, rng) search = QDEvo(propose=propose, evaluate=lambda rule: schedule_metrics(rule, training), embed=embed, fitness_weights=(-1, -1), similarity=.85, seed=seed) stats = search.run(budget + 3, initial=((0, 1, 0), (0, 0, 1), (1, 1, 1)), proposal_limit=budget) reports[label] = dict(stats=asdict(stats), niches=len(search.clusters), retained=[ dict(rule=row.heuristic, held_out=schedule_metrics(row.heuristic, held_out)) for cluster in search.clusters for row in cluster ]) return reports def main(argv=None): """Run one example locally or with the opt-in model client.""" methods = dict(neighborhood=neighborhood, ideagent=ideagent, tasks=tasks, qdevo=qdevo) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("method", choices=methods) parser.add_argument("--backend", choices=("offline", "openrouter", "litellm"), default="offline") parser.add_argument("--model") parser.add_argument("--openrouter-key-file", type=Path) parser.add_argument("--budget", type=int, default=12, help="Maximum proposals per method or comparison arm") parser.add_argument("--seed", type=int, default=11) args = parser.parse_args(argv) if args.budget < 1 or args.seed < 0: parser.error("Use a positive budget and a nonnegative seed.") model = None if args.backend != "offline": if not args.model: parser.error("Supply --model for a live backend.") try: key = (args.openrouter_key_file.read_text() if args.openrouter_key_file else os.environ.get("OPENROUTER_API_KEY", "")).strip() except (OSError, UnicodeError): parser.error("The OpenRouter key file could not be read.") if not key: parser.error("Set OPENROUTER_API_KEY or supply --openrouter-key-file.") adapter = openrouter_completion if args.backend == "openrouter" else litellm_completion try: model = Model(adapter(args.model, key)) except RuntimeError as error: parser.exit(1, f"{error}\n") try: result = methods[args.method](model, args.budget, args.seed) except (RuntimeError, ValueError) as error: parser.exit(1, f"{error}\n") if model is not None: result["model_calls"] = dict(model.calls) result["api_tokens"] = dict(model.tokens) print(json.dumps(result, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())