""" subset_loader.py — trajectory-level subsetting for D4RL hopper-medium-v2. Used by launch.py to monkey-patch d4rl.qlearning_dataset so that the authors' UNMODIFIED training scripts (StBR main.py, SPOT main.py AND SPOT train_vae.py) train on an identical trajectory-level subset of hopper-medium-v2. Semantics (disclosed in the repro report): 1. Segment the RAW dataset (env.get_dataset()) into trajectories at every transition where terminal OR timeout is True (standard D4RL v2 convention). 2. Sample n_sub = round(fraction * n_trajs) trajectory indices with np.random.RandomState(seed).permutation — deterministic per (fraction, seed). The run seed is also used as the subset seed. 3. Map selected trajectories onto the d4rl.qlearning_dataset arrays. d4rl.qlearning_dataset (pinned commit 4aff6f8) keeps transitions i where i < N-1 and timeouts[i] is False — it drops the last transition of every timeout-terminated trajectory and the final raw row. The mapping below reproduces exactly what a full-data run would see for those transitions. 4. Save the subset recipe (trajectory ranges + counts) to JSON so subsets are reproducible and auditable without storing the data itself. """ import json import os import numpy as np _ORIG = None # original d4rl.qlearning_dataset, set by launch.py _CONF = None # dict(fraction, seed, out_dir) _CACHE = {} def set_original(fn): global _ORIG _ORIG = fn def configure(fraction, seed, out_dir): global _CONF _CONF = dict(fraction=fraction, seed=seed, out_dir=out_dir) def _raw_trajectories(env): """(raw dataset, starts, ends) — trajectories end at terminal OR timeout.""" d = env.get_dataset() done = np.logical_or(d['terminals'], d['timeouts']) ends = np.flatnonzero(done) starts = np.concatenate(([0], ends[:-1] + 1)) assert len(starts) == len(ends), 'trajectory segmentation failed' return d, starts, ends def patched_qlearning_dataset(env, dataset=None, **kwargs): """Drop-in replacement for d4rl.qlearning_dataset(env) that returns the subset.""" assert _ORIG is not None and _CONF is not None, 'subset_loader not configured' full = _ORIG(env, dataset=dataset, **kwargs) fraction, seed = _CONF['fraction'], _CONF['seed'] key = (round(float(fraction), 4), int(seed)) if key not in _CACHE: raw, starts, ends = _raw_trajectories(env) n_raw = int(len(raw['rewards'])) n_trajs = int(len(starts)) kept = np.zeros(n_raw, dtype=bool) kept[: n_raw - 1] = ~np.asarray(raw['timeouts'][: n_raw - 1], dtype=bool) rng = np.random.RandomState(int(seed)) n_sub = max(1, int(round(float(fraction) * n_trajs))) sel = np.sort(rng.permutation(n_trajs)[:n_sub]) mask = np.zeros(n_raw, dtype=bool) ranges = [] for j in sel: lo, hi = int(starts[j]), int(ends[j]) + 1 hi = min(hi, n_raw - 1) # qlearning never keeps raw row N-1 seg = kept[lo:hi] mask[lo:hi] |= seg ranges.append([lo, hi - 1, int(seg.sum())]) assert int(mask.sum()) == sum(r[2] for r in ranges) sub = {k: full[k][mask] for k in full.keys()} recipe = { 'env': str(env.spec.id), 'fraction': float(fraction), 'subset_seed': int(seed), 'n_trajs_total': n_trajs, 'n_trajs_selected': int(n_sub), 'selected_trajectory_indices': [int(i) for i in sel], 'raw_ranges_start_end_nkept': ranges, 'n_transitions_raw_qlearning': int(n_raw), 'n_transitions_subset': int(mask.sum()), 'rule': 'trajectories segmented at terminal|timeout; sample without replacement; ' 'qlearning_dataset drops timeout-final transitions (terminate_on_end=False)', } if _CONF['out_dir']: os.makedirs(_CONF['out_dir'], exist_ok=True) path = os.path.join(_CONF['out_dir'], f'subset_f{fraction}_seed{seed}.json') with open(path, 'w') as fh: json.dump(recipe, fh) print(f'[subset] fraction={fraction} seed={seed}: {n_sub}/{n_trajs} trajectories, ' f'{int(mask.sum())}/{n_raw} transitions (qlearning-space)', flush=True) _CACHE[key] = (mask, sub, recipe) return _CACHE[key][1]