Download code_src/df_rise/df_data.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 8.21 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_data.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/df_data.py
-
curl -L -o df_data.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_data.py
8.21 kB
| """Diffusion Forcing corpus adapter (gen_q#274). | |
| CORPUS. The SAME DINOv2 cache every other scorer in tab:flagship reads -- `cache/<task>`: | |
| z.f16.npy [N, 1536] frozen DINOv2 ViT-S/14 cls+GeM features, 2 cameras x 2 channels | |
| proprio.f32.npy [N, 9] robot0_eef_pos / _quat / gripper_qpos | |
| act.f32.npy [N, 7] the OSC action actually executed | |
| meta.npz ep_from / ep_to / ep_len / ep_success (+ ep_src into the source HDF5) | |
| No pixels are read. DINO-WM trains on the TOKEN form of this same cache (cache/<task>/tokens); | |
| Diffusion Forcing here trains on the POOLED 1545-d form, which is the same frames, the same episodes | |
| and the same encoder -- stated explicitly because #274 requires saying which of the two we used. | |
| STATE DEFINITION is the project's, not a new one (data.py:245): | |
| x = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip), feat = concat(z, proprio) | |
| with mu / sd / sd_floor / z_clip read from the cache's own feat_stats.npz. A DF-specific | |
| normalisation on top of that would make DF's inputs incomparable with every other column's. | |
| REWARD is the binary data-provenance label -- `ep_success`, constant over an episode, 1 on every | |
| frame of an expert episode -- i.e. exactly what `train_rsm.py --reward-mode dense` feeds the | |
| membership head and exactly what RISE's own 0/1 critic label is (LAUNCH_MATRIX, 2026-09-18 13:05). | |
| No shaped reward and no goal signal: #274's fairness condition. | |
| CONSEQUENCE, stated because it changes how DF's guidance must be read: a per-episode-constant | |
| label carries no WITHIN-episode temporal signal. Guiding toward it does not mean "move toward the | |
| goal"; it means "generate a trajectory that looks like it came from the expert partition". That is | |
| the same information every other column gets, which is the point, but it is NOT the dense | |
| step-reward DF's maze2d planner was designed around, and the guidance term degenerates to a single | |
| scalar per plan rather than a per-step return. Reported, not hidden. | |
| SPLIT is the one `LiberoRSMData(seed=seed)` uses -- np.random.default_rng(seed).permutation(n_ep), | |
| first max(1, 0.1*n_ep) episodes held out (data.py:124-126) -- so DF's validation episodes are the | |
| episodes every other scorer held out. | |
| WINDOWS. DF consumes (t b (fs c)) tokens: `frame_stack` consecutive frames per token, `n_tokens` | |
| tokens per sequence. A window is drawn inside ONE episode (never across a boundary) and is padded at | |
| the tail with the episode's last frame, with a `mask` marking the padded frames so the loss and the | |
| fidelity metric ignore them. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| OBS_DIM, ACT_DIM, REW_DIM = 1545, 7, 1 | |
| BUNDLE_DIM = OBS_DIM + ACT_DIM + REW_DIM # 1553 | |
| class DFCacheData: | |
| def __init__(self, cache, frame_stack: int = 8, n_tokens: int = 8, val_frac: float = 0.1, | |
| seed: int = 0, in_ram: bool = True): | |
| self.root = Path(cache) | |
| m = np.load(self.root / "meta.npz", allow_pickle=True) | |
| self.ep_from = m["ep_from"].astype(np.int64) | |
| self.ep_to = m["ep_to"].astype(np.int64) | |
| self.ep_len = m["ep_len"].astype(np.int64) | |
| self.ep_success = m["ep_success"].astype(np.float32) | |
| self.n_ep = len(self.ep_len) | |
| self.adim = int(m["adim"]) | |
| assert self.adim == ACT_DIM, f"{cache}: adim {self.adim} != {ACT_DIM}" | |
| mode = None if in_ram else "r" | |
| self.z = np.load(self.root / "z.f16.npy", mmap_mode=mode) | |
| self.pr = np.load(self.root / "proprio.f32.npy", mmap_mode=mode) | |
| self.act = np.load(self.root / "act.f32.npy", mmap_mode=mode) | |
| assert self.z.shape[0] == self.pr.shape[0] == self.act.shape[0], "cache arrays disagree on N" | |
| assert self.z.shape[1] + self.pr.shape[1] == OBS_DIM, \ | |
| f"{cache}: {self.z.shape[1]}+{self.pr.shape[1]} != {OBS_DIM}" | |
| fs = np.load(self.root / "feat_stats.npz") | |
| self.mu = fs["mu"].astype(np.float32) | |
| self.sd = np.maximum(fs["sd"].astype(np.float32), float(fs["sd_floor"])) | |
| self.z_clip = float(fs["z_clip"]) | |
| self.frame_stack, self.n_tokens = int(frame_stack), int(n_tokens) | |
| # T is the PLAN length in frames (a whole number of tokens). A window holds T + 1 frames: | |
| # frame 0 is the conditioning observation that becomes token 0, frames 1..T are the plan, so | |
| # the plan is always divisible by frame_stack. | |
| self.T = self.frame_stack * self.n_tokens | |
| self.W = self.T + 1 | |
| rng = np.random.default_rng(seed) | |
| n_val = max(1, int(val_frac * self.n_ep)) | |
| perm = rng.permutation(self.n_ep) | |
| self.val_eps = np.sort(perm[:n_val]) | |
| self.train_eps = np.sort(perm[n_val:]) | |
| print(f"[df_data] {cache}: {self.n_ep} eps ({int(self.ep_success.sum())} expert), " | |
| f"{self.z.shape[0]} frames, split {len(self.train_eps)} train / {len(self.val_eps)} val, " | |
| f"plan T={self.T} frames (fs={self.frame_stack} x {self.n_tokens} tokens), " | |
| f"window {self.W} frames", flush=True) | |
| # ---- state ------------------------------------------------------------- | |
| def obs_rows(self, rows): | |
| """cache row indices -> normalised 1545-d state, EXACTLY data.py's definition.""" | |
| feat = np.concatenate([np.asarray(self.z[rows], np.float32), | |
| np.asarray(self.pr[rows], np.float32)], axis=-1) | |
| x = (feat - self.mu) / self.sd | |
| if self.z_clip: | |
| np.clip(x, -self.z_clip, self.z_clip, out=x) | |
| return x | |
| def normalize_feat(feat, mu, sd, z_clip): | |
| """The same map applied to a live env feature vector at planning time.""" | |
| x = (feat - mu) / sd | |
| if z_clip: | |
| x = np.clip(x, -z_clip, z_clip) | |
| return x | |
| # ---- windows ----------------------------------------------------------- | |
| def sample(self, batch: int, rng, split: str = "train", device="cpu"): | |
| """-> bundle [W, B, 1553], mask [W, B] (1 = real frame, 0 = tail padding), W = T + 1.""" | |
| pool = self.train_eps if split == "train" else self.val_eps | |
| eps = pool[rng.integers(0, len(pool), size=batch)] | |
| bun = np.zeros((self.W, batch, BUNDLE_DIM), np.float32) | |
| msk = np.zeros((self.W, batch), np.float32) | |
| for b, e in enumerate(eps): | |
| L = int(self.ep_len[e]) | |
| # start uniformly in the episode; a window may run past the end and is padded there. | |
| s = int(rng.integers(0, max(1, L))) | |
| n = min(self.W, L - s) | |
| rows = self.ep_from[e] + np.arange(s, s + n) | |
| bun[:n, b, :OBS_DIM] = self.obs_rows(rows) | |
| bun[:n, b, OBS_DIM:OBS_DIM + ACT_DIM] = np.asarray(self.act[rows], np.float32) | |
| msk[:n, b] = 1.0 | |
| if n < self.W: # hold the last real frame, mask says it is padding | |
| bun[n:, b, :OBS_DIM + ACT_DIM] = bun[n - 1, b, :OBS_DIM + ACT_DIM] | |
| bun[:, b, -1] = self.ep_success[e] # provenance label on every frame of the window | |
| return (torch.from_numpy(bun).to(device), torch.from_numpy(msk).to(device)) | |
| def bundle_stats(self, n: int = 20000, seed: int = 0): | |
| """Per-channel mean/std of the bundle over TRAIN frames, for DF's own input normaliser. | |
| The obs channels are already unit-scale by construction, so this mostly matters for the | |
| action channels and the reward channel.""" | |
| rng = np.random.default_rng(seed) | |
| rows = np.concatenate([np.arange(self.ep_from[e], self.ep_to[e]) for e in self.train_eps]) | |
| take = rows if len(rows) <= n else rows[rng.choice(len(rows), n, replace=False)] | |
| take = np.sort(take) | |
| obs = self.obs_rows(take) | |
| act = np.asarray(self.act[take], np.float32) | |
| lab = np.repeat(self.ep_success[self.train_eps].mean(), 1).astype(np.float32) | |
| mean = np.concatenate([obs.mean(0), act.mean(0), lab]) | |
| std = np.concatenate([obs.std(0), act.std(0), | |
| np.array([max(self.ep_success[self.train_eps].std(), 1e-3)], np.float32)]) | |
| return mean.astype(np.float32), np.maximum(std, 1e-3).astype(np.float32) | |