cjgogo commited on
Commit
431f7cd
·
verified ·
1 Parent(s): 66c5695

Upload folder using huggingface_hub

Browse files
.rsi/laneB/hpace/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """HiPACE data curation primitives."""
2
+
3
+ from .config import load_config
4
+ from .act_trainer import ACTCommandTrainer
5
+
6
+ __all__ = ["ACTCommandTrainer", "load_config"]
7
+ __version__ = "2.0.0"
.rsi/laneB/hpace/act_dataset.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from bisect import bisect_right
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Sequence
7
+
8
+ import h5py
9
+ import numpy as np
10
+
11
+ from .act_preprocessing import policy_images
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class NormalizationStats:
16
+ qpos_mean: np.ndarray
17
+ qpos_std: np.ndarray
18
+ action_mean: np.ndarray
19
+ action_std: np.ndarray
20
+
21
+ def to_dict(self) -> dict[str, np.ndarray]:
22
+ return {
23
+ "qpos_mean": self.qpos_mean,
24
+ "qpos_std": self.qpos_std,
25
+ "action_mean": self.action_mean,
26
+ "action_std": self.action_std,
27
+ }
28
+
29
+
30
+ def load_sampling_cache(path: str | Path) -> tuple[list[str], list[np.ndarray]]:
31
+ cache = np.load(path, allow_pickle=False)
32
+ demo_ids = [str(item) for item in cache["demo_ids"]]
33
+ flat = np.asarray(cache["frame_probabilities"], dtype=np.float64)
34
+ offsets = np.asarray(cache["frame_probability_offsets"], dtype=np.int64)
35
+ frame_probabilities = [flat[offsets[i] : offsets[i + 1]] for i in range(len(demo_ids))]
36
+ return demo_ids, frame_probabilities
37
+
38
+
39
+ def compute_normalization_stats(hdf5_path: str | Path, demo_ids: Sequence[str], qpos_key: str = "robot0_joint_pos") -> NormalizationStats:
40
+ qpos, actions = [], []
41
+ with h5py.File(hdf5_path, "r") as dataset:
42
+ for demo_id in demo_ids:
43
+ qpos.append(np.asarray(dataset[f"data/{demo_id}/obs/{qpos_key}"], dtype=np.float32))
44
+ actions.append(np.asarray(dataset[f"data/{demo_id}/actions"], dtype=np.float32))
45
+ qpos_array = np.concatenate(qpos)
46
+ action_array = np.concatenate(actions)
47
+ return NormalizationStats(
48
+ qpos_array.mean(0),
49
+ np.maximum(qpos_array.std(0), 1e-2),
50
+ action_array.mean(0),
51
+ np.maximum(action_array.std(0), 1e-2),
52
+ )
53
+
54
+
55
+ class RoboMimicACTDataset:
56
+ """Frame-indexed RoboMimic dataset returning official ACT batch tuples."""
57
+
58
+ def __init__(
59
+ self,
60
+ hdf5_path: str | Path,
61
+ demo_ids: Sequence[str],
62
+ chunk_size: int,
63
+ stats: NormalizationStats,
64
+ image_keys: Sequence[str] = ("agentview_image",),
65
+ qpos_key: str = "robot0_joint_pos",
66
+ ):
67
+ import torch
68
+
69
+ self.torch = torch
70
+ self.hdf5_path = str(hdf5_path)
71
+ self.demo_ids = tuple(demo_ids)
72
+ self.chunk_size = chunk_size
73
+ self.stats = stats
74
+ self.image_keys = tuple(image_keys)
75
+ self.qpos_key = qpos_key
76
+ self._hdf5 = None
77
+ with h5py.File(self.hdf5_path, "r") as dataset:
78
+ self.lengths = [len(dataset[f"data/{demo_id}/actions"]) for demo_id in self.demo_ids]
79
+ for demo_id, length in zip(self.demo_ids, self.lengths):
80
+ if len(dataset[f"data/{demo_id}/obs/{qpos_key}"]) != length:
81
+ raise ValueError(f"qpos/action length mismatch in {demo_id}")
82
+ for image_key in self.image_keys:
83
+ if len(dataset[f"data/{demo_id}/obs/{image_key}"]) != length:
84
+ raise ValueError(f"image/action length mismatch in {demo_id}/{image_key}")
85
+ self.offsets = np.concatenate(([0], np.cumsum(self.lengths)))
86
+
87
+ def __len__(self) -> int:
88
+ return int(self.offsets[-1])
89
+
90
+ @property
91
+ def hdf5(self):
92
+ if self._hdf5 is None:
93
+ self._hdf5 = h5py.File(self.hdf5_path, "r", swmr=True)
94
+ return self._hdf5
95
+
96
+ def locate(self, index: int) -> tuple[int, int]:
97
+ if index < 0 or index >= len(self):
98
+ raise IndexError(index)
99
+ demo_index = bisect_right(self.offsets, index) - 1
100
+ return demo_index, int(index - self.offsets[demo_index])
101
+
102
+ def __getitem__(self, index: int):
103
+ demo_index, frame_index = self.locate(index)
104
+ demo = self.hdf5[f"data/{self.demo_ids[demo_index]}"]
105
+ qpos = np.asarray(demo[f"obs/{self.qpos_key}"][frame_index], dtype=np.float32)
106
+ images = np.stack([np.asarray(demo[f"obs/{key}"][frame_index], dtype=np.float32) for key in self.image_keys])
107
+ images = policy_images(images)
108
+ available = min(self.chunk_size, self.lengths[demo_index] - frame_index)
109
+ actions = np.zeros((self.chunk_size, demo["actions"].shape[-1]), dtype=np.float32)
110
+ actions[:available] = demo["actions"][frame_index : frame_index + available]
111
+ is_pad = np.ones(self.chunk_size, dtype=bool)
112
+ is_pad[:available] = False
113
+ qpos = (qpos - self.stats.qpos_mean) / self.stats.qpos_std
114
+ actions = (actions - self.stats.action_mean) / self.stats.action_std
115
+ return (
116
+ self.torch.from_numpy(qpos).float(),
117
+ self.torch.from_numpy(images).float(),
118
+ self.torch.from_numpy(actions).float(),
119
+ self.torch.from_numpy(is_pad),
120
+ )
121
+
122
+
123
+ def frame_sampling_weights(dataset: RoboMimicACTDataset, demo_ids: Sequence[str], probabilities: Sequence[np.ndarray]) -> np.ndarray:
124
+ by_demo = {demo_id: np.asarray(values, dtype=np.float64) for demo_id, values in zip(demo_ids, probabilities)}
125
+ weights = []
126
+ for demo_id, length in zip(dataset.demo_ids, dataset.lengths):
127
+ if demo_id not in by_demo or len(by_demo[demo_id]) != length:
128
+ raise ValueError(f"Sampling cache does not match {demo_id}")
129
+ weights.append(by_demo[demo_id])
130
+ flat = np.concatenate(weights)
131
+ return flat / flat.sum()
.rsi/laneB/hpace/act_preprocessing.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single source of truth for ACT image preprocessing.
2
+
3
+ Official ACT feeds the policy image/255.0 in both training (third_party/act/utils.py)
4
+ and rollout (imitate_episodes.py); there is no ImageNet mean/std normalisation in the
5
+ reference implementation. Training and evaluation must call this one function so the
6
+ policy never sees a different input distribution than it was trained on.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+
12
+
13
+ def policy_images(images: np.ndarray) -> np.ndarray:
14
+ """Convert uint8 (..., H, W, C) frames to float32 (..., C, H, W) in [0, 1]."""
15
+ array = np.asarray(images, dtype=np.float32)
16
+ if array.size and float(array.max()) > 1.0:
17
+ array = array / 255.0
18
+ return np.ascontiguousarray(np.moveaxis(array, -1, -3))
.rsi/laneB/hpace/act_trainer.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shlex
5
+ import subprocess
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Mapping, Sequence
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class ACTTrainingResult:
13
+ best_checkpoint: Path
14
+ last_checkpoint: Path
15
+
16
+
17
+ class ACTCommandTrainer:
18
+ """Run a real ACT entry point while enforcing HiPACE checkpoint policy.
19
+
20
+ The command receives HIPACE_DATASET, HIPACE_WEIGHTS, HIPACE_OUTPUT_DIR,
21
+ HIPACE_SEED, and HIPACE_EPOCHS. This avoids pretending that robomimic has
22
+ an ACTTrainer API; adapters can target the official ACT repository or a
23
+ local RoboMimic-compatible ACT implementation.
24
+ """
25
+
26
+ def __init__(self, command: str | Sequence[str]):
27
+ self.command = shlex.split(command) if isinstance(command, str) else list(command)
28
+ if not self.command:
29
+ raise ValueError("ACT training command cannot be empty")
30
+
31
+ def train(
32
+ self,
33
+ dataset: str | Path,
34
+ weights: str | Path,
35
+ output_dir: str | Path,
36
+ seed: int,
37
+ epochs: int,
38
+ extra_env: Mapping[str, str] | None = None,
39
+ ) -> ACTTrainingResult:
40
+ output = Path(output_dir)
41
+ output.mkdir(parents=True, exist_ok=True)
42
+ env = os.environ.copy()
43
+ env.update(
44
+ HIPACE_DATASET=str(Path(dataset).resolve()),
45
+ HIPACE_WEIGHTS=str(Path(weights).resolve()),
46
+ HIPACE_OUTPUT_DIR=str(output.resolve()),
47
+ HIPACE_SEED=str(seed),
48
+ HIPACE_EPOCHS=str(epochs),
49
+ )
50
+ env.update(extra_env or {})
51
+ subprocess.run(self.command, check=True, env=env)
52
+ best, last = output / "best.ckpt", output / "last.ckpt"
53
+ missing = [str(path) for path in (best, last) if not path.is_file()]
54
+ if missing:
55
+ raise RuntimeError(f"ACT command did not create required checkpoints: {missing}")
56
+ extras = sorted(path for path in output.glob("*.ckpt") if path not in {best, last})
57
+ if extras:
58
+ raise RuntimeError(f"Checkpoint policy violation; remove intermediate checkpoints: {extras}")
59
+ return ACTTrainingResult(best, last)
60
+
.rsi/laneB/hpace/config.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from copy import deepcopy
4
+ from pathlib import Path
5
+ from typing import Any, Mapping
6
+
7
+ import yaml
8
+
9
+
10
+ def _merge(base: dict[str, Any], override: Mapping[str, Any]) -> dict[str, Any]:
11
+ for key, value in override.items():
12
+ if isinstance(value, Mapping) and isinstance(base.get(key), dict):
13
+ _merge(base[key], value)
14
+ else:
15
+ base[key] = value
16
+ return base
17
+
18
+
19
+ def load_config(path: str | Path = "configs/default.yaml", overrides: Mapping[str, Any] | None = None) -> dict[str, Any]:
20
+ with Path(path).open("r", encoding="utf-8") as handle:
21
+ config = yaml.safe_load(handle)
22
+ if not isinstance(config, dict):
23
+ raise ValueError(f"Configuration must be a mapping: {path}")
24
+ return _merge(deepcopy(config), overrides or {})
25
+
26
+
27
+ def ensure_directories(config: Mapping[str, Any]) -> None:
28
+ paths = config["paths"]
29
+ for key in ("cache_dir", "checkpoint_dir", "results_dir", "videos_dir"):
30
+ Path(paths[key]).mkdir(parents=True, exist_ok=True)
31
+
.rsi/laneB/hpace/data_loader.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import pickle
4
+ import re
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Callable, Iterable
8
+
9
+ import h5py
10
+ import numpy as np
11
+
12
+
13
+ ProgressProvider = Callable[[str, np.ndarray], np.ndarray]
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class SegmentedTrajectory:
18
+ demo_id: str
19
+ length: int
20
+ valid_phases: tuple[int, ...]
21
+ phase_label: np.ndarray
22
+ progress_raw: np.ndarray
23
+
24
+
25
+ def _natural_demo_key(name: str) -> tuple[int, str]:
26
+ match = re.search(r"(\d+)$", name)
27
+ return (int(match.group(1)) if match else 2**31, name)
28
+
29
+
30
+ def get_demo_ids(hdf5: h5py.File) -> list[str]:
31
+ if "data" not in hdf5:
32
+ raise KeyError("RoboMimic HDF5 must contain a 'data' group")
33
+ return sorted(hdf5["data"].keys(), key=_natural_demo_key)
34
+
35
+
36
+ def smooth_progress(progress: np.ndarray, window: int = 5) -> np.ndarray:
37
+ values = np.asarray(progress, dtype=np.float32).reshape(-1)
38
+ if values.size == 0:
39
+ raise ValueError("Progress sequence cannot be empty")
40
+ if not np.isfinite(values).all():
41
+ raise ValueError("Progress sequence contains non-finite values")
42
+ if window < 1:
43
+ raise ValueError("Smoothing window must be positive")
44
+ width = min(window, values.size)
45
+ kernel = np.ones(width, dtype=np.float32)
46
+ count = np.convolve(np.ones_like(values), kernel, mode="same")
47
+ return np.clip(np.convolve(values, kernel, mode="same") / count, 0.0, 1.0)
48
+
49
+
50
+ def segment_progress(progress: np.ndarray) -> tuple[np.ndarray, tuple[int, ...]]:
51
+ values = np.clip(np.asarray(progress, dtype=np.float32).reshape(-1), 0.0, 1.0)
52
+ labels = np.minimum((values * 4).astype(np.int8), 3)
53
+ max_progress = float(values.max())
54
+ n_valid = 1 + int(max_progress >= 0.25) + int(max_progress >= 0.5) + int(max_progress >= 0.75)
55
+ return labels, tuple(range(n_valid))
56
+
57
+
58
+ def segment_dataset(
59
+ hdf5_path: str | Path,
60
+ progress_provider: ProgressProvider,
61
+ output_path: str | Path,
62
+ image_key: str = "agentview_image",
63
+ window: int = 5,
64
+ ) -> list[SegmentedTrajectory]:
65
+ trajectories: list[SegmentedTrajectory] = []
66
+ with h5py.File(hdf5_path, "r") as dataset:
67
+ for demo_id in get_demo_ids(dataset):
68
+ obs = dataset[f"data/{demo_id}/obs"]
69
+ if image_key not in obs:
70
+ raise KeyError(f"Missing data/{demo_id}/obs/{image_key}")
71
+ images = obs[image_key][:]
72
+ progress = smooth_progress(progress_provider(demo_id, images), window)
73
+ if len(progress) != len(images):
74
+ raise ValueError(f"Progress length mismatch for {demo_id}: {len(progress)} != {len(images)}")
75
+ labels, valid = segment_progress(progress)
76
+ trajectories.append(SegmentedTrajectory(demo_id, len(images), valid, labels, progress))
77
+ target = Path(output_path)
78
+ target.parent.mkdir(parents=True, exist_ok=True)
79
+ with target.open("wb") as handle:
80
+ pickle.dump(trajectories, handle, protocol=pickle.HIGHEST_PROTOCOL)
81
+ return trajectories
82
+
83
+
84
+ def load_segmented(path: str | Path) -> list[SegmentedTrajectory]:
85
+ with Path(path).open("rb") as handle:
86
+ value = pickle.load(handle)
87
+ if not isinstance(value, list) or not all(isinstance(item, SegmentedTrajectory) for item in value):
88
+ raise ValueError(f"Invalid segmented trajectory cache: {path}")
89
+ return value
90
+
91
+
92
+ class NPZProgressProvider:
93
+ """Read explicit per-frame progress arrays without inventing missing SCIZOR scores."""
94
+
95
+ def __init__(self, path: str | Path):
96
+ self._scores = np.load(path, allow_pickle=False)
97
+
98
+ def __call__(self, demo_id: str, images: np.ndarray) -> np.ndarray:
99
+ if demo_id not in self._scores:
100
+ raise KeyError(f"No progress scores for {demo_id}")
101
+ return np.asarray(self._scores[demo_id], dtype=np.float32)
102
+
.rsi/laneB/hpace/experiments.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Mapping, Sequence
5
+
6
+ import numpy as np
7
+
8
+ from .value_fusion import fuse_values, stable_softmax
9
+
10
+
11
+ def _unpack_frames(cache) -> list[np.ndarray]:
12
+ weights = cache["frame_weights"]
13
+ offsets = cache["frame_weight_offsets"]
14
+ return [weights[offsets[i] : offsets[i + 1]] for i in range(len(offsets) - 1)]
15
+
16
+
17
+ def save_weight_cache(path: str | Path, demo_ids: Sequence[str], trajectory_probabilities: np.ndarray, frame_weights: Sequence[np.ndarray]) -> Path:
18
+ trajectory = np.asarray(trajectory_probabilities, dtype=np.float64)
19
+ trajectory /= trajectory.sum()
20
+ frames = []
21
+ for probability, weights in zip(trajectory, frame_weights):
22
+ weights = np.asarray(weights, dtype=np.float64)
23
+ frames.append(probability * weights / weights.sum())
24
+ offsets = np.concatenate(([0], np.cumsum([len(item) for item in frames])))
25
+ target = Path(path)
26
+ target.parent.mkdir(parents=True, exist_ok=True)
27
+ np.savez_compressed(
28
+ target,
29
+ demo_ids=np.asarray(demo_ids),
30
+ trajectory_probabilities=trajectory,
31
+ frame_probabilities=np.concatenate(frames),
32
+ frame_probability_offsets=offsets,
33
+ )
34
+ return target
35
+
36
+
37
+ def generate_baseline_weights(quality_path: str | Path, full_scores_path: str | Path, output_dir: str | Path, temperature: float = 0.5, seed: int = 42) -> dict[str, Path]:
38
+ quality = np.load(quality_path, allow_pickle=False)
39
+ scores = np.load(full_scores_path, allow_pickle=False)
40
+ demo_ids = quality["demo_ids"]
41
+ all_frames = _unpack_frames(quality)
42
+ candidate = scores["candidate_idx"].astype(int)
43
+ candidate_ids = demo_ids[candidate]
44
+ candidate_frames = [all_frames[index] for index in candidate]
45
+ output = Path(output_dir)
46
+ result = {
47
+ "full": save_weight_cache(output / "full.npz", demo_ids, np.ones(len(demo_ids)), [np.ones_like(item) for item in all_frames]),
48
+ }
49
+ rng = np.random.default_rng(seed)
50
+ random_indices = np.sort(rng.choice(len(demo_ids), len(candidate), replace=False))
51
+ result["random"] = save_weight_cache(output / "random.npz", demo_ids[random_indices], np.ones(len(candidate)), [np.ones_like(all_frames[index]) for index in random_indices])
52
+ # SCIZOR's own curation keeps the demonstrations it scores as least
53
+ # suboptimal; use the progress score itself rather than HiPACE's fused
54
+ # q_quality, which already includes the frame/redundancy terms.
55
+ progress_all = np.asarray(quality["progress_score"], dtype=np.float64)
56
+ progress_candidates = progress_all[candidate]
57
+ result["scizor"] = save_weight_cache(output / "scizor.npz", candidate_ids, stable_softmax(progress_candidates, temperature), candidate_frames)
58
+ result["qoq"] = save_weight_cache(output / "qoq.npz", candidate_ids, stable_softmax(scores["q_policy"], temperature), candidate_frames)
59
+ result["cupid"] = save_weight_cache(output / "cupid.npz", candidate_ids, stable_softmax(scores["q_perf"], temperature), candidate_frames)
60
+ return result
61
+
62
+
63
+ def generate_ablation_weights(
64
+ mode: str,
65
+ quality_path: str | Path,
66
+ scores_path: str | Path,
67
+ embeddings_path: str | Path,
68
+ output_path: str | Path,
69
+ fusion_cfg: Mapping[str, float],
70
+ ) -> Path:
71
+ def load_embedding_cache(path):
72
+ """Accept either one npz or a directory of per-demo .npy files."""
73
+ source = Path(path)
74
+ if source.is_dir():
75
+ files = sorted(source.glob("*.npy"))
76
+ if not files:
77
+ raise ValueError(f"embedding directory contains no .npy files: {source}")
78
+ return {item.stem: np.load(item, mmap_mode="r", allow_pickle=False) for item in files}
79
+ data = np.load(source, allow_pickle=False)
80
+ return {key: np.asarray(data[key], dtype=np.float32) for key in data.files}
81
+
82
+ quality = np.load(quality_path, allow_pickle=False)
83
+ scores = np.load(scores_path, allow_pickle=False)
84
+ embeddings = load_embedding_cache(embeddings_path)
85
+ candidate = scores["candidate_idx"].astype(int)
86
+ demo_ids = quality["demo_ids"][candidate]
87
+ all_frames = _unpack_frames(quality)
88
+ frame_weights = [all_frames[index] for index in candidate]
89
+ trajectory_embeddings = np.stack([embeddings[str(demo_id)].mean(axis=0) for demo_id in demo_ids])
90
+ q_quality = np.asarray(scores["q_quality"], dtype=np.float32)
91
+ if mode == "no-routing" and "is_expensive" in scores and not np.asarray(scores["is_expensive"]).all():
92
+ raise ValueError("no-routing requires a score cache computed expensively for every candidate")
93
+ if mode == "no-dynamic":
94
+ q_policy = np.clip(0.4 * q_quality, 0, 1)
95
+ q_perf = np.clip(0.3 * q_quality, 0, 1)
96
+ else:
97
+ q_policy = np.asarray(scores["q_policy"], dtype=np.float32)
98
+ q_perf = np.asarray(scores["q_perf"], dtype=np.float32)
99
+ fusion = fuse_values(q_quality, q_policy, q_perf, trajectory_embeddings, frame_weights, fusion_cfg, include_diversity=mode != "no-diversity")
100
+ return save_weight_cache(output_path, demo_ids, fusion.trajectory_probabilities, frame_weights)
.rsi/laneB/hpace/influence_scorer.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Iterable, Mapping, Sequence
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+
8
+
9
+ def minmax(values: Sequence[float]) -> np.ndarray:
10
+ array = np.asarray(values, dtype=np.float64)
11
+ if not np.isfinite(array).all():
12
+ raise ValueError("Influence scores contain non-finite values")
13
+ low, high = float(array.min()), float(array.max())
14
+ if high == low:
15
+ return np.full(array.shape, 0.5, dtype=np.float32)
16
+ return ((array - low) / (high - low)).astype(np.float32)
17
+
18
+
19
+ def cosine_similarity_max(gradient: Any, references: Sequence[Any]) -> float:
20
+ import torch
21
+
22
+ if not references:
23
+ raise ValueError("At least one reference gradient is required")
24
+ vector = gradient.detach().flatten()
25
+ scores = [torch.nn.functional.cosine_similarity(vector, item.detach().flatten(), dim=0) for item in references]
26
+ return float(torch.stack(scores).max().cpu())
27
+
28
+
29
+ def select_action_head_parameters(model: Any, last_n_tensors: int = 4) -> list[Any]:
30
+ named = [(name, parameter) for name, parameter in model.named_parameters() if parameter.requires_grad]
31
+ preferred = [parameter for name, parameter in named if any(token in name.lower() for token in ("action_head", "action_proj", "output"))]
32
+ selected = preferred if preferred else [parameter for _, parameter in named[-last_n_tensors:]]
33
+ if not selected:
34
+ raise ValueError("Model has no trainable parameters")
35
+ return selected
36
+
37
+
38
+ def compute_per_sample_gradient(model: Any, sample: Any, loss_fn: Callable[[Any, Any], Any], parameters: Sequence[Any] | None = None) -> Any:
39
+ """Compute a flattened gradient without taking an optimizer step."""
40
+ import torch
41
+
42
+ params = list(parameters or select_action_head_parameters(model))
43
+ model.zero_grad(set_to_none=True)
44
+ loss = loss_fn(model, sample)
45
+ gradients = torch.autograd.grad(loss, params, retain_graph=False, create_graph=False, allow_unused=True)
46
+ flat = [torch.zeros_like(parameter).flatten() if gradient is None else gradient.detach().flatten() for parameter, gradient in zip(params, gradients)]
47
+ return torch.cat(flat)
48
+
49
+
50
+ def phase_matched_policy_score(sample_gradients: Mapping[int, Any], reference_gradients: Mapping[int, Sequence[Any]]) -> float:
51
+ scores = [cosine_similarity_max(gradient, reference_gradients[phase]) for phase, gradient in sample_gradients.items() if reference_gradients.get(phase)]
52
+ if not scores:
53
+ raise ValueError("Sample has no phase-matched reference gradient")
54
+ return float(np.clip((max(scores) + 1.0) / 2.0, 0.0, 1.0))
55
+
56
+
57
+ def kfold_performance_influence(
58
+ candidate_indices: Iterable[int],
59
+ evaluate_without: Callable[[int], float],
60
+ baseline_score: float,
61
+ ) -> dict[int, float]:
62
+ """Normalize leave-one-out performance deltas; policy updates live in the callback."""
63
+ indices = list(candidate_indices)
64
+ raw = np.asarray([baseline_score - evaluate_without(index) for index in indices], dtype=np.float64)
65
+ normalized = minmax(raw)
66
+ return {index: float(score) for index, score in zip(indices, normalized)}
67
+
68
+
69
+ class PrecomputedInfluenceScorer:
70
+ """Strict adapter for expensive scores generated by QoQ/CUPID jobs."""
71
+
72
+ def __init__(self, path: str):
73
+ data = np.load(path, allow_pickle=False)
74
+ self.policy = np.asarray(data["q_policy"], dtype=np.float32)
75
+ self.performance = np.asarray(data["q_perf"], dtype=np.float32)
76
+
77
+ def __call__(self, index: int) -> tuple[float, float]:
78
+ return float(self.policy[index]), float(self.performance[index])
79
+
.rsi/laneB/hpace/manifest.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import platform
6
+ import subprocess
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Mapping, Sequence
10
+
11
+
12
+ def sha256_file(path: str | Path, chunk_size: int = 1024 * 1024) -> str:
13
+ digest = hashlib.sha256()
14
+ with Path(path).open("rb") as handle:
15
+ for chunk in iter(lambda: handle.read(chunk_size), b""):
16
+ digest.update(chunk)
17
+ return digest.hexdigest()
18
+
19
+
20
+ def collect_manifest(
21
+ task: str,
22
+ method: str,
23
+ seed: int,
24
+ dataset: str | Path,
25
+ command: Sequence[str],
26
+ artifacts: Mapping[str, str | Path] | None = None,
27
+ ) -> dict:
28
+ git_commit = "unknown"
29
+ try:
30
+ git_commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
31
+ except (OSError, subprocess.CalledProcessError):
32
+ pass
33
+ result = {
34
+ "task": task,
35
+ "method": method,
36
+ "seed": seed,
37
+ "dataset": str(Path(dataset).resolve()),
38
+ "dataset_sha256": sha256_file(dataset),
39
+ "command": list(command),
40
+ "git_commit": git_commit,
41
+ "python": platform.python_version(),
42
+ "platform": platform.platform(),
43
+ "created_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
44
+ "artifacts": {name: str(Path(path).resolve()) for name, path in (artifacts or {}).items()},
45
+ }
46
+ return result
47
+
48
+
49
+ def write_manifest(manifest: Mapping, path: str | Path) -> Path:
50
+ target = Path(path)
51
+ target.parent.mkdir(parents=True, exist_ok=True)
52
+ target.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
53
+ return target
54
+
.rsi/laneB/hpace/mjx_evaluator.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Mapping, Sequence
8
+
9
+ import numpy as np
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class SeedMetrics:
14
+ seed: int
15
+ success_rate: float
16
+ ood_success_rate: float | None
17
+ phase_success_rate: tuple[float, float, float, float]
18
+ gpu_hours: float = 0.0
19
+
20
+
21
+ def phase_failure_rates(
22
+ progress_sequences: Sequence[np.ndarray],
23
+ completed: Sequence[bool] | None = None,
24
+ ) -> dict[str, float]:
25
+ """Share of trajectories that reached a phase but did not finish it.
26
+
27
+ Phase ``p`` spans progress ``[p/4, (p+1)/4)``. A trajectory "reaches" phase p
28
+ when its maximum progress is at least ``p/4`` and "finishes" it at
29
+ ``(p+1)/4`` - except for the last phase, where reaching exactly 1.0 is both a
30
+ knife-edge and unreliable: the SCIZOR-derived proxy is not perfectly aligned
31
+ with task completion (rollouts have been observed at max progress 1.000
32
+ without the environment reporting success, and at 0.968 with it). Pass
33
+ ``completed`` - the environment's ground-truth success flag per rollout - to
34
+ use it for the final phase, which is the recommended usage.
35
+ """
36
+ if not progress_sequences:
37
+ raise ValueError("At least one rollout progress sequence is required")
38
+ maxima = np.asarray([np.clip(np.asarray(item, dtype=np.float32), 0.0, 1.0).max() for item in progress_sequences])
39
+ if completed is not None:
40
+ finished_all = np.asarray(completed, dtype=bool)
41
+ if len(finished_all) != len(maxima):
42
+ raise ValueError("completed flags must match the number of progress sequences")
43
+ else:
44
+ finished_all = None
45
+ result: dict[str, float] = {}
46
+ for phase in range(4):
47
+ lower = phase / 4.0
48
+ upper = (phase + 1) / 4.0
49
+ reached = maxima >= lower
50
+ if phase == 3 and finished_all is not None:
51
+ finished = finished_all
52
+ else:
53
+ finished = maxima >= upper
54
+ result[f"phase{phase}"] = float(1.0 - np.mean(finished[reached])) if reached.any() else 0.0
55
+ return result
56
+
57
+
58
+ def aggregate_metrics(metrics: Sequence[SeedMetrics]) -> dict[str, float]:
59
+ if not metrics:
60
+ raise ValueError("No seed metrics supplied")
61
+ success = np.asarray([item.success_rate for item in metrics])
62
+ ood_values = [item.ood_success_rate for item in metrics if item.ood_success_rate is not None]
63
+ output = {
64
+ "success_mean": float(success.mean()),
65
+ "success_std": float(success.std(ddof=1)) if len(success) > 1 else 0.0,
66
+ # Only emitted when at least one seed actually ran an OOD evaluation.
67
+ "ood_success_mean": float(np.mean(ood_values)) if ood_values else None,
68
+ "ood_success_std": float(np.std(ood_values, ddof=1)) if len(ood_values) > 1 else (0.0 if ood_values else None),
69
+ "n_seeds_with_ood": len(ood_values),
70
+ "gpu_hours": float(sum(item.gpu_hours for item in metrics)),
71
+ }
72
+ phase_values = np.asarray([item.phase_success_rate for item in metrics])
73
+ for phase in range(4):
74
+ output[f"phase{phase}_success_mean"] = float(phase_values[:, phase].mean())
75
+ output[f"phase{phase}_success_std"] = float(phase_values[:, phase].std(ddof=1)) if len(metrics) > 1 else 0.0
76
+ return output
77
+
78
+
79
+ def load_seed_metrics(path: str | Path) -> SeedMetrics:
80
+ with Path(path).open("r", encoding="utf-8") as handle:
81
+ value = json.load(handle)
82
+ return SeedMetrics(
83
+ seed=int(value["seed"]),
84
+ success_rate=float(value["success_rate"]),
85
+ ood_success_rate=float(value["ood_success_rate"]),
86
+ phase_success_rate=tuple(float(value[f"phase{index}_success_rate"]) for index in range(4)),
87
+ gpu_hours=float(value.get("gpu_hours", 0.0)),
88
+ )
89
+
90
+
91
+ def write_metrics_csv(rows: Sequence[Mapping[str, object]], path: str | Path) -> None:
92
+ if not rows:
93
+ raise ValueError("No metrics rows supplied")
94
+ target = Path(path)
95
+ target.parent.mkdir(parents=True, exist_ok=True)
96
+ fields = list(rows[0].keys())
97
+ with target.open("w", encoding="utf-8", newline="") as handle:
98
+ writer = csv.DictWriter(handle, fieldnames=fields)
99
+ writer.writeheader()
100
+ writer.writerows(rows)
101
+
102
+
103
+ def require_mjx_model_compatibility(model) -> None:
104
+ """Fail early when a MuJoCo model uses callbacks unsupported by MJX."""
105
+ try:
106
+ from mujoco import mjx
107
+ mjx.put_model(model)
108
+ except Exception as exc:
109
+ raise RuntimeError(
110
+ "This environment cannot be converted to MJX. RoboMimic tasks are "
111
+ "robosuite environments and require a dedicated pure-MuJoCo/MJX port."
112
+ ) from exc
.rsi/laneB/hpace/pipeline.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Mapping
6
+
7
+ import numpy as np
8
+
9
+ from .config import ensure_directories
10
+ from .data_loader import NPZProgressProvider, segment_dataset
11
+ from .influence_scorer import PrecomputedInfluenceScorer, minmax
12
+ from .router import route_and_score
13
+ from .scizor_scorer import score_quality
14
+ from .value_fusion import fuse_values
15
+ from .resources import enforce_disk_budget
16
+
17
+
18
+ def load_embeddings(path: str | Path) -> dict[str, np.ndarray]:
19
+ source = Path(path)
20
+ if source.is_dir():
21
+ files = sorted(source.glob("*.npy"))
22
+ if not files:
23
+ raise ValueError(f"Embedding directory contains no .npy files: {source}")
24
+ return {item.stem: np.load(item, mmap_mode="r", allow_pickle=False) for item in files}
25
+ data = np.load(source, allow_pickle=False)
26
+ return {key: np.asarray(data[key], dtype=np.float32) for key in data.files}
27
+
28
+
29
+ def run_curation(
30
+ dataset_path: str | Path,
31
+ progress_path: str | Path,
32
+ embeddings_path: str | Path,
33
+ fail_rates_path: str | Path,
34
+ expensive_scores_path: str | Path,
35
+ config: Mapping,
36
+ ) -> Path:
37
+ ensure_directories(config)
38
+ budget_paths = [config["paths"][key] for key in ("data_root", "cache_dir", "checkpoint_dir", "results_dir", "videos_dir")]
39
+ enforce_disk_budget(budget_paths, config["resources"]["max_disk_gb"])
40
+ quality, segmented, embeddings = prepare_quality(dataset_path, progress_path, embeddings_path, config)
41
+ cache = Path(config["paths"]["cache_dir"])
42
+ candidate = quality.candidate_indices
43
+ candidate_quality = minmax(quality.q_quality[candidate])
44
+ with Path(fail_rates_path).open("r", encoding="utf-8") as handle:
45
+ fail_rates = json.load(handle)
46
+ scorer = PrecomputedInfluenceScorer(str(expensive_scores_path))
47
+ routed = route_and_score(
48
+ candidate_quality,
49
+ [segmented[index].valid_phases for index in candidate],
50
+ fail_rates,
51
+ scorer,
52
+ config["routing"],
53
+ [phase_frame_shares(segmented[index]) for index in candidate],
54
+ )
55
+ np.savez_compressed(
56
+ cache / "full_scores.npz",
57
+ candidate_idx=candidate,
58
+ q_quality=candidate_quality,
59
+ q_policy=routed.q_policy,
60
+ q_perf=routed.q_perf,
61
+ is_expensive=routed.is_expensive,
62
+ )
63
+ trajectory_embeddings = np.stack([embeddings[quality.demo_ids[index]].mean(axis=0) for index in candidate])
64
+ fusion = fuse_values(
65
+ candidate_quality,
66
+ routed.q_policy,
67
+ routed.q_perf,
68
+ trajectory_embeddings,
69
+ [quality.frame_weights[index] for index in candidate],
70
+ config["fusion"],
71
+ )
72
+ weights_path = cache / "sample_weights.npz"
73
+ offsets = np.concatenate(([0], np.cumsum([len(item) for item in fusion.frame_probabilities])))
74
+ np.savez_compressed(
75
+ weights_path,
76
+ demo_ids=np.asarray([quality.demo_ids[index] for index in candidate]),
77
+ trajectory_probabilities=fusion.trajectory_probabilities,
78
+ frame_probabilities=np.concatenate(fusion.frame_probabilities),
79
+ frame_probability_offsets=offsets,
80
+ values=fusion.values,
81
+ cluster_labels=fusion.cluster_labels,
82
+ diversity_bonus=fusion.diversity_bonus,
83
+ )
84
+ enforce_disk_budget(budget_paths, config["resources"]["max_disk_gb"])
85
+ return weights_path
86
+
87
+
88
+ def prepare_quality(
89
+ dataset_path: str | Path,
90
+ progress_path: str | Path,
91
+ embeddings_path: str | Path,
92
+ config: Mapping,
93
+ ):
94
+ """Segmentation + static quality. Runs before any expensive score exists."""
95
+ ensure_directories(config)
96
+ cache = Path(config["paths"]["cache_dir"])
97
+ segmented = segment_dataset(
98
+ dataset_path,
99
+ NPZProgressProvider(progress_path),
100
+ cache / "trajectories_segmented.pkl",
101
+ config["data"]["image_key"],
102
+ config["data"]["progress_window"],
103
+ )
104
+ embeddings = load_embeddings(embeddings_path)
105
+ quality = score_quality(
106
+ dataset_path,
107
+ segmented,
108
+ embeddings,
109
+ config["quality"],
110
+ cache / "q_quality_scores.npz",
111
+ config["data"]["action_key"],
112
+ )
113
+ return quality, segmented, embeddings
114
+
115
+
116
+ def phase_frame_shares(trajectory) -> np.ndarray:
117
+ """Fraction of a trajectory's frames that sit in each phase."""
118
+ counts = np.bincount(np.asarray(trajectory.phase_label).astype(int), minlength=4)
119
+ return counts / max(int(counts.sum()), 1)
.rsi/laneB/hpace/provenance.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Curations-generation guard for grid summaries.
2
+
3
+ Runs record ``curation_provenance.json`` (weights / fail-rates / manifest hashes)
4
+ when training starts. Summaries must refuse to merge runs from different
5
+ generations instead of quietly averaging them, which is how audit 5.6 happened.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+
12
+
13
+ def load_provenance(run_dir: str | Path) -> dict | None:
14
+ path = Path(run_dir) / "curation_provenance.json"
15
+ if not path.exists():
16
+ return None
17
+ return json.loads(path.read_text(encoding="utf-8"))
18
+
19
+
20
+ def generation_key(provenance: dict | None) -> tuple | None:
21
+ if not provenance:
22
+ return None
23
+ # Key on the sampling weights the run actually consumed. Including the curation
24
+ # manifest would flag runs as different generations whenever any curation file
25
+ # is regenerated, even if this run's input (its weights file) is byte-identical -
26
+ # e.g. the Phase-C pools, which never read fail rates.
27
+ return (provenance.get("weights_sha256"),)
28
+
29
+
30
+ def check_single_generation(runs: list[tuple[str, dict | None]]) -> dict:
31
+ """Raise when the given runs span more than one curation generation.
32
+
33
+ ``runs`` is a list of ``(label, provenance)`` pairs. Runs without provenance
34
+ are reported but tolerated (they predate the guard).
35
+ """
36
+ generations: dict[tuple, list[str]] = {}
37
+ missing: list[str] = []
38
+ for label, provenance in runs:
39
+ key = generation_key(provenance)
40
+ if key is None:
41
+ missing.append(label)
42
+ continue
43
+ generations.setdefault(key, []).append(label)
44
+ if len(generations) > 1:
45
+ summary = {str(key): labels for key, labels in generations.items()}
46
+ raise RuntimeError(
47
+ "refusing to merge runs from different curation generations: "
48
+ + json.dumps(summary, indent=2)
49
+ )
50
+ return {
51
+ "generations": len(generations),
52
+ "runs_without_provenance": missing,
53
+ "key": next(iter(generations), None),
54
+ }
.rsi/laneB/hpace/resources.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+
6
+ def directory_size_bytes(path: str | Path) -> int:
7
+ root = Path(path)
8
+ return sum(item.stat().st_size for item in root.rglob("*") if item.is_file()) if root.exists() else 0
9
+
10
+
11
+ def enforce_disk_budget(paths: list[str | Path], max_gb: float) -> None:
12
+ used = sum(directory_size_bytes(path) for path in paths)
13
+ limit = int(max_gb * 1024**3)
14
+ if used > limit:
15
+ raise RuntimeError(f"HiPACE disk budget exceeded: {used / 1024**3:.2f} GiB > {max_gb:.2f} GiB")
16
+
.rsi/laneB/hpace/results.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Iterable, Mapping, Sequence
8
+
9
+ import numpy as np
10
+
11
+ from .mjx_evaluator import SeedMetrics, aggregate_metrics, write_metrics_csv
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class EpisodeResult:
16
+ success: bool
17
+ ood_success: bool | None
18
+ phase_success: tuple[bool, bool, bool, bool]
19
+ elapsed_seconds: float = 0.0
20
+
21
+
22
+ def load_episode_results(path: str | Path) -> list[EpisodeResult]:
23
+ records = []
24
+ lines = [line for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]
25
+ for line_number, line in enumerate(lines, 1):
26
+ try:
27
+ item = json.loads(line)
28
+ except json.JSONDecodeError:
29
+ # A still-running evaluation can leave a torn final line; ignore only that.
30
+ if line_number == len(lines):
31
+ break
32
+ raise ValueError(f"Invalid episode JSON at {path}:{line_number}") from None
33
+ try:
34
+ records.append(
35
+ EpisodeResult(
36
+ bool(item["success"]),
37
+ # None means "this run did not measure OOD"; reporting it as
38
+ # False would fabricate a 0.0 OOD column in the tables.
39
+ None if "ood_success" not in item else bool(item["ood_success"]),
40
+ tuple(bool(item[f"phase{index}_success"]) for index in range(4)),
41
+ float(item.get("elapsed_seconds", 0.0)),
42
+ )
43
+ )
44
+ except (KeyError, TypeError, ValueError) as exc:
45
+ raise ValueError(f"Invalid episode JSON at {path}:{line_number}") from exc
46
+ if not records:
47
+ raise ValueError(f"No episode records in {path}")
48
+ return records
49
+
50
+
51
+ def summarize_seed(path: str | Path, seed: int | None = None, gpu_hours: float = 0.0) -> SeedMetrics:
52
+ records = load_episode_results(path)
53
+ phase = np.asarray([item.phase_success for item in records], dtype=np.float32)
54
+ ood_values = [item.ood_success for item in records if item.ood_success is not None]
55
+ return SeedMetrics(
56
+ seed=int(seed if seed is not None else seed_from_path(path)),
57
+ success_rate=float(np.mean([item.success for item in records])),
58
+ ood_success_rate=float(np.mean(ood_values)) if ood_values else None,
59
+ phase_success_rate=tuple(float(value) for value in phase.mean(axis=0)),
60
+ gpu_hours=float(gpu_hours),
61
+ )
62
+
63
+
64
+ def seed_from_path(path: str | Path) -> int:
65
+ """Recover the seed from either `..._seed42/episodes.jsonl` or `episodes_42.jsonl`."""
66
+ for part in (Path(path).parent.name, Path(path).stem):
67
+ match = re.search(r"seed[_=-]?(\d+)", part) or re.search(r"(\d+)$", part)
68
+ if match:
69
+ return int(match.group(1))
70
+ return 0
71
+
72
+
73
+ def summarize_method(method: str, seed_files: Sequence[str | Path], output: str | Path, gpu_hours: Sequence[float] | None = None) -> dict[str, object]:
74
+ hours = list(gpu_hours or [0.0] * len(seed_files))
75
+ if len(hours) != len(seed_files):
76
+ raise ValueError("gpu_hours must have one entry per seed file")
77
+ metrics = [summarize_seed(path, gpu_hours=hour) for path, hour in zip(seed_files, hours)]
78
+ row = {"method": method, **aggregate_metrics(metrics), "n_seeds": len(metrics), "n_episodes_per_seed": len(load_episode_results(seed_files[0]))}
79
+ write_metrics_csv([row], output)
80
+ return row
81
+
82
+
83
+ def validate_episode_count(paths: Iterable[str | Path], expected: int) -> None:
84
+ for path in paths:
85
+ actual = len(load_episode_results(path))
86
+ if actual != expected:
87
+ raise ValueError(f"{path} contains {actual} episodes; expected exactly {expected}")
.rsi/laneB/hpace/router.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Callable, Mapping, Sequence
5
+
6
+ import numpy as np
7
+
8
+
9
+ ExpensiveScorer = Callable[[int], tuple[float, float]]
10
+
11
+
12
+ def weak_phase_value(phase_frame_share: Sequence[Sequence[float]], phase_fail_rate: Mapping[str, float]) -> np.ndarray:
13
+ """Per-candidate value of its data for the phases the policy fails.
14
+
15
+ ``score_i = sum_p fail_rate(p) * frame_share_i(p)``
16
+
17
+ This replaces the previous binary "does this trajectory touch a weak phase"
18
+ test (constant on pools of complete demonstrations) and the constant fast-path
19
+ mapping (0.4 / 0.3 x q_quality), which made HiPACE's weights a monotone
20
+ transform of static quality whenever the expensive queue was small.
21
+ """
22
+ fail = np.asarray([float(phase_fail_rate.get(f"phase{phase}", 0.0)) for phase in range(4)], dtype=np.float64)
23
+ shares = np.asarray(phase_frame_share, dtype=np.float64)
24
+ if shares.ndim != 2 or shares.shape[1] != 4:
25
+ raise ValueError("phase_frame_share must be (n_candidates, 4)")
26
+ return np.clip(shares @ fail, 0.0, 1.0)
27
+
28
+
29
+ def rank_by_value(values: np.ndarray, budget: float) -> np.ndarray:
30
+ """Top-``budget`` share of candidates by value (deterministic tie-breaking)."""
31
+ if not 0.0 <= budget <= 1.0:
32
+ raise ValueError("budget must be in [0, 1]")
33
+ count = int(np.ceil(len(values) * budget))
34
+ mask = np.zeros(len(values), dtype=bool)
35
+ if count:
36
+ mask[np.argsort(np.asarray(values), kind="stable")[-count:]] = True
37
+ return mask
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class RoutingResult:
42
+ q_policy: np.ndarray
43
+ q_perf: np.ndarray
44
+ is_expensive: np.ndarray
45
+
46
+
47
+ def build_expensive_mask(
48
+ q_quality: np.ndarray,
49
+ valid_phases: Sequence[Sequence[int]],
50
+ phase_fail_rate: Mapping[str, float],
51
+ quality_top_ratio: float = 0.5,
52
+ phase_fail_threshold: float = 0.3,
53
+ phase_frame_share: Sequence[Sequence[float]] | None = None,
54
+ min_weak_phase_share: float = 0.0,
55
+ relative_fail_factor: float | None = None,
56
+ ) -> np.ndarray:
57
+ """Which candidates are worth the expensive scorer.
58
+
59
+ Two conditions must hold: the candidate is in the top ``quality_top_ratio`` by
60
+ static quality, and it covers enough data in a phase the current policy fails.
61
+
62
+ The coverage test exists because a "does this trajectory contain a weak phase"
63
+ test is constant on pools of complete demonstrations: every demonstration spans
64
+ every phase, so the condition was either always true (Can/Square) or never true
65
+ (Lift) and the routing degenerated into a quality-percentile cut. Passing
66
+ ``phase_frame_share`` (the fraction of each candidate's frames per phase) with a
67
+ positive ``min_weak_phase_share`` makes the condition depend on how much of the
68
+ trajectory actually sits in the weak phase, which does vary across candidates.
69
+ """
70
+ quality = np.asarray(q_quality, dtype=np.float32)
71
+ if len(quality) != len(valid_phases):
72
+ raise ValueError("Quality scores and phase metadata have different lengths")
73
+ if not 0.0 <= quality_top_ratio <= 1.0:
74
+ raise ValueError("quality_top_ratio must be in [0, 1]")
75
+ top_count = int(np.ceil(len(quality) * quality_top_ratio))
76
+ high_quality = np.zeros(len(quality), dtype=bool)
77
+ if top_count:
78
+ high_quality[np.argsort(quality, kind="stable")[-top_count:]] = True
79
+ # Which phases count as "weak"? An absolute threshold interacts badly with the
80
+ # number of rollouts and with how many phases happen to sit near the cutoff
81
+ # (with sub-goal rates 0.37/0.26/0.07/0.00 a fixed 0.3 left only phase 0, whose
82
+ # frame share is nearly constant across demonstrations, so the condition became
83
+ # constant again). A scale-free rule - weak if the failure rate is at least
84
+ # ``relative_fail_factor`` of the worst phase - keeps the weak set meaningful.
85
+ fail_values = {phase: float(phase_fail_rate.get(f"phase{phase}", 0.0)) for phase in range(4)}
86
+ if relative_fail_factor is not None and max(fail_values.values(), default=0.0) > 0:
87
+ cutoff = relative_fail_factor * max(fail_values.values())
88
+ else:
89
+ cutoff = phase_fail_threshold
90
+
91
+ weak_phase = np.zeros(len(quality), dtype=bool)
92
+ for index, phases in enumerate(valid_phases):
93
+ weak = [phase for phase in phases if fail_values.get(phase, 0.0) >= cutoff > 0.0]
94
+ if not weak:
95
+ continue
96
+ if phase_frame_share is None:
97
+ weak_phase[index] = True
98
+ continue
99
+ share = float(np.sum([phase_frame_share[index][phase] for phase in weak]))
100
+ weak_phase[index] = share >= min_weak_phase_share
101
+ return high_quality & weak_phase
102
+
103
+
104
+ def route_and_score(
105
+ q_quality: np.ndarray,
106
+ valid_phases: Sequence[Sequence[int]],
107
+ phase_fail_rate: Mapping[str, float],
108
+ expensive_scorer: ExpensiveScorer,
109
+ routing_cfg: Mapping[str, float],
110
+ phase_frame_share: Sequence[Sequence[float]] | None = None,
111
+ ) -> RoutingResult:
112
+ quality = np.asarray(q_quality, dtype=np.float32)
113
+ selection = str(routing_cfg.get("selection", "phase_value"))
114
+ if selection == "phase_value":
115
+ if phase_frame_share is None:
116
+ raise ValueError("phase_value routing needs per-candidate phase frame shares")
117
+ # The policy's own failure rates define the value of a candidate's frames;
118
+ # the same score drives the expensive queue and the fast-path fallback, so
119
+ # the unmasked candidates are no longer a monotone transform of quality.
120
+ values = weak_phase_value(phase_frame_share, phase_fail_rate).astype(np.float32)
121
+ mask = rank_by_value(values, float(routing_cfg.get("expensive_budget", 0.3)))
122
+ policy = values.copy()
123
+ perf = values.copy()
124
+ else:
125
+ mask = build_expensive_mask(
126
+ quality,
127
+ valid_phases,
128
+ phase_fail_rate,
129
+ routing_cfg["quality_top_ratio"],
130
+ routing_cfg["phase_fail_threshold"],
131
+ phase_frame_share,
132
+ float(routing_cfg.get("min_weak_phase_share", 0.0)),
133
+ routing_cfg.get("relative_fail_factor"),
134
+ )
135
+ policy = np.clip(quality * routing_cfg["fast_policy_scale"], 0.0, 1.0)
136
+ perf = np.clip(quality * routing_cfg["fast_perf_scale"], 0.0, 1.0)
137
+ for index in np.flatnonzero(mask):
138
+ policy[index], perf[index] = expensive_scorer(int(index))
139
+ return RoutingResult(np.clip(policy, 0.0, 1.0), np.clip(perf, 0.0, 1.0), mask)
.rsi/laneB/hpace/scizor_compat.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Import shims for running SCIZOR code in this environment.
2
+
3
+ SCIZOR's modules import TensorFlow and flax at module import time, but only for
4
+ helpers HiPACE never calls: TensorFlow is used by ``view_dataset_info`` (frame
5
+ annotation for ``visualize()``) and flax by a wandb logging helper. Installing
6
+ TensorFlow + torch in one process segfaults here, and pinning a jax/flax pair
7
+ that satisfies both SCIZOR and robomimic's diffusers==0.11.1 was not possible
8
+ (diffusers needs ``jax.random.KeyArray``, which newer jax removed, while newer
9
+ flax needs jax APIs the older releases lack).
10
+
11
+ Stubbing those two imports leaves the code paths HiPACE does use - the
12
+ discriminator, the HDF5 pair sampling, and the scoring maths - completely
13
+ untouched. Call ``install()`` before importing SCIZOR modules.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import importlib.machinery
18
+ import sys
19
+ import types
20
+
21
+
22
+ def _stub(name: str) -> types.ModuleType:
23
+ module = types.ModuleType(name)
24
+ # Third-party availability checks call importlib.util.find_spec(), which
25
+ # raises for a sys.modules entry whose __spec__ is None.
26
+ module.__spec__ = importlib.machinery.ModuleSpec(name, loader=None)
27
+ module.__version__ = "0.0.0"
28
+ return module
29
+
30
+
31
+ def _unavailable(name: str):
32
+ def _raise(*_args, **_kwargs):
33
+ raise NotImplementedError(f"{name} is unavailable in this environment")
34
+
35
+ return _raise
36
+
37
+
38
+ def install() -> None:
39
+ if "curation.utils.view_dataset_info" not in sys.modules:
40
+ module = _stub("curation.utils.view_dataset_info")
41
+ module.apply_filter = _unavailable("view_dataset_info.apply_filter (requires TensorFlow)")
42
+ sys.modules["curation.utils.view_dataset_info"] = module
43
+
44
+ if "flax" not in sys.modules:
45
+ flax = _stub("flax")
46
+ traverse_util = _stub("flax.traverse_util")
47
+ traverse_util.flatten_dict = _unavailable("flax.traverse_util.flatten_dict (requires jax)")
48
+ flax.traverse_util = traverse_util
49
+ sys.modules["flax"] = flax
50
+ sys.modules["flax.traverse_util"] = traverse_util
.rsi/laneB/hpace/scizor_progress.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single implementation of SCIZOR per-frame progress scoring.
2
+
3
+ Both the curation side (``scripts/run_scizor.py``) and the evaluation side
4
+ (``scripts/eval_act_robosuite.py``) must compute progress identically - a drift
5
+ between two copies of this logic is what previously made training and evaluation
6
+ disagree. Everything they share lives here.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ SCIZOR = ROOT / "third_party" / "SCIZOR"
17
+
18
+
19
+ def prepare_import_path() -> None:
20
+ """Make SCIZOR's own fork of dlimp and its modules importable, with shims."""
21
+ for entry in (str(SCIZOR / "dlimp"), str(SCIZOR), str(ROOT)):
22
+ if entry not in sys.path:
23
+ sys.path.insert(0, entry)
24
+ from .scizor_compat import install
25
+
26
+ install()
27
+
28
+
29
+ class ScizorProgressScorer:
30
+ """Turns frames into the inverted suboptimality proxy used as progress."""
31
+
32
+ def __init__(
33
+ self,
34
+ model_path: str | Path,
35
+ goal_seconds: str = "1.0,2.0,4.0",
36
+ frequency: int = 20,
37
+ batch_size: int = 256,
38
+ ):
39
+ prepare_import_path()
40
+ import torch
41
+ from curation.video_encoding.suboptimal_hdf5 import Evaluator, PreprocessDataset
42
+
43
+ self.torch = torch
44
+ self.preprocess_dataset = PreprocessDataset
45
+ self.evaluator = Evaluator(str(model_path))
46
+ self.goal_time = [float(value) for value in str(goal_seconds).split(",")]
47
+ self.evaluator.goal_time = self.goal_time
48
+ self.frequency = frequency
49
+ self.batch_size = batch_size
50
+
51
+ def score(self, frames: np.ndarray, image_key: str = "agentview_image") -> np.ndarray:
52
+ """Return per-frame progress (1 - SCIZOR suboptimality) for one trajectory."""
53
+ goal_dist = np.asarray([int(value * self.frequency) for value in self.goal_time], dtype=np.int64)
54
+ size = self.evaluator.hdf5_config["obs_keys"][image_key]
55
+ dataset = self.preprocess_dataset(np.asarray(frames, dtype=np.uint8), goal_dist, size)
56
+ rank_prob = np.concatenate(
57
+ [
58
+ self.evaluator.inference.get_score(batch)
59
+ for batch in self.torch.utils.data.DataLoader(dataset, batch_size=self.batch_size, shuffle=False)
60
+ ],
61
+ axis=0,
62
+ )
63
+ raw = np.asarray(self.evaluator.rank_prob_to_score(rank_prob, dataset.dist, self.frequency), dtype=np.float32)
64
+ if len(raw) != len(dataset):
65
+ raise RuntimeError(f"SCIZOR returned {len(raw)} scores for {len(dataset)} frames")
66
+ return np.clip(1.0 - raw, 0.0, 1.0)
.rsi/laneB/hpace/scizor_scorer.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Mapping, Sequence
6
+
7
+ import h5py
8
+ import numpy as np
9
+ from sklearn.cluster import KMeans
10
+
11
+ from .data_loader import SegmentedTrajectory
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class QualityScores:
16
+ demo_ids: tuple[str, ...]
17
+ candidate_indices: np.ndarray
18
+ q_quality: np.ndarray
19
+ progress_score: np.ndarray
20
+ redundancy_score: np.ndarray
21
+ frame_score: np.ndarray
22
+ frame_weights: tuple[np.ndarray, ...]
23
+
24
+
25
+ def l2_normalize(values: np.ndarray) -> np.ndarray:
26
+ values = np.asarray(values, dtype=np.float32)
27
+ norm = np.linalg.norm(values, axis=-1, keepdims=True)
28
+ return values / np.maximum(norm, 1e-12)
29
+
30
+
31
+ def frame_redundancy(embeddings: Sequence[np.ndarray], n_clusters: int, seed: int = 42) -> tuple[np.ndarray, ...]:
32
+ lengths = [len(item) for item in embeddings]
33
+ if any(length == 0 for length in lengths):
34
+ raise ValueError("Every trajectory needs at least one embedding")
35
+ all_embeddings = l2_normalize(np.concatenate(embeddings, axis=0))
36
+ cluster_count = min(n_clusters, len(all_embeddings))
37
+ labels = KMeans(n_clusters=cluster_count, random_state=seed, n_init=10).fit_predict(all_embeddings)
38
+ redundancy = np.zeros(len(all_embeddings), dtype=np.float32)
39
+ for cluster_id in range(cluster_count):
40
+ indices = np.flatnonzero(labels == cluster_id)
41
+ if len(indices) < 2:
42
+ continue
43
+ similarity = all_embeddings[indices] @ all_embeddings[indices].T
44
+ np.fill_diagonal(similarity, -np.inf)
45
+ redundancy[indices] = np.clip(similarity.max(axis=1), 0.0, 1.0)
46
+ offsets = np.cumsum([0, *lengths])
47
+ return tuple(redundancy[offsets[i] : offsets[i + 1]] for i in range(len(lengths)))
48
+
49
+
50
+ def compute_frame_weights(actions: np.ndarray, progress: np.ndarray, redundancy: np.ndarray, cfg: Mapping[str, float]) -> np.ndarray:
51
+ actions = np.asarray(actions, dtype=np.float32)
52
+ progress = np.asarray(progress, dtype=np.float32)
53
+ if len(actions) != len(progress) or len(redundancy) != len(progress):
54
+ raise ValueError("Actions, progress, and redundancy must have the same length")
55
+ weights = np.ones(len(progress), dtype=np.float32)
56
+ if len(progress) > 1:
57
+ action_delta = np.linalg.norm(np.diff(actions, axis=0), axis=-1)
58
+ progress_delta = np.abs(np.diff(progress))
59
+ event = np.zeros(len(progress), dtype=bool)
60
+ event[1:] |= action_delta > cfg["event_action_delta_threshold"]
61
+ event[1:] |= progress_delta > cfg["event_progress_delta_threshold"]
62
+ else:
63
+ event = np.zeros(1, dtype=bool)
64
+ if actions.ndim == 2 and actions.shape[1]:
65
+ event |= np.abs(actions[:, -1]) > cfg["event_gripper_threshold"]
66
+ high_redundancy = redundancy >= np.quantile(redundancy, 0.75)
67
+ weights[high_redundancy] = 0.5
68
+ weights[event] = 1.5
69
+ return weights / 1.5
70
+
71
+
72
+ def score_quality(
73
+ hdf5_path: str | Path,
74
+ segmented: Sequence[SegmentedTrajectory],
75
+ embeddings: Mapping[str, np.ndarray],
76
+ quality_cfg: Mapping[str, float],
77
+ output_path: str | Path | None = None,
78
+ action_key: str = "actions",
79
+ ) -> QualityScores:
80
+ demo_ids = tuple(item.demo_id for item in segmented)
81
+ missing = set(demo_ids) - set(embeddings)
82
+ if missing:
83
+ raise KeyError(f"Missing embeddings for: {sorted(missing)}")
84
+ redundancy = frame_redundancy([embeddings[key] for key in demo_ids], int(quality_cfg["redundancy_clusters"]))
85
+ frame_weights: list[np.ndarray] = []
86
+ with h5py.File(hdf5_path, "r") as dataset:
87
+ for item, red in zip(segmented, redundancy):
88
+ actions = dataset[f"data/{item.demo_id}/{action_key}"][:]
89
+ frame_weights.append(compute_frame_weights(actions, item.progress_raw, red, quality_cfg))
90
+ progress_score = np.asarray([item.progress_raw.mean() for item in segmented], dtype=np.float32)
91
+ redundancy_score = np.asarray([item.mean() for item in redundancy], dtype=np.float32)
92
+ frame_score = np.asarray([item.mean() for item in frame_weights], dtype=np.float32)
93
+ q_quality = (
94
+ quality_cfg["w_progress"] * progress_score
95
+ + quality_cfg["w_frame"] * frame_score
96
+ - quality_cfg["w_redundancy"] * redundancy_score
97
+ ).astype(np.float32)
98
+ n_drop = int(np.floor(len(q_quality) * quality_cfg["drop_bottom_ratio"]))
99
+ candidate = np.argsort(q_quality, kind="stable")[n_drop:].astype(np.int64)
100
+ result = QualityScores(demo_ids, candidate, q_quality, progress_score, redundancy_score, frame_score, tuple(frame_weights))
101
+ if output_path is not None:
102
+ save_quality_scores(result, output_path)
103
+ return result
104
+
105
+
106
+ def save_quality_scores(scores: QualityScores, path: str | Path) -> None:
107
+ lengths = np.asarray([len(item) for item in scores.frame_weights], dtype=np.int64)
108
+ offsets = np.concatenate(([0], np.cumsum(lengths)))
109
+ target = Path(path)
110
+ target.parent.mkdir(parents=True, exist_ok=True)
111
+ np.savez_compressed(
112
+ target,
113
+ demo_ids=np.asarray(scores.demo_ids),
114
+ candidate_idx=scores.candidate_indices,
115
+ q_quality_traj=scores.q_quality,
116
+ progress_score=scores.progress_score,
117
+ redundancy_score=scores.redundancy_score,
118
+ frame_score=scores.frame_score,
119
+ frame_weights=np.concatenate(scores.frame_weights),
120
+ frame_weight_offsets=offsets,
121
+ )
122
+
.rsi/laneB/hpace/value_fusion.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Mapping, Sequence
5
+
6
+ import numpy as np
7
+ from sklearn.cluster import KMeans
8
+
9
+ from .scizor_scorer import l2_normalize
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class FusionResult:
14
+ values: np.ndarray
15
+ trajectory_probabilities: np.ndarray
16
+ frame_probabilities: tuple[np.ndarray, ...]
17
+ cluster_labels: np.ndarray
18
+ diversity_bonus: np.ndarray
19
+
20
+
21
+ def stable_softmax(values: np.ndarray, temperature: float) -> np.ndarray:
22
+ if temperature <= 0:
23
+ raise ValueError("Softmax temperature must be positive")
24
+ logits = np.asarray(values, dtype=np.float64) / temperature
25
+ logits -= logits.max()
26
+ result = np.exp(logits)
27
+ return result / result.sum()
28
+
29
+
30
+ def fuse_values(
31
+ q_quality: np.ndarray,
32
+ q_policy: np.ndarray,
33
+ q_perf: np.ndarray,
34
+ trajectory_embeddings: np.ndarray,
35
+ frame_weights: Sequence[np.ndarray],
36
+ cfg: Mapping[str, float],
37
+ seed: int = 42,
38
+ include_diversity: bool = True,
39
+ ) -> FusionResult:
40
+ quality, policy, perf = map(lambda value: np.asarray(value, dtype=np.float32), (q_quality, q_policy, q_perf))
41
+ if not (len(quality) == len(policy) == len(perf) == len(trajectory_embeddings) == len(frame_weights)):
42
+ raise ValueError("All trajectory-level inputs must have the same length")
43
+ count = len(quality)
44
+ n_clusters = min(int(cfg["k_diversity_clusters"]), count)
45
+ if n_clusters < 1:
46
+ raise ValueError("Cannot fuse an empty candidate pool")
47
+ labels = KMeans(n_clusters=n_clusters, random_state=seed, n_init=10).fit_predict(l2_normalize(trajectory_embeddings))
48
+ cluster_sizes = np.bincount(labels, minlength=n_clusters)
49
+ bonus = cfg["diversity_bonus_max"] * (1.0 - cluster_sizes[labels] / count)
50
+ if not include_diversity:
51
+ bonus = np.zeros(count, dtype=np.float64)
52
+ values = cfg["w_quality"] * quality + cfg["w_policy"] * policy + cfg["w_perf"] * perf + bonus
53
+ trajectory_probabilities = stable_softmax(values, cfg["softmax_temperature"])
54
+ per_frame: list[np.ndarray] = []
55
+ for trajectory_probability, weights in zip(trajectory_probabilities, frame_weights):
56
+ weights = np.asarray(weights, dtype=np.float64)
57
+ if len(weights) == 0 or np.any(weights < 0) or weights.sum() <= 0:
58
+ raise ValueError("Frame weights must be non-negative with a positive sum")
59
+ per_frame.append(trajectory_probability * weights / weights.sum())
60
+ return FusionResult(values, trajectory_probabilities, tuple(per_frame), labels, bonus)
61
+
.rsi/laneB/hpace/weighted_sampler.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator, Sequence
4
+
5
+ import numpy as np
6
+
7
+
8
+ def flatten_hierarchical_probabilities(frame_probabilities: Sequence[np.ndarray]) -> np.ndarray:
9
+ if not frame_probabilities:
10
+ raise ValueError("At least one trajectory is required")
11
+ probabilities = np.concatenate([np.asarray(item, dtype=np.float64) for item in frame_probabilities])
12
+ if np.any(probabilities < 0) or probabilities.sum() <= 0:
13
+ raise ValueError("Sampling probabilities must be non-negative with a positive sum")
14
+ return probabilities / probabilities.sum()
15
+
16
+
17
+ class WeightedTrajectorySampler:
18
+ """Framework-neutral trajectory/frame sampler used by ACT and robomimic adapters."""
19
+
20
+ def __init__(self, demo_ids: Sequence[str], frame_probabilities: Sequence[np.ndarray], seed: int = 42):
21
+ if len(demo_ids) != len(frame_probabilities):
22
+ raise ValueError("demo_ids and frame_probabilities must have equal length")
23
+ self.demo_ids = tuple(demo_ids)
24
+ self.frame_probabilities = tuple(np.asarray(item, dtype=np.float64) for item in frame_probabilities)
25
+ self.trajectory_probabilities = np.asarray([item.sum() for item in self.frame_probabilities], dtype=np.float64)
26
+ self.trajectory_probabilities /= self.trajectory_probabilities.sum()
27
+ self.rng = np.random.default_rng(seed)
28
+
29
+ def sample_trajectory(self) -> str:
30
+ return str(self.rng.choice(self.demo_ids, p=self.trajectory_probabilities))
31
+
32
+ def sample_frame(self, demo_id: str) -> int:
33
+ index = self.demo_ids.index(demo_id)
34
+ weights = self.frame_probabilities[index]
35
+ return int(self.rng.choice(len(weights), p=weights / weights.sum()))
36
+
37
+ def sample(self) -> tuple[str, int]:
38
+ demo_id = self.sample_trajectory()
39
+ return demo_id, self.sample_frame(demo_id)
40
+