# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Learn two continuous-control routes from a static mixed-quality transition log. """Train DiveOff offline and audit a fixed panel of latent codes on fresh resets.""" import argparse import json from dataclasses import asdict import gymnasium as gym import numpy as np import torch from qdpy.rl import DiveOff, DiveOffConfig, PolicyConfig class ForkNavigation(gym.Env): """Choose a corridor at a fork and hold position in it to finish the route.""" observation_space = gym.spaces.Box(-1., 1., (3,), dtype=np.float32) action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32) horizon = 6 def _observation(self): return np.array([2 * self.time / self.horizon - 1., self.lane, self.offset], dtype=np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.lane = self.time = 0 self.offset = self.np_random.uniform(-.12, .12) return self._observation(), {} def step(self, action): """Apply a physical action and return a true task reward.""" turning = float(action[0]) if self.time == 0: self.lane = int(np.sign(turning)) if abs(turning) >= .30 else 0 target = self.lane * .78 + .25 * self.offset score = 1. - (turning - target)**2 if self.lane else 0. self.time += 1 return self._observation(), score, self.time == self.horizon, False, {"lane": self.lane} def transition_log(): """Collect left, right, and exploratory episodes once, outside training.""" env = ForkNavigation() rng = np.random.default_rng(571) rows = [] for episode in range(72): obs, _ = env.reset(seed=episode + 15) route = (1., -1., 1., -1., 0., 0.)[episode % 6] for _ in range(env.horizon): turning = (.78 * route + rng.normal(0., .08)) if route else rng.uniform(-1., 1.) action = np.array([np.clip(turning, -1., 1.)], dtype=np.float32) nxt, reward, terminated, _, _ = env.step(action) rows.append((obs, action, reward, nxt, terminated)) obs = nxt env.close() names = ("observations", "actions", "rewards", "next_observations", "terminated") return {name: np.stack(column) for name, column in zip(names, zip(*rows))} def audit(policy): """Measure return and supported routes at a fixed latent-code panel.""" seeds = (1001, 1003, 1009) codes = np.linspace(-2.5, 2.5, 17) env = ForkNavigation() audits = [] for latent in codes: values, lanes = [], [] for seed in seeds: obs, _ = env.reset(seed=seed) total = 0. for _ in range(env.horizon): obs, reward, _, _, info = env.step(policy.act(obs, (latent,))) total += reward values.append(total / env.horizon) lanes.append(info["lane"]) score = float(np.mean(values)) audits.append(dict(code=float(latent), mean_step_return=score, lane=lanes[0] if len(set(lanes)) == 1 else 0)) env.close() successful = [row for row in audits if row["lane"] and row["mean_step_return"] >= .70] return dict(verified_routes=sorted({row["lane"] for row in successful}), successful_codes=len(successful), best_mean_step_return=max(row["mean_step_return"] for row in audits), verification_steps=len(seeds) * len(codes) * env.horizon, audit=audits) def run(method, updates, pretrain, seed): """Train from the same transitions with or without the latent recovery term.""" config = DiveOffConfig( latent_size=1, pretrain_updates=pretrain, batch_size=64, advantage_samples=4, policy_delay=2, representation_hidden_sizes=(32, 32), critic_hidden_sizes=(32, 32), reconstruction_std=.22, information_weight=.6 if method == "diveoff" else 0., actor_learning_rate=.001, critic_learning_rate=.001, representation_learning_rate=.001, information_learning_rate=.0005, ) search = DiveOff(ForkNavigation.observation_space, ForkNavigation.action_space, config=config, policy=PolicyConfig((32, 32)), seed=seed, **transition_log()) stats = search.train(updates) return dict(method=method, seed=seed, **asdict(stats), **audit(search.policy())) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--updates", type=int, default=800) parser.add_argument("--pretrain", type=int, default=256) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33]) args = parser.parse_args() torch.set_num_threads(1) for seed in args.seeds: for name in ("diveoff", "diveoff-no-information"): print(json.dumps(run(name, args.updates, args.pretrain, seed), sort_keys=True))