Parent selection, surrogate search, and diverse skills ====================================================== These examples compare which elites to breed, which designs to evaluate, and how to reuse or learn a repertoire. Every suite runs on CPU. Install PyTorch for DSAGE's default surrogate and use ``qdpy[rl]`` for DOMiNO. The remaining examples use the base package. .. _nss-me: NSS-ME ------ NSS-ME selects parents from fronts in descriptor space. For each combination of coordinate signs, look for a strictly fitter elite that Pareto-dominates the candidate in that signed direction. An elite enters the first front when at least one direction is empty. Remove that front and repeat to rank the remaining archive. .. code-block:: python from qdpy.algorithms import NSSMAPElites from qdpy.containers import Grid grid = Grid(shape=(6, 6), fitness_domain=((0., 1.),), features_domain=((0., 1.),) * 2) search = NSSMAPElites(grid, budget=96, dimension=3, batch_size=8, sigma=.12, optimisation_task="max", seed=11) def evaluate(genome): return (1. - (genome[2] - .65) ** 2,), tuple(genome[:2]) search.optimise(evaluate) print(grid.filled_bins, grid.best.fitness.values) Use ``ask_batch()`` and ``tell_batch()`` for an external evaluator. Both Grid and CVTGrid work with one fitness objective and one elite per cell. Exact sorting has up to 2 to the power of the descriptor dimension directions. Start with small descriptor vectors and compare cost against uniform or Monte Carlo Elites selection. See `Wang et al. (IJCAI 2023)`_. .. _dsage: DSAGE ----- DSAGE alternates between actual simulator calls and a search that uses a model to predict fitness and descriptors. It picks at most one elite from each selected region of a coarser predicted grid. Measure those genomes before admitting them to the reported archive. Small batches let the model update more often for a fixed simulation budget. .. code-block:: python from qdpy.algorithms import DSAGE, DSAGESurrogate from qdpy.containers import Grid from examples.selection_and_skills import maze grid = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),)) search = DSAGE(grid, dimension=25, initial_samples=12, surrogate_evaluations=48, simulation_batch_size=4, surrogate=DSAGESurrogate(width=32, epochs=20, seed=11), seed=11) stats = search.run(maze, budget=32) print(stats.evaluations, stats.surrogate_evaluations, grid.filled_bins) The simulator returns a ``DSAGEMeasurement``. Its optional auxiliary field can hold a visitation map or another fixed-shape observation. The supplied PyTorch model first predicts the auxiliary values and uses them together with the genome to predict fitness and descriptors. A custom model supplies ``fit(X, targets, auxiliary)`` and ``predict(X)``. Prediction columns are fitness followed by descriptor coordinates. Use an encoder to map a genome to the model's input representation. The pilot encodes binary walls before fitting. ``run`` spends an additional real evaluation budget. The model can include finite measurements outside the archive bounds in its training set, while the live grid retains only admissible records. ``last_surrogate_archive`` contains predictions for inspection. See `Bhatt et al. (NeurIPS 2022)`_. .. _hierarchical-trial-and-error: Hierarchical Trial and Error ---------------------------- Build layers of skills that call primitives from the layer below. Each upper-level candidate is evaluated as its expanded sequence. The first descriptor axes specify a nominal displacement. Use secondary descriptor axes to keep different ways of making that displacement. .. code-block:: python from qdpy.algorithms import HierarchicalRepertoire, HierarchicalTrialAndError, RTESkill primitive = (RTESkill((1.,), (1.,)), RTESkill((2.,), (1.,))) repertoire = HierarchicalRepertoire(primitive) def measure(keys): family = keys[0].genome[0] return 3. - family, (1.,), (family,) repertoire.add_layer(measure, shape=(1, 2), features_domain=((0., 2.), (1., 2.)), sequence_length=1, budget=20, seed=3) planner = HierarchicalTrialAndError(repertoire, simulations=8, horizon=1, seed=9) def execute(state, genome): return (state[0] + (genome[0] == 2.),) path = planner.run((0.,), (2.,), execute, max_trials=5) print(path.states[-1], planner.stats) During deployment the first primitive stalls. The primary planner reuses Reset-free Trial-and-Error to choose a displacement. A secondary Gaussian process chooses among the measured compositions in that cell based on the observed endpoint error and uncertainty. This implementation uses finite secondary alternatives and additive state displacements. Count macro trials and real primitive calls separately when comparing with a flat repertoire. See `Allard et al.`_. .. _domino: DOMiNO ------ DOMiNO shares one actor across a finite set of latent policies. The reference policy maximises task reward. Other policies receive an intrinsic reward for visiting different state-action features. Each policy has a multiplier that puts more weight on task reward when its estimated reward rate falls below the floor. .. code-block:: python from examples.selection_and_skills import run_domino # Install qdpy[rl]. The same 3,840-step budget applies to both runs. for mode in ("domino", "reward-only"): audit = run_domino(mode, seed=11) print(audit["reward_rates"], audit["satisfaction"], audit["mean_distance"]) To supply your own environment, instantiate ``qdpy.rl.DOMiNO`` with a Gymnasium environment factory and ``feature(observation, action, info)``. The feature should describe the current state or state-action pair. In the pilot it is a one-hot action vector. ``train(max_env_steps)`` uses a hard step cap. ``act(observation, skill)`` chooses a skill directly. ``evaluate()`` uses common held-out reset seeds and reports each latent policy's mean episode return, reward per step, and average feature vector. The floor is in units of average reward per step. Set it explicitly or derive it from the reference policy with ``optimality_ratio``. Use an explicit floor when rewards are negative. This synchronous version uses PPO and one mixed-reward baseline. The reference trains with V-trace and separate reward heads. The optional ``contact_distance`` uses the paper's attraction-repulsion term. See `Zahavy et al. (ICLR 2023)`_. .. _qdaif: QDAIF ----- Use one callback to propose text and another to evaluate it under a fixed rubric. Variation receives parent texts in a tuple and a NumPy generator. The judge returns numeric quality and descriptors in the archive's domains. For a language model, these can come from rubric scores and category probabilities. .. code-block:: python from qdpy.algorithms import QDAIF from qdpy.containers import Grid grid = Grid(shape=3, features_domain=((0., 1.),), fitness_domain=((0., 1.),)) search = QDAIF(grid, seed=11) # Replay three recorded judgments for the same rubric. ratings = {"river bends": (.7, (.1,)), "clouds gather": (.8, (.5,)), "stones shine": (.9, (.9,))} proposals = iter(ratings) stats = search.run(lambda parents, rng: next(proposals), ratings.__getitem__, proposal_budget=3, judgment_budget=3) print(search.best, stats.judgments) Pass ``parent_count=0`` for independent sampling. Exact duplicate texts reuse their first judgment. Track proposal calls and judgment calls separately, since duplicate proposals still spend calls. The example uses a reproducible lookup rubric. A caller can replace either callback with a local model or a provider adapter. See `Bradley et al.`_. .. _qdaif-hosted-models: Run QDAIF with OpenRouter or LiteLLM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The :download:`hosted model example <../examples/qdaif_llm.py>` uses one model to propose short descriptions of a rainy town and to grade them. The grade combines clarity and originality. Sensory imagery and whimsy define the two archive axes. QDAIF supplies archived text as a parent and keeps the highest-scoring sentence in each cell. The deterministic replay uses the same callback interface. .. code-block:: sh python examples/qdaif_llm.py replay To try the HTTP adapter, set ``OPENROUTER_API_KEY`` in your environment or use ``--openrouter-key-file`` with a local key file. From the checkout root, a run with a budget of one can make one proposal request and one judgment request. .. code-block:: sh python examples/qdaif_llm.py openrouter --model openai/gpt-4.1-mini --budget 1 The LiteLLM adapter routes through the same OpenRouter account. Install the client separately in your environment. Both commands take the same OpenRouter model slug. The LiteLLM adapter adds the ``openrouter/`` prefix. .. code-block:: sh uv pip install "litellm==1.111.0" # With pip, use python -m pip install "litellm==1.111.0" python examples/qdaif_llm.py litellm --model openai/gpt-4.1-mini --budget 1 The live backends request JSON mode. Choose a model that supports it. The script prints the archive, proposal and judgment counts, and prompt and completion tokens reported by the API. ``responses_with_usage`` counts replies that included both token counts. The seed controls QDAIF's parent selection, and the replay mode gives fixed responses for testing. See `OpenRouter chat completions`_ and `LiteLLM routing through OpenRouter`_. See :doc:`tutorial_llm_qd` for further workflows with these same adapters. Run the seeded comparisons -------------------------- .. code-block:: shell python examples/selection_and_skills.py core --quick --seeds 11 python examples/selection_and_skills.py dsage --quick --seeds 11 python examples/selection_and_skills.py domino --quick --seeds 11 See :doc:`selection_and_skills_benchmarks` for the full pilot budgets and individual runs. .. _Wang et al. (IJCAI 2023): https://ijcai.org/proceedings/2023/482 .. _Bhatt et al. (NeurIPS 2022): https://arxiv.org/abs/2206.04199 .. _Allard et al.: https://arxiv.org/abs/2210.09918 .. _Zahavy et al. (ICLR 2023): https://openreview.net/forum?id=kjkdzBW3b8p .. _Bradley et al.: https://arxiv.org/abs/2310.13032 .. _OpenRouter chat completions: https://openrouter.ai/docs/api/api-reference/chat/send-chat-completion-request .. _LiteLLM routing through OpenRouter: https://docs.litellm.ai/docs/providers/openrouter