Graspmax / geomatch_v3 /README.md
Dimios45's picture
geomatch_v3: add final epoch-199 checkpoint + evaluation README
a747d36 verified
|
Raw History Blame Contribute Delete
15.6 kB

GeoMatch v3 β€” trained on correct keypoints

Training complete: 200/200 epochs, 37.97 h, zero errors. Not yet evaluated in Isaac Gym β€” grasp success rate is unknown.

This folder holds the first GeoMatch run trained against verified-correct end-effector keypoints. Every earlier run in this repository was trained on keypoint data that was wrong in some way (see Bug history). Both checkpoints below are published so the Isaac Gym evaluation can be run on either.

Contents

file what it is md5
checkpoint_final.pth epoch 199 (end of the 200-epoch schedule) 289419788d5740f04cdb5446d0099241
checkpoint_epoch100.pth epoch 100 (halfway) d64777639b55f339fb3f9513c5731848
robot_keypoints.json required β€” the canonical keypoints, never released upstream 3bbd2df2a990a505f31883ac64f9cb60
robot_centroids.json loaded by HandModel, not used in the math d3305eafbb691c1f87890dd98e2db506
INFO.md detailed training record, keypoint verification, contact-label analysis

checkpoint_final.pth sha256: 8f72bde46214a144434b9d807b1bfa700fecc04e401ca0bd94e73a01e766a915

Both are raw state_dict (collections.OrderedDict, 72 tensors, 1,890,309 params), verified free of NaN/Inf. Architecture is identical to geomatch_v1 / geomatch_v2.

Which one to evaluate

Evaluate both. They cannot be ranked from the training curves:

epoch 100 epoch 199 (final)
train loss / acc 1.675200 / 0.6890 1.616352 / 0.7283
val loss / acc 1.751752 / 0.6421 1.784622 / 0.6923

Training accuracy is clearly better at epoch 199. Validation loss is better at epoch 100 while validation accuracy is better at epoch 199 β€” they disagree. Validation is only 10 objects and swings Β±0.05 between adjacent epochs, so neither metric resolves this, and neither predicts grasp success. Isaac Gym is the tiebreak.


Evaluation guide

⚠️ Read this first: three traps

  1. generate_grasps_for_obj.py hardcodes the checkpoint filename. Line 328 loads os.path.join(args.saved_model_dir, 'weights/grasp_gnn.pth') β€” it ignores which checkpoint you meant. To evaluate epoch 100 you must stage it under that exact name, or you will silently evaluate whatever grasp_gnn.pth happens to be. See Stage 3.
  2. The keypoint JSONs must be byte-identical between training and evaluation. IK solves for these exact keypoint positions. A mismatch produces systematically wrong grasps with no error message β€” this is the failure that cost this project months. Verify md5sum robot_keypoints.json β†’ 3bbd2df2a990a505f31883ac64f9cb60.
  3. Isaac Gym needs its own Python 3.8 + CUDA environment, separate from the training env. It will not run on AMD/ROCm at all.

What is NOT in the upstream repo

Referenced in the older geomatch_v2_repro/EVAL_INFO.md but absent from google-deepmind/geomatch:

  • evaluate.py β€” the cheap contact-precision sanity check. Does not exist.
  • refine_grasps_cmap_adam.py β€” the force-closure refinement wrapper. Does not exist; the underlying CMapAdam class does exist at GenDexGrasp/utils_model/CMapAdam.py.
  • bridge_to_gendexgrasp.py β€” converts GeoMatch grasp output into the layout run_grasp_test.py expects. Does not exist. A working replacement is given in Stage 4.

Pipeline overview

[env A: py3.9, torch]                          [env B: py3.8 + CUDA + Isaac Gym]
generate_grasps_for_all_objs.py                run_grasp_test.py
   └─> logs_out_grasps/<obj>/gen_grasps.pt        └─> reads logs_gen/<dataset>/<tra_dir>/
                    β”‚                                          β–²
                    └──────── bridge (Stage 4) β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Stage 0 β€” repo and data

git clone https://github.com/Dimios45/geomatch && cd geomatch
git checkout geomatch++          # the branch with the fixed train.py + verify_keypoints.py

Dataset: the MultiDex subset from GenDexGrasp β€” you need dataset/CMapDataset-sqrt_align/ (cmap_dataset.pt, object_point_clouds.pt, split_train_validate_objects.json) and data/urdf/ + data/object/.

Split is GenDexGrasp's own: 48 train / 10 validation objects (the paper text says 38 train, which contradicts its own 58-object total; the released split file has 48).

Stage 1 β€” environment A (grasp generation)

Python 3.9, PyTorch 2.x. Known-good on ROCm 6.2.4 with torch 2.5.1+rocm6.2; CUDA works too.

conda create -n geomatch python=3.9 -y && conda activate geomatch
pip install torch --index-url https://download.pytorch.org/whl/rocm6.2   # or the CUDA index
pip install pytorch-kinematics==0.7.6 urdf_parser_py trimesh transforms3d \
            scipy numpy==1.26.4 matplotlib plotly tqdm tensorboard

numpy must stay <2. Sanity check:

python -c "from pytorch_kinematics.urdf_parser_py.urdf import Box; import urdf_parser_py.urdf; print('ok')"

Stage 2 β€” data directory and keypoints

HandModel reads the keypoint JSONs from data_dir, not from the repo root:

D=/path/to/grasp_gnn_v3
mkdir -p $D && cd $D
ln -s /path/to/GenDexGrasp/dataset/CMapDataset-sqrt_align .
ln -s /path/to/GenDexGrasp/data/urdf .
# from THIS HuggingFace folder:
cp robot_keypoints.json robot_centroids.json $D/
md5sum $D/robot_keypoints.json     # must be 3bbd2df2a990a505f31883ac64f9cb60

Build the preprocessed graphs (needed by the generation script), then verify:

cd /path/to/geomatch
python create_gnn_dataset.py --dataset_basedir $D \
  --object_mesh_basedir /path/to/GenDexGrasp/data/object --gnn_dataset_basedir $D

python verify_keypoints.py --dataset_basedir $D    # must exit 0

verify_keypoints.py (on the geomatch++ branch) checks that every keypoint link exists in the URDF, that keypoints lie on the mesh surface, that repeated links occupy contiguous indices, and that keypoints map to distinct point-cloud samples. Expect two non-blocking notices on ezgripper's proximal finger links (3.3 mm and 9.2 mm off surface) β€” known and documented in INFO.md.

Stage 3 β€” generate grasps

Because of trap #1, stage each checkpoint under weights/grasp_gnn.pth:

# ---- final (epoch 199) ----
mkdir -p eval_final/weights
cp checkpoint_final.pth eval_final/weights/grasp_gnn.pth

# ---- epoch 100 ----
mkdir -p eval_ep100/weights
cp checkpoint_epoch100.pth eval_ep100/weights/grasp_gnn.pth

Then run generation once per checkpoint:

python generate_grasps_for_all_objs.py \
  --saved_model_dir eval_final \
  --data_dir $D \
  --output_dir logs_out_grasps_final/

python generate_grasps_for_all_objs.py \
  --saved_model_dir eval_ep100 \
  --data_dir $D \
  --output_dir logs_out_grasps_ep100/

This writes logs_out_grasps_*/<object_name>/gen_grasps.pt, containing:

{'info': ['object_name','robot_name','pred_keypoints','robot_final_keypoints',
          'init_pose','pred_grasp_pose','sample_idx'],
 'metadata': [ {... 'pred_grasp_pose': <tensor>, 'sample_idx': int, 'scale': 1.0}, ... ]}

pred_grasp_pose is the IK solution β€” the field the simulator needs. Per the paper, 4 grasps per object-gripper are sampled from the top-[0, 20, 50, 100] predicted keypoint configurations, and pre-grasp keypoints are offset 5 mm along the surface normal before SciPy TRF IK (generate_grasps_for_obj.py:385-391, already implemented).

Stage 4 β€” bridge to GenDexGrasp format

run_grasp_test.py does not read gen_grasps.pt. It expects, under GenDexGrasp/logs_gen/<dataset>/:

  • split_train_validate_objects.json (with a validate key)
  • a trajectory subdirectory of files named <prefix>-<object_name>-<N>.pt, each a dict with keys q_tra and energy; it takes q_tra[energy.min(dim=0)[1], -1, :] and concatenates one pose per file.

The filename is parsed as split('-')[1] == object_name and int(split('-')[2].split('.pt')[0]), so the prefix must contain no -. Object names use + (contactdb+apple), so they are safe.

Save as bridge_to_gendexgrasp.py and run it in env A:

"""Convert GeoMatch gen_grasps.pt into the layout run_grasp_test.py expects."""
import argparse, json, os, shutil, torch

p = argparse.ArgumentParser()
p.add_argument('--grasp_dir', required=True)      # logs_out_grasps_final/
p.add_argument('--robot_name', required=True)     # ezgripper | barrett | shadowhand
p.add_argument('--gendexgrasp_root', required=True)
p.add_argument('--dataset_tag', required=True)    # e.g. geomatch_v3_final_barrett
p.add_argument('--split_json', required=True)     # .../split_train_validate_objects.json
a = p.parse_args()

out = os.path.join(a.gendexgrasp_root, 'logs_gen', a.dataset_tag)
tra = os.path.join(out, 'tra_dir')
os.makedirs(tra, exist_ok=True)
shutil.copy(a.split_json, os.path.join(out, 'split_train_validate_objects.json'))

n = 0
for obj in sorted(os.listdir(a.grasp_dir)):
    f = os.path.join(a.grasp_dir, obj, 'gen_grasps.pt')
    if not os.path.exists(f):
        continue
    samples = [s for s in torch.load(f, weights_only=False)['metadata']
               if s['robot_name'] == a.robot_name]
    for i, s in enumerate(samples):
        q = torch.as_tensor(s['pred_grasp_pose']).float().reshape(1, 1, -1)
        torch.save({'q_tra': q, 'energy': torch.zeros(1, 1)},
                   os.path.join(tra, f'geomatch-{obj}-{i}.pt'))
        n += 1
    print(f'{obj}: {len(samples)} grasps')
print(f'wrote {n} files -> {tra}')

energy is all-zeros because GeoMatch has already selected its grasps; energy.min(dim=0)[1] then picks index 0, and q_tra[..., -1, :] returns the pose. One file = one grasp, so 4 files per object gives the paper's 4 grasps per object-gripper.

Optional force-closure refinement. The paper (Appendix C) applies one Adam step at step size 0.05 before the physics test, reusing GenDexGrasp's own machinery. Use GenDexGrasp/utils_model/CMapAdam.py (CMapAdam, learning_rate=0.05, a single step) on pred_grasp_pose prior to writing each .pt. Report whether you applied it β€” it is a real difference in protocol, and the earlier 5–10% results were obtained with it applied.

Stage 5 β€” environment B (Isaac Gym)

Isaac Gym Preview 4 requires Python 3.8 and an NVIDIA GPU; download it from developer.nvidia.com/isaac-gym (registration required β€” it cannot be pip-installed).

conda env create -f GenDexGrasp/requirements.yaml   # pins python=3.8.13
conda activate gendexgrasp
cd isaacgym/python && pip install -e .
python -c "from isaacgym import gymapi; print('isaacgym ok')"

run_grasp_test.py also imports deepdiff, yaml, and trimesh.

Stage 6 β€” run the physics test

Only ezgripper, barrett, shadowhand are implemented (grasp_test_force_*.py); anything else raises NotImplementedError. Those are exactly the paper's three evaluated grippers.

cd /path/to/GenDexGrasp
conda activate gendexgrasp
for R in ezgripper barrett shadowhand; do
  python run_grasp_test.py --robot_name $R --dataset geomatch_v3_final_$R --mode test
done

Results land in logs_gen/<dataset>/test_record-<hash>.json, per object: total_num, succ_num, succ_flag.

Test protocol (already implemented in the harness): 0.5 m/sΒ² acceleration applied sequentially along Β±x, Β±y, Β±z for 1 s (60 sim steps) each; a grasp succeeds only if object displacement stays under 2 cm in all six directions.

Aggregate:

import json, glob
for f in glob.glob('logs_gen/geomatch_v3_final_*/test_record-*.json'):
    r = json.load(open(f))
    s = sum(v['succ_num'] for k, v in r.items() if k != 'cfg')
    t = sum(v['total_num'] for k, v in r.items() if k != 'cfg')
    print(f'{f}: {s}/{t} = {100*s/t:.1f}%')

Targets

gripper paper (GeoMatch, in-domain)
EZGripper 75.0%
Barrett 90.0%
ShadowHand 72.5%
mean 79.17%

For calibration against this repo's history: geomatch_v1 scored 0%, and geomatch_v2_repro at epoch 50 scored 5–10%. Anything in that range means something is still wrong upstream of the simulator β€” re-check the keypoint md5 first.

Validation objects (the 10 held out at training): contactdb+apple, contactdb+camera, contactdb+cylinder_medium, contactdb+rubber_duck, contactdb+door_knob, contactdb+water_bottle, ycb+baseball, ycb+pear, ycb+potted_meat_can, ycb+tomato_soup_can.


Training record

epochs 200 (0–199), 37.97 h, 1Γ— AMD MI300X (ROCm 6.2.4), torch 2.5.1
batch size 64 (upstream train.py default; the paper states none)
optimizer Adam, Ξ²=(0.9, 0.99), weight_decay=0, lr 1e-4 constant
precision FP32 (no AMP)
Ξ» robot / matchnet 500 / 200 Β· Ξ±/Ξ² = 0.5/0.5
N keypoints / KNN 6 / 8
point clouds object 2048, end-effector 1000 (ezgripper 768)
seed 42
data 41,871 train + 8,931 validate = 50,802 grasps (matches the paper)
integrity 400/400 progress bars ran the full 655 (train) / 140 (val) steps

That last row matters: geomatch_v2 was invalidated by silent DataLoader starvation, so every epoch of this run was checked for full step count. None were short.

Trajectory: train accuracy 0.0395 β†’ 0.7283. Validation loss fell to ~1.75 by epoch 80 then drifted mildly up to ~1.785 while validation accuracy improved from ~0.65 to ~0.69 β€” the two disagree, which is why both checkpoints are published.

Bug history

run keypoint data Isaac Gym
geomatch_v1 2Γ— scale bug + ShadowHand axis-swap at the wrong stage 0%
geomatch_v2 keypoints fixed, but DataLoader saw ~7.3% of data per epoch invalid
geomatch_v2_repro full data, but keypoints derived from link centroids 5–10% @ ep50
geomatch_v3 (this) real robot_keypoints.json unmeasured

robot_keypoints.json and robot_centroids.json were never released upstream β€” see google-deepmind/geomatch issue #1 (open since Feb 2024). The paper specifies they were chosen by hand:

"The canonical contact points kα΅’ ∈ V_G on the surface of each end-effector are selected visually." β€” arXiv:2312.03864 Β§3.1

Both files are included here so this run is reproducible. Switching from centroid-derived to real keypoints improved contact supervision on all three evaluated grippers (ezgripper 3.74β†’5.66 of 6 keypoints in contact, barrett 4.08β†’4.47, shadowhand 4.17β†’4.26). Details in INFO.md.

Loading

import torch, sys
sys.path.append(".")            # repo root with config.py and models/
import config
from models.geomatch import GeoMatch

model = GeoMatch(config).cuda()
model.load_state_dict(torch.load("checkpoint_final.pth", map_location="cuda"))
model.eval()

Citation

@inproceedings{attarian2023geometry,
  title={Geometry Matching for Multi-Embodiment Grasping},
  author={Attarian, Maria and Asif, Muhammad Adil and Liu, Jingzhou and Hari, Ruthrash
          and Garg, Animesh and Gilitschenski, Igor and Tompson, Jonathan},
  booktitle={Proceedings of the 7th Conference on Robot Learning (CoRL)},
  year={2023}
}

Original GeoMatch code Β© 2023 DeepMind Technologies Limited, Apache License 2.0.