Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions scripts/benchmark/grasp_opt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Grasp Optimization Benchmark

Dexterous grasp synthesis for the MANO hand: RoboKit LM vs annealed GD, each on mesh and SDF collision.

## Data

- 128 fixed scenes from the DexGraspNet test split, spread over the objects.
- 32 grasps per scene: 4096 grasps per run.

## Protocol

- graspkit's MANO floating preset. LM: 64 iterations, 24 candidates per grasp. GD: 6000 iterations.
- Collision against the object mesh, or a 64³ SDF baked from it. Scoring always uses the mesh.
- Each grasp is motion-planned, then lifted in ManiSkill under external forces.
- One untimed warmup solve per method. Mean ± std over 5 runs (seeds 0–4).

The optimizer must retain its scene buffers, variables, terms, solver, and CUDA graphs after warmup. Each run copies
its initial state into the existing buffers and resets contacts, RNG, and optimizer state. Rebuilding a solver inside
`optimize()` includes allocation and graph capture in `time_s`, contradicting the setup exclusion below.

## Metrics

- `time_s`: solver time for all 4096 grasps, excluding scene loading and setup (s) ↓
- `success_percent`: grasps that plan and hold the object under perturbation (%) ↑
- `q1`: Ferrari–Canny ε-metric; contacts within 5 mm, friction 0.5, 8-edge cones; 0 when not force-closure ↑
- `pen_mm`: max hand–object penetration per grasp, averaged (mm) ↓
- `*_std`: std over runs

## Run

```shell
uv run scripts/benchmark/grasp_opt/run_benchmark.py
uv run scripts/benchmark/grasp_opt/run_benchmark.py --methods LM-sdf --csv-path lm_sdf.csv # one method
```

Uses graspkit 0.1.0 and its public Hugging Face dataset. Each method takes 7–12 min on an RTX 4090; `results.csv`
ran them on three cards. `inspect_cases.py` shows each method's first-run grasps on their scenes, worst
scenes first.
115 changes: 115 additions & 0 deletions scripts/benchmark/grasp_opt/inspect_cases.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# /// script
# requires-python = ">=3.10,<3.11"
# dependencies = [
# "graspkit[maniskill]==0.1.0",
# "robokit[pt-cu126]",
# "warp-lang==1.10.1",
# "torchvision",
# "scipy",
# "tabulate",
# "tyro",
# ]
#
# [[tool.uv.index]]
# name = "pytorch-cu126"
# url = "https://download.pytorch.org/whl/cu126"
# explicit = true
#
# [tool.uv]
# override-dependencies = ["robokit[pt-cu126]"]
#
# [tool.uv.sources]
# robokit = { path = "../../..", editable = true }
# torchvision = { index = "pytorch-cu126" }
# ///
"""Inspect each method's first saved grasp per scene, worst success first, no solving; `--outputs PATH` picks the run.

Displays:
- Scene: target object and the selected method's grasp.
- Scores: planning/lifting success, Q1, and penetration.

uv run scripts/benchmark/grasp_opt/inspect_cases.py
"""

import os
import sys
import time
from pathlib import Path

import numpy as np
import transforms3d
import trimesh
import tyro
import viser
from graspkit.assets import REVISION
from graspkit.configs.robot.mano import mano_right
from graspkit.constants import GRASPKIT_HOME, HF_REPO_ID, OBJECT_COLOR, ROBOT_COLOR
from graspkit.scene.scene_description import SceneDescription
from viser.extras import ViserUrdf

from robokit.assets import fetch


sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent))

from scripts.benchmark.grasp_opt.run_benchmark import OUTPUTS, SCENES # noqa: E402


def main(outputs: Path = OUTPUTS, port: int = 8080) -> None:
solved = {p.stem: dict(np.load(p)) for p in sorted(outputs.glob("*.npz"))}
if not solved:
raise SystemExit(f"no grasps in {outputs}; run run_benchmark.py first")
os.chdir(GRASPKIT_HOME) # scene files name meshes relative to graspkit's data root
all_scenes = SceneDescription.load_scene_descriptions_msgpack(
str(fetch([SCENES], REVISION, HF_REPO_ID, GRASPKIT_HOME) / SCENES)
)
scene_ids = list(next(iter(solved.values()))["scene_ids"])
order = np.argsort(np.mean([s["success"].mean(1) for s in solved.values()], 0), kind="stable")
server = viser.ViserServer(port=port)
hand = server.scene.add_frame("/hand", show_axes=False)
urdf = ViserUrdf(
server, Path(mano_right.urdf_or_mjcf_path), root_node_name="/hand", mesh_color_override=ROBOT_COLOR
)
method = server.gui.add_dropdown("Method", tuple(solved))
scene = server.gui.add_slider("Scene", min=0, max=len(scene_ids) - 1, step=1, initial_value=0)
grasp = server.gui.add_slider(
"Grasp", min=0, max=solved[method.value]["qpos"].shape[1] - 1, step=1, initial_value=0
)
info = server.gui.add_markdown("")

@server.on_client_connect
def _(client: viser.ClientHandle) -> None: # hand-scale view of the object, which sits near the origin
client.camera.position, client.camera.look_at = (0.4, 0.4, 0.4), (0.0, 0.0, 0.05)

@scene.on_update
def load(_=None) -> None:
desc = all_scenes[scene_ids[order[scene.value]]]
m = desc.meshes[desc.target_actor_id]
mesh = trimesh.load(m.collision_mesh_path, force="mesh").apply_scale(m.scales)
server.scene.add_mesh_simple(
"/object", mesh.vertices, mesh.faces, color=OBJECT_COLOR, position=m.position, wxyz=m.quaternion
)
show()

@method.on_update
@grasp.on_update
def show(_=None) -> None:
s, i, g = solved[method.value], order[scene.value], grasp.value
q, ok = s["qpos"][i, g], bool(s["success"][i, g]) # base xyz + rxyz euler, then the fingers
hand.position, hand.wxyz = q[:3], transforms3d.euler.euler2quat(*q[3:6], axes="rxyz")
urdf.update_cfg(q[6:])
info.content = "\n\n".join(
[f"`{scene_ids[i]}`"]
+ [f"**{name}**: {100 * r['success'][i].mean():.0f}% success" for name, r in solved.items()]
+ [
f"**Grasp {g}**: {'success' if ok else 'failure'} · Q1 {s['q1'][i, g]:.3f} · pen {s['pen_mm'][i, g]:.2f} mm"
]
)

load()
while True:
time.sleep(1.0)


if __name__ == "__main__":
tyro.cli(main)
6 changes: 6 additions & 0 deletions scripts/benchmark/grasp_opt/results.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# gpu=NVIDIA GeForce RTX 4090 | cpu=Intel(R) Xeon(R) Gold 5120 CPU @ 2.20GHz | commit=9aad06e0 | date=2026-10-31 21:45 UTC
method,runs,grasps,time_s,time_s_std,success_percent,success_percent_std,q1,q1_std,pen_mm,pen_mm_std
LM-mesh,5,4096,15.58514147521928,0.020992491468382633,48.9306640625,0.49828617106675477,0.0673247008974448,0.0004762452602928089,0.6908354163169861,0.01649978455085281
GD-mesh,5,4096,18.457512796763332,0.3762288432381222,43.447265625,0.5318904830525868,0.06901003428685655,0.0008113420664109907,1.3855822086334229,0.011177568163863711
LM-sdf,5,4096,3.6412636409979315,0.0033042057085348677,48.4716796875,0.650459537921947,0.06552888939298061,0.001034915946286311,0.6912956714630127,0.014245912221117174
GD-sdf,5,4096,4.4064599495846775,0.017392542598298907,43.6328125,0.421565189338855,0.06481860334131409,0.0008267063991889776,1.4061045885086059,0.02518325232055651
Loading
Loading