Quality-Diversity Actor-Critic ============================== Use model-free QDAC to learn one continuous actor that can pursue several desired behaviors. At deployment, give it a desired skill and the current observation on every step. Train standalone SAC on the same reward if you need a reference policy with no skill input. QDAC collects experience into a replay buffer. An archive is useful for comparing achieved behaviors after training. Install the existing RL extra from a checkout with ``python -m pip install -e '.[rl]'`` or ``uv pip install -e '.[rl]'``. Both learners use Gymnasium and PyTorch and run on CPU by default. Define a timestep behavior -------------------------- The environment factory must produce a fresh single Gymnasium environment with a fixed-size numeric ``Box`` observation and a bounded floating-point ``Box`` action. Standard Gymnasium wrappers can flatten structured observations. The reward should express the original task and can be signed. Keep it independent of the requested skill so replay can safely relabel goals. This custom environment exposes a velocity coordinate in its observation. Thrust sets the next velocity while the reward favors moving at 0.3. The skill asks for a particular average velocity. .. code-block:: python import gymnasium as gym import numpy as np from qdpy.rl import PolicyConfig, QDAC, QDACConfig class Velocity(gym.Env): observation_space = gym.spaces.Box(-2., 2., (1,), dtype=np.float32) action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.velocity = float(self.np_random.uniform(-0.2, 0.2)) return self._observation(), {"velocity": self.velocity} def _observation(self): return np.array([self.velocity], dtype=np.float32) def step(self, action): self.velocity = 0.5 * self.velocity + float(action[0]) reward = 1. - (self.velocity - 0.3) ** 2 return self._observation(), reward, False, False, {"velocity": self.velocity} def velocity_feature(observation, action, info): return (info["velocity"],) bounds = ((-1., 1.),) learner = QDAC( Velocity, feature=velocity_feature, skill_bounds=bounds, policy=PolicyConfig((32, 32)), max_episode_steps=32, seed=11, config=QDACConfig( gamma=0.9, delta=0.1, replay_capacity=10_000, batch_size=64, learning_starts=128, critic_hidden_sizes=(64, 64), actor_learning_rate=0.001, critic_learning_rate=0.001, temperature_learning_rate=0.003, multiplier_hidden_sizes=(32, 32), ), ) stats = learner.train(max_env_steps=4096) print(stats.env_steps, stats.successor_feature_updates, stats.temperature) The callback is called **before** each step. It sees the original-shaped observation and info from reset or the previous step, plus the physical action selected for this step. Return a finite vector with one coordinate per skill dimension. A state-only feature can ignore the action. An action-dependent feature can derive the commanded velocity directly from it, as in the accompanying example. If the environment reports state features in info, populate them on reset as well as on each step. Declare each skill coordinate as a finite physical interval. QDAC maps these intervals to ``[-1, 1]`` internally, so training distances weight equal fractions of each interval equally. Achieved features can exceed the bounds. They are recorded at their actual value. To restrict the sampled skills, supply ``skill_sampler(rng)``, returning a physical vector inside the bounds using the supplied NumPy generator. For example, a direction can use cosine and sine features bounded by ``[-1, 1]`` with a sampler that draws a uniform angle and returns its cosine and sine. The resulting distance is chord distance in the embedding. Use the same feature coordinates and units at training and evaluation. Export the actor and evaluate requested skills ---------------------------------------------- .. code-block:: python from qdpy.containers import Grid from qdpy.rl import SkillConditionedPolicy, evaluate_skills learner.policy.save("velocity-policy.npz") actor = SkillConditionedPolicy.load("velocity-policy.npz") with Velocity() as env: observation, _ = env.reset(seed=100_011) thrust = actor.act(observation, (0.5,)) sampled_thrust = actor.act(observation, (0.5,), deterministic=False) geometry = Grid(shape=(12,), features_domain=((-2., 2.),), fitness_domain=((-140., 32.),)) scores = evaluate_skills( Velocity, actor, [(-0.5,), (0.,), (0.5,)], feature=velocity_feature, episodes=5, max_episode_steps=32, tolerance=0.2, seed=100_011, archive=geometry, qd_offset=140., ) for goal in scores.skills: print(goal.desired, goal.achieved, goal.return_, goal.satisfaction_rate) print(scores.coverage, scores.archive_coverage, scores.archive_qd_score) The numeric NPZ artifact contains the network weights, observation shape, action shape, action bounds and dtype, and physical skill bounds. Loading requires the RL extra. It needs neither an environment factory nor the training feature callback. Stochastic inference starts a fresh random stream from the seed passed to ``load``. Default inference uses the squashed mean. The artifact is for inference. To spend another training budget on the same learner, call ``train`` again. Each call opens a fresh environment and retains the replay and optimizer state. Evaluation uses the same held-out reset seeds at every goal. For each episode, it measures arithmetic mean timestep features and undiscounted return. For each goal, ``achieved`` is the mean descriptor in physical coordinates. ``distance`` is the mean of the per-episode Euclidean distances in normalized coordinates. ``satisfaction_rate`` counts individual episodes within tolerance. ``coverage`` counts goals whose **mean error** is within tolerance. Fixed-skill ``qd_score`` sums the mean return plus ``qd_offset`` at those covered goals. Choose the evaluation tolerance and score offset before comparing runs. Training ``delta`` uses the predicted discounted feature average and can differ from evaluation tolerance. With a ``Grid`` or ``CVTGrid``, the passive metrics also count achieved cells, report their fraction of the available cells and sum their best mean return plus the same offset. A missed skill can still occupy an achieved cell. Achievements outside the geometry remain visible in the per-goal results. Evaluation leaves any supplied grid's contents intact. These metrics describe the actors over the specified evaluation goals. They differ from the scores of an archive grown over an entire search. SAC and the QDAC updates ------------------------ Use ``SAC(Velocity, config=SACConfig(), max_episode_steps=32, seed=11)`` to train a reward-only actor. It takes the observation alone. Export it via ``learner.policy.save(path)`` and load it via ``SACPolicy.load(path)``. To compare it on the same evaluation goals, pass ``lambda obs, goal: actor.act(obs)`` to ``evaluate_skills`` along with ``skill_bounds``. The goals still determine how the resulting behavior is scored. The model-free QDAC update follows Algorithm 2 in the ICML paper and the authors' SCOPA implementation. Each episode holds one sampled skill. By default, each replay minibatch includes both the recorded skills and a copy of the same transitions with newly sampled skills. Rewards, features, actions, and episode boundaries are preserved in the copied batch. - Two reward critics use the smaller target estimate and subtract the entropy term when bootstrapping. The QDAC actor uses the mean of the current reward estimates. Standalone SAC uses their minimum. - Two successor-feature networks predict the discounted sum of the normalized timestep features. Their Bellman target uses the mean of the target networks without an entropy term. QDAC scales the prediction by ``1 - gamma`` to estimate a discounted feature average. True terminations shorten that sum. In tasks with short terminal episodes, the discount and feature bounds affect which predicted skills are reachable. - A state- and skill-conditioned sigmoid multiplier learns whether that predicted average misses the skill. Its classification target is one when the distance is at least ``delta``, matching the reference code. The actor blends reward and a vector pseudo-Huber feature penalty with this learned weight. - Both methods learn the entropy weight in normalized action coordinates and update the critic targets with Polyak averaging. Standalone SAC warms up with uniform actions and QDAC uses its stochastic actor. Default entropy targets are respectively minus the action dimension and minus half that dimension. QDAC masks Gymnasium time-limit transitions in both Bellman losses, matching the reference implementation. An actual termination keeps its immediate reward and feature with no bootstrap. A simultaneous termination and truncation uses the termination semantics. SAC bootstraps at time limits from the final observation and treats an actual termination as terminal. A one-step time-limit wrapper can therefore mask every QDAC Bellman target. For a genuinely one-step task, signal termination instead. The implementation uses a single Gymnasium environment, PyTorch ReLU networks, one update per step after warmup, and smaller default networks and batches than the large vectorized Brax runs in the paper. For related continuous-control methods, see :ref:`qdac-mb-training` and :ref:`smerl-skill-discovery`. For categorical controls, see :doc:`qdac_discrete_variants`. CPU comparison -------------- Run the included asymmetric two-control velocity example from a checkout. Each of the three methods receives the same training interaction budget. Evaluation uses three episodes at each of nine goals, for 432 additional steps per exported actor. .. code-block:: bash python -m examples.qdac --steps 8000 --seeds 11 29 47 The output directory contains individual policy NPZ files and JSONL with returns, tracking errors, constraint and archive metrics, update counts and training time. :download:`Recorded runs ` use one Torch thread. This task checks tracking and export on a small, reproducible environment. The authors' locomotion experiments have different environments, compute budgets, and evaluation protocols. The table shows means across three seeds, with a tolerance of 0.25. The archive geometry was an 8 × 8 grid. Timings are from one Torch thread on a shared Intel Xeon E5-2630 v4 host (Python 3.12.14, NumPy 2.5.5, PyTorch 2.15.0+cpu, and Gymnasium 1.4.0). Training time excludes export and held-out evaluation. The methods share an interaction budget and use their own optimizer schedules. .. list-table:: :header-rows: 1 * - Method - Return - Skill error - Episode success - Goal coverage - Achieved cells - Achieved-cell QD score - Train time (s) * - SAC - 16.00 - 0.903 - 3.7% - 0.0% - 1.0 - 16.00 - 39.5 * - QDAC - 14.29 - 0.124 - 90.1% - 92.6% - 9.0 - 128.59 - 86.5 * - DCRL-MAP-Elites - 14.06 - 0.032 - 100.0% - 100.0% - 9.0 - 126.50 - 5.5 SAC earned the highest return while reaching a single behavior cell. QDAC covered 25 of 27 goal–seed pairs and DCRL covered all 27. Both conditioned actors occupied nine achieved cells per seed. References ---------- - Grillotti et al., `Quality-Diversity Actor-Critic: Learning High-Performing and Diverse Behaviors via Value and Successor Features Critics `_, ICML 2024. - `Authors' project page `_. Reference `training updates `_ and `losses `_. - Haarnoja et al., `Soft Actor-Critic Algorithms and Applications `_ and the `ICML SAC paper `_. - Faldor et al., `MAP-Elites with Descriptor-Conditioned Gradients and Archive Distillation `_, for DCRL-MAP-Elites. See :doc:`tutorial_descriptor_conditioned_rl`.