MC-AURORA with learned descriptors ================================== An MC-AURORA search keeps several MAP-Elites grids for the same problem. Each grid uses a different autoencoder to describe an evaluated solution. One shared training archive, called the depot, holds the observations from which the encoders learn. A candidate can land in different cells across grids even though its genome and fitness stay the same. This example uses the CPU. Install QDpy and PyTorch under the same Python with pip or uv. From the repository root with an active virtual environment, use one of these commands. .. code-block:: bash python -m pip install -e . torch # Or, in a uv-managed environment uv pip install -e . torch Then run the example. .. code-block:: bash python examples/mc_aurora.py --seed 42 The default uses eight-dimensional, normalised Rastrigin and two 16 by 16 grids. It evaluates 128 uniform candidates for the first training set before starting its 1,024-evaluation search budget. The JSON report includes each grid's occupancy and QD score, the number of distinct elites, archive overlap, and the loss from every refit. What the evaluator supplies --------------------------- The evaluator returns QDpy's usual ``(fitness, features, scores)`` triple. Put the observations to encode in a named score. The evaluator can still return hand-designed features for analysis. They are stored alongside the fitness and remain available to the depot. .. code-block:: python import numpy as np from qdpy.benchmarks.artificial_landscapes import rastrigin_normalised def evaluate(individual): measurements = np.array(individual, dtype=np.float32) return rastrigin_normalised(individual), individual[:2], {"observation": measurements} Return an independent array for each evaluation. Supply a finite numeric array of the same shape for every individual. If the observations are already scalar named scores, pass their names in order as ``base_scores``. The default model flattens arrays and has a tanh decoder. Scale continuous observations to the decoder's output range, or pass models suited to the data. The same script includes a ball trajectory evaluator. Each observation is a two-channel array containing horizontal and vertical positions at 64 time steps. The objective is landing error. Landing distance and apex height supply a separate, fixed space for comparing the depot and the elites. .. code-block:: bash python examples/mc_aurora.py --task trajectory --seed 42 Set up the grids and the trainer -------------------------------- The quantile transform maps each latent coordinate to the unit interval, so the grids can use fixed bounds. During a refit, the coordinator fits the transform on the same depot sample used to train that encoder. Later candidates use the fitted transform until the next refit. Before the first fit, provisional encoders use a sigmoid mapping. .. code-block:: python import random from qdpy.algorithms import AlternatingAlgWrapper, CuriosityMutPolyBounded from qdpy.containers import Container, Grid, MCAurora random.seed(42) np.random.seed(42) depot = Container(fitness_domain=((0., 1.),), storage_type="orderedset") grids = [ Grid(shape=(16, 16), features_domain=((0., 1.), (0., 1.)), fitness_domain=((0., 1.),)) for _ in range(2) ] learned = MCAurora(grids, depot, observation_score="observation", training_period=256, epochs=5, seed=42) children = [ CuriosityMutPolyBounded(archive, budget=1024, dimension=8, init_pb=0.1, batch_size=64) for archive in learned.archives ] search = AlternatingAlgWrapper(children, budget=1024, batch_size=64) learned.attach(search) search.optimise(evaluate) Run this with the evaluator above in scope. The Python and NumPy seeds control the search. The coordinator seed controls default model initialisation and training sampling. The CLI pretraining phase adds evaluated uniform candidates to the depot and calls ``learned.fit()`` before starting search. To freeze the encoders after a manual fit, set ``training_period=0``. The two child optimisers alternate proposals. By default each evaluated candidate goes to the grid that proposed it, and valid evaluations are offered to the depot. An ordered-set depot keeps one record per equal genome. Refits are checked after evaluation batches and at search completion. They trigger once when the depot crosses one or more new multiples of ``training_period``. The depot's growth counts unique stored records when an ordered set is used. With ``rebuild_from="elites"``, each refit reinserts the entries retained by each grid into that grid. Set ``rebuild_from="depot"`` to offer every record to every grid during refits. For an initially empty grid, the first fit uses the depot. To share every new evaluation during search as well, set ``tell_all=True`` on the alternating wrapper. These two sharing decisions are independent. Use separate, initially empty fixed grids with fitness domains that can accept the depot records. The trainer prepares replacement grids using the fitted descriptors before updating the active grids. Use ``learned.archives`` as the optimiser containers so admission uses the correct encoder. Choose a model and diversity term --------------------------------- The objective starts with mean squared reconstruction error over models and observations. By default, models train together with reconstruction alone. The following options modify the shared objective. .. list-table:: :header-rows: 1 * - Option - Behavior with a positive diversity weight * - ``none`` - Minimise reconstruction error. * - ``outputs`` - Reward the mean squared deviation of each decoded observation from the ensemble mean for that same observation. * - ``covariance`` - Penalise the mean absolute off-diagonal sample covariance across all concatenated latent coordinates. * - ``correlation`` - Reward the average correlation matrix distance between encoders. This option uses equal latent widths. Select a term with ``--diversity`` and set its strength with ``--diversity-weight``. In the Python API, pass one PyTorch module per grid with ``models=[model_a, model_b]``. Each module needs trainable parameters and ``encoder(batch)`` and ``decoder(latent)`` callables. Its encoder returns a matrix of shape ``(batch_size, latent_width)``. The latent width matches the grid's descriptor dimension. Its decoder returns the original batch shape. The coordinator trains CPU copies so that an unsuccessful refit can leave the active models available. The method follows the shared-depot and ensemble-training design in the `MC-AURORA paper `__. The Rastrigin and ball trajectory examples use smaller models and explicit loss reductions. BipedalWalker-v3 ---------------- Install PyTorch and Gymnasium's Box2D extra in the QDpy environment. The example was checked with Python 3.11 and runs headless. .. code-block:: bash python -m pip install -e . torch "gymnasium[box2d]" # Or, in a uv-managed environment uv pip install -e . torch "gymnasium[box2d]" The default smoke preset evaluates 12 warmup policies and 24 search policies. It runs two 60-step episodes per policy and uses two learned grids. .. code-block:: bash python examples/bipedal_walker/mc_aurora_walker.py --seed 42 The ``paper`` preset follows the paper's four-grid online reconstruction case, ``qt-reco-4-ns``. It uses a 24–40–40–4 tanh controller with 2,804 evolved parameters. Each evaluation averages the return over five episodes capped at 300 steps. The evaluator averages each of the 24 Gymnasium state coordinates in 30-step windows. It pads early terminations with zeros before averaging and scales the window means into the unit interval. The result is a 120-by-10 float32 input for each temporal autoencoder. Each encoder supplies two quantile-mapped descriptors for a 25-by-25 grid. .. code-block:: bash python examples/bipedal_walker/mc_aurora_walker.py --profile paper \ --seed 42 --executor concurrent --workers 4 --output walker.json The full preset requests 10,000 warmup evaluations, 100,000 search evaluations, and 200 epochs per fit. A shorter run can override the budgets and epoch count while keeping the observation layout. .. code-block:: bash python examples/bipedal_walker/mc_aurora_walker.py --profile paper \ --warmup 6 --budget 8 --batch-size 4 --training-period 4 \ --epochs 2 --training-batch-size 4 --executor concurrent --workers 2 The example uses Gymnasium and reuses a fixed set of terrain seeds across policies. Its transposed convolutions preserve the temporal width and the current coordinator reports training loss. Those choices differ from the original simulator, unpooling decoder, and holdout validation protocol. The report gives raw mean returns and raw QD scores, along with occupancy and overlap. Use repeated runs and the published protocol for direct comparisons with the paper's results. Run with parallel evaluation ---------------------------- The evaluator can run in worker threads or processes. The current encoders, archive updates, and PyTorch training stay on the coordinator. Use pack sizes above one when the overhead per call matters. For example: .. code-block:: bash python examples/mc_aurora.py --task trajectory --archives 3 --warmup 1024 \ --budget 25000 --training-period 8000 --batch-size 256 --pack-size 32 \ --executor concurrent --workers 4 --diversity correlation --diversity-weight 0.1 \ --tell-all --rebuild-from depot --output mc-aurora.json Use ``--max-training-samples`` to bound the training and quantile fit for each refit. Depot rebuilds still encode all depot entries. Elites-only rebuilds keep that part of the cost tied to grid capacity. ``--torch-threads`` sets CPU threads used for model training. The tutorial uses one to leave cores available to evaluation workers. Executors can finish packs in different orders. Even when workers return the same measurements for a given candidate, different admission order can affect the next parent selection and the training depot's order. Compare several seeds and report the executor and pack size when comparing searches. Interpret the report -------------------- Compare the number of distinct elites with the sum of per-grid filled bins to see how much membership overlaps. The default originality and overlap metrics compare genome tuples. QD scores sum normalised fitness within a grid and depend on its occupancy and learned partition. The example reports paired KL divergence from the depot's reference-feature distribution to that of the union of elites. Both histograms use bins in the same fixed space. Lower KL means the distributions are closer. See :doc:`api_reference` for the coordinator, archive policies, and metric arguments. For the single-archive workflow, see :doc:`api_experiments`.