Sparse rewards, interpretable trees, and population diversity ============================================================= The examples in this tutorial share a command-line driver. SERENE, DvD-ES, and decision-tree inference use the base install. Training decision trees uses QDpy's existing Gymnasium rollout code through the RL extra. .. code-block:: bash python -m pip install qdpy python examples/serene_trees_dvd.py sparse --seeds 7 13 23 python examples/serene_trees_dvd.py dvd --seeds 7 13 23 uv run --extra rl python examples/serene_trees_dvd.py trees --policy-dir build/tree-policies For the settings, comparisons, and raw results, see :doc:`serene_trees_dvd_benchmarks`. .. _serene-trees-dvd-serene: SERENE ------ When useful reward is rare, SERENE uses a novelty population to explore behavioural space. A rewarding discovery can start a local emitter that selects for reward. The search alternates call budgets between these two activities and retains reward elites separately from novelty records. .. code-block:: python from qdpy.algorithms import SERENE from qdpy.containers import Grid def evaluate(genome, rollout_seed): x, y = genome distance = ((x - 0.8)**2 + (y - 0.2)**2)**0.5 reward = 1.0 - distance if distance < 0.15 else 0.0 return reward, (x, y) archive = Grid( shape=(12, 12), features_domain=((0., 1.), (0., 1.)), fitness_domain=((0., 1.),), fitness_weights=(1.,), ) search = SERENE(archive, dimension=2, reward_threshold=0.0, seed=7) stats = search.run(evaluate, budget=600) print(stats.first_reward_evaluation, stats.emitter_evaluations) print(len(search.novelty_archive), len(archive)) Use a seed from the callback for stochastic resets. Return ``None`` for a failed assessment. A failed call still uses its phase budget. Use finite, comparably scaled descriptor coordinates for Euclidean novelty. Select grid bounds that retain the rewarding behaviours of interest. An out-of-grid observation can still contribute novelty. The first above-threshold reward counts as a discovery even if its descriptor is outside the grid. Each rewarding cell can launch one emitter per search instance. The probe retains the best members, and an emitter qualifies for further calls if the probe improves the best reward. Eligible emitters compete by novelty and recent improvement and retire after repeated failed improvements. Exceptionally novel offspring can contribute to the bounded exploration memory. Pausing at any budget boundary preserves the proposal stream and phase state. These are QDpy's bounded defaults. The paper queues individual reward discoveries, estimates mutation scale from neighbours, and measures improvement over windows of emitter generations. Source: Paolo, Coninx, Doncieux and Laflaquière. `Sparse Reward Exploration via Novelty Search and Emitters `_. GECCO 2021. .. _serene-trees-dvd-tree-map-elites: Decision-tree MAP-Elites ------------------------ Supply a factory for a single Gymnasium environment with finite observations from a numeric ``Box`` and actions from ``Discrete``. The threshold ranges have one interval per flattened observation coordinate. Use ranges where plausible splits occur, even when the observation space itself has infinite bounds. .. code-block:: python import gymnasium as gym from qdpy.algorithms import DecisionTreePolicy from qdpy.rl import DecisionTreeMAPElites def make_environment(): return gym.make("CartPole-v1") search = DecisionTreeMAPElites( [(-2.4, 2.4), (-2.0, 2.0), (-0.21, 0.21), (-2.0, 2.0)], max_depth=4, entropy_bins=8, train_episodes=12, evaluation_episodes=4, max_episode_steps=200, seed=7, ) stats = search.run(make_environment, max_env_steps=32_000) search.best_policy.save("cartpole-tree.json") policy = DecisionTreePolicy.load("cartpole-tree.json") audit = search.evaluate(make_environment, policy, episodes=20, seed=401) print(stats.env_steps, len(search.archive), audit.mean_return) Each candidate evolves by subtree replacement or restart. Its leaves start with fresh action values, learned by epsilon-greedy tabular Q-learning. Scoring uses a common set of deterministic reset seeds and greedy actions. At termination the target is the transition reward. At truncation the learner can bootstrap from the successor observation. The descriptor's first coordinate is split depth. The second is the Shannon entropy of the actions actually taken during the scoring episodes, divided by the logarithm of the action count. A one-action environment has entropy zero. Both training and scoring count against ``max_env_steps``. A tree starts when its worst-case cost fits. Earlier episode endings can reduce its actual cost. Use ``search.policy_for(elite)`` to inspect a policy from any filled cell, and report audits on fresh seeds separately. Set ``selection="quality"`` to select only the highest-scoring parent while retaining the same reporting grid and training loop. The saved JSON describes the test at each node, both branches, and the greedy leaf actions. ``qdpy.algorithms.DecisionTreePolicy`` can load it with a base installation. The loader converts observations to float32 before comparing split values, as the rollout code does. This first version uses genetic programming with axis-aligned splits and subtree mutation. The source paper also studies grammar-based evolution and threshold optimization. Source: Ferigo, Custode and Iacca. `Quality–diversity optimization of decision trees for interpretable reinforcement learning `_. Neural Computing and Applications, published online in 2023. .. _serene-trees-dvd-dvd-es: Diversity via Determinants ES ----------------------------- DvD-ES jointly optimizes a population. Supply its initial parameter vectors and an evaluator that returns one scalar reward and one behaviour embedding per call. For a policy, a useful embedding is its actions on a small bank of shared observations. Keep the embedding coordinates comparable across members of each perturbation. .. code-block:: python import numpy as np from qdpy.algorithms import DvDES, behavior_logdet probes = np.array([-1., 0., 1.]) def evaluate(genome, rollout_seed): bias, slope = genome embedding = np.tanh(bias + slope * probes) reward = -abs(abs(embedding[1]) - 0.7) return reward, embedding initial = [[-0.3, 0.0], [0.1, 0.1], [0.4, -0.1]] search = DvDES(initial, pairs=4, bandwidth=0.7, ind_domain=(-2., 2.), seed=7) stats = search.run(evaluate, budget=search.initialization_cost + 32 * search.round_cost) print(stats.updates, stats.mixed_updates) print(behavior_logdet([member.embedding for member in search.population], bandwidth=0.7)) The default Thompson sampler selects between reward-only and mixed rounds according to changes in the best measured reward. Set ``diversity_weight=0.5`` for a fixed balance or ``diversity_weight=0.0`` for matched independent ES. Separate rank scaling applies to local rewards and to the log determinants of entire population perturbations. Each round consumes up to ``population_size * (2 * pairs + 1)`` calls, including fresh center measurements. A returned ``None`` invalidates that round. Inspect ``search.population`` for the measured centers from the last successful round. Only complete rounds start within a call budget. Smaller remainders can be carried over by the caller. Use separate rollout seeds to assess reward after training. The kernel volume measures how different the embeddings are, so compare it with held-out returns or the number of distinct useful behaviours. If simulation steps vary per rollout, track their number in the evaluator. DvD-ES budgets calls. Source: Parker-Holder, Pacchiano, Choromanski and Roberts. `Effective Diversity in Population-Based Reinforcement Learning `_. NeurIPS 2020.