OpenGHz's picture
Add keypose-data/StackPyramid-v1
2ba0b15 verified
Raw History Blame Contribute Delete
22.7 kB
"""Collect annotated native StackCube experts and map labels through pose replay.
The upstream expert is unchanged. Its planner factory is temporarily wrapped in
this single-process CLI to observe executed primitives; trial plans are excluded.
An optional task-irrelevant perturbation (segment time scaling, pauses, detours
through an offset via-point and tapered joint jitter) changes how each planned
move is executed; primitive targets, and so keypose labels, stay the expert's.
"""
import hashlib
import importlib.metadata
import inspect
import json
import time
from pathlib import Path
from typing import Any
from unittest.mock import patch
import gymnasium as gym
import mani_skill.envs # noqa: F401
import numpy as np
import sapien
import torch
from mani_skill.utils import common
from mani_skill.utils.wrappers.record import RecordEpisode
from pydantic import (
BaseModel,
ConfigDict,
Field,
NonNegativeFloat,
NonNegativeInt,
PositiveFloat,
PositiveInt,
SkipValidation,
)
from pydantic_settings import CliApp
from lim.keypose_data import (
AnnotationConfig,
AuditConfig,
KeyposeSegment,
audit_dataset,
write_annotations,
)
from lim.replay_pose import (
TargetReplayConfig,
replace_last,
replay_targets,
tree_first,
)
from lim.tasks import expert_module
FREE_SPACE = ("approach", "place_pose")
"""Moves away from contact: the reach above cube A and the transport onto B."""
class PerturbationConfig(BaseModel, frozen=True):
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
time_scale: tuple[PositiveFloat, PositiveFloat] = (1.0, 1.0)
"""Log-uniform range of each move's duration factor (>1 slower)."""
pause_probability: float = Field(default=0.0, ge=0, le=1)
"""Chance that a move holds its current command mid-way."""
pause_steps: tuple[PositiveInt, PositiveInt] = (3, 10)
"""Inclusive range of held steps."""
detour_probability: float = Field(default=0.0, ge=0, le=1)
"""Chance that a free-space move first passes an offset via-point."""
detour_m: NonNegativeFloat = 0.0
"""Sideways offset of the via-point from the straight path's midpoint
(plus half of it upwards)."""
jitter_rad: NonNegativeFloat = 0.0
"""Std of smooth joint noise on free-space moves, tapered to zero at both ends."""
jitter_smoothing_steps: PositiveFloat = 5.0
"""Gaussian smoothing width of the joint noise, in control steps."""
seed: NonNegativeInt = 20261005
"""Perturbation stream; each attempt uses (seed, scene seed)."""
PERTURBATION_LEVELS = {
1: PerturbationConfig(time_scale=(0.8, 1.25), pause_probability=0.2,
detour_probability=0.2, detour_m=0.03, jitter_rad=0.005),
2: PerturbationConfig(time_scale=(0.67, 1.5), pause_probability=0.4,
detour_probability=0.4, detour_m=0.05, jitter_rad=0.01),
3: PerturbationConfig(time_scale=(0.5, 2.0), pause_probability=0.6,
detour_probability=0.6, detour_m=0.08, jitter_rad=0.02),
}
class CollectionConfig(BaseModel, frozen=True):
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
output_dir: Path
"""New dataset directory; existing files are never overwritten."""
episodes: PositiveInt = 100
"""Number of successful pose demonstrations to retain."""
seed_start: NonNegativeInt = 71000
"""First fresh scene seed, incremented once per attempt without retries."""
max_attempts: PositiveInt = 150
"""Finite attempt budget including planner and converted-execution failures."""
save_video: bool = False
"""Record successful raw-expert videos for a small visual audit."""
perturbation_level: int = Field(default=0, ge=0, le=3)
"""0 keeps the native execution; 1-3 apply PERTURBATION_LEVELS."""
max_episode_steps: PositiveInt = 200
"""Environment time limit recorded with the data (truncation flags)."""
task: str = "StackCube-v1"
"""ManiSkill task with an annotated native expert (lim.tasks)."""
class PlannerConfig(BaseModel, frozen=True):
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
planner: Any
"""Native Panda planner; all motions are executed by this object."""
recorder: Any
"""RecordEpisode supplies the actual dense-action clock."""
segments: SkipValidation[list[KeyposeSegment]]
"""Append-only events for this one expert attempt."""
sequence: tuple[tuple[str, str], ...] | None = None
"""Expected (kind, name) primitives; None records whatever the expert
executes, named by kind and position."""
perturbation: PerturbationConfig | None = None
rng: SkipValidation[Any] = None
"""numpy Generator for this attempt's perturbation draws."""
log: SkipValidation[list] = Field(default_factory=list)
"""One record per executed move describing the applied perturbation."""
class PlanningFailure(RuntimeError):
pass
def pose_vector(pose):
return tuple(
float(x)
for x in np.r_[
common.to_numpy(pose.p).reshape(3), common.to_numpy(pose.q).reshape(4)
]
)
class AnnotatedPlanner:
# These are the native StackCube expert's primitives, not an invented phase split.
stack_cube_sequence = (
("move", "approach"),
("move", "grasp_pose"),
("close", "close_gripper"),
("move", "lift"),
("move", "place_pose"),
("open", "open_gripper"),
)
def __init__(self, config: PlannerConfig):
self.config = config
def name(self, index, kind):
if self.config.sequence is None:
return f"{kind}_{index}"
return self.config.sequence[index][1]
def record(self, kind, target, gripper, execute):
index = len(self.config.segments)
sequence = self.config.sequence
if sequence is not None and (index >= len(sequence) or sequence[index][0] != kind):
raise ValueError("Upstream expert primitive sequence changed")
start = len(self.config.recorder._trajectory_buffer.action) - 1
goal = pose_vector(target)
result = execute()
if isinstance(result, int) and result == -1:
raise PlanningFailure(
f"Native planning failed during {self.name(index, kind)}"
)
end = len(self.config.recorder._trajectory_buffer.action) - 1
if end <= start:
raise ValueError("Executed primitive recorded no actions")
self.config.segments.append(
KeyposeSegment(
name=self.name(index, kind),
kind=kind,
start=start,
end=end,
target_pose=goal,
gripper=gripper,
)
)
return result
def move_to_pose_with_screw(self, pose, dry_run=False, refine_steps=0):
planner = self.config.planner
if dry_run:
return planner.move_to_pose_with_screw(
pose, dry_run=True, refine_steps=refine_steps
)
if self.config.perturbation is None:
execute = lambda: planner.move_to_pose_with_screw(pose, refine_steps=refine_steps)
else:
name = self.name(len(self.config.segments), "move")
execute = lambda: self.perturbed_move(pose, name, refine_steps)
return self.record("move", pose, int(planner.gripper_state), execute)
def perturbed_move(self, pose, name, refine_steps):
"""Execute one planned move with this attempt's perturbation."""
planner, config, rng = self.config.planner, self.config.perturbation, self.config.rng
free = name in FREE_SPACE
record = {"segment": name, "detour": False}
goals = [pose]
if free and rng.random() < config.detour_probability and config.detour_m > 0:
start = common.to_numpy(planner.base_env.agent.tcp.pose.p).reshape(3)
end = common.to_numpy(pose.p).reshape(3)
direction = end[:2] - start[:2]
if np.linalg.norm(direction) < 1e-6:
angle = rng.uniform(0, 2 * np.pi)
direction = np.array([np.cos(angle), np.sin(angle)])
side = np.array([-direction[1], direction[0]]) / np.linalg.norm(direction)
side *= rng.choice([-1.0, 1.0]) * config.detour_m
via = (start + end) / 2 + np.r_[side, config.detour_m / 2]
via_pose = sapien.Pose(via, common.to_numpy(pose.q).reshape(4))
if planner.move_to_pose_with_screw(via_pose, dry_run=True) != -1:
goals = [via_pose, pose]
record.update(detour=True, via=via.tolist())
result = None
for index, goal in enumerate(goals):
plan = planner.move_to_pose_with_screw(goal, dry_run=True)
if isinstance(plan, int) and plan == -1:
return -1
positions = np.asarray(plan["position"], dtype=np.float64)
scale = float(np.exp(rng.uniform(*np.log(config.time_scale))))
steps = max(2, round(len(positions) * scale))
grid = np.linspace(0, len(positions) - 1, steps)
positions = np.stack(
[np.interp(grid, np.arange(len(positions)), joint) for joint in positions.T], -1
)
if free and config.jitter_rad > 0 and steps > 2:
noise = rng.normal(size=positions.shape)
width = config.jitter_smoothing_steps
radius = min(int(3 * width), (steps - 1) // 2)
kernel = np.exp(-0.5 * (np.arange(-radius, radius + 1) / width) ** 2)
noise = np.stack([np.convolve(n, kernel, mode="same") for n in noise.T], -1)
noise /= noise.std(0, keepdims=True) + 1e-12
taper = np.sin(np.linspace(0, np.pi, steps))[:, None]
positions = positions + config.jitter_rad * noise * taper
pause = 0
if index == len(goals) - 1 and rng.random() < config.pause_probability:
pause = int(rng.integers(config.pause_steps[0], config.pause_steps[1] + 1))
at = int(rng.integers(1, steps))
positions = np.concatenate(
[positions[:at], np.repeat(positions[at - 1 : at], pause, 0), positions[at:]]
)
record.setdefault("parts", []).append(
{"planned_steps": len(plan["position"]), "time_scale": scale,
"executed_steps": len(positions), "pause_steps": pause}
)
velocity = np.gradient(positions, axis=0) / planner.base_env.control_timestep
result = planner.follow_path(
{"position": positions, "velocity": velocity}, refine_steps=refine_steps
)
self.config.log.append(record)
return result
def close_gripper(self, t=6, gripper_state=None):
planner = self.config.planner
return self.record(
"close",
planner.base_env.agent.tcp.pose,
int(planner.CLOSED if gripper_state is None else gripper_state),
lambda: planner.close_gripper(t=t, gripper_state=gripper_state),
)
def open_gripper(self, t=6, gripper_state=None):
planner = self.config.planner
return self.record(
"open",
planner.base_env.agent.tcp.pose,
int(planner.OPEN if gripper_state is None else gripper_state),
lambda: planner.open_gripper(t=t, gripper_state=gripper_state),
)
def close(self):
self.config.planner.close()
def clear_recording(recorder):
if recorder._trajectory_buffer is not None:
recorder.flush_trajectory(save=False)
if recorder.save_video:
recorder.flush_video(save=False)
def sha256(path):
digest = hashlib.sha256()
with Path(path).open("rb") as f:
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def run(config: CollectionConfig):
if config.max_attempts < config.episodes:
raise ValueError("Attempt budget cannot be smaller than the requested dataset")
torch.set_num_threads(4)
config.output_dir.mkdir(parents=True, exist_ok=False)
(config.output_dir / "config.json").write_text(
config.model_dump_json(indent=2) + "\n"
)
# Freeze the actual collector, replay code and native expert used for this dataset.
from lim import keypose_data, replay_pose
expert = expert_module(config.task)
files = [
Path(__file__),
Path(keypose_data.__file__),
Path(replay_pose.__file__),
Path(inspect.getfile(expert)),
]
provenance = {
"source_sha256": {str(p): sha256(p) for p in files},
"software_versions": {
p: importlib.metadata.version(p)
for p in ["mani-skill", "sapien", "torch", "numpy", "mplib"]
},
"observation_policy": "all RGB, TCP, qpos/qvel and dense actions retained",
"annotation_policy": "native primitive targets/events; no image or action decimation",
"expert_information": "native expert uses simulator object poses to create labels; not policy inputs",
"perturbation": PERTURBATION_LEVELS[config.perturbation_level].model_dump(mode="json")
if config.perturbation_level
else None,
}
snapshot = config.output_dir / "source_snapshot"
snapshot.mkdir()
for p in files:
(snapshot / p.name).write_bytes(p.read_bytes())
(config.output_dir / "provenance.json").write_text(
json.dumps(provenance, indent=2) + "\n"
)
kwargs = {
"sim_backend": "physx_cpu",
"num_envs": 1,
"max_episode_steps": config.max_episode_steps,
"reward_mode": "sparse",
"render_mode": "rgb_array",
"sensor_configs": {"shader_pack": "default"},
"human_render_camera_configs": {"shader_pack": "default"},
"viewer_camera_configs": {"shader_pack": "default"},
}
raw = RecordEpisode(
gym.make(config.task, obs_mode="rgb", control_mode="pd_joint_pos", **kwargs),
output_dir=str(config.output_dir / "source"),
trajectory_name="trajectory",
save_on_reset=False,
save_video=config.save_video,
video_fps=20,
source_type="motionplanning",
source_desc=f"native {config.task} expert with primitive annotations",
)
original = gym.make(
config.task, obs_mode="none", control_mode="pd_joint_pos", **kwargs
)
target = RecordEpisode(
gym.make(
config.task, obs_mode="rgb", control_mode="pd_ee_delta_pose", **kwargs
),
output_dir=str(config.output_dir / "pose"),
trajectory_name="trajectory",
save_on_reset=False,
save_video=False,
source_type="motionplanning",
source_desc="pose replay with exact source-action annotation mapping",
)
started = time.monotonic()
accepted = 0
attempts = []
native_planner = expert.PandaArmMotionPlanningSolver
sequence = AnnotatedPlanner.stack_cube_sequence if config.task == "StackCube-v1" else None
try:
for attempt in range(config.max_attempts):
seed = config.seed_start + attempt
clear_recording(raw)
clear_recording(target)
segments = []
planners = []
perturbation = PERTURBATION_LEVELS.get(config.perturbation_level)
moves = []
rng = (
np.random.default_rng([perturbation.seed, seed]) if perturbation else None
)
def factory(
*args,
_planners=planners,
_segments=segments,
_moves=moves,
_perturbation=perturbation,
_rng=rng,
**kwargs,
):
planner = native_planner(*args, **kwargs)
_planners.append(planner)
return AnnotatedPlanner(
PlannerConfig(
planner=planner,
recorder=raw,
segments=_segments,
sequence=sequence,
perturbation=_perturbation,
rng=_rng,
log=_moves,
)
)
failure = None
try:
# Scoped single-process adapter; the upstream function and planner remain unchanged.
with patch.object(expert, "PandaArmMotionPlanningSolver", factory):
result = expert.solve(raw, seed=seed, debug=False, vis=False)
raw_success = not isinstance(result, int) and bool(
result[-1]["success"].item()
)
except PlanningFailure as error:
raw_success = False
failure = str(error)
finally:
for planner in planners:
planner.close()
record = {
"attempt": attempt,
"seed": seed,
"raw_success": raw_success,
"pose_success": False,
"failure": failure,
}
if perturbation is not None:
record["perturbation"] = moves
if raw_success:
if sequence is not None and len(segments) != len(sequence):
raise ValueError("Successful source has incomplete annotations")
raw_steps = len(raw._trajectory_buffer.action) - 1
raw.flush_trajectory()
source_id = raw._episode_id
source_group = raw._h5_file[f"traj_{source_id}"]
write_annotations(
source_group,
AnnotationConfig(
segments=tuple(segments),
source_steps=raw_steps,
target_to_source=tuple(range(raw_steps)),
),
)
raw._h5_file.flush()
if config.save_video:
raw.flush_video(name=f"seed{seed}")
original.reset(seed=seed)
target.reset(seed=seed)
initial = tree_first(source_group["env_states"])
original.unwrapped.set_state_dict(initial)
target.unwrapped.set_state_dict(initial)
obs = target.unwrapped.get_obs()
replace_last(target._trajectory_buffer.state, common.batch(initial))
replace_last(
target._trajectory_buffer.observation,
common.to_numpy(common.batch(obs)),
)
# Exact identity/state correspondence is checked before executing any converted action.
for name in ["qpos", "qvel"]:
np.testing.assert_allclose(
common.to_numpy(obs["agent"][name])[0],
source_group[f"obs/agent/{name}"][0],
rtol=0,
atol=1e-6,
)
mapping = []
info = replay_targets(
TargetReplayConfig(
original=original,
target=target,
actions=source_group["actions"][:],
on_target_step=mapping.append,
)
)
pose_success = bool(info["success"].item())
record.update(
source_episode_id=source_id,
source_steps=raw_steps,
pose_steps=len(mapping),
pose_success=pose_success,
)
if pose_success:
target.flush_trajectory()
output_id = target._episode_id
write_annotations(
target._h5_file[f"traj_{output_id}"],
AnnotationConfig(
segments=tuple(segments),
source_steps=raw_steps,
target_to_source=tuple(mapping),
),
)
target._json_data["episodes"][-1].update(
source_episode_id=source_id, source_episode_seed=seed
)
target._h5_file.flush()
accepted += 1
record["output_episode_id"] = output_id
# Explicitly discard failed buffers before reset, including the last attempt.
clear_recording(raw)
clear_recording(target)
record.update(accepted=accepted, elapsed_s=time.monotonic() - started)
attempts.append(record)
with (config.output_dir / "attempts.jsonl").open("a") as f:
f.write(json.dumps(record) + "\n")
(config.output_dir / "progress.json").write_text(
json.dumps(record, indent=2) + "\n"
)
print("KEYPOSE_ATTEMPT", json.dumps(record), flush=True)
if accepted == config.episodes:
break
finally:
clear_recording(raw)
clear_recording(target)
raw.close()
original.close()
target.close()
audits = {}
for variant in ["source", "pose"]:
audit = audit_dataset(
AuditConfig(
dataset=config.output_dir / variant / "trajectory.h5",
output=config.output_dir / f"audit-{variant}.json",
source_dataset=config.output_dir / "source" / "trajectory.h5"
if variant == "pose"
else None,
)
)
audits[variant] = {k: v for k, v in audit.items() if k != "rows"}
summary = {
"status": "complete"
if accepted == config.episodes
else "insufficient_successes",
"requested": config.episodes,
"accepted": accepted,
"attempted": len(attempts),
"wall_s": time.monotonic() - started,
"audits": audits,
"scope": "new annotated demonstration data; no learned keypose policy evaluated",
}
(config.output_dir / "result.json").write_text(json.dumps(summary, indent=2) + "\n")
print("KEYPOSE_COMPLETE", json.dumps(summary), flush=True)
if accepted != config.episodes:
raise RuntimeError("Collection exhausted its declared attempt budget")
return summary
if __name__ == "__main__":
run(CliApp.run(CollectionConfig))