""" 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 raw row and every timeout transition (e.g. hopper-medium-v2 keeps 999,998 of 1,000,000 raw rows). It preserves the raw ORDER of kept rows, so qlearning row m corresponds to kept raw index kept_pos[m]; trajectory ranges are mapped with searchsorted and an assert guards the length match. 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)) # rows kept by d4rl.qlearning_dataset (terminate_on_end=False): # raw index i is kept iff i < N-1 and timeouts[i] is False kept = np.zeros(n_raw, dtype=bool) kept[: n_raw - 1] = ~np.asarray(raw['timeouts'][: n_raw - 1], dtype=bool) kept_pos = np.flatnonzero(kept) # qlearning row index for each kept raw index n_ql = int(kept_pos.size) assert n_ql == int(len(full['rewards'])), ( f'qlearning mapping mismatch: {n_ql} kept raw rows vs ' f'{len(full["rewards"])} qlearning rows') 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_ql, dtype=bool) ranges = [] for j in sel: lo = int(np.searchsorted(kept_pos, int(starts[j]), side='left')) hi = int(np.searchsorted(kept_pos, int(ends[j]) + 1, side='left')) mask[lo:hi] = True ranges.append([lo, hi - 1, hi - lo]) 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], 'selected_trajectory_raw_ranges_start_end': [ [int(starts[j]), int(ends[j])] for j in sel], 'ql_ranges_start_end_nkept': ranges, 'n_transitions_raw': n_raw, 'n_transitions_qlearning_full': n_ql, 'n_transitions_subset': int(mask.sum()), 'rule': 'trajectories segmented at terminal|timeout; sample without ' 'replacement; qlearning_dataset keeps i