OpenGHz's picture
Add fair-comparison/flow-v1
0a3f650 verified
Raw History Blame Contribute Delete
8.69 kB
"""Execute recorded expert keyposes, without using their dense action trajectories.
This is an oracle controller diagnostic on demonstration initial states, NOT a
learned-policy evaluation. Saved keypose order and targets are privileged labels.
"""
import hashlib
import json
import time
from pathlib import Path
import gymnasium as gym
import h5py
import mani_skill.envs # noqa: F401
import numpy as np
import torch
from mani_skill.utils import common
from pydantic import BaseModel, ConfigDict, PositiveInt
from pydantic_settings import CliApp
from lim.keypose_control import KeyposeControlConfig, encode_keypose, keypose_command
from lim.replay_pose import tree_first
class OracleConfig(BaseModel, frozen=True):
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
dataset: Path
"""Annotated pose demonstration H5; only initial state and keypose labels read."""
output_dir: Path
"""New diagnostic directory; all attempts and step records retained."""
episodes: PositiveInt = 10
"""First numerically ordered demonstrations, never a selected successful subset."""
max_steps: PositiveInt = 200
"""Same finite episode horizon as policy evaluation."""
event_steps: PositiveInt = 6
"""Fixed open/close dwell after measured arrival, matching native expert duration."""
control: KeyposeControlConfig = KeyposeControlConfig()
"""Frozen TCP tracking parameters, also used by the learned policy transport."""
def run(config: OracleConfig):
torch.set_num_threads(4)
config.output_dir.mkdir(parents=True, exist_ok=False)
metadata = json.loads(config.dataset.with_suffix(".json").read_text())
episodes = sorted(metadata["episodes"], key=lambda e: e["episode_id"])[
: config.episodes
]
if len(episodes) != config.episodes:
raise ValueError("Insufficient annotated episodes")
kwargs = metadata["env_info"]["env_kwargs"] | {
"max_episode_steps": config.max_steps
}
env = gym.make(metadata["env_info"]["env_id"], **kwargs)
results = []
started = time.time()
try:
with (
h5py.File(config.dataset, "r") as data,
(config.output_dir / "steps.jsonl").open("x") as steps,
):
for episode in episodes:
group = data[f"traj_{episode['episode_id']}"]
env.reset(**episode["reset_kwargs"])
base = env.unwrapped
base.set_state_dict(tree_first(group["env_states"]))
obs = base.get_obs()
arm = base.agent.controller.controllers["arm"]
if (
arm.config.frame != "root_translation:root_aligned_body_rotation"
or arm.config.use_target
or not arm.config.use_delta
or not arm.config.normalize_action
or not np.isclose(arm.config.rot_lower, -0.1)
):
raise ValueError("Unexpected controller semantics")
np.testing.assert_allclose(
base.agent.robot.pose.q.cpu(), [[1, 0, 0, 0]], atol=1e-6
)
np.testing.assert_allclose(
arm.action_space_high[:3].cpu(), [0.1] * 3, atol=1e-7
)
np.testing.assert_allclose(
arm.action_space_low[:3].cpu(), [-0.1] * 3, atol=1e-7
)
key = group["keyframes"]
targets = encode_keypose(
torch.from_numpy(key["target_pose_world"][:]),
torch.from_numpy(key["gripper_command"][:]),
)
kinds = key["kind"].asstr()[:]
current = torch.as_tensor(obs["extra"]["tcp_pose"])
grip = (
(torch.as_tensor(obs["agent"]["qpos"])[..., 7:9].mean(-1) + 0.01)
/ 0.05
* 2
- 1
).clamp(-1, 1)
index, dwell, once, end = 0, 0, False, False
transitions = []
for step in range(config.max_steps):
executed_index = min(index, len(targets) - 1)
target = targets[executed_index][None]
command, reached, pe, re = keypose_command(
current, target, grip, config.control
)
before = current.clone()
obs, _, _terminated, truncated, info = env.step(command)
grip = command[:, -1].clone()
current = torch.as_tensor(obs["extra"]["tcp_pose"])
end = bool(info["success"].item())
once |= end
reached_before = bool(reached.item())
if index < len(targets):
# Once started, an event lasts its fixed six steps even
# if contact briefly moves the TCP outside tolerance.
dwell = dwell + 1 if (reached_before or dwell > 0) else 0
needed = 1 if kinds[index] == "move" else config.event_steps
if dwell >= needed:
transitions.append(
{
"keyframe": index,
"after_step": step + 1,
"position_error_m": pe.item(),
"rotation_error_rad": re.item(),
}
)
index += 1
dwell = 0
steps.write(
json.dumps(
{
"seed": episode["episode_seed"],
"step": step + 1,
"target_index_executed": executed_index,
"target": target[0].tolist(),
"tcp_before": before[0].tolist(),
"command": command[0].tolist(),
"tcp_after": current[0].tolist(),
"position_error_m": pe.item(),
"rotation_error_rad": re.item(),
"success": end,
"cubeA_pose": common.to_numpy(base.cubeA.pose.raw_pose)[
0
].tolist(),
"cubeB_pose": common.to_numpy(base.cubeB.pose.raw_pose)[
0
].tolist(),
}
)
+ "\n"
)
if bool(truncated.item()):
if step + 1 != config.max_steps:
raise ValueError("Unexpected truncation")
break
row = {
"seed": episode["episode_seed"],
"episode_id": episode["episode_id"],
"success_once": once,
"success_at_end": end,
"steps": step + 1,
"completed_keyframes": index,
"keyframes": len(targets),
"transitions": transitions,
}
results.append(row)
with (config.output_dir / "episodes.jsonl").open("a") as output:
output.write(json.dumps(row) + "\n")
print("ORACLE_EPISODE", json.dumps(row), flush=True)
finally:
env.close()
result = {
"config": config.model_dump(mode="json"),
"episodes": len(results),
"success_once": sum(r["success_once"] for r in results),
"success_at_end": sum(r["success_at_end"] for r in results),
"all_keyframes_completed": sum(
r["completed_keyframes"] == r["keyframes"] for r in results
),
"started_epoch": started,
"ended_epoch": time.time(),
"scope": "Privileged annotated goals and ordered stages on demonstration initial states; no learned policy, no heldout task score",
}
with config.dataset.open("rb") as stream:
result["dataset_sha256"] = hashlib.file_digest(stream, "sha256").hexdigest()
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n")
print("KEYPOSE_ORACLE_COMPLETE", json.dumps(result), flush=True)
if __name__ == "__main__":
run(CliApp.run(OracleConfig))