"""Next-keypose supervision with optional training-only observation selection.""" import hashlib import json from pathlib import Path from typing import Any import h5py import numpy as np import torch from pydantic import BaseModel, ConfigDict, NonNegativeFloat from torch.utils.data import Dataset from lim.keypose_context import CONTEXT_DIM, KeyposeContextMode from lim.keypose_control import encode_keypose from lim.keypose_phase import KEYPOSE_PHASE_NAMES class KeyposeSamplingConfig(BaseModel, frozen=True): model_config = ConfigDict( extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False ) gripper_initial_only: bool = False """Keep only obs[start] of each close/open primitive; retain original labels.""" motion_endpoint_radius_m: NonNegativeFloat = 0 """Exclude all move observations within this XYZ radius of obs[end]; zero disables.""" @property def active(self): return self.gripper_initial_only or self.motion_endpoint_radius_m > 0 class KeyposeDatasetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: Any """Native preprocessed RGB dataset; full observations and sample order retained.""" source: Path """Annotated H5 used to construct the native dataset in numeric trajectory order.""" sampling: KeyposeSamplingConfig = KeyposeSamplingConfig() """Training-only subset; full stored trajectories remain the normalization population.""" phase_supervision: bool = False """Return the six-class primitive index separately from observations/actions.""" context: KeyposeContextMode = "none" """Add completed_target11 without changing state/RGB, actions or selected slices.""" stop_supervision: bool = False """Return final-primitive terminal intent separately from observations/actions.""" class KeyposeDataset(Dataset): def __init__(self, config: KeyposeDatasetConfig): self.config = config self.dataset = config.dataset self.trajectories = {**self.dataset.trajectories, "actions": []} self.phase_labels = [] self.stop_labels = [] self.completed_targets = [] if config.stop_supervision and ( config.context != "previous_target" or config.sampling.active or config.phase_supervision ): raise ValueError( "Stop supervision preserves the full previous-target dataset without phase" ) selected = [] records = [] with h5py.File(config.source, "r") as file: names = sorted(file, key=lambda name: int(name.split("_")[-1]))[ : self.dataset.num_traj ] if len(names) != self.dataset.num_traj: raise ValueError( "Keypose and native datasets select different trajectories" ) for name, dense in zip( names, self.dataset.trajectories["actions"], strict=True ): key = file[name]["keyframes"] indices = torch.from_numpy(key["action_keyframe_index"][:]).long() if config.phase_supervision or config.stop_supervision: if ( "name" not in key or tuple(key["name"].asstr()[:]) != KEYPOSE_PHASE_NAMES or indices.ndim != 1 or not ( (indices >= 0) & (indices < len(KEYPOSE_PHASE_NAMES)) ).all() ): raise ValueError( "Phase supervision requires the canonical six primitive labels" ) if config.phase_supervision: self.phase_labels.append(indices) if config.stop_supervision: self.stop_labels.append( (indices == len(key["name"]) - 1).float() ) poses = torch.from_numpy(key["target_pose_world"][:]) gripper = torch.from_numpy(key["gripper_command"][:]) if len(indices) != len(dense) or dense.shape[-1] != 7: raise ValueError("Expected aligned unencoded dense pose actions") if not torch.equal(gripper[indices], dense[:, -1]): raise ValueError("Keypose event and dense gripper labels disagree") targets = encode_keypose(poses, gripper) self.trajectories["actions"].append(targets[indices]) if config.context != "none": starts = key["start_action"][:] ends = key["end_action"][:] if ( indices.ndim != 1 or len(starts) != len(targets) or len(ends) != len(targets) or not len(starts) or starts[0] != 0 or ends[-1] != len(dense) or np.any(ends <= starts) or not np.array_equal(starts[1:], ends[:-1]) or not np.array_equal( indices.numpy(), np.searchsorted(ends, np.arange(len(dense)), side="right"), ) ): raise ValueError( "Completed-goal context requires contiguous pre-action primitive indices" ) context = targets.new_zeros((len(indices), CONTEXT_DIM)) if config.context == "previous_target": valid = indices > 0 context[valid, :10] = targets[indices[valid] - 1] context[valid, -1] = 1 self.completed_targets.append(context) keep = np.ones(len(dense), dtype=bool) protected_starts = [] if config.sampling.active: starts, ends = key["start_action"][:], key["end_action"][:] kinds = key["kind"].asstr()[:] if ( not len(starts) or len(starts) != len(ends) or len(kinds) != len(starts) or starts[0] != 0 or ends[-1] != len(dense) or np.any(ends <= starts) or not np.array_equal(starts[1:], ends[:-1]) or not np.array_equal( indices.numpy(), np.searchsorted(ends, np.arange(len(dense)), side="right"), ) ): raise ValueError("Invalid primitive boundaries for sampling") tcp = file[name]["obs/extra/tcp_pose"][:].astype(np.float64) if len(tcp) != len(dense) + 1 or not np.isfinite(tcp).all(): raise ValueError( "Expected finite pre-action and terminal TCP observations" ) for start, end, kind in zip(starts, ends, kinds, strict=True): if kind in ("close", "open"): if config.sampling.gripper_initial_only: keep[start + 1 : end] = False elif kind == "move": if config.sampling.motion_endpoint_radius_m > 0: near = ( np.linalg.norm( tcp[start:end, :3] - tcp[end, :3], axis=1 ) <= config.sampling.motion_endpoint_radius_m ) keep[start:end] &= ~near else: raise ValueError(f"Unknown primitive kind: {kind}") protected_starts = starts[~keep[starts]].tolist() keep[starts] = True selected.append(keep) records.append( { "trajectory": name, "original_samples": len(dense), "retained_indices": np.flatnonzero(keep).tolist(), "protected_segment_starts": protected_starts, } ) self.slices = [ (trajectory, step) for trajectory, step in self.dataset.slices if selected[trajectory][step] ] expected = sum(int(mask.sum()) for mask in selected) if len(self.slices) != expected or len(set(self.slices)) != expected: raise ValueError( "Native sample index does not cover each obs_t exactly once" ) encoded_indices = json.dumps(self.slices, separators=(",", ":")).encode() self.sample_selection = { "config": config.sampling.model_dump(mode="json"), "original_samples": sum(len(mask) for mask in selected), "retained_samples": len(self.slices), "normalization_population": "all original unfiltered obs_t and keypose targets", "index_sha256": hashlib.sha256(encoded_indices).hexdigest(), "trajectories": records, } if config.stop_supervision: labels = torch.cat(self.stop_labels) self.stop_label_summary = { "contract": "stop_after_target = original action_keyframe_index equals final primitive index; label only, no terminal observation or success input", "samples": len(labels), "positive": int(labels.sum()), "negative": int((labels == 0).sum()), "labels_sha256": hashlib.sha256(labels.numpy().tobytes()).hexdigest(), "sample_index_sha256": self.sample_selection["index_sha256"], } def __getattr__(self, name): return getattr(self.dataset, name) def __len__(self): return len(self.slices) def __getitem__(self, index): trajectory, step = self.slices[index] observation = { k: v[step] for k, v in self.trajectories["observations"][trajectory].items() } if self.config.context != "none": observation["completed_target"] = self.completed_targets[trajectory][ step ].clone() target = self.trajectories["actions"][trajectory][step] # Preserve the native query embeddings/parameter count and loss averaging. # All queries predict the SAME next primitive target, not future timed deltas. # No terminal padding or future-frame observation is needed for this target. sample = { "observations": observation, "actions": target[None].repeat(self.num_queries, 1), } if self.config.phase_supervision: sample["phase"] = self.phase_labels[trajectory][step] if self.config.stop_supervision: sample["stop_after_target"] = self.stop_labels[trajectory][step] return sample class FirstKeyposeAgentConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) agent: Any """Frozen ACT whose queries all supervise the next world-frame keypose.""" class FirstKeyposeAgent: def __init__(self, config: FirstKeyposeAgentConfig): self.config = config def __getattr__(self, name): return getattr(self.config.agent, name) def get_action(self, obs): return self.config.agent.get_action(obs)[:, :1]