Distill a repertoire with the Quality-Diversity Transformer¶
The QD Transformer learns one continuous policy from saved trajectories. Give it a target behavior descriptor when the episode starts. It uses past observations and actions to choose the next action. See the Quality-Diversity Transformer paper.
Install the existing RL extra from a checkout with
pip install '.[rl]' or uv sync --extra rl. The example uses
teacher policies with different behaviors. The first observation
reveals a sign that later observations hide, so the policy must
remember the sign to produce the requested behavior.
from qdpy.rl import QualityDiversityTransformer
from examples.qdt_distillation import SignMemory, make_transformer, rollout, teacher_data
env = SignMemory()
try:
episodes = teacher_data(env)
descriptors = [(episode.final_info["descriptor"],) for episode in episodes]
search = make_transformer(env, seed=11)
metrics = search.fit(episodes, descriptors, epochs=55, batch_size=8, learning_rate=.003)
print(metrics.transitions, metrics.updates, metrics.loss)
search.save("qdt.npz")
restored = QualityDiversityTransformer.load("qdt.npz")
policy = restored.policy_for((.44,))
measured = rollout(env, policy, seed=105)
print(measured.final_info["descriptor"])
finally:
env.close()
For a real repertoire, collect complete qdpy.rl.Episode records
from its policies and pair them with the desired training descriptors.
An episode has one more observation than action. The fitted model
expects the same observation shape, Box action bounds, and descriptor
coordinates. Set QDTConfig.context_length to cover the longest
episode. The first implementation uses caller-supplied trajectories
for offline distillation.
Each prediction sees the requested descriptor, the current observation,
and earlier observations and actions. The causal attention mask hides
the action it is predicting. Short episodes can share a minibatch
with long ones. The loss includes only actual transitions. The
checkpoint contains model weights and numeric spaces. New sessions
made with policy_for() have independent histories. Reset a session
for a new episode and pass its physical action to the environment
before sending the next observation.
python examples/qdt_distillation.py
The Interactive and repertoire workflow benchmarks compare the Transformer with selecting the nearest archived teacher and offline feed-forward imitation on the same held-out descriptors.