Download fair-comparison/extract-train-v1/code/lim/real_chunks.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/extract-train-v1/code/lim/real_chunks.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/extract-train-v1/code/lim/real_chunks.py
-
curl -L -o real_chunks.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/extract-train-v1/code/lim/real_chunks.py
10.8 kB
| """Chunk labels for recorded real demonstrations (lim.umi_data, lim.keypose_extract). | |
| Each item has the ten values of the simulated chunk-relative labels -- translation | |
| / 0.1 m, lim.action_encoding 6D rotation, gripper -- but in the current hand frame: | |
| ``item = inv(T_t) @ T_target``. The simulated labels keep world axes because the | |
| Panda root is fixed. A hand-held recording has no fixed root (the VIO origin is the | |
| head at the start of each recording), so only the hand's own frame carries across | |
| demonstrations, and a robot executes ``T_t @ item`` from its measured TCP. | |
| Item i of the chunk at frame t stands for frame ``tau = t + stride * (i + 1)``: | |
| - ``dense``: the pose reached at tau; | |
| - ``future_endpoint``: the endpoint of the segment that the move into tau belongs | |
| to (``fendpoint_fg`` of the simulated comparison); | |
| - both: the gripper width at tau. | |
| Items past the cropped end repeat the final frame. The final frame is also the last | |
| segment's endpoint, so both supervisions pad identically. Every frame with a | |
| following frame is a sample; the policy state is the current gripper width alone, | |
| since an absolute pose has no meaning across recordings. | |
| Statistics, fitted on the training demonstrations and shared by both supervisions | |
| as in simulation: pose values are z-scored over the dense in-range items (std | |
| floored at ``action_floor``); the gripper width, label and state alike, is mapped | |
| to [-1, 1] by the widest opening, ``2 * width / open - 1``. | |
| """ | |
| import json | |
| from pathlib import Path | |
| from typing import Literal | |
| import h5py | |
| import numpy as np | |
| import torch | |
| from mani_skill.utils.geometry.rotation_conversions import quaternion_to_matrix | |
| from pydantic import ( | |
| BaseModel, | |
| ConfigDict, | |
| Field, | |
| NonNegativeInt, | |
| PositiveFloat, | |
| PositiveInt, | |
| ) | |
| from torch.utils.data import Dataset | |
| from lim.action_encoding import matrix_to_sixd, sixd_to_matrix | |
| from lim.umi_data import FORMAT, file_digest | |
| TRANSLATION_SCALE = 0.1 | |
| """Metres per translation label unit, as the simulated labels.""" | |
| SHA256 = r"^[0-9a-f]{64}$" | |
| class RealChunkConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) | |
| dataset: Path | |
| """Converted demonstrations (lim.umi_data).""" | |
| dataset_sha256: str = Field(pattern=SHA256) | |
| keyframes: Path | |
| """Extracted segments of the same dataset (lim.keypose_extract); fixes the kept | |
| demonstrations and where each is cropped.""" | |
| keyframes_sha256: str = Field(pattern=SHA256) | |
| supervision: Literal["dense", "future_endpoint"] | |
| num_queries: PositiveInt = 50 | |
| frame_stride: PositiveInt = 2 | |
| """Recorded frames per item (2 at 30 Hz: items 1/15 s apart).""" | |
| camera: str = "wrist" | |
| dev_demonstrations: NonNegativeInt = 15 | |
| """Kept demonstrations held out for development, drawn once by split_seed.""" | |
| split_seed: int = 0 | |
| action_floor: PositiveFloat = 0.01 | |
| """Minimum std of a pose value, in label units.""" | |
| class RealNormalization(BaseModel, frozen=True): | |
| model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) | |
| dataset_sha256: str = Field(pattern=SHA256) | |
| keyframes_sha256: str = Field(pattern=SHA256) | |
| trajectories: PositiveInt | |
| samples: PositiveInt | |
| """Dense in-range items the pose statistics were fitted on.""" | |
| pose_center: tuple[float, ...] = Field(min_length=9, max_length=9) | |
| pose_scale: tuple[PositiveFloat, ...] = Field(min_length=9, max_length=9) | |
| gripper_open_m: PositiveFloat | |
| """Widest opening in the training demonstrations; maps to +1.""" | |
| def affine(self): | |
| """(center, scale) of the ten action values; the gripper's maps [0, open] to [-1, 1].""" | |
| half = self.gripper_open_m / 2 | |
| return (torch.tensor([*self.pose_center, half], dtype=torch.float64), | |
| torch.tensor([*self.pose_scale, half], dtype=torch.float64)) | |
| def state(self, width): | |
| half = self.gripper_open_m / 2 | |
| return (width - half) / half | |
| def split(trajs, config: RealChunkConfig): | |
| """Training and development demonstrations, each in recorded order.""" | |
| order = sorted(trajs, key=lambda name: int(name.split("_")[-1])) | |
| if config.dev_demonstrations >= len(order): | |
| raise ValueError("No training demonstrations would remain") | |
| rng = np.random.default_rng(config.split_seed) | |
| dev = set(rng.choice(order, config.dev_demonstrations, replace=False).tolist()) | |
| return {"train": [t for t in order if t not in dev], "dev": [t for t in order if t in dev]} | |
| def item_frames(frames, num_queries, stride): | |
| """(frames - 1, num_queries) frames the items stand for, clamped to the last, and | |
| whether each is in range.""" | |
| tau = torch.arange(frames - 1)[:, None] + stride * (torch.arange(num_queries)[None] + 1) | |
| return tau.clamp(max=frames - 1), tau <= frames - 1 | |
| def relative_items(anchor, target): | |
| """inv(T(anchor)) @ T(target) as translation / 0.1 and 6D; poses are xyz,wxyz.""" | |
| rotation = quaternion_to_matrix(anchor[..., 3:]).transpose(-1, -2) | |
| return torch.cat([ | |
| torch.einsum("...ij,...j->...i", rotation, target[..., :3] - anchor[..., :3]) / TRANSLATION_SCALE, | |
| matrix_to_sixd(rotation @ quaternion_to_matrix(target[..., 3:])), | |
| ], -1) | |
| def restore(anchor, items): | |
| """World position and rotation matrix of hand-frame items (inverse of relative_items).""" | |
| rotation = quaternion_to_matrix(anchor[..., 3:]) | |
| position = anchor[..., :3] + torch.einsum("...ij,...j->...i", rotation, items[..., :3] * TRANSLATION_SCALE) | |
| return position, rotation @ sixd_to_matrix(items[..., 3:9]) | |
| class RealChunkDataset(Dataset): | |
| """Samples of one part of the split, loaded into memory. | |
| Items are ``{"observations": {"state": (1,), "rgb": (1, 3, H, W) uint8}, | |
| "actions": (num_queries, 10) normalized, "valid": (num_queries,)}``. The training | |
| part fits the statistics; the development part takes the training part's. | |
| """ | |
| def __init__(self, config: RealChunkConfig, part: Literal["train", "dev"], | |
| statistics: RealNormalization | None = None): | |
| if (part == "train") != (statistics is None): | |
| raise ValueError("Only the training part fits statistics; others take them") | |
| for path, expected in ((config.dataset, config.dataset_sha256), (config.keyframes, config.keyframes_sha256)): | |
| if file_digest(path) != expected: | |
| raise ValueError(f"{path} differs from its declared sha256") | |
| self.config = config | |
| anchors, chunks, valids, widths, images, population = [], [], [], [], [], [] | |
| with h5py.File(config.dataset, "r") as data, h5py.File(config.keyframes, "r") as keys: | |
| if data.attrs["format"] != FORMAT or keys.attrs["dataset_sha256"] != config.dataset_sha256: | |
| raise ValueError("Keyframes were extracted from another dataset") | |
| self.trajs = split(list(keys), config)[part] | |
| for traj in self.trajs: | |
| key = keys[f"{traj}/keyframes"] | |
| frames = int(key.attrs["frames"]) | |
| ends = torch.from_numpy(key["end_action"][:]) | |
| segment = torch.from_numpy(key["action_keyframe_index"][:]) | |
| if ends[-1] != frames - 1 or len(segment) != frames - 1: | |
| raise ValueError(f"{traj}: keyframes do not cover the cropped frames") | |
| pose = torch.from_numpy(data[f"{traj}/obs/hand_pose"][:frames]) | |
| width = torch.from_numpy(data[f"{traj}/obs/gripper_width"][:frames]) | |
| tau, valid = item_frames(frames, config.num_queries, config.frame_stride) | |
| anchor = pose[:-1, None] | |
| dense = relative_items(anchor, pose[tau]) | |
| population.append(dense[valid]) | |
| if config.supervision == "dense": | |
| items = dense | |
| else: | |
| items = relative_items(anchor, pose[ends[segment[tau - 1]]]) | |
| chunks.append(torch.cat([items, width[tau, None]], -1)) | |
| anchors.append(pose[:-1]) | |
| valids.append(valid) | |
| widths.append(width[:-1]) | |
| rgb = data[f"{traj}/obs/rgb/{config.camera}"][:frames - 1] | |
| images.append(torch.from_numpy(rgb).permute(0, 3, 1, 2)[:, None].contiguous()) | |
| if statistics is None: | |
| population = torch.cat(population) | |
| statistics = RealNormalization( | |
| dataset_sha256=config.dataset_sha256, keyframes_sha256=config.keyframes_sha256, | |
| trajectories=len(self.trajs), samples=len(population), | |
| pose_center=population.mean(0).tolist(), | |
| pose_scale=population.std(0, correction=0).clamp_min(config.action_floor).tolist(), | |
| gripper_open_m=float(torch.cat(widths).max()), | |
| ) | |
| elif (statistics.dataset_sha256, statistics.keyframes_sha256) != (config.dataset_sha256, | |
| config.keyframes_sha256): | |
| raise ValueError("Statistics belong to another dataset") | |
| self.statistics = statistics | |
| center, scale = statistics.affine() | |
| self.anchors = anchors | |
| # Unnormalized items and gripper widths, for policies with their own statistics. | |
| self.raw = chunks | |
| self.widths = widths | |
| self.chunks = [((c - center) / scale).float() for c in chunks] | |
| self.valid = valids | |
| self.states = [statistics.state(w)[:, None].float() for w in widths] | |
| self.images = images | |
| self.slices = [(j, t) for j, chunk in enumerate(chunks) for t in range(len(chunk))] | |
| self.num_traj = len(self.trajs) | |
| def __len__(self): | |
| return len(self.slices) | |
| def __getitem__(self, index): | |
| j, t = self.slices[index] | |
| return {"observations": {"state": self.states[j][t], "rgb": self.images[j][t]}, | |
| "actions": self.chunks[j][t], "valid": self.valid[j][t]} | |
| def describe(self): | |
| return {"trajs": self.trajs, "samples": len(self), "statistics": json.loads(self.statistics.model_dump_json())} | |
| def unnormalize(prediction, statistics: RealNormalization): | |
| center, scale = statistics.affine() | |
| return prediction.double() * scale.to(prediction.device) + center.to(prediction.device) | |
| def item_errors(prediction, label): | |
| """Per-item position (m), rotation (rad) and gripper (m) errors of unnormalized items.""" | |
| position = (prediction[..., :3] - label[..., :3]).norm(dim=-1) * TRANSLATION_SCALE | |
| relative = sixd_to_matrix(prediction[..., 3:9]).transpose(-1, -2) @ sixd_to_matrix(label[..., 3:9]) | |
| trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1) | |
| rotation = torch.arccos(((trace - 1) / 2).clamp(-1, 1)) | |
| return position, rotation, (prediction[..., 9] - label[..., 9]).abs() | |